max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
450 | <reponame>YangHao666666/hawq
/*-------------------------------------------------------------------------
*
* cdb_dump_util.h
*
*
*-------------------------------------------------------------------------
*/
#ifndef CDB_DUMP_UTIL_H
#define CDB_DUMP_UTIL_H
#include <regex.h>
#include "cdb_seginst.h"
#define CDB_BACKUP_KEY_LEN 14
/* --------------------------------------------------------------------------------------------------
* This needs to be the same as that in cdbbackup.h in src/backend/cdb/cdbbackup.c
*/
typedef enum backup_file_type
{
BFT_BACKUP = 0,
BFT_BACKUP_STATUS = 1,
BFT_RESTORE_STATUS = 2
} BackupFileType;
/* --------------------------------------------------------------------------------------------------
* Structure for holding the command line options for both backup and restore
*/
typedef struct input_options
{
char *pszDBName;
char *pszPGHost;
char *pszPGPort;
char *pszUserName;
char *pszBackupDirectory;
char *pszReportDirectory;
char *pszCompressionProgram;
char *pszPassThroughParms;
char *pszCmdLineParms;
char *pszKey;
char *pszMasterDBName;
char *pszRawDumpSet;
ActorSet actors;
BackupLoc backupLocation;
bool bOnErrorStop;
} InputOptions;
/* issues either a listen or notify command on connection pConn */
extern void DoCancelNotifyListen(PGconn *pConn, bool bListen,
const char *pszCDBDumpKey,
int CDBInstID,
int CDBSegID,
int target_db_id,
const char *pszSuffix);
/* frees data allocated inside an InputOptions struct */
extern void FreeInputOptions(InputOptions * pInputOpts);
/* Generates a 14 digit timestamp key */
extern char *GenerateTimestampKey(void);
/* gets an int from a regex match */
extern int GetMatchInt(regmatch_t *pMatch, char *pszInput);
/* gets an stringt from a regex match */
extern char *GetMatchString(regmatch_t *pMatch, char *pszInput);
/* creates a formatted time string with the current time */
extern char *GetTimeNow(char *szTimeNow);
/* creates a connection where the password may be prompted for */
extern PGconn *GetMasterConnection(const char *progName, const char *pszDBName, const char *pszPGHost,
const char *pszPGPort, const char *pszUserName,
int reqPwd, int ignoreVersion, bool bDispatch);
/* creates a connection based on SegmentInstance* parameter */
extern PGconn *MakeDBConnection(const SegmentDatabase *pSegDB, bool bDispatch);
/* returns a formatted char * */
extern char *MakeString(const char *fmt,...);
/* breaks the input parameter associated with --cdb-k into its components for cdb_dump and cdb_restore*/
extern bool ParseCDBDumpInfo(const char *progName, char *pszCDBDumpInfo, char **ppCDBDumpKey, int *pCDBInstID, int *pCDBSegID, char **ppCDBPassThroughCredentials);
/* reads the contents out of the appropriate file on the database server */
extern char *ReadBackendBackupFile(PGconn *pConn, const char *pszBackupDirectory, const char *pszKey, BackupFileType fileType, const char *progName);
/* returns strdup if not NULL, NULL otherwise */
extern char *Safe_strdup(const char *s);
/* returns the string if not null, otherwise the default */
extern const char *StringNotNull(const char *pszInput, const char *pszDefault);
/* writes a formatted message to stderr */
extern void mpp_err_msg(const char *loglevel, const char *prog, const char *fmt,...);
/* writes a formatted message to stderr and caches it in a static var for later use */
extern void mpp_err_msg_cache(const char *loglevel, const char *prog, const char *fmt,...);
/* writes a formatted message to stdout */
extern void mpp_msg(const char *loglevel, const char *prog, const char *fmt,...);
/* writes the contents to the appropriate file on the database server */
/*extern char* WriteBackendBackupFile( PGconn* pConn, const char* pszBackupDirectory, const char* pszKey, const char* pszBackupScript );*/
/* writes a status message to a status file with naming convention based on instid, segid, and Key */
/* extern bool WriteStatusToFile( const char* pszMessage, const char* pszDirectory, const char* pszKey, int instid, int segid, bool bIsBackup ); */
extern char *get_early_error(void);
/* Base64 Encoding and Decoding Routines */
/* Base64 Data is assumed to be in a NULL terminated string */
/* Data is just assumed to be an array of chars, with a length */
extern char *DataToBase64(char *pszIn, unsigned int InLen);
extern char *Base64ToData(char *pszIn, unsigned int *pOutLen);
extern char *nextToken(register char **stringp, register const char *delim);
extern int parseDbidSet(int *dbidset, char *dump_set);
#endif /* CDB_DUMP_UTIL_H */
| 1,481 |
1,253 | <filename>libraries/CRC/test/unit_test_crc16.cpp
//
// FILE: unit_test_crc16.cpp
// AUTHOR: <NAME>
// DATE: 2021-03-31
// PURPOSE: unit tests for the CRC library
// https://github.com/RobTillaart/CRC
// https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md
//
// supported assertions
// ----------------------------
// assertEqual(expected, actual); // a == b
// assertNotEqual(unwanted, actual); // a != b
// assertComparativeEquivalent(expected, actual); // abs(a - b) == 0 or (!(a > b) && !(a < b))
// assertComparativeNotEquivalent(unwanted, actual); // abs(a - b) > 0 or ((a > b) || (a < b))
// assertLess(upperBound, actual); // a < b
// assertMore(lowerBound, actual); // a > b
// assertLessOrEqual(upperBound, actual); // a <= b
// assertMoreOrEqual(lowerBound, actual); // a >= b
// assertTrue(actual);
// assertFalse(actual);
// assertNull(actual);
// // special cases for floats
// assertEqualFloat(expected, actual, epsilon); // fabs(a - b) <= epsilon
// assertNotEqualFloat(unwanted, actual, epsilon); // fabs(a - b) >= epsilon
// assertInfinity(actual); // isinf(a)
// assertNotInfinity(actual); // !isinf(a)
// assertNAN(arg); // isnan(a)
// assertNotNAN(arg); // !isnan(a)
#include <ArduinoUnitTests.h>
#include "Arduino.h"
#include "CRC16.h"
char str[24] = "123456789";
uint8_t * data = (uint8_t *) str;
unittest_setup()
{
}
unittest_teardown()
{
}
unittest(test_crc16)
{
fprintf(stderr, "TEST CRC16\n");
CRC16 crc;
crc.setPolynome(0x1021);
crc.setStartXOR(0xFFFF);
crc.add(data, 9);
assertEqual(0x29B1, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xBB3D, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0x1D0F);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xE5CC, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xFEE8, crc.getCRC());
crc.reset();
crc.setPolynome(0xC867);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x4C06, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setStartXOR(0x800D);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x9ECF, crc.getCRC());
crc.reset();
crc.setPolynome(0x0589);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0001);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x007E, crc.getCRC());
crc.reset();
crc.setPolynome(0x0589);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x007F, crc.getCRC());
crc.reset();
crc.setPolynome(0x3D65);
crc.setStartXOR(0x0000);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xEA82, crc.getCRC());
crc.reset();
crc.setPolynome(0x3D65);
crc.setStartXOR(0x0000);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xC2B7, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xD64E, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setStartXOR(0x0000);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x44C2, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x6F91, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0xB2AA);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x63D0, crc.getCRC());
crc.reset();
crc.setPolynome(0x8BB7);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xD0DB, crc.getCRC());
crc.reset();
crc.setPolynome(0xA097);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x0FB3, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0x89EC);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x26B1, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xB4C8, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0xC6C6);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xBF05, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x2189, crc.getCRC());
crc.reset();
crc.setPolynome(0x8005);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0x0000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x4B37, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0xFFFF);
crc.setEndXOR(0xFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x906E, crc.getCRC());
crc.reset();
crc.setPolynome(0x1021);
crc.setStartXOR(0x0000);
crc.setEndXOR(0x0000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x31C3, crc.getCRC());
/*
assertEqual(0x29B1, crc16(data, 9, 0x1021, 0xFFFF, 0x0000, false, false ));
assertEqual(0xBB3D, crc16(data, 9, 0x8005, 0x0000, 0x0000, true, true ));
assertEqual(0xE5CC, crc16(data, 9, 0x1021, 0x1D0F, 0x0000, false, false ));
assertEqual(0xFEE8, crc16(data, 9, 0x8005, 0x0000, 0x0000, false, false ));
assertEqual(0x4C06, crc16(data, 9, 0xC867, 0xFFFF, 0x0000, false, false ));
assertEqual(0x9ECF, crc16(data, 9, 0x8005, 0x800D, 0x0000, false, false ));
assertEqual(0x007E, crc16(data, 9, 0x0589, 0x0000, 0x0001, false, false ));
assertEqual(0x007F, crc16(data, 9, 0x0589, 0x0000, 0x0000, false, false ));
assertEqual(0xEA82, crc16(data, 9, 0x3D65, 0x0000, 0xFFFF, true, true ));
assertEqual(0xC2B7, crc16(data, 9, 0x3D65, 0x0000, 0xFFFF, false, false ));
assertEqual(0xD64E, crc16(data, 9, 0x1021, 0xFFFF, 0xFFFF, false, false ));
assertEqual(0x44C2, crc16(data, 9, 0x8005, 0x0000, 0xFFFF, true, true ));
assertEqual(0x6F91, crc16(data, 9, 0x1021, 0xFFFF, 0x0000, true, true ));
assertEqual(0x63D0, crc16(data, 9, 0x1021, 0xB2AA, 0x0000, true, true ));
assertEqual(0xD0DB, crc16(data, 9, 0x8BB7, 0x0000, 0x0000, false, false ));
assertEqual(0x0FB3, crc16(data, 9, 0xA097, 0x0000, 0x0000, false, false ));
assertEqual(0x26B1, crc16(data, 9, 0x1021, 0x89EC, 0x0000, true, true ));
assertEqual(0xB4C8, crc16(data, 9, 0x8005, 0xFFFF, 0xFFFF, true, true ));
assertEqual(0xBF05, crc16(data, 9, 0x1021, 0xC6C6, 0x0000, true, true ));
assertEqual(0x2189, crc16(data, 9, 0x1021, 0x0000, 0x0000, true, true ));
assertEqual(0x4B37, crc16(data, 9, 0x8005, 0xFFFF, 0x0000, true, true ));
assertEqual(0x906E, crc16(data, 9, 0x1021, 0xFFFF, 0xFFFF, true, true ));
assertEqual(0x31C3, crc16(data, 9, 0x1021, 0x0000, 0x0000, false, false ));
*/
}
unittest_main()
// --------
| 4,038 |
625 | /*
* 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.datasketches.tuple.arrayofdoubles;
import static org.testng.Assert.assertEquals;
import org.apache.datasketches.Util;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayOfDoublesCompactSketchTest {
@Test
public void heapToDirectExactTwoDoubles() {
ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build();
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
ArrayOfDoublesCompactSketch csk = sketch1.compact();
Memory mem = Memory.wrap(csk.toByteArray());
ArrayOfDoublesSketch sketch2 = new DirectArrayOfDoublesCompactSketch(mem);
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@Test
public void directToHeapExactTwoDoubles() {
ArrayOfDoublesUpdatableSketch sketch1 =
new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(WritableMemory.writableWrap(new byte[1000000]));
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
sketch1.update("a", new double[] {1, 2});
sketch1.update("b", new double[] {1, 2});
sketch1.update("c", new double[] {1, 2});
sketch1.update("d", new double[] {1, 2});
ArrayOfDoublesSketch sketch2 =
new HeapArrayOfDoublesCompactSketch(
Memory.wrap(sketch1.compact(WritableMemory.writableWrap(new byte[1000000])).toByteArray()));
Assert.assertFalse(sketch2.isEmpty());
Assert.assertFalse(sketch2.isEstimationMode());
Assert.assertEquals(sketch2.getEstimate(), 4.0);
Assert.assertEquals(sketch2.getUpperBound(1), 4.0);
Assert.assertEquals(sketch2.getLowerBound(1), 4.0);
Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE);
Assert.assertEquals(sketch2.getTheta(), 1.0);
double[][] values = sketch2.getValues();
Assert.assertEquals(values.length, 4);
for (double[] array: values) {
Assert.assertEquals(array.length, 2);
Assert.assertEquals(array[0], 2.0);
Assert.assertEquals(array[1], 4.0);
}
}
@SuppressWarnings("unused")
@Test
public void checkGetValuesAndKeysMethods() {
ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder();
bldr.setNominalEntries(16).setNumberOfValues(2);
HeapArrayOfDoublesQuickSelectSketch hqssk = (HeapArrayOfDoublesQuickSelectSketch) bldr.build();
hqssk.update("a", new double[] {1, 2});
hqssk.update("b", new double[] {3, 4});
hqssk.update("c", new double[] {5, 6});
hqssk.update("d", new double[] {7, 8});
final double[][] values = hqssk.getValues();
final double[] values1d = hqssk.getValuesAsOneDimension();
final long[] keys = hqssk.getKeys();
HeapArrayOfDoublesCompactSketch hcsk = (HeapArrayOfDoublesCompactSketch)hqssk.compact();
final double[][] values2 = hcsk.getValues();
final double[] values1d2 = hcsk.getValuesAsOneDimension();
final long[] keys2 = hcsk.getKeys();
assertEquals(values2, values);
assertEquals(values1d2, values1d);
assertEquals(keys2, keys);
Memory hqsskMem = Memory.wrap(hqssk.toByteArray());
DirectArrayOfDoublesQuickSelectSketchR dqssk =
(DirectArrayOfDoublesQuickSelectSketchR)ArrayOfDoublesSketch.wrap(hqsskMem, Util.DEFAULT_UPDATE_SEED);
final double[][] values3 = dqssk.getValues();
final double[] values1d3 = dqssk.getValuesAsOneDimension();
final long[] keys3 = dqssk.getKeys();
assertEquals(values3, values);
assertEquals(values1d3, values1d);
assertEquals(keys3, keys);
Memory hcskMem = Memory.wrap(hcsk.toByteArray());
DirectArrayOfDoublesCompactSketch dcsk2 =
(DirectArrayOfDoublesCompactSketch)ArrayOfDoublesSketch.wrap(hcskMem, Util.DEFAULT_UPDATE_SEED);
final double[][] values4 = dqssk.getValues();
final double[] values1d4 = dqssk.getValuesAsOneDimension();
final long[] keys4 = dqssk.getKeys();
assertEquals(values4, values);
assertEquals(values1d4, values1d);
assertEquals(keys4, keys);
}
}
| 2,269 |
4,756 | /*
* Copyright (C) 2011 The Libphonenumber Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.i18n.phonenumbers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.i18n.phonenumbers.CombineGeoData.Range;
import org.junit.Test;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Unit tests for CombineGeoData class.
*
* @author <NAME>
*/
public class CombineGeoDataTest {
@Test
public void createSortedPrefixArray() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("122", null);
phonePrefixMap.put("42", null);
phonePrefixMap.put("4012", null);
phonePrefixMap.put("1000", null);
String[] sortedPrefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
assertEquals("1000", sortedPrefixes[0]);
assertEquals("122", sortedPrefixes[1]);
assertEquals("4012", sortedPrefixes[2]);
assertEquals("42", sortedPrefixes[3]);
}
@Test
public void findRangeEndFromStart() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33130", "Paris");
phonePrefixMap.put("33139", "Paris");
phonePrefixMap.put("334", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
int rangeEnd = CombineGeoData.findRangeEnd(prefixes, phonePrefixMap, 0);
assertEquals(1, rangeEnd);
}
@Test
public void findRangeEndFromMiddle() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33130", "Paris");
phonePrefixMap.put("33139", "Paris");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
int rangeEnd = CombineGeoData.findRangeEnd(prefixes, phonePrefixMap, 2);
assertEquals(3, rangeEnd);
}
@Test
public void findRangeEndWithSameLocationButDifferentPrefix() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33130", "Paris");
phonePrefixMap.put("3314", "Paris");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
int rangeEnd = CombineGeoData.findRangeEnd(prefixes, phonePrefixMap, 0);
assertEquals(0, rangeEnd);
}
@Test
public void createRanges() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33120", "Paris");
phonePrefixMap.put("33130", "Paris");
phonePrefixMap.put("33139", "Paris");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
List<Range> ranges = CombineGeoData.createRanges(prefixes, phonePrefixMap);
assertEquals(3, ranges.size());
assertEquals(0, ranges.get(0).start);
assertEquals(0, ranges.get(0).end);
assertEquals(1, ranges.get(1).start);
assertEquals(2, ranges.get(1).end);
assertEquals(3, ranges.get(2).start);
assertEquals(4, ranges.get(2).end);
}
@Test
public void findConflict() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33130", "Saint Germain en Laye");
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33139", "Paris");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
assertTrue(CombineGeoData.findConflict(prefixes, 3313, 0, 0));
}
@Test
public void conflictBefore() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33130", "Saint Germain en Laye");
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33139", "Paris");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
List<Range> ranges = CombineGeoData.createRanges(prefixes, phonePrefixMap);
assertTrue(CombineGeoData.hasConflict(ranges, 1, prefixes, 3313));
}
@Test
public void conflictAfter() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33122", "Poissy");
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33138", "Paris");
phonePrefixMap.put("33139", "Saint Germain en Laye");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
List<Range> ranges = CombineGeoData.createRanges(prefixes, phonePrefixMap);
assertEquals(4, ranges.size());
assertTrue(CombineGeoData.hasConflict(ranges, 1, prefixes, 3313));
}
@Test
public void noConflict() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33122", "Poissy");
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33138", "Paris");
phonePrefixMap.put("33149", "Saint Germain en Laye");
phonePrefixMap.put("3341", "Marseille");
phonePrefixMap.put("3342", "Marseille");
String[] prefixes = CombineGeoData.createSortedPrefixArray(phonePrefixMap);
List<Range> ranges = CombineGeoData.createRanges(prefixes, phonePrefixMap);
assertEquals(4, ranges.size());
assertFalse(CombineGeoData.hasConflict(ranges, 1, prefixes, 3313));
}
@Test
public void combineRemovesLastDigit() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33122", "Poissy");
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33149", "Saint Germain en Laye");
phonePrefixMap.put("3342", "Marseille");
phonePrefixMap = CombineGeoData.combine(phonePrefixMap);
assertEquals(4, phonePrefixMap.size());
assertEquals("Poissy", phonePrefixMap.get("3312"));
assertEquals("Paris", phonePrefixMap.get("3313"));
assertEquals("Saint Germain en Laye", phonePrefixMap.get("3314"));
assertEquals("Marseille", phonePrefixMap.get("334"));
}
@Test
public void combineMergesSamePrefixAndLocation() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33133", "Paris");
phonePrefixMap.put("33134", "Paris");
phonePrefixMap = CombineGeoData.combine(phonePrefixMap);
assertEquals(1, phonePrefixMap.size());
assertEquals("Paris", phonePrefixMap.get("3313"));
}
@Test
public void combineWithNoPossibleCombination() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("3312", "Poissy");
phonePrefixMap.put("3313", "Paris");
phonePrefixMap.put("3314", "Saint Germain en Laye");
phonePrefixMap = CombineGeoData.combine(phonePrefixMap);
assertEquals(3, phonePrefixMap.size());
assertEquals("Poissy", phonePrefixMap.get("3312"));
assertEquals("Paris", phonePrefixMap.get("3313"));
assertEquals("Saint Germain en Laye", phonePrefixMap.get("3314"));
}
@Test
public void combineMultipleTimes() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("33132", "Paris");
phonePrefixMap.put("33133", "Paris");
phonePrefixMap.put("33134", "Paris");
phonePrefixMap = CombineGeoData.combineMultipleTimes(phonePrefixMap);
assertEquals(1, phonePrefixMap.size());
assertEquals("Paris", phonePrefixMap.get("3"));
}
@Test
public void combineMultipleTimesWithPrefixesWithDifferentLengths() {
SortedMap<String, String> phonePrefixMap = new TreeMap<String, String>();
phonePrefixMap.put("332", "Paris");
phonePrefixMap.put("33133", "Paris");
phonePrefixMap.put("41", "Marseille");
phonePrefixMap = CombineGeoData.combineMultipleTimes(phonePrefixMap);
assertEquals(2, phonePrefixMap.size());
assertEquals("Paris", phonePrefixMap.get("3"));
assertEquals("Marseille", phonePrefixMap.get("4"));
}
}
| 3,172 |
32,544 | package com.baeldung.jpa.entity;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class StudentEntityIntegrationTest {
private EntityManagerFactory emf;
private EntityManager em;
@Before
public void setup() {
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
em = emf.createEntityManager();
}
@Test
public void persistStudentThenRetrieveTheDetails() {
Student student = createStudentWithRelevantDetails();
persist(student);
clearThePersistenceContext();
List<Student> students = getStudentsFromTable();
checkAssertionsWith(students);
}
@After
public void destroy() {
if (em != null) {
em.close();
}
if (emf != null) {
emf.close();
}
}
private void clearThePersistenceContext() {
em.clear();
}
private void checkAssertionsWith(List<Student> students) {
assertEquals(1, students.size());
Student john = students.get(0);
assertEquals(1L, john.getId().longValue());
assertEquals(null, john.getAge());
assertEquals("John", john.getName());
}
private List<Student> getStudentsFromTable() {
String selectQuery = "SELECT student FROM Student student";
TypedQuery<Student> selectFromStudentTypedQuery = em.createQuery(selectQuery, Student.class);
List<Student> students = selectFromStudentTypedQuery.getResultList();
return students;
}
private void persist(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
private Student createStudentWithRelevantDetails() {
Student student = new Student();
student.setAge(20); // the 'age' field has been annotated with @Transient
student.setName("John");
Date date = getDate();
student.setBirthDate(date);
student.setGender(Gender.MALE);
return student;
}
private Date getDate() {
LocalDate localDate = LocalDate.of(2008, 7, 20);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}
| 748 |
521 | /* $Id: UIApplianceEditorWidget.cpp $ */
/** @file
* VBox Qt GUI - UIApplianceEditorWidget class implementation.
*/
/*
* Copyright (C) 2009-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else /* !VBOX_WITH_PRECOMPILED_HEADERS */
/* Qt includes: */
# include <QComboBox>
# include <QDir>
# include <QCheckBox>
# include <QHeaderView>
# include <QLabel>
# include <QLineEdit>
# include <QSpinBox>
# include <QTextEdit>
/* GUI includes: */
# include "QITreeView.h"
# include "VBoxGlobal.h"
# include "VBoxOSTypeSelectorButton.h"
# include "UIApplianceEditorWidget.h"
# include "UIConverter.h"
# include "UIIconPool.h"
# include "UILineTextEdit.h"
# include "UIMessageCenter.h"
/* COM includes: */
# include "CSystemProperties.h"
#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */
/** Describes the interface of Appliance item.
* Represented as a tree structure with a parent & multiple children. */
class UIApplianceModelItem : public QITreeViewItem
{
public:
/** Constructs root item with specified @a iNumber, @a enmType and @a pParent. */
UIApplianceModelItem(int iNumber, ApplianceModelItemType enmType, QITreeView *pParent);
/** Constructs non-root item with specified @a iNumber, @a enmType and @a pParentItem. */
UIApplianceModelItem(int iNumber, ApplianceModelItemType enmType, UIApplianceModelItem *pParentItem);
/** Destructs item. */
virtual ~UIApplianceModelItem();
/** Returns the item type. */
ApplianceModelItemType type() const { return m_enmType; }
/** Returns the parent of the item. */
UIApplianceModelItem *parent() const { return m_pParentItem; }
/** Appends the passed @a pChildItem to the item's list of children. */
void appendChild(UIApplianceModelItem *pChildItem);
/** Returns the child specified by the @a iIndex. */
virtual UIApplianceModelItem *childItem(int iIndex) const /* override */;
/** Returns the row of the item in the parent. */
int row() const;
/** Returns the number of children. */
virtual int childCount() const /* override */;
/** Returns the number of columns. */
int columnCount() const { return 3; }
/** Returns the item text. */
virtual QString text() const /* override */;
/** Returns the item flags for the given @a iColumn. */
virtual Qt::ItemFlags itemFlags(int /* iColumn */) const { return 0; }
/** Defines the @a iRole data for the item at @a iColumn to @a value. */
virtual bool setData(int /* iColumn */, const QVariant & /* value */, int /* iRole */) { return false; }
/** Returns the data stored under the given @a iRole for the item referred to by the @a iColumn. */
virtual QVariant data(int /* iColumn */, int /* iRole */) const { return QVariant(); }
/** Returns the widget used to edit the item specified by @a idx for editing.
* @param pParent Brings the parent to be assigned for newly created editor.
* @param styleOption Bring the style option set for the newly created editor. */
virtual QWidget *createEditor(QWidget * /* pParent */, const QStyleOptionViewItem & /* styleOption */, const QModelIndex & /* idx */) const { return 0; }
/** Defines the contents of the given @a pEditor to the data for the item at the given @a idx. */
virtual bool setEditorData(QWidget * /* pEditor */, const QModelIndex & /* idx */) const { return false; }
/** Defines the data for the item at the given @a idx in the @a pModel to the contents of the given @a pEditor. */
virtual bool setModelData(QWidget * /* pEditor */, QAbstractItemModel * /* pModel */, const QModelIndex & /* idx */) { return false; }
/** Restores the default values. */
virtual void restoreDefaults() {}
/** Cache currently stored values, such as @a finalStates, @a finalValues and @a finalExtraValues. */
virtual void putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues);
protected:
/** Holds the item number. */
int m_iNumber;
/** Holds the item type. */
ApplianceModelItemType m_enmType;
/** Holds the parent item reference. */
UIApplianceModelItem *m_pParentItem;
/** Holds the list of children item instances. */
QList<UIApplianceModelItem*> m_childItems;
};
/** UIApplianceModelItem subclass representing Appliance Virtual System item. */
class UIVirtualSystemItem : public UIApplianceModelItem
{
public:
/** Constructs item passing @a iNumber and @a pParentItem to the base-class.
* @param comDescription Brings the Virtual System Description. */
UIVirtualSystemItem(int iNumber, CVirtualSystemDescription comDescription, UIApplianceModelItem *pParentItem);
/** Returns the data stored under the given @a iRole for the item referred to by the @a iColumn. */
virtual QVariant data(int iColumn, int iRole) const /* override */;
/** Cache currently stored values, such as @a finalStates, @a finalValues and @a finalExtraValues. */
virtual void putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues) /* override */;
private:
/** Holds the Virtual System Description. */
CVirtualSystemDescription m_comDescription;
};
/** UIApplianceModelItem subclass representing Appliance Virtual Hardware item. */
class UIVirtualHardwareItem : public UIApplianceModelItem
{
friend class UIApplianceSortProxyModel;
/** Data roles. */
enum
{
TypeRole = Qt::UserRole,
ModifiedRole
};
public:
/** Constructs item passing @a iNumber and @a pParentItem to the base-class.
* @param enmVSDType Brings the Virtual System Description type.
* @param strRef Brings something totally useless.
* @param strOrigValue Brings the original value.
* @param strConfigValue Brings the configuration value.
* @param strExtraConfigValue Brings the extra configuration value. */
UIVirtualHardwareItem(int iNumber,
KVirtualSystemDescriptionType enmVSDType,
const QString &strRef,
const QString &strOrigValue,
const QString &strConfigValue,
const QString &strExtraConfigValue,
UIApplianceModelItem *pParentItem);
/** Returns the item flags for the given @a iColumn. */
virtual Qt::ItemFlags itemFlags(int iColumn) const /* override */;
/** Defines the @a iRole data for the item at @a iColumn to @a value. */
virtual bool setData(int iColumn, const QVariant &value, int iRole) /* override */;
/** Returns the data stored under the given @a iRole for the item referred to by the @a iColumn. */
virtual QVariant data(int iColumn, int iRole) const /* override */;
/** Returns the widget used to edit the item specified by @a idx for editing.
* @param pParent Brings the parent to be assigned for newly created editor.
* @param styleOption Bring the style option set for the newly created editor. */
virtual QWidget *createEditor(QWidget *pParent, const QStyleOptionViewItem &styleOption, const QModelIndex &idx) const /* override */;
/** Defines the contents of the given @a pEditor to the data for the item at the given @a idx. */
virtual bool setEditorData(QWidget *pEditor, const QModelIndex &idx) const /* override */;
/** Defines the data for the item at the given @a idx in the @a pModel to the contents of the given @a pEditor. */
virtual bool setModelData(QWidget *pEditor, QAbstractItemModel *pModel, const QModelIndex &idx) /* override */;
/** Restores the default values. */
virtual void restoreDefaults() /* override */;
/** Cache currently stored values, such as @a finalStates, @a finalValues and @a finalExtraValues. */
virtual void putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues) /* override */;
private:
/** Holds the Virtual System Description type. */
KVirtualSystemDescriptionType m_enmVSDType;
/** Holds something totally useless. */
QString m_strRef;
/** Holds the original value. */
QString m_strOrigValue;
/** Holds the configuration value. */
QString m_strConfigValue;
/** Holds the default configuration value. */
QString m_strConfigDefaultValue;
/** Holds the extra configuration value. */
QString m_strExtraConfigValue;
/** Holds the item check state. */
Qt::CheckState m_checkState;
/** Holds whether item was modified. */
bool m_fModified;
};
/*********************************************************************************************************************************
* Class UIApplianceModelItem implementation. *
*********************************************************************************************************************************/
UIApplianceModelItem::UIApplianceModelItem(int iNumber, ApplianceModelItemType enmType, QITreeView *pParent)
: QITreeViewItem(pParent)
, m_iNumber(iNumber)
, m_enmType(enmType)
, m_pParentItem(0)
{
}
UIApplianceModelItem::UIApplianceModelItem(int iNumber, ApplianceModelItemType enmType, UIApplianceModelItem *pParentItem)
: QITreeViewItem(pParentItem)
, m_iNumber(iNumber)
, m_enmType(enmType)
, m_pParentItem(pParentItem)
{
}
UIApplianceModelItem::~UIApplianceModelItem()
{
qDeleteAll(m_childItems);
}
void UIApplianceModelItem::appendChild(UIApplianceModelItem *pChildItem)
{
AssertPtr(pChildItem);
m_childItems << pChildItem;
}
UIApplianceModelItem *UIApplianceModelItem::childItem(int iIndex) const
{
return m_childItems.value(iIndex);
}
int UIApplianceModelItem::row() const
{
if (m_pParentItem)
return m_pParentItem->m_childItems.indexOf(const_cast<UIApplianceModelItem*>(this));
return 0;
}
int UIApplianceModelItem::childCount() const
{
return m_childItems.count();
}
QString UIApplianceModelItem::text() const
{
switch (type())
{
case ApplianceModelItemType_VirtualSystem:
return tr("%1", "col.1 text")
.arg(data(ApplianceViewSection_Description, Qt::DisplayRole).toString());
case ApplianceModelItemType_VirtualHardware:
return tr("%1: %2", "col.1 text: col.2 text")
.arg(data(ApplianceViewSection_Description, Qt::DisplayRole).toString())
.arg(data(ApplianceViewSection_ConfigValue, Qt::DisplayRole).toString());
default:
break;
}
return QString();
}
void UIApplianceModelItem::putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues)
{
for (int i = 0; i < childCount(); ++i)
childItem(i)->putBack(finalStates, finalValues, finalExtraValues);
}
/*********************************************************************************************************************************
* Class UIVirtualSystemItem implementation. *
*********************************************************************************************************************************/
UIVirtualSystemItem::UIVirtualSystemItem(int iNumber, CVirtualSystemDescription comDescription, UIApplianceModelItem *pParentItem)
: UIApplianceModelItem(iNumber, ApplianceModelItemType_VirtualSystem, pParentItem)
, m_comDescription(comDescription)
{
}
QVariant UIVirtualSystemItem::data(int iColumn, int iRole) const
{
QVariant value;
if (iColumn == ApplianceViewSection_Description &&
iRole == Qt::DisplayRole)
value = UIApplianceEditorWidget::tr("Virtual System %1").arg(m_iNumber + 1);
return value;
}
void UIVirtualSystemItem::putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues)
{
/* Resize the vectors */
unsigned long iCount = m_comDescription.GetCount();
finalStates.resize(iCount);
finalValues.resize(iCount);
finalExtraValues.resize(iCount);
/* Recursively fill the vectors */
UIApplianceModelItem::putBack(finalStates, finalValues, finalExtraValues);
/* Set all final values at once */
m_comDescription.SetFinalValues(finalStates, finalValues, finalExtraValues);
}
/*********************************************************************************************************************************
* Class UIVirtualHardwareItem implementation. *
*********************************************************************************************************************************/
UIVirtualHardwareItem::UIVirtualHardwareItem(int iNumber,
KVirtualSystemDescriptionType enmVSDType,
const QString &strRef,
const QString &aOrigValue,
const QString &strConfigValue,
const QString &strExtraConfigValue,
UIApplianceModelItem *pParentItem)
: UIApplianceModelItem(iNumber, ApplianceModelItemType_VirtualHardware, pParentItem)
, m_enmVSDType(enmVSDType)
, m_strRef(strRef)
, m_strOrigValue(aOrigValue)
, m_strConfigValue(strConfigValue)
, m_strConfigDefaultValue(strConfigValue)
, m_strExtraConfigValue(strExtraConfigValue)
, m_checkState(Qt::Checked)
, m_fModified(false)
{
}
Qt::ItemFlags UIVirtualHardwareItem::itemFlags(int iColumn) const
{
Qt::ItemFlags enmFlags = 0;
if (iColumn == ApplianceViewSection_ConfigValue)
{
/* Some items are checkable */
if (m_enmVSDType == KVirtualSystemDescriptionType_Floppy ||
m_enmVSDType == KVirtualSystemDescriptionType_CDROM ||
m_enmVSDType == KVirtualSystemDescriptionType_USBController ||
m_enmVSDType == KVirtualSystemDescriptionType_SoundCard ||
m_enmVSDType == KVirtualSystemDescriptionType_NetworkAdapter)
enmFlags |= Qt::ItemIsUserCheckable;
/* Some items are editable */
if ((m_enmVSDType == KVirtualSystemDescriptionType_Name ||
m_enmVSDType == KVirtualSystemDescriptionType_Product ||
m_enmVSDType == KVirtualSystemDescriptionType_ProductUrl ||
m_enmVSDType == KVirtualSystemDescriptionType_Vendor ||
m_enmVSDType == KVirtualSystemDescriptionType_VendorUrl ||
m_enmVSDType == KVirtualSystemDescriptionType_Version ||
m_enmVSDType == KVirtualSystemDescriptionType_Description ||
m_enmVSDType == KVirtualSystemDescriptionType_License ||
m_enmVSDType == KVirtualSystemDescriptionType_OS ||
m_enmVSDType == KVirtualSystemDescriptionType_CPU ||
m_enmVSDType == KVirtualSystemDescriptionType_Memory ||
m_enmVSDType == KVirtualSystemDescriptionType_SoundCard ||
m_enmVSDType == KVirtualSystemDescriptionType_NetworkAdapter ||
m_enmVSDType == KVirtualSystemDescriptionType_HardDiskControllerIDE ||
m_enmVSDType == KVirtualSystemDescriptionType_HardDiskImage) &&
m_checkState == Qt::Checked) /* Item has to be enabled */
enmFlags |= Qt::ItemIsEditable;
}
return enmFlags;
}
bool UIVirtualHardwareItem::setData(int iColumn, const QVariant &value, int iRole)
{
bool fDone = false;
switch (iRole)
{
case Qt::CheckStateRole:
{
if (iColumn == ApplianceViewSection_ConfigValue &&
(m_enmVSDType == KVirtualSystemDescriptionType_Floppy ||
m_enmVSDType == KVirtualSystemDescriptionType_CDROM ||
m_enmVSDType == KVirtualSystemDescriptionType_USBController ||
m_enmVSDType == KVirtualSystemDescriptionType_SoundCard ||
m_enmVSDType == KVirtualSystemDescriptionType_NetworkAdapter))
{
m_checkState = static_cast<Qt::CheckState>(value.toInt());
fDone = true;
}
break;
}
case Qt::EditRole:
{
if (iColumn == ApplianceViewSection_OriginalValue)
m_strOrigValue = value.toString();
else if (iColumn == ApplianceViewSection_ConfigValue)
m_strConfigValue = value.toString();
break;
}
default: break;
}
return fDone;
}
QVariant UIVirtualHardwareItem::data(int iColumn, int iRole) const
{
QVariant value;
switch (iRole)
{
case Qt::EditRole:
{
if (iColumn == ApplianceViewSection_OriginalValue)
value = m_strOrigValue;
else if (iColumn == ApplianceViewSection_ConfigValue)
value = m_strConfigValue;
break;
}
case Qt::DisplayRole:
{
if (iColumn == ApplianceViewSection_Description)
{
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_Name: value = UIApplianceEditorWidget::tr("Name"); break;
case KVirtualSystemDescriptionType_Product: value = UIApplianceEditorWidget::tr("Product"); break;
case KVirtualSystemDescriptionType_ProductUrl: value = UIApplianceEditorWidget::tr("Product-URL"); break;
case KVirtualSystemDescriptionType_Vendor: value = UIApplianceEditorWidget::tr("Vendor"); break;
case KVirtualSystemDescriptionType_VendorUrl: value = UIApplianceEditorWidget::tr("Vendor-URL"); break;
case KVirtualSystemDescriptionType_Version: value = UIApplianceEditorWidget::tr("Version"); break;
case KVirtualSystemDescriptionType_Description: value = UIApplianceEditorWidget::tr("Description"); break;
case KVirtualSystemDescriptionType_License: value = UIApplianceEditorWidget::tr("License"); break;
case KVirtualSystemDescriptionType_OS: value = UIApplianceEditorWidget::tr("Guest OS Type"); break;
case KVirtualSystemDescriptionType_CPU: value = UIApplianceEditorWidget::tr("CPU"); break;
case KVirtualSystemDescriptionType_Memory: value = UIApplianceEditorWidget::tr("RAM"); break;
case KVirtualSystemDescriptionType_HardDiskControllerIDE: value = UIApplianceEditorWidget::tr("Storage Controller (IDE)"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSATA: value = UIApplianceEditorWidget::tr("Storage Controller (SATA)"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSCSI: value = UIApplianceEditorWidget::tr("Storage Controller (SCSI)"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSAS: value = UIApplianceEditorWidget::tr("Storage Controller (SAS)"); break;
case KVirtualSystemDescriptionType_CDROM: value = UIApplianceEditorWidget::tr("DVD"); break;
case KVirtualSystemDescriptionType_Floppy: value = UIApplianceEditorWidget::tr("Floppy"); break;
case KVirtualSystemDescriptionType_NetworkAdapter: value = UIApplianceEditorWidget::tr("Network Adapter"); break;
case KVirtualSystemDescriptionType_USBController: value = UIApplianceEditorWidget::tr("USB Controller"); break;
case KVirtualSystemDescriptionType_SoundCard: value = UIApplianceEditorWidget::tr("Sound Card"); break;
case KVirtualSystemDescriptionType_HardDiskImage: value = UIApplianceEditorWidget::tr("Virtual Disk Image"); break;
default: value = UIApplianceEditorWidget::tr("Unknown Hardware Item"); break;
}
}
else if (iColumn == ApplianceViewSection_OriginalValue)
value = m_strOrigValue;
else if (iColumn == ApplianceViewSection_ConfigValue)
{
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_Description:
case KVirtualSystemDescriptionType_License:
{
/* Shorten the big text if there is more than
* one line */
QString strTmp(m_strConfigValue);
int i = strTmp.indexOf('\n');
if (i > -1)
strTmp.replace(i, strTmp.length(), "...");
value = strTmp; break;
}
case KVirtualSystemDescriptionType_OS: value = vboxGlobal().vmGuestOSTypeDescription(m_strConfigValue); break;
case KVirtualSystemDescriptionType_Memory: value = m_strConfigValue + " " + VBoxGlobal::tr("MB", "size suffix MBytes=1024 KBytes"); break;
case KVirtualSystemDescriptionType_SoundCard: value = gpConverter->toString(static_cast<KAudioControllerType>(m_strConfigValue.toInt())); break;
case KVirtualSystemDescriptionType_NetworkAdapter: value = gpConverter->toString(static_cast<KNetworkAdapterType>(m_strConfigValue.toInt())); break;
default: value = m_strConfigValue; break;
}
}
break;
}
case Qt::ToolTipRole:
{
if (iColumn == ApplianceViewSection_ConfigValue)
{
if (!m_strOrigValue.isEmpty())
value = UIApplianceEditorWidget::tr("<b>Original Value:</b> %1").arg(m_strOrigValue);
}
break;
}
case Qt::DecorationRole:
{
if (iColumn == ApplianceViewSection_Description)
{
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_Name: value = UIIconPool::iconSet(":/name_16px.png"); break;
case KVirtualSystemDescriptionType_Product:
case KVirtualSystemDescriptionType_ProductUrl:
case KVirtualSystemDescriptionType_Vendor:
case KVirtualSystemDescriptionType_VendorUrl:
case KVirtualSystemDescriptionType_Version:
case KVirtualSystemDescriptionType_Description:
case KVirtualSystemDescriptionType_License: value = UIIconPool::iconSet(":/description_16px.png"); break;
case KVirtualSystemDescriptionType_OS: value = UIIconPool::iconSet(":/os_type_16px.png"); break;
case KVirtualSystemDescriptionType_CPU: value = UIIconPool::iconSet(":/cpu_16px.png"); break;
case KVirtualSystemDescriptionType_Memory: value = UIIconPool::iconSet(":/ram_16px.png"); break;
case KVirtualSystemDescriptionType_HardDiskControllerIDE: value = UIIconPool::iconSet(":/ide_16px.png"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSATA: value = UIIconPool::iconSet(":/sata_16px.png"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSCSI: value = UIIconPool::iconSet(":/scsi_16px.png"); break;
case KVirtualSystemDescriptionType_HardDiskControllerSAS: value = UIIconPool::iconSet(":/scsi_16px.png"); break;
case KVirtualSystemDescriptionType_HardDiskImage: value = UIIconPool::iconSet(":/hd_16px.png"); break;
case KVirtualSystemDescriptionType_CDROM: value = UIIconPool::iconSet(":/cd_16px.png"); break;
case KVirtualSystemDescriptionType_Floppy: value = UIIconPool::iconSet(":/fd_16px.png"); break;
case KVirtualSystemDescriptionType_NetworkAdapter: value = UIIconPool::iconSet(":/nw_16px.png"); break;
case KVirtualSystemDescriptionType_USBController: value = UIIconPool::iconSet(":/usb_16px.png"); break;
case KVirtualSystemDescriptionType_SoundCard: value = UIIconPool::iconSet(":/sound_16px.png"); break;
default: break;
}
}
else if (iColumn == ApplianceViewSection_ConfigValue && m_enmVSDType == KVirtualSystemDescriptionType_OS)
value = vboxGlobal().vmGuestOSTypeIcon(m_strConfigValue);
break;
}
case Qt::FontRole:
{
/* If the item is unchecked mark it with italic text. */
if (iColumn == ApplianceViewSection_ConfigValue &&
m_checkState == Qt::Unchecked)
{
QFont font = qApp->font();
font.setItalic(true);
value = font;
}
break;
}
case Qt::ForegroundRole:
{
/* If the item is unchecked mark it with gray text. */
if (iColumn == ApplianceViewSection_ConfigValue &&
m_checkState == Qt::Unchecked)
{
QPalette pal = qApp->palette();
value = pal.brush(QPalette::Disabled, QPalette::WindowText);
}
break;
}
case Qt::CheckStateRole:
{
if (iColumn == ApplianceViewSection_ConfigValue &&
(m_enmVSDType == KVirtualSystemDescriptionType_Floppy ||
m_enmVSDType == KVirtualSystemDescriptionType_CDROM ||
m_enmVSDType == KVirtualSystemDescriptionType_USBController ||
m_enmVSDType == KVirtualSystemDescriptionType_SoundCard ||
m_enmVSDType == KVirtualSystemDescriptionType_NetworkAdapter))
value = m_checkState;
break;
}
case UIVirtualHardwareItem::TypeRole:
{
value = m_enmVSDType;
break;
}
case UIVirtualHardwareItem::ModifiedRole:
{
if (iColumn == ApplianceViewSection_ConfigValue)
value = m_fModified;
break;
}
}
return value;
}
QWidget *UIVirtualHardwareItem::createEditor(QWidget *pParent, const QStyleOptionViewItem & /* styleOption */, const QModelIndex &idx) const
{
QWidget *pEditor = 0;
if (idx.column() == ApplianceViewSection_ConfigValue)
{
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_OS:
{
VBoxOSTypeSelectorButton *pButton = new VBoxOSTypeSelectorButton(pParent);
/* Fill the background with the highlight color in the case
* the button hasn't a rectangle shape. This prevents the
* display of parts from the current text on the Mac. */
#ifdef VBOX_WS_MAC
/* Use the palette from the tree view, not the one from the
* editor. */
QPalette p = pButton->palette();
p.setBrush(QPalette::Highlight, pParent->palette().brush(QPalette::Highlight));
pButton->setPalette(p);
#endif /* VBOX_WS_MAC */
pButton->setAutoFillBackground(true);
pButton->setBackgroundRole(QPalette::Highlight);
pEditor = pButton;
break;
}
case KVirtualSystemDescriptionType_Name:
case KVirtualSystemDescriptionType_Product:
case KVirtualSystemDescriptionType_ProductUrl:
case KVirtualSystemDescriptionType_Vendor:
case KVirtualSystemDescriptionType_VendorUrl:
case KVirtualSystemDescriptionType_Version:
{
QLineEdit *pLineEdit = new QLineEdit(pParent);
pEditor = pLineEdit;
break;
}
case KVirtualSystemDescriptionType_Description:
case KVirtualSystemDescriptionType_License:
{
UILineTextEdit *pLineTextEdit = new UILineTextEdit(pParent);
pEditor = pLineTextEdit;
break;
}
case KVirtualSystemDescriptionType_CPU:
{
QSpinBox *pSpinBox = new QSpinBox(pParent);
pSpinBox->setRange(UIApplianceEditorWidget::minGuestCPUCount(), UIApplianceEditorWidget::maxGuestCPUCount());
pEditor = pSpinBox;
break;
}
case KVirtualSystemDescriptionType_Memory:
{
QSpinBox *pSpinBox = new QSpinBox(pParent);
pSpinBox->setRange(UIApplianceEditorWidget::minGuestRAM(), UIApplianceEditorWidget::maxGuestRAM());
pSpinBox->setSuffix(" " + VBoxGlobal::tr("MB", "size suffix MBytes=1024 KBytes"));
pEditor = pSpinBox;
break;
}
case KVirtualSystemDescriptionType_SoundCard:
{
QComboBox *pComboBox = new QComboBox(pParent);
pComboBox->addItem(gpConverter->toString(KAudioControllerType_AC97), KAudioControllerType_AC97);
pComboBox->addItem(gpConverter->toString(KAudioControllerType_SB16), KAudioControllerType_SB16);
pComboBox->addItem(gpConverter->toString(KAudioControllerType_HDA), KAudioControllerType_HDA);
pEditor = pComboBox;
break;
}
case KVirtualSystemDescriptionType_NetworkAdapter:
{
QComboBox *pComboBox = new QComboBox(pParent);
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_Am79C970A), KNetworkAdapterType_Am79C970A);
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_Am79C973), KNetworkAdapterType_Am79C973);
#ifdef VBOX_WITH_E1000
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_I82540EM), KNetworkAdapterType_I82540EM);
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_I82543GC), KNetworkAdapterType_I82543GC);
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_I82545EM), KNetworkAdapterType_I82545EM);
#endif /* VBOX_WITH_E1000 */
#ifdef VBOX_WITH_VIRTIO
pComboBox->addItem(gpConverter->toString(KNetworkAdapterType_Virtio), KNetworkAdapterType_Virtio);
#endif /* VBOX_WITH_VIRTIO */
pEditor = pComboBox;
break;
}
case KVirtualSystemDescriptionType_HardDiskControllerIDE:
{
QComboBox *pComboBox = new QComboBox(pParent);
pComboBox->addItem(gpConverter->toString(KStorageControllerType_PIIX3), "PIIX3");
pComboBox->addItem(gpConverter->toString(KStorageControllerType_PIIX4), "PIIX4");
pComboBox->addItem(gpConverter->toString(KStorageControllerType_ICH6), "ICH6");
pEditor = pComboBox;
break;
}
case KVirtualSystemDescriptionType_HardDiskImage:
{
/* disabled for now
UIFilePathSelector *pFileChooser = new UIFilePathSelector(pParent);
pFileChooser->setMode(UIFilePathSelector::Mode_File);
pFileChooser->setResetEnabled(false);
*/
QLineEdit *pLineEdit = new QLineEdit(pParent);
pEditor = pLineEdit;
break;
}
default: break;
}
}
return pEditor;
}
bool UIVirtualHardwareItem::setEditorData(QWidget *pEditor, const QModelIndex & /* idx */) const
{
bool fDone = false;
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_OS:
{
if (VBoxOSTypeSelectorButton *pButton = qobject_cast<VBoxOSTypeSelectorButton*>(pEditor))
{
pButton->setOSTypeId(m_strConfigValue);
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_HardDiskControllerIDE:
{
if (QComboBox *pComboBox = qobject_cast<QComboBox*>(pEditor))
{
int i = pComboBox->findData(m_strConfigValue);
if (i != -1)
pComboBox->setCurrentIndex(i);
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_CPU:
case KVirtualSystemDescriptionType_Memory:
{
if (QSpinBox *pSpinBox = qobject_cast<QSpinBox*>(pEditor))
{
pSpinBox->setValue(m_strConfigValue.toInt());
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_Name:
case KVirtualSystemDescriptionType_Product:
case KVirtualSystemDescriptionType_ProductUrl:
case KVirtualSystemDescriptionType_Vendor:
case KVirtualSystemDescriptionType_VendorUrl:
case KVirtualSystemDescriptionType_Version:
{
if (QLineEdit *pLineEdit = qobject_cast<QLineEdit*>(pEditor))
{
pLineEdit->setText(m_strConfigValue);
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_Description:
case KVirtualSystemDescriptionType_License:
{
if (UILineTextEdit *pLineTextEdit = qobject_cast<UILineTextEdit*>(pEditor))
{
pLineTextEdit->setText(m_strConfigValue);
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_SoundCard:
case KVirtualSystemDescriptionType_NetworkAdapter:
{
if (QComboBox *pComboBox = qobject_cast<QComboBox*>(pEditor))
{
int i = pComboBox->findData(m_strConfigValue.toInt());
if (i != -1)
pComboBox->setCurrentIndex(i);
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_HardDiskImage:
{
/* disabled for now
if (UIFilePathSelector *pFileChooser = qobject_cast<UIFilePathSelector*>(pEditor))
{
pFileChooser->setPath(m_strConfigValue);
}
*/
if (QLineEdit *pLineEdit = qobject_cast<QLineEdit*>(pEditor))
{
pLineEdit->setText(m_strConfigValue);
fDone = true;
}
break;
}
default: break;
}
return fDone;
}
bool UIVirtualHardwareItem::setModelData(QWidget *pEditor, QAbstractItemModel *pModel, const QModelIndex & idx)
{
bool fDone = false;
switch (m_enmVSDType)
{
case KVirtualSystemDescriptionType_OS:
{
if (VBoxOSTypeSelectorButton *pButton = qobject_cast<VBoxOSTypeSelectorButton*>(pEditor))
{
m_strConfigValue = pButton->osTypeId();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_HardDiskControllerIDE:
{
if (QComboBox *pComboBox = qobject_cast<QComboBox*>(pEditor))
{
m_strConfigValue = pComboBox->itemData(pComboBox->currentIndex()).toString();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_CPU:
case KVirtualSystemDescriptionType_Memory:
{
if (QSpinBox *pSpinBox = qobject_cast<QSpinBox*>(pEditor))
{
m_strConfigValue = QString::number(pSpinBox->value());
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_Name:
{
if (QLineEdit *pLineEdit = qobject_cast<QLineEdit*>(pEditor))
{
/* When the VM name is changed the path of the disk images
* should be also changed. So first of all find all disk
* images corresponding to this appliance. Next check if
* they are modified by the user already. If not change the
* path to the new path. */
/* Create an index of this position, but in column 0. */
QModelIndex c0Index = pModel->index(idx.row(), 0, idx.parent());
/* Query all items with the type HardDiskImage and which
* are child's of this item. */
QModelIndexList list = pModel->match(c0Index,
UIVirtualHardwareItem::TypeRole,
KVirtualSystemDescriptionType_HardDiskImage,
-1,
Qt::MatchExactly | Qt::MatchWrap | Qt::MatchRecursive);
for (int i = 0; i < list.count(); ++i)
{
/* Get the index for the config value column. */
QModelIndex hdIndex = pModel->index(list.at(i).row(), ApplianceViewSection_ConfigValue, list.at(i).parent());
/* Ignore it if was already modified by the user. */
if (!hdIndex.data(ModifiedRole).toBool())
/* Replace any occurrence of the old VM name with
* the new VM name. */
{
QStringList splittedOriginalPath = hdIndex.data(Qt::EditRole).toString().split(QDir::separator());
QStringList splittedNewPath;
foreach (QString a, splittedOriginalPath)
{
(a.compare(m_strConfigValue) == 0) ? splittedNewPath << pLineEdit->text() : splittedNewPath << a;
}
QString newPath = splittedNewPath.join(QDir::separator());
pModel->setData(hdIndex,
newPath,
Qt::EditRole);
}
}
m_strConfigValue = pLineEdit->text();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_Product:
case KVirtualSystemDescriptionType_ProductUrl:
case KVirtualSystemDescriptionType_Vendor:
case KVirtualSystemDescriptionType_VendorUrl:
case KVirtualSystemDescriptionType_Version:
{
if (QLineEdit *pLineEdit = qobject_cast<QLineEdit*>(pEditor))
{
m_strConfigValue = pLineEdit->text();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_Description:
case KVirtualSystemDescriptionType_License:
{
if (UILineTextEdit *pLineTextEdit = qobject_cast<UILineTextEdit*>(pEditor))
{
m_strConfigValue = pLineTextEdit->text();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_SoundCard:
case KVirtualSystemDescriptionType_NetworkAdapter:
{
if (QComboBox *pComboBox = qobject_cast<QComboBox*>(pEditor))
{
m_strConfigValue = pComboBox->itemData(pComboBox->currentIndex()).toString();
fDone = true;
}
break;
}
case KVirtualSystemDescriptionType_HardDiskImage:
{
/* disabled for now
if (UIFilePathSelector *pFileChooser = qobject_cast<UIFilePathSelector*>(pEditor))
{
m_strConfigValue = pFileChooser->path();
}
*/
if (QLineEdit *pLineEdit = qobject_cast<QLineEdit*>(pEditor))
{
m_strConfigValue = pLineEdit->text();
fDone = true;
}
break;
}
default: break;
}
if (fDone)
m_fModified = true;
return fDone;
}
void UIVirtualHardwareItem::restoreDefaults()
{
m_strConfigValue = m_strConfigDefaultValue;
m_checkState = Qt::Checked;
}
void UIVirtualHardwareItem::putBack(QVector<BOOL> &finalStates, QVector<QString> &finalValues, QVector<QString> &finalExtraValues)
{
finalStates[m_iNumber] = m_checkState == Qt::Checked;
finalValues[m_iNumber] = m_strConfigValue;
finalExtraValues[m_iNumber] = m_strExtraConfigValue;
UIApplianceModelItem::putBack(finalStates, finalValues, finalExtraValues);
}
/*********************************************************************************************************************************
* Class UIApplianceModel implementation. *
*********************************************************************************************************************************/
UIApplianceModel::UIApplianceModel(QVector<CVirtualSystemDescription>& aVSDs, QITreeView *pParent)
: QAbstractItemModel(pParent)
, m_pRootItem(new UIApplianceModelItem(0, ApplianceModelItemType_Root, pParent))
{
for (int iVSDIndex = 0; iVSDIndex < aVSDs.size(); ++iVSDIndex)
{
CVirtualSystemDescription vsd = aVSDs[iVSDIndex];
UIVirtualSystemItem *pVirtualSystemItem = new UIVirtualSystemItem(iVSDIndex, vsd, m_pRootItem);
m_pRootItem->appendChild(pVirtualSystemItem);
/** @todo ask Dmitry about include/COMDefs.h:232 */
QVector<KVirtualSystemDescriptionType> types;
QVector<QString> refs;
QVector<QString> origValues;
QVector<QString> configValues;
QVector<QString> extraConfigValues;
QList<int> hdIndexes;
QMap<int, UIVirtualHardwareItem*> controllerMap;
vsd.GetDescription(types, refs, origValues, configValues, extraConfigValues);
for (int i = 0; i < types.size(); ++i)
{
/* We add the hard disk images in an second step, so save a
reference to them. */
if (types[i] == KVirtualSystemDescriptionType_HardDiskImage)
hdIndexes << i;
else
{
UIVirtualHardwareItem *pHardwareItem = new UIVirtualHardwareItem(i, types[i], refs[i], origValues[i], configValues[i], extraConfigValues[i], pVirtualSystemItem);
pVirtualSystemItem->appendChild(pHardwareItem);
/* Save the hard disk controller types in an extra map */
if (types[i] == KVirtualSystemDescriptionType_HardDiskControllerIDE ||
types[i] == KVirtualSystemDescriptionType_HardDiskControllerSATA ||
types[i] == KVirtualSystemDescriptionType_HardDiskControllerSCSI ||
types[i] == KVirtualSystemDescriptionType_HardDiskControllerSAS)
controllerMap[i] = pHardwareItem;
}
}
QRegExp rx("controller=(\\d+);?");
/* Now process the hard disk images */
for (int iHDIndex = 0; iHDIndex < hdIndexes.size(); ++iHDIndex)
{
int i = hdIndexes[iHDIndex];
QString ecnf = extraConfigValues[i];
if (rx.indexIn(ecnf) != -1)
{
/* Get the controller */
UIVirtualHardwareItem *pControllerItem = controllerMap[rx.cap(1).toInt()];
if (pControllerItem)
{
/* New hardware item as child of the controller */
UIVirtualHardwareItem *pStorageItem = new UIVirtualHardwareItem(i, types[i], refs[i], origValues[i], configValues[i], extraConfigValues[i], pControllerItem);
pControllerItem->appendChild(pStorageItem);
}
}
}
}
}
UIApplianceModel::~UIApplianceModel()
{
if (m_pRootItem)
delete m_pRootItem;
}
QModelIndex UIApplianceModel::root() const
{
return index(0, 0);
}
QModelIndex UIApplianceModel::index(int iRow, int iColumn, const QModelIndex &parentIdx /* = QModelIndex() */) const
{
if (!hasIndex(iRow, iColumn, parentIdx))
return QModelIndex();
UIApplianceModelItem *pItem = !parentIdx.isValid() ? m_pRootItem :
static_cast<UIApplianceModelItem*>(parentIdx.internalPointer())->childItem(iRow);
return pItem ? createIndex(iRow, iColumn, pItem) : QModelIndex();
}
QModelIndex UIApplianceModel::parent(const QModelIndex &idx) const
{
if (!idx.isValid())
return QModelIndex();
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(idx.internalPointer());
UIApplianceModelItem *pParentItem = pItem->parent();
if (pParentItem)
return createIndex(pParentItem->row(), 0, pParentItem);
else
return QModelIndex();
}
int UIApplianceModel::rowCount(const QModelIndex &parentIdx /* = QModelIndex() */) const
{
return !parentIdx.isValid() ? 1 /* only root item has invalid parent */ :
static_cast<UIApplianceModelItem*>(parentIdx.internalPointer())->childCount();
}
int UIApplianceModel::columnCount(const QModelIndex &parentIdx /* = QModelIndex() */) const
{
return !parentIdx.isValid() ? m_pRootItem->columnCount() :
static_cast<UIApplianceModelItem*>(parentIdx.internalPointer())->columnCount();
}
Qt::ItemFlags UIApplianceModel::flags(const QModelIndex &idx) const
{
if (!idx.isValid())
return 0;
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(idx.internalPointer());
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | pItem->itemFlags(idx.column());
}
QVariant UIApplianceModel::headerData(int iSection, Qt::Orientation enmOrientation, int iRole) const
{
if (iRole != Qt::DisplayRole ||
enmOrientation != Qt::Horizontal)
return QVariant();
QString strTitle;
switch (iSection)
{
case ApplianceViewSection_Description: strTitle = UIApplianceEditorWidget::tr("Description"); break;
case ApplianceViewSection_ConfigValue: strTitle = UIApplianceEditorWidget::tr("Configuration"); break;
}
return strTitle;
}
bool UIApplianceModel::setData(const QModelIndex &idx, const QVariant &value, int iRole)
{
if (!idx.isValid())
return false;
UIApplianceModelItem *pTtem = static_cast<UIApplianceModelItem*>(idx.internalPointer());
return pTtem->setData(idx.column(), value, iRole);
}
QVariant UIApplianceModel::data(const QModelIndex &idx, int iRole /* = Qt::DisplayRole */) const
{
if (!idx.isValid())
return QVariant();
UIApplianceModelItem *pTtem = static_cast<UIApplianceModelItem*>(idx.internalPointer());
return pTtem->data(idx.column(), iRole);
}
QModelIndex UIApplianceModel::buddy(const QModelIndex &idx) const
{
if (!idx.isValid())
return QModelIndex();
if (idx.column() == ApplianceViewSection_ConfigValue)
return idx;
else
return index(idx.row(), ApplianceViewSection_ConfigValue, idx.parent());
}
void UIApplianceModel::restoreDefaults(QModelIndex parentIdx /* = QModelIndex() */)
{
/* By default use the root: */
if (!parentIdx.isValid())
parentIdx = root();
/* Get corresponding parent item and enumerate it's children: */
UIApplianceModelItem *pParentItem = static_cast<UIApplianceModelItem*>(parentIdx.internalPointer());
for (int i = 0; i < pParentItem->childCount(); ++i)
{
/* Reset children item data to default: */
pParentItem->childItem(i)->restoreDefaults();
/* Recursively process children item: */
restoreDefaults(index(i, 0, parentIdx));
}
/* Notify the model about the changes: */
emit dataChanged(index(0, 0, parentIdx), index(pParentItem->childCount() - 1, 0, parentIdx));
}
void UIApplianceModel::putBack()
{
QVector<BOOL> v1;
QVector<QString> v2;
QVector<QString> v3;
m_pRootItem->putBack(v1, v2, v3);
}
/*********************************************************************************************************************************
* Class UIApplianceDelegate implementation. *
*********************************************************************************************************************************/
UIApplianceDelegate::UIApplianceDelegate(QAbstractProxyModel *pProxy, QObject *pParent /* = 0 */)
: QItemDelegate(pParent)
, m_pProxy(pProxy)
{
}
QWidget *UIApplianceDelegate::createEditor(QWidget *pParent, const QStyleOptionViewItem &styleOption, const QModelIndex &idx) const
{
if (!idx.isValid())
return QItemDelegate::createEditor(pParent, styleOption, idx);
QModelIndex index(idx);
if (m_pProxy)
index = m_pProxy->mapToSource(idx);
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(index.internalPointer());
QWidget *pEditor = pItem->createEditor(pParent, styleOption, index);
/* Allow UILineTextEdit to commit data early: */
if (pEditor && qobject_cast<UILineTextEdit*>(pEditor))
connect(pEditor, SIGNAL(sigFinished(QWidget*)), this, SIGNAL(commitData(QWidget*)));
if (pEditor == 0)
return QItemDelegate::createEditor(pParent, styleOption, index);
else
return pEditor;
}
void UIApplianceDelegate::setEditorData(QWidget *pEditor, const QModelIndex &idx) const
{
if (!idx.isValid())
return QItemDelegate::setEditorData(pEditor, idx);
QModelIndex index(idx);
if (m_pProxy)
index = m_pProxy->mapToSource(idx);
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(index.internalPointer());
if (!pItem->setEditorData(pEditor, index))
QItemDelegate::setEditorData(pEditor, index);
}
void UIApplianceDelegate::setModelData(QWidget *pEditor, QAbstractItemModel *pModel, const QModelIndex &idx) const
{
if (!idx.isValid())
return QItemDelegate::setModelData(pEditor, pModel, idx);
QModelIndex index = pModel->index(idx.row(), idx.column());
if (m_pProxy)
index = m_pProxy->mapToSource(idx);
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(index.internalPointer());
if (!pItem->setModelData(pEditor, pModel, idx))
QItemDelegate::setModelData(pEditor, pModel, idx);
}
void UIApplianceDelegate::updateEditorGeometry(QWidget *pEditor, const QStyleOptionViewItem &styleOption, const QModelIndex & /* idx */) const
{
if (pEditor)
pEditor->setGeometry(styleOption.rect);
}
QSize UIApplianceDelegate::sizeHint(const QStyleOptionViewItem &styleOption, const QModelIndex &idx) const
{
QSize size = QItemDelegate::sizeHint(styleOption, idx);
#ifdef VBOX_WS_MAC
int h = 28;
#else
int h = 24;
#endif
size.setHeight(RT_MAX(h, size.height()));
return size;
}
#ifdef VBOX_WS_MAC
bool UIApplianceDelegate::eventFilter(QObject *pObject, QEvent *pEvent)
{
if (pEvent->type() == QEvent::FocusOut)
{
/* On Mac OS X Cocoa the OS type selector widget loses it focus when
* the popup menu is shown. Prevent this here, cause otherwise the new
* selected OS will not be updated. */
VBoxOSTypeSelectorButton *pButton = qobject_cast<VBoxOSTypeSelectorButton*>(pObject);
if (pButton && pButton->isMenuShown())
return false;
/* The same counts for the text edit buttons of the license or
* description fields. */
else if (qobject_cast<UILineTextEdit*>(pObject))
return false;
}
return QItemDelegate::eventFilter(pObject, pEvent);
}
#endif /* VBOX_WS_MAC */
/*********************************************************************************************************************************
* Class UIApplianceSortProxyModel implementation. *
*********************************************************************************************************************************/
/* static */
KVirtualSystemDescriptionType UIApplianceSortProxyModel::s_aSortList[] =
{
KVirtualSystemDescriptionType_Name,
KVirtualSystemDescriptionType_Product,
KVirtualSystemDescriptionType_ProductUrl,
KVirtualSystemDescriptionType_Vendor,
KVirtualSystemDescriptionType_VendorUrl,
KVirtualSystemDescriptionType_Version,
KVirtualSystemDescriptionType_Description,
KVirtualSystemDescriptionType_License,
KVirtualSystemDescriptionType_OS,
KVirtualSystemDescriptionType_CPU,
KVirtualSystemDescriptionType_Memory,
KVirtualSystemDescriptionType_Floppy,
KVirtualSystemDescriptionType_CDROM,
KVirtualSystemDescriptionType_USBController,
KVirtualSystemDescriptionType_SoundCard,
KVirtualSystemDescriptionType_NetworkAdapter,
KVirtualSystemDescriptionType_HardDiskControllerIDE,
KVirtualSystemDescriptionType_HardDiskControllerSATA,
KVirtualSystemDescriptionType_HardDiskControllerSCSI,
KVirtualSystemDescriptionType_HardDiskControllerSAS
};
UIApplianceSortProxyModel::UIApplianceSortProxyModel(QObject *pParent)
: QSortFilterProxyModel(pParent)
{
}
bool UIApplianceSortProxyModel::filterAcceptsRow(int iSourceRow, const QModelIndex &srcParenIdx) const
{
/* By default enable all, we will explicitly filter out below */
if (srcParenIdx.isValid())
{
QModelIndex i = srcParenIdx.child(iSourceRow, 0);
if (i.isValid())
{
UIApplianceModelItem *pItem = static_cast<UIApplianceModelItem*>(i.internalPointer());
/* We filter hardware types only */
if (pItem->type() == ApplianceModelItemType_VirtualHardware)
{
UIVirtualHardwareItem *hwItem = static_cast<UIVirtualHardwareItem*>(pItem);
/* The license type shouldn't be displayed */
if (m_aFilteredList.contains(hwItem->m_enmVSDType))
return false;
}
}
}
return true;
}
bool UIApplianceSortProxyModel::lessThan(const QModelIndex &leftIdx, const QModelIndex &rightIdx) const
{
if (!leftIdx.isValid() ||
!rightIdx.isValid())
return false;
UIApplianceModelItem *pLeftItem = static_cast<UIApplianceModelItem*>(leftIdx.internalPointer());
UIApplianceModelItem *pRightItem = static_cast<UIApplianceModelItem*>(rightIdx.internalPointer());
/* We sort hardware types only */
if (!(pLeftItem->type() == ApplianceModelItemType_VirtualHardware &&
pRightItem->type() == ApplianceModelItemType_VirtualHardware))
return false;
UIVirtualHardwareItem *pHwLeft = static_cast<UIVirtualHardwareItem*>(pLeftItem);
UIVirtualHardwareItem *pHwRight = static_cast<UIVirtualHardwareItem*>(pRightItem);
for (unsigned int i = 0; i < RT_ELEMENTS(s_aSortList); ++i)
if (pHwLeft->m_enmVSDType == s_aSortList[i])
{
for (unsigned int a = 0; a <= i; ++a)
if (pHwRight->m_enmVSDType == s_aSortList[a])
return true;
return false;
}
return true;
}
/*********************************************************************************************************************************
* Class UIApplianceEditorWidget implementation. *
*********************************************************************************************************************************/
/* static */
int UIApplianceEditorWidget::m_minGuestRAM = -1;
int UIApplianceEditorWidget::m_maxGuestRAM = -1;
int UIApplianceEditorWidget::m_minGuestCPUCount = -1;
int UIApplianceEditorWidget::m_maxGuestCPUCount = -1;
UIApplianceEditorWidget::UIApplianceEditorWidget(QWidget *pParent /* = 0 */)
: QIWithRetranslateUI<QWidget>(pParent)
, m_pAppliance(0)
, m_pModel(0)
{
/* Make sure all static content is properly initialized */
initSystemSettings();
/* Create layout: */
QVBoxLayout *pLayout = new QVBoxLayout(this);
{
/* Configure information layout: */
pLayout->setContentsMargins(0, 0, 0, 0);
/* Create information pane: */
m_pPaneInformation = new QWidget;
{
/* Create information layout: */
QVBoxLayout *pLayoutInformation = new QVBoxLayout(m_pPaneInformation);
{
/* Configure information layout: */
pLayoutInformation->setContentsMargins(0, 0, 0, 0);
/* Create tree-view: */
m_pTreeViewSettings = new QITreeView;
{
/* Configure tree-view: */
m_pTreeViewSettings->setAlternatingRowColors(true);
m_pTreeViewSettings->setAllColumnsShowFocus(true);
m_pTreeViewSettings->header()->setStretchLastSection(true);
m_pTreeViewSettings->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);
m_pTreeViewSettings->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
/* Add tree-view into information layout: */
pLayoutInformation->addWidget(m_pTreeViewSettings);
}
/* Create check-box: */
m_pCheckBoxReinitMACs = new QCheckBox;
{
/* Configure check-box: */
m_pCheckBoxReinitMACs->setHidden(true);
/* Add tree-view into information layout: */
pLayoutInformation->addWidget(m_pCheckBoxReinitMACs);
}
}
/* Add information pane into layout: */
pLayout->addWidget(m_pPaneInformation);
}
/* Create warning pane: */
m_pPaneWarning = new QWidget;
{
/* Configure warning pane: */
m_pPaneWarning->hide();
m_pPaneWarning->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
/* Create warning layout: */
QVBoxLayout *pLayoutWarning = new QVBoxLayout(m_pPaneWarning);
{
/* Configure warning layout: */
pLayoutWarning->setContentsMargins(0, 0, 0, 0);
/* Create label: */
m_pLabelWarning = new QLabel;
{
/* Add label into warning layout: */
pLayoutWarning->addWidget(m_pLabelWarning);
}
/* Create text-edit: */
m_pTextEditWarning = new QTextEdit;
{
/* Configure text-edit: */
m_pTextEditWarning->setReadOnly(true);
m_pTextEditWarning->setMaximumHeight(50);
m_pTextEditWarning->setAutoFormatting(QTextEdit::AutoBulletList);
/* Add text-edit into warning layout: */
pLayoutWarning->addWidget(m_pTextEditWarning);
}
}
/* Add warning pane into layout: */
pLayout->addWidget(m_pPaneWarning);
}
}
/* Translate finally: */
retranslateUi();
}
void UIApplianceEditorWidget::restoreDefaults()
{
/* Make sure model exists, it's being created in sub-classes: */
if (m_pModel)
m_pModel->restoreDefaults();
}
void UIApplianceEditorWidget::retranslateUi()
{
/* Translate information pane tree-view: */
m_pTreeViewSettings->setWhatsThis(tr("Detailed list of all components of all virtual machines of the current appliance"));
/* Translate information pane check-box: */
m_pCheckBoxReinitMACs->setText(tr("&Reinitialize the MAC address of all network cards"));
m_pCheckBoxReinitMACs->setToolTip(tr("When checked a new unique MAC address will assigned to all configured network cards."));
/* Translate warning pane label: */
m_pLabelWarning->setText(tr("Warnings:"));
}
/* static */
void UIApplianceEditorWidget::initSystemSettings()
{
if (m_minGuestRAM == -1)
{
/* We need some global defaults from the current VirtualBox
installation */
CSystemProperties sp = vboxGlobal().virtualBox().GetSystemProperties();
m_minGuestRAM = sp.GetMinGuestRAM();
m_maxGuestRAM = sp.GetMaxGuestRAM();
m_minGuestCPUCount = sp.GetMinGuestCPUCount();
m_maxGuestCPUCount = sp.GetMaxGuestCPUCount();
}
}
| 27,211 |
995 | <reponame>YuukiTsuchida/v8_embeded<filename>externals/boost/boost/numeric/interval/hw_rounding.hpp
/* Boost interval/hw_rounding.hpp template implementation file
*
* Copyright 2002 <NAME>, <NAME>, <NAME>
* Copyright 2005 <NAME>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or
* copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP
#define BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP
#include <boost/numeric/interval/rounding.hpp>
#include <boost/numeric/interval/rounded_arith.hpp>
#define BOOST_NUMERIC_INTERVAL_NO_HARDWARE
// define appropriate specialization of rounding_control for built-in types
#if defined(__x86_64__) && (defined(__USE_ISOC99) || defined(__APPLE__))
# include <boost/numeric/interval/detail/c99_rounding_control.hpp>
#elif defined(__i386__) || defined(_M_IX86) || defined(__BORLANDC__) || defined(_M_X64)
# include <boost/numeric/interval/detail/x86_rounding_control.hpp>
#elif defined(__i386) && defined(__SUNPRO_CC)
# include <boost/numeric/interval/detail/x86_rounding_control.hpp>
#elif defined(powerpc) || defined(__powerpc__) || defined(__ppc__)
# include <boost/numeric/interval/detail/ppc_rounding_control.hpp>
#elif defined(sparc) || defined(__sparc__)
# include <boost/numeric/interval/detail/sparc_rounding_control.hpp>
#elif defined(alpha) || defined(__alpha__)
# include <boost/numeric/interval/detail/alpha_rounding_control.hpp>
#elif defined(ia64) || defined(__ia64) || defined(__ia64__)
# include <boost/numeric/interval/detail/ia64_rounding_control.hpp>
#endif
#if defined(BOOST_NUMERIC_INTERVAL_NO_HARDWARE) && (defined(__USE_ISOC99) || defined(__MSL__))
# include <boost/numeric/interval/detail/c99_rounding_control.hpp>
#endif
#if defined(BOOST_NUMERIC_INTERVAL_NO_HARDWARE)
# undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE
# error Boost.Numeric.Interval: Please specify rounding control mechanism.
#endif
namespace boost {
namespace numeric {
namespace interval_lib {
/*
* Three specializations of rounded_math<T>
*/
template<>
struct rounded_math<float>
: save_state<rounded_arith_opp<float> >
{};
template<>
struct rounded_math<double>
: save_state<rounded_arith_opp<double> >
{};
template<>
struct rounded_math<long double>
: save_state<rounded_arith_opp<long double> >
{};
} // namespace interval_lib
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_INTERVAL_HW_ROUNDING_HPP
| 1,000 |
316 | <gh_stars>100-1000
#pragma once
// generate an importance sampled brdf direction
CUDA_CALLABLE inline void BRDFSample(const Material& mat, const Vec3& P, const Mat33& frame, const Vec3& V, Vec3& outDir, float& outPdf, Random& rand)
{
outDir = frame*UniformSampleHemisphere(rand);
outPdf = kInv2Pi;
}
CUDA_CALLABLE inline Color BRDFEval(const Material& mat, const Vec3& P, const Vec3& N, const Vec3& V, const Vec3& L)
{
return mat.color*kInvPi;
} | 167 |
399 | package edu.wpi.grip.core.serialization;
import edu.wpi.grip.core.Pipeline;
import edu.wpi.grip.core.Source;
import edu.wpi.grip.core.Step;
import edu.wpi.grip.core.sockets.InputSocket;
import edu.wpi.grip.core.sockets.OutputSocket;
import edu.wpi.grip.core.sockets.Socket;
import edu.wpi.grip.core.sockets.SocketHint;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* An XStream converter for serializing and deserializing sockets. Socket elements include indexes
* to indicate where in the pipeline they are. Input sockets can include values if specified, and
* output sockets can include boolean attributes indicating if they are previewed. Deserializing a
* socket doesn't create the socket itself - this is done when the step is created. Instead, this
* converter is used to reference particular sockets when defining values, previewed flags, and
* connections.
*/
public class SocketConverter implements Converter {
private static final String STEP_ATTRIBUTE = "step";
private static final String SOURCE_ATTRIBUTE = "source";
private static final String SOCKET_ATTRIBUTE = "socket";
private static final String PREVIEWED_ATTRIBUTE = "previewed";
@Inject
private Pipeline pipeline;
@Inject
private Project project;
@Override
public void marshal(Object obj, HierarchicalStreamWriter writer, MarshallingContext context) {
final Socket<?> socket = (Socket<?>) obj;
try {
writer.startNode(project.xstream.getMapper().serializedClass(socket.getClass()));
// Save the location of the socket in the pipeline.
socket.getStep().ifPresent(step -> {
final List<? extends Socket> sockets = (socket.getDirection() == Socket.Direction.INPUT)
? step.getInputSockets()
: step.getOutputSockets();
writer.addAttribute(STEP_ATTRIBUTE, String.valueOf(pipeline.getSteps().indexOf(step)));
writer.addAttribute(SOCKET_ATTRIBUTE, String.valueOf(sockets.indexOf(socket)));
});
socket.getSource().ifPresent(source -> {
final List<? extends Socket> sockets = source.getOutputSockets();
writer.addAttribute(SOURCE_ATTRIBUTE, String.valueOf(pipeline.getSources()
.indexOf(source)));
writer.addAttribute(SOCKET_ATTRIBUTE, String.valueOf(sockets.indexOf(socket)));
});
// Save whether or not output sockets are previewed
if (socket.getDirection() == Socket.Direction.OUTPUT) {
writer.addAttribute(PREVIEWED_ATTRIBUTE, String.valueOf(((OutputSocket) socket)
.isPreviewed()));
}
// Save the value of input sockets that could possibly have been set with the GUI
if (socket.getDirection() == Socket.Direction.INPUT
&& socket.getConnections().isEmpty()
&& socket.getSocketHint().getView() != SocketHint.View.NONE) {
writer.startNode("value");
if (List.class.isAssignableFrom(socket.getSocketHint().getType()) && socket.getValue()
.isPresent()) {
// XStream doesn't have a built-in converter for lists other than ArrayList
context.convertAnother(new ArrayList<>((List<?>) socket.getValue().get()));
} else {
context.convertAnother(socket.getValue().get());
}
writer.endNode();
}
writer.endNode();
} catch (ConversionException ex) {
throw new ConversionException("Error serializing socket: " + socket, ex);
}
}
@Override
@SuppressWarnings("unchecked")
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
try {
reader.moveDown();
final Class<?> nodeClass = project.xstream.getMapper().realClass(reader.getNodeName());
Socket.Direction direction;
if (InputSocket.class.isAssignableFrom(nodeClass)) {
direction = Socket.Direction.INPUT;
} else if (OutputSocket.class.isAssignableFrom(nodeClass)) {
direction = Socket.Direction.OUTPUT;
} else {
throw new IllegalArgumentException("Unexpected socket type: " + nodeClass.getName());
}
// Look up the socket using the saved indexes. Serializing sockets this way makes it so
// different things
// (such as connections) can reference sockets in the pipeline.
Socket socket;
if (reader.getAttribute(STEP_ATTRIBUTE) != null) { // NOPMD
final int stepIndex = Integer.parseInt(reader.getAttribute(STEP_ATTRIBUTE));
final int socketIndex = Integer.parseInt(reader.getAttribute(SOCKET_ATTRIBUTE));
final Step step = pipeline.getSteps().get(stepIndex);
socket = (direction == Socket.Direction.INPUT)
? step.getInputSockets().get(socketIndex)
: step.getOutputSockets().get(socketIndex);
} else if (reader.getAttribute(SOURCE_ATTRIBUTE) != null) { // NOPMD
final int sourceIndex = Integer.parseInt(reader.getAttribute(SOURCE_ATTRIBUTE));
final int socketIndex = Integer.parseInt(reader.getAttribute(SOCKET_ATTRIBUTE));
final Source source = pipeline.getSources().get(sourceIndex);
socket = source.getOutputSockets().get(socketIndex);
} else {
throw new ConversionException("Sockets must have either a step or source attribute");
}
if (socket.getDirection() == Socket.Direction.OUTPUT) {
((OutputSocket) socket).setPreviewed(Boolean.parseBoolean(reader
.getAttribute(PREVIEWED_ATTRIBUTE)));
}
if (reader.hasMoreChildren()) {
reader.moveDown();
if (reader.getNodeName().equals("value")) {
socket.setValue(context.convertAnother(socket, getDeserializedType(socket)));
} else {
throw new IllegalArgumentException("Unexpected node in socket: " + reader.getNodeName());
}
reader.moveUp();
}
reader.moveUp();
return socket;
} catch (RuntimeException e) {
throw new ConversionException("Error deserializing socket", e);
}
}
/**
* This can't always be the type in the socket, since sockets very often hold interfaces, and any
* number of classes may implement that interface.
*
* @return The type to convert a serialized socket value into when deserializing.
*/
private Class<?> getDeserializedType(Socket socket) {
final Class<?> socketType = socket.getSocketHint().getType();
if (socketType.isInterface() || Modifier.isAbstract(socketType.getModifiers())) {
if (socketType.equals(List.class)) {
return ArrayList.class; // NOPMD
} else if (socketType.equals(Number.class)) {
return Double.class;
}
} else {
return socketType;
}
throw new ConversionException("Not sure what concrete class to use for socket with type "
+ socketType);
}
@Override
public boolean canConvert(Class type) {
return Socket.class.isAssignableFrom(type);
}
}
| 2,610 |
766 | <reponame>hdhong/ukefu
/* Copyright 2013-2015 www.snakerflow.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 org.snaker.engine;
import java.util.List;
import org.snaker.engine.access.Page;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Task;
import org.snaker.engine.entity.WorkItem;
/**
* 流程相关的查询服务
* @author yuqs
* @since 1.0
*/
public interface IQueryService {
/**
* 根据流程实例ID获取流程实例对象
* @param orderId 流程实例id
* @return Order 流程实例对象
*/
Order getOrder(String orderId);
/**
* 根据流程实例ID获取历史流程实例对象
* @param orderId 历史流程实例id
* @return HistoryOrder 历史流程实例对象
*/
HistoryOrder getHistOrder(String orderId);
/**
* 根据任务ID获取任务对象
* @param taskId 任务id
* @return Task 任务对象
*/
Task getTask(String taskId);
/**
* 根据任务ID获取历史任务对象
* @param taskId 历史任务id
* @return HistoryTask 历史任务对象
*/
HistoryTask getHistTask(String taskId);
/**
* 根据任务ID获取活动任务参与者数组
* @param taskId 任务id
* @return String[] 参与者id数组
*/
String[] getTaskActorsByTaskId(String taskId);
/**
* 根据任务ID获取历史任务参与者数组
* @param taskId 历史任务id
* @return String[] 历史参与者id数组
*/
String[] getHistoryTaskActorsByTaskId(String taskId);
/**
* 根据filter查询活动任务
* @param filter 查询过滤器
* @return List<Task> 活动任务集合
*/
List<Task> getActiveTasks(QueryFilter filter);
/**
* 根据filter分页查询活动任务
* @param page 分页对象
* @param filter 查询过滤器
* @return List<Task> 活动任务集合
*/
List<Task> getActiveTasks(Page<Task> page, QueryFilter filter);
/**
* 根据filter查询流程实例列表
* @param filter 查询过滤器
* @return List<Order> 活动实例集合
*/
List<Order> getActiveOrders(QueryFilter filter);
/**
* 根据filter分页查询流程实例列表
* @param page 分页对象
* @param filter 查询过滤器
* @return List<Order> 活动实例集合
*/
List<Order> getActiveOrders(Page<Order> page, QueryFilter filter);
/**
* 根据filter查询历史流程实例
* @param filter 查询过滤器
* @return List<HistoryOrder> 历史实例集合
*/
List<HistoryOrder> getHistoryOrders(QueryFilter filter);
/**
* 根据filter分页查询历史流程实例
* @param page 分页对象
* @param filter 查询过滤器
* @return List<HistoryOrder> 历史实例集合
*/
List<HistoryOrder> getHistoryOrders(Page<HistoryOrder> page, QueryFilter filter);
/**
* 根据filter查询所有已完成的任务
* @param filter 查询过滤器
* @return List<HistoryTask> 历史任务集合
*/
List<HistoryTask> getHistoryTasks(QueryFilter filter);
/**
* 根据filter分页查询已完成的历史任务
* @param page 分页对象
* @param filter 查询过滤器
* @return List<HistoryTask> 历史任务集合
*/
List<HistoryTask> getHistoryTasks(Page<HistoryTask> page, QueryFilter filter);
/**
* 根据filter分页查询工作项(包含process、order、task三个实体的字段集合)
* @param page 分页对象
* @param filter 查询过滤器
* @return List<WorkItem> 活动工作项集合
*/
List<WorkItem> getWorkItems(Page<WorkItem> page, QueryFilter filter);
/**
* 根据filter分页查询抄送工作项(包含process、order)
* @param page 分页对象
* @param filter 查询过滤器
* @return List<WorkItem> 抄送工作项集合
*/
List<HistoryOrder> getCCWorks(Page<HistoryOrder> page, QueryFilter filter);
/**
* 根据filter分页查询已完成的历史任务项
* @param page 分页对象
* @param filter 查询过滤器
* @return List<WorkItem> 历史工作项集合
*/
List<WorkItem> getHistoryWorkItems(Page<WorkItem> page, QueryFilter filter);
/**
* 根据类型T、Sql语句、参数查询单个对象
* @param T 类型
* @param sql sql语句
* @param args 参数列表
* @return
*/
public <T> T nativeQueryObject(Class<T> T, String sql, Object... args);
/**
* 根据类型T、Sql语句、参数查询列表对象
* @param T 类型
* @param sql sql语句
* @param args 参数列表
* @return
*/
public <T> List<T> nativeQueryList(Class<T> T, String sql, Object... args);
/**
* 根据类型T、Sql语句、参数分页查询列表对象
* @param page 分页对象
* @param T 类型
* @param sql sql语句
* @param args 参数列表
* @return
*/
public <T> List<T> nativeQueryList(Page<T> page, Class<T> T, String sql, Object... args);
}
| 2,555 |
750 | <reponame>0scarB/piccolo<filename>piccolo/query/__init__.py
from .base import Query
from .methods import (
Alter,
Avg,
Count,
Create,
CreateIndex,
Delete,
DropIndex,
Exists,
Insert,
Max,
Min,
Objects,
Raw,
Select,
Sum,
TableExists,
Update,
)
| 147 |
852 | #include "RecoTracker/TkSeedGenerator/interface/MultiHitGenerator.h"
#include <iostream>
#include <typeinfo>
const OrderedMultiHits& MultiHitGenerator::run(const TrackingRegion& region,
const edm::Event& ev,
const edm::EventSetup& es) {
theHitSets.clear(); // called multiple time for the same seed collection
theHitSets.reserve(localRA.upper());
hitSets(region, theHitSets, ev, es);
theHitSets.shrink_to_fit();
localRA.update(theHitSets.size());
return theHitSets;
}
void MultiHitGenerator::clear() {
theHitSets.clear();
theHitSets.shrink_to_fit();
}
| 298 |
1,909 | package org.knowm.xchange.lykke.service;
import java.io.IOException;
import java.util.List;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.lykke.LykkeAdapter;
import org.knowm.xchange.lykke.LykkeException;
import org.knowm.xchange.lykke.dto.marketdata.LykkeAsset;
import org.knowm.xchange.lykke.dto.marketdata.LykkeAssetPair;
import org.knowm.xchange.lykke.dto.marketdata.LykkeOrderBook;
public class LykkeMarketDataServiceRaw extends LykkeBaseService {
public LykkeMarketDataServiceRaw(Exchange exchange) {
super(exchange);
}
public List<LykkeAssetPair> getAssetPairs() throws IOException {
try {
return lykke.getAssetPairs();
} catch (LykkeException e) {
throw new ExchangeException(e.getMessage());
}
}
public LykkeAssetPair getAssetPairById(CurrencyPair currencyPair) throws IOException {
return lykke.getAssetPairById(LykkeAdapter.adaptToAssetPair(currencyPair));
}
public List<LykkeOrderBook> getAllOrderBooks() throws IOException {
return lykke.getAllOrderBooks();
}
public List<LykkeOrderBook> getLykkeOrderBook(CurrencyPair currencyPair) throws IOException {
return lykke.getOrderBookByAssetPair(LykkeAdapter.adaptToAssetPair(currencyPair));
}
public List<LykkeAsset> getLykkeAssets() throws IOException {
return lykkePublic.getLykkeAsset();
}
}
| 528 |
611 | package fr.adrienbrault.idea.symfony2plugin.tests.dic.linemarker;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFileFactory;
import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME> <<EMAIL>>
* @see fr.adrienbrault.idea.symfony2plugin.dic.linemarker.XmlLineMarkerProvider
*/
public class XmlLineMarkerProviderTest extends SymfonyLightCodeInsightFixtureTestCase {
public void setUp() throws Exception {
super.setUp();
myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("services.xml"));
}
public String getTestDataPath() {
return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/dic/linemarker/fixtures";
}
public void testThatDecoratedServiceShouldProvideMarker() {
assertLineMarker(createXmlFile("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<container>\n" +
" <services>\n" +
" <service id=\"foo_bar_main\" class=\"Foo\\Bar\\Apple\"/>\n" +
" </services>\n" +
"</container>"
),
new LineMarker.ToolTipEqualsAssert("Navigate to decoration")
);
}
public void testThatParentServiceShouldProvideMarker() {
assertLineMarker(createXmlFile("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<container>\n" +
" <services>\n" +
" <service id=\"foo_bar_main\" class=\"Foo\\Bar\\Apple\"/>\n" +
" </services>\n" +
"</container>"
),
new LineMarker.ToolTipEqualsAssert("Navigate to decoration")
);
}
public void testThatDecoratesProvidesOverwriteMarker() {
assertLineMarker(createXmlFile("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<container>\n" +
" <services>\n" +
" <service id=\"foo_bar_main\" decorates=\"app.mailer\"/>\n" +
" </services>\n" +
"</container>"
),
new LineMarker.ToolTipEqualsAssert("Navigate to decorated service")
);
}
public void testThatParentProvidesOverwriteMarker() {
assertLineMarker(createXmlFile("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<container>\n" +
" <services>\n" +
" <service id=\"foo_bar_main\" parent=\"app.mailer\"/>\n" +
" </services>\n" +
"</container>"
),
new LineMarker.ToolTipEqualsAssert("Navigate to parent service")
);
}
@NotNull
private PsiElement createXmlFile(@NotNull String content) {
return PsiFileFactory.getInstance(getProject()).createFileFromText("DUMMY__." + XmlFileType.INSTANCE.getDefaultExtension(), XmlFileType.INSTANCE, content);
}
}
| 1,433 |
1,139 | package com.journaldev.reactive_streams;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;
import com.journaldev.reactive.beans.Employee;
import com.journaldev.reactive.beans.Freelancer;
public class MyReactiveAppWithProcessor {
public static void main(String[] args) throws InterruptedException {
// Create End Publisher
SubmissionPublisher<Employee> publisher = new SubmissionPublisher<>();
// Create Processor
MyProcessor transformProcessor = new MyProcessor(s -> {
return new Freelancer(s.getId(), s.getId() + 100, s.getName());
});
//Create End Subscriber
MyFreelancerSubscriber subs = new MyFreelancerSubscriber();
//Create chain of publisher, processor and subscriber
publisher.subscribe(transformProcessor); // publisher to processor
transformProcessor.subscribe(subs); // processor to subscriber
List<Employee> emps = EmpHelper.getEmps();
// Publish items
System.out.println("Publishing Items to Subscriber");
emps.stream().forEach(i -> publisher.submit(i));
// Logic to wait for messages processing to finish
while (emps.size() != subs.getCounter()) {
Thread.sleep(10);
}
// Closing publishers
publisher.close();
transformProcessor.close();
System.out.println("Exiting the app");
}
}
| 406 |
766 | /*
* Copyright 2017 <NAME>
*
* See LICENCE for the full copyright terms.
*/
#ifndef TYPE_INFO_RE_H
#define TYPE_INFO_RE_H
#include "theft_libfsm.h"
#include "buf.h"
/* Property idea: (a|b) should be the same as union[a, b] */
struct test_re_info {
char tag; /* 'r' */
enum re_dialect dialect;
size_t size;
uint8_t *string;
union {
struct {
int unused;
} literal;
struct {
struct pcre_node *head;
} pcre;
} u;
/* Positive pairs: these strings should match */
size_t pos_count;
struct string_pair *pos_pairs;
/* Negative pairs: these strings should NOT match;
* skip any NULL string pointers -- no error got
* injected in the string, so they were discarded. */
size_t neg_count;
struct string_pair *neg_pairs;
};
enum pcre_node_type {
PN_DOT, /* . */
PN_LITERAL, /* x */
PN_QUESTION, /* (x)? */
PN_KLEENE, /* (x)* */
PN_PLUS, /* (x)+ */
PN_BRACKET, /* [x] or [^x]*/
PN_ALT, /* (x|y|z) */
PN_ANCHOR, /* ^ or $ */
PCRE_NODE_TYPE_COUNT
};
enum pcre_bracket_class {
BRACKET_CLASS_ALNUM = 0x0001, /* alphanumeric */
BRACKET_CLASS_ALPHA = 0x0002, /* alphabetic */
BRACKET_CLASS_ASCII = 0x0004, /* 0-127 */
BRACKET_CLASS_BLANK = 0x0008, /* space or tab */
BRACKET_CLASS_CNTRL = 0x0010, /* control character */
BRACKET_CLASS_DIGIT = 0x0020, /* decimal digit */
BRACKET_CLASS_GRAPH = 0x0040, /* printing, excluding space */
BRACKET_CLASS_LOWER = 0x0080, /* lower case letter */
BRACKET_CLASS_PRINT = 0x0100, /* printing, including space */
BRACKET_CLASS_PUNCT = 0x0200, /* printing, excluding alphanumeric */
BRACKET_CLASS_SPACE = 0x0400, /* white space */
BRACKET_CLASS_UPPER = 0x0800, /* upper case letter */
BRACKET_CLASS_WORD = 0x1000, /* same as \w */
BRACKET_CLASS_XDIGIT = 0x2000, /* hexadecimal digit */
BRACKET_CLASS_MASK = 0x3FFF,
BRACKET_CLASS_COUNT = 14
};
/* Tagged union for a DAG of pcre nodes */
struct pcre_node {
enum pcre_node_type t;
bool has_capture;
size_t capture_id;
union {
struct {
size_t size;
char *string;
} literal;
struct {
int unused;
} dot;
struct {
struct pcre_node *inner;
} question;
struct {
struct pcre_node *inner;
} kleene;
struct {
struct pcre_node *inner;
} plus;
struct { /* bit-set of chars in group */
bool negated;
uint64_t set[256 / (8 * sizeof (uint64_t))];
enum pcre_bracket_class class_flags;
} bracket;
struct {
size_t count;
struct pcre_node **alts;
} alt;
struct {
enum pcre_anchor_type {
PCRE_ANCHOR_NONE, /* shrunk away */
PCRE_ANCHOR_START,
PCRE_ANCHOR_END,
PCRE_ANCHOR_TYPE_COUNT,
} type;
struct pcre_node *inner;
} anchor;
} u;
};
struct flatten_env {
struct test_env *env;
uint8_t verbosity;
struct buf *b;
};
extern const struct theft_type_info type_info_re;
enum theft_alloc_res
type_info_re_literal_build_info(struct theft *t,
struct test_re_info *info);
enum theft_alloc_res
type_info_re_pcre_build_info(struct theft *t,
struct test_re_info *info);
void type_info_re_pcre_free(struct pcre_node *node);
#endif
| 1,330 |
12,278 | /*<-
Copyright (c) 2016 <NAME>
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
->*/
#include <boost/callable_traits/detail/config.hpp>
#ifndef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES
int main(){}
#else
//[ is_noexcept
#include <boost/callable_traits/is_noexcept.hpp>
namespace ct = boost::callable_traits;
struct foo;
static_assert(ct::is_noexcept<int() noexcept>::value, "");
static_assert(ct::is_noexcept<int(*)() noexcept>::value, "");
static_assert(ct::is_noexcept<int(&)() noexcept>::value, "");
static_assert(ct::is_noexcept<int(foo::*)() const noexcept>::value, "");
static_assert(!ct::is_noexcept<int()>::value, "");
static_assert(!ct::is_noexcept<int(*)()>::value, "");
static_assert(!ct::is_noexcept<int(&)()>::value, "");
static_assert(!ct::is_noexcept<int(foo::*)() const>::value, "");
int main() {}
//]
#endif
| 365 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_CERTIFICATE_TRANSPARENCY_SINGLE_TREE_TRACKER_H_
#define COMPONENTS_CERTIFICATE_TRANSPARENCY_SINGLE_TREE_TRACKER_H_
#include <map>
#include <string>
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "net/cert/ct_verifier.h"
#include "net/cert/signed_tree_head.h"
#include "net/cert/sth_observer.h"
namespace net {
class CTLogVerifier;
class X509Certificate;
namespace ct {
struct SignedCertificateTimestamp;
} // namespace ct
} // namespace net
namespace certificate_transparency {
// Tracks the state of an individual Certificate Transparency Log's Merkle Tree.
// A CT Log constantly issues Signed Tree Heads, for which every older STH must
// be incorporated into the current/newer STH. As new certificates are logged,
// new SCTs are produced, and eventually, those SCTs are incorporated into the
// log and a new STH is produced, with there being an inclusion proof between
// the SCTs and the new STH, and a consistency proof between the old STH and the
// new STH.
// This class receives STHs provided by/observed by the embedder, with the
// assumption that STHs have been checked for consistency already. As SCTs are
// observed, their status is checked against the latest STH to ensure they were
// properly logged. If an SCT is newer than the latest STH, then this class
// verifies that when an STH is observed that should have incorporated those
// SCTs, the SCTs (and their corresponding entries) are present in the log.
//
// To accomplish this, this class needs to be notified of when new SCTs are
// observed (which it does by implementing net::CTVerifier::Observer) and when
// new STHs are observed (which it does by implementing net::ct::STHObserver).
// Once connected to sources providing that data, the status for a given SCT
// can be queried by calling GetLogEntryInclusionCheck.
class SingleTreeTracker : public net::CTVerifier::Observer,
public net::ct::STHObserver {
public:
// TODO(eranm): This enum will expand to include check success/failure,
// see crbug.com/506227
enum SCTInclusionStatus {
// SCT was not observed by this class and is not currently pending
// inclusion check. As there's no evidence the SCT this status relates
// to is verified (it was never observed via OnSCTVerified), nothing
// is done with it.
SCT_NOT_OBSERVED,
// SCT was observed but the STH known to this class is not old
// enough to check for inclusion, so a newer STH is needed first.
SCT_PENDING_NEWER_STH,
// SCT is known and there's a new-enough STH to check inclusion against.
// Actual inclusion check has to be performed.
SCT_PENDING_INCLUSION_CHECK
};
explicit SingleTreeTracker(scoped_refptr<const net::CTLogVerifier> ct_log);
~SingleTreeTracker() override;
// net::ct::CTVerifier::Observer implementation.
// TODO(eranm): Extract CTVerifier::Observer to SCTObserver
// Performs an inclusion check for the given certificate if the latest
// STH known for this log is older than sct.timestamp + Maximum Merge Delay,
// enqueues the SCT for future checking later on.
// Should only be called with SCTs issued by the log this instance tracks.
// TODO(eranm): Make sure not to perform any synchronous, blocking operation
// here as this callback is invoked during certificate validation.
void OnSCTVerified(net::X509Certificate* cert,
const net::ct::SignedCertificateTimestamp* sct) override;
// net::ct::STHObserver implementation.
// After verification of the signature over the |sth|, uses this
// STH for future inclusion checks.
// Must only be called for STHs issued by the log this instance tracks.
void NewSTHObserved(const net::ct::SignedTreeHead& sth) override;
// Returns the status of a given log entry that is assembled from
// |cert| and |sct|. If |cert| and |sct| were not previously observed,
// |sct| is not an SCT for |cert| or |sct| is not for this log,
// SCT_NOT_OBSERVED will be returned.
SCTInclusionStatus GetLogEntryInclusionStatus(
net::X509Certificate* cert,
const net::ct::SignedCertificateTimestamp* sct);
private:
// Holds the latest STH fetched and verified for this log.
net::ct::SignedTreeHead verified_sth_;
// The log being tracked.
scoped_refptr<const net::CTLogVerifier> ct_log_;
// List of log entries pending inclusion check.
// TODO(eranm): Rather than rely on the timestamp, extend to to use the
// whole MerkleTreeLeaf (RFC6962, section 3.4.) as a key. See
// https://crbug.com/506227#c22 and https://crbug.com/613495
std::map<base::Time, SCTInclusionStatus> entries_status_;
DISALLOW_COPY_AND_ASSIGN(SingleTreeTracker);
};
} // namespace certificate_transparency
#endif // COMPONENTS_CERTIFICATE_TRANSPARENCY_SINGLE_TREE_TRACKER_H_
| 1,560 |
357 | <gh_stars>100-1000
/*
* Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.vmware.identity.rest.core.client.test.integration;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class IntegrationTestProperties {
private static final String CONFIG_LOCATION = "src/integration-test/resources/config.properties";
private static final String CONFIG_SYSTEM_TENANT = "system.tenant";
private static final String CONFIG_SYSTEM_DOMAIN = "system.domain";
private static final String CONFIG_SYSTEM_ADMIN_USERNAME = "system.admin.username";
private static final String CONFIG_SYSTEM_ADMIN_PASSWORD = "<PASSWORD>";
private static final String HOST_PROPERTY = "host";
private static final String CONFIG_PROPERTY = "config";
private Properties properties;
private String host;
public IntegrationTestProperties() {
host = System.getProperty(HOST_PROPERTY);
if (host == null || host.length() == 0) {
throw new IllegalArgumentException("Failed to retrieve hostname or IP address");
}
String configPath = System.getProperty(CONFIG_PROPERTY, CONFIG_LOCATION);
properties = new Properties();
try {
FileInputStream in = new FileInputStream(configPath);
properties.load(in);
in.close();
} catch (IOException e) {
throw new IllegalArgumentException("Error loading config", e);
}
properties.putAll(System.getProperties());
}
public String getHost() {
return host;
}
public String getSystemTenant() {
return properties.getProperty(CONFIG_SYSTEM_TENANT);
}
public String getSystemDomain() {
return properties.getProperty(CONFIG_SYSTEM_DOMAIN);
}
public String getSystemAdminUsername() {
return properties.getProperty(CONFIG_SYSTEM_ADMIN_USERNAME);
}
public String getSystemAdminPassword() {
return properties.getProperty(CONFIG_SYSTEM_ADMIN_PASSWORD);
}
public String getProperty(String property) {
return properties.getProperty(property);
}
}
| 918 |
1,486 | <reponame>rsumnerz/ios_system
/* Placed in the public domain. */
/*
* _FORTIFY_SOURCE includes a misguided check for FD_SET(n)/FD_ISSET(b)
* where n > FD_SETSIZE. This breaks OpenSSH and other programs that
* explicitly allocate fd_sets. To avoid this, we wrap FD_SET in a
* function compiled without _FORTIFY_SOURCE.
*/
#include "config.h"
#if defined(HAVE_FEATURES_H) && defined(_FORTIFY_SOURCE)
# include <features.h>
# if defined(__GNU_LIBRARY__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 15) && (_FORTIFY_SOURCE > 0)
# undef _FORTIFY_SOURCE
# undef __USE_FORTIFY_LEVEL
# include <sys/socket.h>
void kludge_FD_SET(int n, fd_set *set) {
FD_SET(n, set);
}
int kludge_FD_ISSET(int n, fd_set *set) {
return FD_ISSET(n, set);
}
# endif /* __GLIBC_PREREQ(2, 15) && (_FORTIFY_SOURCE > 0) */
# endif /* __GNU_LIBRARY__ && __GLIBC_PREREQ */
#endif /* HAVE_FEATURES_H && _FORTIFY_SOURCE */
| 385 |
2,151 | <filename>ui/file_manager/image_loader/manifest.json
{
// chrome-extension://pmfjbimdmchhbnneeidfognadeopoehp
"key": "<KEY>",
"name": "Image loader",
"version": "0.1",
"description": "Image loader",
"incognito" : "split",
"manifest_version": 2,
"permissions": [
"chrome://resources/",
{
"fileSystem": ["requestFileSystem"]
},
"fileManagerPrivate",
"https://www.google-analytics.com/",
"https://www.googledrive.com/",
"https://lh3.googleusercontent.com/",
"metricsPrivate",
"storage"
],
"content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj; style-src 'self' blob: filesystem:; frame-src 'self' blob: filesystem:; img-src 'self' blob: filesystem: data:; media-src 'self' blob: filesystem:; connect-src 'self' blob: filesystem: https://www.googledrive.com https://www.google-analytics.com https://lh3.googleusercontent.com",
"background": {
"scripts": [
"chrome://resources/js/analytics.js",
"chrome://resources/js/assert.js",
"background_scripts.js"
],
"persistent": false
},
"web_accessible_resources": ["image_loader_client.js"]
}
| 465 |
2,023 | from functools import wraps
from inspect import getargspec, isfunction
from itertools import izip, ifilter, starmap
def autoassign(*names, **kwargs):
"""
autoassign(function) -> method
autoassign(*argnames) -> decorator
autoassign(exclude=argnames) -> decorator
allow a method to assign (some of) its arguments as attributes of
'self' automatically. E.g.
>>> class Foo(object):
... @autoassign
... def __init__(self, foo, bar): pass
...
>>> breakfast = Foo('spam', 'eggs')
>>> breakfast.foo, breakfast.bar
('spam', 'eggs')
To restrict autoassignment to 'bar' and 'baz', write:
@autoassign('bar', 'baz')
def method(self, foo, bar, baz): ...
To prevent 'foo' and 'baz' from being autoassigned, use:
@autoassign(exclude=('foo', 'baz'))
def method(self, foo, bar, baz): ...
"""
if kwargs:
exclude, f = set(kwargs['exclude']), None
sieve = lambda l:ifilter(lambda nv: nv[0] not in exclude, l)
elif len(names) == 1 and isfunction(names[0]):
f = names[0]
sieve = lambda l:l
else:
names, f = set(names), None
sieve = lambda l: ifilter(lambda nv: nv[0] in names, l)
def decorator(f):
fargnames, _, _, fdefaults = getargspec(f)
# Remove self from fargnames and make sure fdefault is a tuple
fargnames, fdefaults = fargnames[1:], fdefaults or ()
defaults = list(sieve(izip(reversed(fargnames), reversed(fdefaults))))
@wraps(f)
def decorated(self, *args, **kwargs):
assigned = dict(sieve(izip(fargnames, args)))
assigned.update(sieve(kwargs.iteritems()))
for _ in starmap(assigned.setdefault, defaults): pass
self.__dict__.update(assigned)
return f(self, *args, **kwargs)
return decorated
return f and decorator(f) or decorator
#---------- Examples of use ------------------
>>> class Test(object):
... @autoassign('foo', 'bar')
... def __init__(self, foo, bar=3, baz=6):
... "some clever stuff going on here"
... print 'baz =', baz
...
>>> class Test2(object):
... @autoassign
... def __init__(self, foo, bar): pass
...
>>> class Test3(object):
... @autoassign(exclude=('foo', 'bar'))
... def __init__(self, foo, bar, baz=5, **kwargs): pass
...
>>> t = Test(1, 2, 5)
baz = 5
>>> u = Test(foo=8)
baz = 6
>>> v = Test2(10, 11)
>>> w = Test3(100, 101, foobar=102)
>>>
>>> print Test.__init__.__doc__
some clever stuff going on here
>>>
>>> print t.foo
1
>>> print t.bar
2
>>>
>>> print u.foo
8
>>> print u.bar
3
>>>
>>> print v.foo, v.bar # 10 11
10 11
>>> print w.baz, w.foobar # 5 102
5 102
>>> for obj, attr in ('w', 'foo'), ('w', 'bar'), ('t', 'baz'):
... try:
... getattr(globals()[obj], attr)
... except AttributeError:
... print '%s.%s raises AttributeError' % (obj, attr)
...
w.foo raises AttributeError
w.bar raises AttributeError
t.baz raises AttributeError
>>>
| 1,331 |
715 | <filename>JavaSource/src/main/java/cn/xiaowenjie/daos/ConfigDao.java
package cn.xiaowenjie.daos;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import cn.xiaowenjie.beans.Config;
/**
* 配置类DAO
*
* @author 肖文杰 https://github.com/xwjie/
*
*/
public interface ConfigDao extends PagingAndSortingRepository<Config, Long> {
Config findByName(String name);
@Query(value = "select t from Config t where t.name like %?1% or t.value like %?1% or t.description like %?1%", nativeQuery = false)
Page<Config> findAllByKeyword(String keyword, Pageable pageable);
} | 269 |
707 | from . import analyzer_test
from . import dag_test
from . import generator_test
from . import info_test
from . import refiner_test
from . import utils_test | 44 |
2,151 | /*
* Copyright (C) 2015 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.databinding.testapp;
import android.databinding.testapp.BR;
import android.databinding.testapp.databinding.MultiArgAdapterTestBinding;
import android.test.UiThreadTest;
import static android.databinding.testapp.adapter.MultiArgTestAdapter.MultiBindingClass1;
import static android.databinding.testapp.adapter.MultiArgTestAdapter.MultiBindingClass2;
import static android.databinding.testapp.adapter.MultiArgTestAdapter.join;
public class MultiArgAdapterTest extends BaseDataBinderTest<MultiArgAdapterTestBinding> {
public MultiArgAdapterTest() {
super(MultiArgAdapterTestBinding.class);
}
@UiThreadTest
public void testMultiArgIsCalled() {
initBinder();
MultiBindingClass1 obj1 = new MultiBindingClass1();
MultiBindingClass2 obj2 = new MultiBindingClass2();
MultiBindingClass1 obj3 = new MultiBindingClass1();
MultiBindingClass2 obj4 = new MultiBindingClass2();
obj1.setValue("a", false);
obj2.setValue("b", false);
obj3.setValue("c", false);
obj4.setValue("d", false);
mBinder.setObj1(obj1);
mBinder.setObj2(obj2);
mBinder.setObj3(obj3);
mBinder.setObj4(obj4);
mBinder.executePendingBindings();
assertEquals(mBinder.merged.getText().toString(), join(obj1, obj2));
assertEquals(mBinder.view2.getText().toString(), join(obj2));
assertEquals(mBinder.view3.getText().toString(), join(obj3));
assertEquals(mBinder.view4.getText().toString(), join(obj4));
String prev2 = mBinder.view2.getText().toString();
String prevValue = mBinder.merged.getText().toString();
obj1.setValue("o", false);
mBinder.executePendingBindings();
assertEquals(prevValue, mBinder.merged.getText().toString());
obj2.setValue("p", false);
mBinder.executePendingBindings();
assertEquals(prevValue, mBinder.merged.getText().toString());
// now invalidate obj1 only, obj2 should be evaluated as well
obj1.notifyPropertyChanged(BR._all);
String prev3 = mBinder.view3.getText().toString();
String prev4 = mBinder.view4.getText().toString();
obj3.setValue("q", false);
obj4.setValue("r", false);
mBinder.executePendingBindings();
assertEquals(join(obj1, obj2), mBinder.merged.getText().toString());
assertEquals("obj2 should not be re-evaluated", prev2, mBinder.view2.getText().toString());
// make sure 3 and 4 are not invalidated
assertEquals("obj3 should not be re-evaluated", prev3, mBinder.view3.getText().toString());
assertEquals("obj4 should not be re-evaluated", prev4, mBinder.view4.getText().toString());
}
@UiThreadTest
public void testSetWithOldValues() throws Throwable {
initBinder();
MultiBindingClass1 obj1 = new MultiBindingClass1();
MultiBindingClass2 obj2 = new MultiBindingClass2();
MultiBindingClass1 obj3 = new MultiBindingClass1();
MultiBindingClass2 obj4 = new MultiBindingClass2();
obj1.setValue("a", false);
obj2.setValue("b", false);
obj3.setValue("c", false);
obj4.setValue("d", false);
mBinder.setObj1(obj1);
mBinder.setObj2(obj2);
mBinder.setObj3(obj3);
mBinder.setObj4(obj4);
mBinder.executePendingBindings();
assertEquals("null -> a", mBinder.view7.getText().toString());
assertEquals("null, null -> a, b", mBinder.view8.getText().toString());
obj1.setValue("x", true);
obj2.setValue("y", true);
mBinder.executePendingBindings();
assertEquals("a -> x", mBinder.view7.getText().toString());
assertEquals("a, b -> x, y", mBinder.view8.getText().toString());
obj1.setValue("x", true);
obj2.setValue("y", true);
mBinder.executePendingBindings();
// Calls setter
assertEquals("x -> x", mBinder.view7.getText().toString());
assertEquals("x, y -> x, y", mBinder.view8.getText().toString());
obj2.setValue("z", true);
mBinder.executePendingBindings();
// only the two-arg value changed
assertEquals("x -> x", mBinder.view7.getText().toString());
assertEquals("x, y -> x, z", mBinder.view8.getText().toString());
}
}
| 1,978 |
419 |
/***************************************************************************
*
Copyright 2013 CertiVox UK Ltd. *
*
This file is part of CertiVox MIRACL Crypto SDK. *
*
The CertiVox MIRACL Crypto SDK provides developers with an *
extensive and efficient set of cryptographic functions. *
For further information about its features and functionalities please *
refer to http://www.certivox.com *
*
* The CertiVox MIRACL Crypto SDK is free software: you can *
redistribute it and/or modify it under the terms of the *
GNU Affero General Public License as published by the *
Free Software Foundation, either version 3 of the License, *
or (at your option) any later version. *
*
* The CertiVox MIRACL Crypto SDK 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 Affero General Public License for more details. *
*
* You should have received a copy of the GNU Affero General Public *
License along with CertiVox MIRACL Crypto SDK. *
If not, see <http://www.gnu.org/licenses/>. *
*
You can be released from the requirements of the license by purchasing *
a commercial license. Buying such a license is mandatory as soon as you *
develop commercial activities involving the CertiVox MIRACL Crypto SDK *
without disclosing the source code of your own applications, or shipping *
the CertiVox MIRACL Crypto SDK with a closed source product. *
*
***************************************************************************/
/*
* MIRACL Chinese Remainder Thereom routines (for use with small moduli)
* mrscrt.c
*/
#include <stdlib.h>
#include "miracl.h"
#ifdef MR_FP
#include <math.h>
#endif
static mr_utype in_range(mr_utype x,mr_utype y)
{ /* x=x%y, and positive */
mr_utype r;
#ifdef MR_FP
mr_small dres;
#endif
r=MR_REMAIN(x,y);
if (r<0) r+=y;
return r;
}
#ifndef MR_STATIC
BOOL scrt_init(_MIPD_ small_chinese *c,int r,mr_utype *moduli)
{ /* calculate CRT constants - returns FALSE if there is a problem */
int i,j,k;
if (r<1) return FALSE;
if (r==1)
{
c->NP=1;
c->M=(mr_utype *)mr_alloc(_MIPP_ r,sizeof(mr_utype));
if (c->M==NULL) return FALSE;
c->M[0]=moduli[0];
return TRUE;
}
for (i=0;i<r;i++) if (moduli[i]<2) return FALSE;
c->M=(mr_utype *)mr_alloc(_MIPP_ r,sizeof(mr_utype));
if (c->M==NULL) return FALSE;
c->C=(mr_utype *)mr_alloc(_MIPP_ r*(r-1)/2,sizeof(mr_utype));
if (c->C==NULL)
{ /* no room */
mr_free(c->M);
return FALSE;
}
c->V=(mr_utype *)mr_alloc(_MIPP_ r,sizeof(mr_utype));
if (c->V==NULL)
{ /* no room */
mr_free(c->M);
mr_free(c->C);
return FALSE;
}
for (k=0,i=0;i<r;i++)
{
c->M[i]=moduli[i];
for (j=0;j<i;j++,k++)
c->C[k]=invers(c->M[j],c->M[i]);
}
c->NP=r;
return TRUE;
}
void scrt_end(small_chinese *c)
{ /* clean up after CRT */
if (c->NP<1)
{
c->NP=0;
return;
}
if (c->NP==1)
{
mr_free(c->M);
c->NP=0;
return;
}
mr_free(c->M);
mr_free(c->V);
mr_free(c->C);
c->NP=0;
}
#endif
void scrt(_MIPD_ small_chinese *c,mr_utype *u,big x)
{ /* Chinese Remainder Thereom *
* Calculate x given remainders u[i] mod M[i] */
int i,j,k,len;
mr_utype *V,*C,*M;
mr_small t;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
#ifdef MR_FP_ROUNDING
mr_large im;
#endif
V=c->V;
C=c->C;
M=c->M;
len=c->NP;
if (len<1) return;
if (len==1)
{
t=smul(1,in_range(u[0],M[0]),M[0]);
convert(_MIPP_ 1,mr_mip->w5);
mr_pmul(_MIPP_ mr_mip->w5,t,x);
return;
}
V[0]=u[0];
k=0;
for (i=1;i<len;i++)
{ /* Knuth P. 274 */
V[i]=u[i] - V[0];
#ifdef MR_FP_ROUNDING
im=mr_invert(M[i]);
imuldiv(V[i],C[k],(mr_small)0,M[i],im,&V[i]);
if (V[i]<0) V[i]+=M[i];
#else
V[i]=smul(in_range(V[i],M[i]),C[k],M[i]);
#endif
k++;
if (i==1) continue;
#ifndef MR_FP
#ifdef INLINE_ASM
#if INLINE_ASM == 3
#define MR_IMPASM
ASM mov ebx,DWORD PTR V
ASM mov esi,DWORD PTR M
ASM mov edi,DWORD PTR C
ASM mov ecx,1
ASM mov edx,DWORD PTR i
ASM mov esi,[esi+4*edx]
s1:
ASM cmp ecx,edx
ASM jge s2
ASM mov eax,[ebx+4*edx]
ASM push edx
ASM sub eax,[ebx+4*ecx]
ASM cdq
ASM idiv esi
ASM mov eax,edx
ASM add eax,esi
ASM mov edx,DWORD PTR k
ASM mul DWORD PTR [edi+4*edx]
ASM div esi
ASM mov eax,edx
ASM pop edx
ASM mov [ebx+4*edx],eax
ASM inc DWORD PTR k
ASM inc ecx
ASM jmp s1
s2:
ASM nop
#endif
#if INLINE_ASM == 4
#define MR_IMPASM
ASM (
"movl %0,%%ecx\n"
"movl %1,%%ebx\n"
"movl %2,%%esi\n"
"movl %3,%%edi\n"
"movl %4,%%edx\n"
"pushl %%ebp\n"
"movl $1,%%ebp\n"
"movl (%%esi,%%edx,4),%%esi\n"
"0:\n"
"cmpl %%edx,%%ebp\n"
"jge 1f\n"
"movl (%%ebx,%%edx,4),%%eax\n"
"subl (%%ebx,%%ebp,4),%%eax\n"
"pushl %%edx\n"
"cltd \n"
"idivl %%esi\n"
"movl %%edx,%%eax\n"
"addl %%esi,%%eax\n"
"mull (%%edi,%%ecx,4)\n"
"divl %%esi\n"
"movl %%edx,%%eax\n"
"popl %%edx\n"
"movl %%eax,(%%ebx,%%edx,4)\n"
"incl %%ecx\n"
"incl %%ebp\n"
"jmp 0b\n"
"1:\n"
"popl %%ebp\n"
"movl %%ecx,%0\n"
:"=m"(k)
:"m"(V),"m"(M),"m"(C),"m"(i)
:"eax","edi","esi","ebx","ecx","edx","memory"
);
#endif
#endif
#endif
#ifndef MR_IMPASM
for (j=1;j<i;j++,k++)
{
V[i]-=V[j];
#ifdef MR_FP_ROUNDING
imuldiv(V[i],C[k],(mr_small)0,M[i],im,&V[i]);
if (V[i]<0) V[i]+=M[i];
#else
V[i]=smul(in_range(V[i],M[i]),C[k],M[i]);
#endif
}
#endif
}
convert(_MIPP_ 1,x);
mr_pmul(_MIPP_ x,(mr_small)V[0],x);
convert(_MIPP_ 1,mr_mip->w5);
for (j=1;j<len;j++)
{
mr_pmul(_MIPP_ mr_mip->w5,(mr_small)(M[j-1]),mr_mip->w5);
mr_pmul(_MIPP_ mr_mip->w5,(mr_small)(V[j]),mr_mip->w0);
mr_padd(_MIPP_ x,mr_mip->w0,x);
}
}
| 4,531 |
9,402 | /**
* \file
*/
#include <windows.h>
#include "w32error.h"
guint32
mono_w32error_get_last (void)
{
return GetLastError ();
}
void
mono_w32error_set_last (guint32 error)
{
SetLastError (error);
}
guint32
mono_w32error_unix_to_win32 (guint32 error)
{
g_assert_not_reached ();
}
| 131 |
2,206 | <reponame>showkawa/deeplearning4j
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.imports.listeners;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Disabled
public class ImportModelDebugger {
@Test
@Disabled
public void doTest(){
main(new String[0]);
}
public static void main(String[] args) {
File modelFile = new File("C:\\Temp\\TF_Graphs\\cifar10_gan_85\\tf_model.pb");
File rootDir = new File("C:\\Temp\\TF_Graphs\\cifar10_gan_85");
SameDiff sd = TFGraphMapper.importGraph(modelFile);
ImportDebugListener l = ImportDebugListener.builder(rootDir)
.checkShapesOnly(true)
.floatingPointEps(1e-5)
.onFailure(ImportDebugListener.OnFailure.EXCEPTION)
.logPass(true)
.build();
sd.setListeners(l);
Map<String,INDArray> ph = loadPlaceholders(rootDir);
List<String> outputs = sd.outputs();
sd.output(ph, outputs);
}
public static Map<String, INDArray> loadPlaceholders(File rootDir){
File dir = new File(rootDir, "__placeholders");
if(!dir.exists()){
throw new IllegalStateException("Cannot find placeholders: directory does not exist: " + dir.getAbsolutePath());
}
Map<String, INDArray> ret = new HashMap<>();
Iterator<File> iter = FileUtils.iterateFiles(dir, null, true);
while(iter.hasNext()){
File f = iter.next();
if(!f.isFile())
continue;
String s = dir.toURI().relativize(f.toURI()).getPath();
int idx = s.lastIndexOf("__");
String name = s.substring(0, idx);
INDArray arr = Nd4j.createFromNpyFile(f);
ret.put(name, arr);
}
return ret;
}
}
| 1,192 |
1,104 | <gh_stars>1000+
{
"html": "mhrpg.html",
"css": "mhrpg.css",
"preview": "marvel-heroic-rpg-preview.png",
"authors": "<NAME>. (@flynnwastaken), <NAME> (@trueshinken)",
"patreon": "https://www.patreon.com/flynnwastaken",
"roll20userid": "1969239",
"instructions": "Most buttons add dice to the dice pool, which is then rolled by the 'Roll Pool' button. View the code and make requests at [flynnwastaken's repository](https://github.com/flynnwastaken/marvel-heroic-roleplaying-roll20-character-sheet/).\nPlease enjoy!",
"useroptions": [
{
"attribute": "sheetTab",
"displayname": "Sheet Type:",
"type": "select",
"options": [
"Player Stats|stats",
"Player Details|details",
"NPC|npc"
],
"default": "stats",
"description": "Toggles newly created sheets to shows the Player or NPC page by default."
}
],
"legacy": true
} | 359 |
455 | <gh_stars>100-1000
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.cas;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.transformAsync;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import build.bazel.remote.execution.v2.Digest;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.Write;
import build.buildfarm.common.io.FeedbackOutputStream;
import com.google.common.hash.HashingOutputStream;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
class MemoryWriteOutputStream extends FeedbackOutputStream implements Write {
private final ContentAddressableStorage storage;
private final Digest digest;
private final ListenableFuture<ByteString> writtenFuture;
private final ByteString.Output out;
private final SettableFuture<Void> future = SettableFuture.create();
private SettableFuture<Void> closedFuture = null;
private HashingOutputStream hashOut;
MemoryWriteOutputStream(
ContentAddressableStorage storage,
Digest digest,
ListenableFuture<ByteString> writtenFuture) {
this.storage = storage;
this.digest = digest;
this.writtenFuture = writtenFuture;
if (digest.getSizeBytes() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
String.format(
"content size %d exceeds maximum of %d", digest.getSizeBytes(), Integer.MAX_VALUE));
}
out = ByteString.newOutput((int) digest.getSizeBytes());
hashOut = DigestUtil.forDigest(digest).newHashingOutputStream(out);
writtenFuture.addListener(
() -> {
future.set(null);
try {
hashOut.close();
} catch (IOException e) {
// ignore
}
},
directExecutor());
}
String hash() {
return hashOut.hash().toString();
}
Digest getActual() {
return DigestUtil.buildDigest(hash(), getCommittedSize());
}
@Override
public void close() throws IOException {
if (getCommittedSize() >= digest.getSizeBytes()) {
hashOut.close();
closedFuture.set(null);
Digest actual = getActual();
if (!actual.equals(digest)) {
DigestMismatchException e = new DigestMismatchException(actual, digest);
future.setException(e);
throw e;
}
try {
storage.put(new ContentAddressableStorage.Blob(out.toByteString(), digest));
} catch (InterruptedException e) {
future.setException(e);
throw new IOException(e);
}
}
}
@Override
public void flush() throws IOException {
hashOut.flush();
}
@Override
public void write(byte[] b) throws IOException {
hashOut.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
hashOut.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
hashOut.write(b);
}
@Override
public boolean isReady() {
return true;
}
// Write methods
@Override
public long getCommittedSize() {
return isComplete() ? digest.getSizeBytes() : out.size();
}
@Override
public boolean isComplete() {
return writtenFuture.isDone();
}
@Override
public synchronized FeedbackOutputStream getOutput(
long deadlineAfter, TimeUnit deadlineAfterUnits, Runnable onReadyHandler) {
if (closedFuture == null || closedFuture.isDone()) {
closedFuture = SettableFuture.create();
}
return this;
}
@Override
public synchronized ListenableFuture<FeedbackOutputStream> getOutputFuture(
long deadlineAfter, TimeUnit deadlineAfterUnits, Runnable onReadyHandler) {
if (closedFuture == null || closedFuture.isDone()) {
return immediateFuture(getOutput(deadlineAfter, deadlineAfterUnits, onReadyHandler));
}
return transformAsync(
closedFuture,
result -> getOutputFuture(deadlineAfter, deadlineAfterUnits, onReadyHandler),
directExecutor());
}
@Override
public void reset() {
out.reset();
hashOut = DigestUtil.forDigest(digest).newHashingOutputStream(out);
}
@Override
public ListenableFuture<Long> getFuture() {
return Futures.transform(future, result -> digest.getSizeBytes(), directExecutor());
}
}
| 1,701 |
1,542 | """
Title: Image classification with Swin Transformers
Author: [<NAME>](https://twitter.com/rishit_dagli)
Date created: 2021/09/08
Last modified: 2021/09/08
Description: Image classification using Swin Transformers, a general-purpose backbone for computer vision.
"""
"""
This example implements [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030)
by Liu et al. for image classification, and demonstrates it on the
[CIFAR-100 dataset](https://www.cs.toronto.edu/~kriz/cifar.html).
Swin Transformer (**S**hifted **Win**dow Transformer) can serve as a general-purpose backbone
for computer vision. Swin Transformer is a hierarchical Transformer whose
representations are computed with _shifted windows_. The shifted window scheme
brings greater efficiency by limiting self-attention computation to
non-overlapping local windows while also allowing for cross-window connections.
This architecture has the flexibility to model information at various scales and has
a linear computational complexity with respect to image size.
This example requires TensorFlow 2.5 or higher, as well as TensorFlow Addons,
which can be installed using the following commands:
"""
"""shell
pip install -U tensorflow-addons
"""
"""
## Setup
"""
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow import keras
from tensorflow.keras import layers
"""
## Prepare the data
We load the CIFAR-100 dataset through `tf.keras.datasets`,
normalize the images, and convert the integer labels to one-hot encoded vectors.
"""
num_classes = 100
input_shape = (32, 32, 3)
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(f"x_train shape: {x_train.shape} - y_train shape: {y_train.shape}")
print(f"x_test shape: {x_test.shape} - y_test shape: {y_test.shape}")
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i])
plt.show()
"""
## Configure the hyperparameters
A key parameter to pick is the `patch_size`, the size of the input patches.
In order to use each pixel as an individual input, you can set `patch_size` to `(1, 1)`.
Below, we take inspiration from the original paper settings
for training on ImageNet-1K, keeping most of the original settings for this example.
"""
patch_size = (2, 2) # 2-by-2 sized patches
dropout_rate = 0.03 # Dropout rate
num_heads = 8 # Attention heads
embed_dim = 64 # Embedding dimension
num_mlp = 256 # MLP layer size
qkv_bias = True # Convert embedded patches to query, key, and values with a learnable additive value
window_size = 2 # Size of attention window
shift_size = 1 # Size of shifting window
image_dimension = 32 # Initial image size
num_patch_x = input_shape[0] // patch_size[0]
num_patch_y = input_shape[1] // patch_size[1]
learning_rate = 1e-3
batch_size = 128
num_epochs = 40
validation_split = 0.1
weight_decay = 0.0001
label_smoothing = 0.1
"""
## Helper functions
We create two helper functions to help us get a sequence of
patches from the image, merge patches, and apply dropout.
"""
def window_partition(x, window_size):
_, height, width, channels = x.shape
patch_num_y = height // window_size
patch_num_x = width // window_size
x = tf.reshape(
x, shape=(-1, patch_num_y, window_size, patch_num_x, window_size, channels)
)
x = tf.transpose(x, (0, 1, 3, 2, 4, 5))
windows = tf.reshape(x, shape=(-1, window_size, window_size, channels))
return windows
def window_reverse(windows, window_size, height, width, channels):
patch_num_y = height // window_size
patch_num_x = width // window_size
x = tf.reshape(
windows,
shape=(-1, patch_num_y, patch_num_x, window_size, window_size, channels),
)
x = tf.transpose(x, perm=(0, 1, 3, 2, 4, 5))
x = tf.reshape(x, shape=(-1, height, width, channels))
return x
class DropPath(layers.Layer):
def __init__(self, drop_prob=None, **kwargs):
super(DropPath, self).__init__(**kwargs)
self.drop_prob = drop_prob
def call(self, x):
input_shape = tf.shape(x)
batch_size = input_shape[0]
rank = x.shape.rank
shape = (batch_size,) + (1,) * (rank - 1)
random_tensor = (1 - self.drop_prob) + tf.random.uniform(shape, dtype=x.dtype)
path_mask = tf.floor(random_tensor)
output = tf.math.divide(x, 1 - self.drop_prob) * path_mask
return output
"""
## Window based multi-head self-attention
Usually Transformers perform global self-attention, where the relationships between
a token and all other tokens are computed. The global computation leads to quadratic
complexity with respect to the number of tokens. Here, as the [original paper](https://arxiv.org/abs/2103.14030)
suggests, we compute self-attention within local windows, in a non-overlapping manner.
Global self-attention leads to quadratic computational complexity in the number of patches,
whereas window-based self-attention leads to linear complexity and is easily scalable.
"""
class WindowAttention(layers.Layer):
def __init__(
self, dim, window_size, num_heads, qkv_bias=True, dropout_rate=0.0, **kwargs
):
super(WindowAttention, self).__init__(**kwargs)
self.dim = dim
self.window_size = window_size
self.num_heads = num_heads
self.scale = (dim // num_heads) ** -0.5
self.qkv = layers.Dense(dim * 3, use_bias=qkv_bias)
self.dropout = layers.Dropout(dropout_rate)
self.proj = layers.Dense(dim)
def build(self, input_shape):
num_window_elements = (2 * self.window_size[0] - 1) * (
2 * self.window_size[1] - 1
)
self.relative_position_bias_table = self.add_weight(
shape=(num_window_elements, self.num_heads),
initializer=tf.initializers.Zeros(),
trainable=True,
)
coords_h = np.arange(self.window_size[0])
coords_w = np.arange(self.window_size[1])
coords_matrix = np.meshgrid(coords_h, coords_w, indexing="ij")
coords = np.stack(coords_matrix)
coords_flatten = coords.reshape(2, -1)
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
relative_coords = relative_coords.transpose([1, 2, 0])
relative_coords[:, :, 0] += self.window_size[0] - 1
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
relative_position_index = relative_coords.sum(-1)
self.relative_position_index = tf.Variable(
initial_value=tf.convert_to_tensor(relative_position_index), trainable=False
)
def call(self, x, mask=None):
_, size, channels = x.shape
head_dim = channels // self.num_heads
x_qkv = self.qkv(x)
x_qkv = tf.reshape(x_qkv, shape=(-1, size, 3, self.num_heads, head_dim))
x_qkv = tf.transpose(x_qkv, perm=(2, 0, 3, 1, 4))
q, k, v = x_qkv[0], x_qkv[1], x_qkv[2]
q = q * self.scale
k = tf.transpose(k, perm=(0, 1, 3, 2))
attn = q @ k
num_window_elements = self.window_size[0] * self.window_size[1]
relative_position_index_flat = tf.reshape(
self.relative_position_index, shape=(-1,)
)
relative_position_bias = tf.gather(
self.relative_position_bias_table, relative_position_index_flat
)
relative_position_bias = tf.reshape(
relative_position_bias, shape=(num_window_elements, num_window_elements, -1)
)
relative_position_bias = tf.transpose(relative_position_bias, perm=(2, 0, 1))
attn = attn + tf.expand_dims(relative_position_bias, axis=0)
if mask is not None:
nW = mask.get_shape()[0]
mask_float = tf.cast(
tf.expand_dims(tf.expand_dims(mask, axis=1), axis=0), tf.float32
)
attn = (
tf.reshape(attn, shape=(-1, nW, self.num_heads, size, size))
+ mask_float
)
attn = tf.reshape(attn, shape=(-1, self.num_heads, size, size))
attn = keras.activations.softmax(attn, axis=-1)
else:
attn = keras.activations.softmax(attn, axis=-1)
attn = self.dropout(attn)
x_qkv = attn @ v
x_qkv = tf.transpose(x_qkv, perm=(0, 2, 1, 3))
x_qkv = tf.reshape(x_qkv, shape=(-1, size, channels))
x_qkv = self.proj(x_qkv)
x_qkv = self.dropout(x_qkv)
return x_qkv
"""
## The complete Swin Transformer model
Finally, we put together the complete Swin Transformer by replacing the standard multi-head
attention (MHA) with shifted windows attention. As suggested in the
original paper, we create a model comprising of a shifted window-based MHA
layer, followed by a 2-layer MLP with GELU nonlinearity in between, applying
`LayerNormalization` before each MSA layer and each MLP, and a residual
connection after each of these layers.
Notice that we only create a simple MLP with 2 Dense and
2 Dropout layers. Often you will see models using ResNet-50 as the MLP which is
quite standard in the literature. However in this paper the authors use a
2-layer MLP with GELU nonlinearity in between.
"""
class SwinTransformer(layers.Layer):
def __init__(
self,
dim,
num_patch,
num_heads,
window_size=7,
shift_size=0,
num_mlp=1024,
qkv_bias=True,
dropout_rate=0.0,
**kwargs,
):
super(SwinTransformer, self).__init__(**kwargs)
self.dim = dim # number of input dimensions
self.num_patch = num_patch # number of embedded patches
self.num_heads = num_heads # number of attention heads
self.window_size = window_size # size of window
self.shift_size = shift_size # size of window shift
self.num_mlp = num_mlp # number of MLP nodes
self.norm1 = layers.LayerNormalization(epsilon=1e-5)
self.attn = WindowAttention(
dim,
window_size=(self.window_size, self.window_size),
num_heads=num_heads,
qkv_bias=qkv_bias,
dropout_rate=dropout_rate,
)
self.drop_path = DropPath(dropout_rate)
self.norm2 = layers.LayerNormalization(epsilon=1e-5)
self.mlp = keras.Sequential(
[
layers.Dense(num_mlp),
layers.Activation(keras.activations.gelu),
layers.Dropout(dropout_rate),
layers.Dense(dim),
layers.Dropout(dropout_rate),
]
)
if min(self.num_patch) < self.window_size:
self.shift_size = 0
self.window_size = min(self.num_patch)
def build(self, input_shape):
if self.shift_size == 0:
self.attn_mask = None
else:
height, width = self.num_patch
h_slices = (
slice(0, -self.window_size),
slice(-self.window_size, -self.shift_size),
slice(-self.shift_size, None),
)
w_slices = (
slice(0, -self.window_size),
slice(-self.window_size, -self.shift_size),
slice(-self.shift_size, None),
)
mask_array = np.zeros((1, height, width, 1))
count = 0
for h in h_slices:
for w in w_slices:
mask_array[:, h, w, :] = count
count += 1
mask_array = tf.convert_to_tensor(mask_array)
# mask array to windows
mask_windows = window_partition(mask_array, self.window_size)
mask_windows = tf.reshape(
mask_windows, shape=[-1, self.window_size * self.window_size]
)
attn_mask = tf.expand_dims(mask_windows, axis=1) - tf.expand_dims(
mask_windows, axis=2
)
attn_mask = tf.where(attn_mask != 0, -100.0, attn_mask)
attn_mask = tf.where(attn_mask == 0, 0.0, attn_mask)
self.attn_mask = tf.Variable(initial_value=attn_mask, trainable=False)
def call(self, x):
height, width = self.num_patch
_, num_patches_before, channels = x.shape
x_skip = x
x = self.norm1(x)
x = tf.reshape(x, shape=(-1, height, width, channels))
if self.shift_size > 0:
shifted_x = tf.roll(
x, shift=[-self.shift_size, -self.shift_size], axis=[1, 2]
)
else:
shifted_x = x
x_windows = window_partition(shifted_x, self.window_size)
x_windows = tf.reshape(
x_windows, shape=(-1, self.window_size * self.window_size, channels)
)
attn_windows = self.attn(x_windows, mask=self.attn_mask)
attn_windows = tf.reshape(
attn_windows, shape=(-1, self.window_size, self.window_size, channels)
)
shifted_x = window_reverse(
attn_windows, self.window_size, height, width, channels
)
if self.shift_size > 0:
x = tf.roll(
shifted_x, shift=[self.shift_size, self.shift_size], axis=[1, 2]
)
else:
x = shifted_x
x = tf.reshape(x, shape=(-1, height * width, channels))
x = self.drop_path(x)
x = x_skip + x
x_skip = x
x = self.norm2(x)
x = self.mlp(x)
x = self.drop_path(x)
x = x_skip + x
return x
"""
## Model training and evaluation
### Extract and embed patches
We first create 3 layers to help us extract, embed and merge patches from the
images on top of which we will later use the Swin Transformer class we built.
"""
class PatchExtract(layers.Layer):
def __init__(self, patch_size, **kwargs):
super(PatchExtract, self).__init__(**kwargs)
self.patch_size_x = patch_size[0]
self.patch_size_y = patch_size[0]
def call(self, images):
batch_size = tf.shape(images)[0]
patches = tf.image.extract_patches(
images=images,
sizes=(1, self.patch_size_x, self.patch_size_y, 1),
strides=(1, self.patch_size_x, self.patch_size_y, 1),
rates=(1, 1, 1, 1),
padding="VALID",
)
patch_dim = patches.shape[-1]
patch_num = patches.shape[1]
return tf.reshape(patches, (batch_size, patch_num * patch_num, patch_dim))
class PatchEmbedding(layers.Layer):
def __init__(self, num_patch, embed_dim, **kwargs):
super(PatchEmbedding, self).__init__(**kwargs)
self.num_patch = num_patch
self.proj = layers.Dense(embed_dim)
self.pos_embed = layers.Embedding(input_dim=num_patch, output_dim=embed_dim)
def call(self, patch):
pos = tf.range(start=0, limit=self.num_patch, delta=1)
return self.proj(patch) + self.pos_embed(pos)
class PatchMerging(tf.keras.layers.Layer):
def __init__(self, num_patch, embed_dim):
super(PatchMerging, self).__init__()
self.num_patch = num_patch
self.embed_dim = embed_dim
self.linear_trans = layers.Dense(2 * embed_dim, use_bias=False)
def call(self, x):
height, width = self.num_patch
_, _, C = x.get_shape().as_list()
x = tf.reshape(x, shape=(-1, height, width, C))
x0 = x[:, fdf8:f53e:61e4::18, fdf8:f53e:61e4::18, :]
x1 = x[:, fdf8:f53e:61e4::18, fdf8:f53e:61e4::18, :]
x2 = x[:, fdf8:f53e:61e4::18, fdf8:f53e:61e4::18, :]
x3 = x[:, fdf8:f53e:61e4::18, fdf8:f53e:61e4::18, :]
x = tf.concat((x0, x1, x2, x3), axis=-1)
x = tf.reshape(x, shape=(-1, (height // 2) * (width // 2), 4 * C))
return self.linear_trans(x)
"""
### Build the model
We put together the Swin Transformer model.
"""
input = layers.Input(input_shape)
x = layers.RandomCrop(image_dimension, image_dimension)(input)
x = layers.RandomFlip("horizontal")(x)
x = PatchExtract(patch_size)(x)
x = PatchEmbedding(num_patch_x * num_patch_y, embed_dim)(x)
x = SwinTransformer(
dim=embed_dim,
num_patch=(num_patch_x, num_patch_y),
num_heads=num_heads,
window_size=window_size,
shift_size=0,
num_mlp=num_mlp,
qkv_bias=qkv_bias,
dropout_rate=dropout_rate,
)(x)
x = SwinTransformer(
dim=embed_dim,
num_patch=(num_patch_x, num_patch_y),
num_heads=num_heads,
window_size=window_size,
shift_size=shift_size,
num_mlp=num_mlp,
qkv_bias=qkv_bias,
dropout_rate=dropout_rate,
)(x)
x = PatchMerging((num_patch_x, num_patch_y), embed_dim=embed_dim)(x)
x = layers.GlobalAveragePooling1D()(x)
output = layers.Dense(num_classes, activation="softmax")(x)
"""
### Train on CIFAR-100
We train the model on CIFAR-100. Here, we only train the model
for 40 epochs to keep the training time short in this example.
In practice, you should train for 150 epochs to reach convergence.
"""
model = keras.Model(input, output)
model.compile(
loss=keras.losses.CategoricalCrossentropy(label_smoothing=label_smoothing),
optimizer=tfa.optimizers.AdamW(
learning_rate=learning_rate, weight_decay=weight_decay
),
metrics=[
keras.metrics.CategoricalAccuracy(name="accuracy"),
keras.metrics.TopKCategoricalAccuracy(5, name="top-5-accuracy"),
],
)
history = model.fit(
x_train,
y_train,
batch_size=batch_size,
epochs=num_epochs,
validation_split=validation_split,
)
"""
Let's visualize the training progress of the model.
"""
plt.plot(history.history["loss"], label="train_loss")
plt.plot(history.history["val_loss"], label="val_loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Train and Validation Losses Over Epochs", fontsize=14)
plt.legend()
plt.grid()
plt.show()
"""
Let's display the final results of the training on CIFAR-100.
"""
loss, accuracy, top_5_accuracy = model.evaluate(x_test, y_test)
print(f"Test loss: {round(loss, 2)}")
print(f"Test accuracy: {round(accuracy * 100, 2)}%")
print(f"Test top 5 accuracy: {round(top_5_accuracy * 100, 2)}%")
"""
The Swin Transformer model we just trained has just 152K parameters, and it gets
us to ~75% test top-5 accuracy within just 40 epochs without any signs of overfitting
as well as seen in above graph. This means we can train this network for longer
(perhaps with a bit more regularization) and obtain even better performance.
This performance can further be improved by additional techniques like cosine
decay learning rate schedule, other data augmentation techniques. While experimenting,
I tried training the model for 150 epochs with a slightly higher dropout and greater
embedding dimensions which pushes the performance to ~72% test accuracy on CIFAR-100
as you can see in the screenshot.

The authors present a top-1 accuracy of 87.3% on ImageNet. The authors also present
a number of experiments to study how input sizes, optimizers etc. affect the final
performance of this model. The authors further present using this model for object detection,
semantic segmentation and instance segmentation as well and report competitive results
for these. You are strongly advised to also check out the
[original paper](https://arxiv.org/abs/2103.14030).
This example takes inspiration from the official
[PyTorch](https://github.com/microsoft/Swin-Transformer) and
[TensorFlow](https://github.com/VcampSoldiers/Swin-Transformer-Tensorflow) implementations.
"""
| 8,489 |
1,007 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appium.java_client.ws;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.openqa.selenium.remote.http.ClientConfig;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpMethod;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.WebSocket;
public class StringWebSocketClient implements WebSocket.Listener,
CanHandleMessages<String>, CanHandleErrors, CanHandleConnects, CanHandleDisconnects {
private final List<Consumer<String>> messageHandlers = new CopyOnWriteArrayList<>();
private final List<Consumer<Throwable>> errorHandlers = new CopyOnWriteArrayList<>();
private final List<Runnable> connectHandlers = new CopyOnWriteArrayList<>();
private final List<Runnable> disconnectHandlers = new CopyOnWriteArrayList<>();
private volatile boolean isListening = false;
private URI endpoint;
private void setEndpoint(URI endpoint) {
this.endpoint = endpoint;
}
@Nullable
public URI getEndpoint() {
return this.endpoint;
}
public boolean isListening() {
return isListening;
}
/**
* Connects web socket client.
*
* @param endpoint The full address of an endpoint to connect to.
* Usually starts with 'ws://'.
*/
public void connect(URI endpoint) {
if (endpoint.equals(this.getEndpoint()) && isListening) {
return;
}
ClientConfig clientConfig = ClientConfig.defaultConfig()
.readTimeout(Duration.ZERO)
.baseUri(endpoint); // To avoid NPE in org.openqa.selenium.remote.http.netty.NettyMessages (line 78)
HttpClient client = HttpClient.Factory.createDefault().createClient(clientConfig);
HttpRequest request = new HttpRequest(HttpMethod.GET, endpoint.toString());
client.openSocket(request, this);
onOpen();
setEndpoint(endpoint);
}
public void onOpen() {
getConnectionHandlers().forEach(Runnable::run);
isListening = true;
}
@Override
public void onClose(int code, String reason) {
getDisconnectionHandlers().forEach(Runnable::run);
isListening = false;
}
@Override
public void onError(Throwable t) {
getErrorHandlers().forEach(x -> x.accept(t));
}
@Override
public void onText(CharSequence data) {
String text = data.toString();
getMessageHandlers().forEach(x -> x.accept(text));
}
@Override
public List<Consumer<String>> getMessageHandlers() {
return messageHandlers;
}
@Override
public List<Consumer<Throwable>> getErrorHandlers() {
return errorHandlers;
}
@Override
public List<Runnable> getConnectionHandlers() {
return connectHandlers;
}
@Override
public List<Runnable> getDisconnectionHandlers() {
return disconnectHandlers;
}
/**
* Remove all the registered handlers.
*/
public void removeAllHandlers() {
removeMessageHandlers();
removeErrorHandlers();
removeConnectionHandlers();
removeDisconnectionHandlers();
}
}
| 1,425 |
3,189 | #include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_LINE_LENGTH 10240
#define MAX_OUTPUT_BUFFER 102400
static void set_tcp_no_delay(evutil_socket_t fd)
{
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
&one, sizeof one);
}
static void signal_cb(evutil_socket_t fd, short what, void *arg)
{
struct event_base *base = arg;
printf("stop\n");
event_base_loopexit(base, NULL);
}
static void echo_read_cb(struct bufferevent *bev, void *ctx)
{
/* This callback is invoked when there is data to read on bev. */
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
while (1) {
size_t eol_len = 0;
struct evbuffer_ptr eol = evbuffer_search_eol(input, NULL, &eol_len, EVBUFFER_EOL_LF);
if (eol.pos < 0) {
// not found '\n'
size_t readable = evbuffer_get_length(input);
if (readable > MAX_LINE_LENGTH) {
printf("input is too long %zd\n", readable);
bufferevent_free(bev);
}
break;
}
else if (eol.pos > MAX_LINE_LENGTH) {
printf("line is too long %zd\n", eol.pos);
bufferevent_free(bev);
break;
}
else {
assert(eol_len == 1);
// int nr = evbuffer_remove_buffer(input, output, eol.pos+1);
// copy input buffer to request
char request[MAX_LINE_LENGTH+1];
assert(eol.pos+1 <= sizeof(request));
int req_len = evbuffer_remove(input, request, eol.pos+1);
assert(req_len == eol.pos+1);
// business logic
char response[MAX_LINE_LENGTH+1];
int resp_len = req_len;
memcpy(response, request, req_len);
// copy response to output buffer
int succeed = evbuffer_add(output, response, resp_len);
assert(succeed == 0);
// high water mark check
if (evbuffer_get_length(output) > MAX_OUTPUT_BUFFER) {
// or, stop reading
bufferevent_free(bev);
break;
}
}
}
}
static void echo_event_cb(struct bufferevent *bev, short events, void *ctx)
{
if (events & BEV_EVENT_ERROR) {
perror("Error from bufferevent");
}
if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
bufferevent_free(bev);
}
}
static void accept_conn_cb(struct evconnlistener *listener,
evutil_socket_t fd, struct sockaddr *address, int socklen,
void *ctx)
{
/* We got a new connection! Set up a bufferevent for it. */
struct event_base *base = evconnlistener_get_base(listener);
struct bufferevent *bev = bufferevent_socket_new(
base, fd, BEV_OPT_CLOSE_ON_FREE);
set_tcp_no_delay(fd);
bufferevent_setcb(bev, echo_read_cb, NULL, echo_event_cb, NULL);
bufferevent_enable(bev, EV_READ|EV_WRITE);
}
int main(int argc, char **argv)
{
struct event_base *base;
struct evconnlistener *listener;
struct sockaddr_in sin;
struct event *evstop;
int port = 9876;
if (argc > 1) {
port = atoi(argv[1]);
}
if (port<=0 || port>65535) {
puts("Invalid port");
return 1;
}
signal(SIGPIPE, SIG_IGN);
base = event_base_new();
if (!base) {
puts("Couldn't open event base");
return 1;
}
evstop = evsignal_new(base, SIGHUP, signal_cb, base);
evsignal_add(evstop, NULL);
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(0);
sin.sin_port = htons(port);
listener = evconnlistener_new_bind(base, accept_conn_cb, NULL,
LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
(struct sockaddr*)&sin, sizeof(sin));
if (!listener) {
perror("Couldn't create listener");
return 1;
}
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(evstop);
event_base_free(base);
return 0;
}
| 1,659 |
575 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PASSWORD_MANAGER_CHANGE_PASSWORD_URL_SERVICE_FACTORY_H_
#define CHROME_BROWSER_PASSWORD_MANAGER_CHANGE_PASSWORD_URL_SERVICE_FACTORY_H_
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace password_manager {
class ChangePasswordUrlService;
}
namespace content {
class BrowserContext;
}
// Creates instances of ChangePasswordUrl per BrowserContext.
class ChangePasswordUrlServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
ChangePasswordUrlServiceFactory();
~ChangePasswordUrlServiceFactory() override;
static ChangePasswordUrlServiceFactory* GetInstance();
static password_manager::ChangePasswordUrlService* GetForBrowserContext(
content::BrowserContext* browser_context);
private:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
#endif // CHROME_BROWSER_PASSWORD_MANAGER_CHANGE_PASSWORD_URL_SERVICE_FACTORY_H_
| 346 |
1,582 | from deepmatch.models import NCF
from ..utils import get_xy_fd_ncf
def test_NCF():
model_name = "NCF"
x, y, user_feature_columns, item_feature_columns = get_xy_fd_ncf(False)
model = NCF(user_feature_columns, item_feature_columns, )
model.compile('adam', "binary_crossentropy")
model.fit(x, y, batch_size=10, epochs=2, validation_split=0.5)
if __name__ == "__main__":
pass
| 167 |
809 | <gh_stars>100-1000
#include "uart.h"
/*
Variable for DM2UART function:
DM_START - start block address for send by UART
BLOCK_SIZE - end block address for send by UART
iterator1 - number one byte for send by UART
iterator2 - counter fifo UART
byte_DM - contain byte for send by UART
*/
int read_DM(int *iterator1, int *iterator2, int block_size, char *byte_dm, int dm_start)
{
if(block_size + dm_start - *iterator1 != 0)
{
if(*iterator1 == 0) *iterator1 = *iterator1 + dm_start;
*byte_dm = *((char*)(*iterator1)); //read 1 byte from DM
*iterator1 = *iterator1 + 1;
*iterator2 = *iterator2 - 1;
return 0;
}
else
{
return 1;
}
}
int full_fifo(int *iterator2)
{
if(*iterator2 == 0)
{
*iterator2 = 32;
return 1;
}
else
{
return 0;
}
}
void DM2UART(UART_TypeDef *UART, int start_address, int size_block)
{
int iterator1, iterator2;
int dm_start, block_size;
char byte_dm;
iterator2 = 32;
iterator1 = 0;
dm_start = start_address;
block_size = size_block;
while(UART_FIFO_TX_EMPTY(UART) != 1);
while(read_DM(&iterator1, &iterator2, block_size,&byte_dm, dm_start) == 0)
{
UART_SEND_BYTE(byte_dm, UART);
if(full_fifo(&iterator2) == 1)
{
while(UART_FIFO_TX_EMPTY(UART) != 1);
}
}
}
| 544 |
2,151 | <filename>test/std/containers/sequences/vector/vector.cons/construct_size.pass.cpp<gh_stars>1000+
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// explicit vector(size_type n);
#include <vector>
#include <cassert>
#include "test_macros.h"
#include "DefaultOnly.h"
#include "min_allocator.h"
#include "test_allocator.h"
#include "asan_testing.h"
template <class C>
void
test2(typename C::size_type n, typename C::allocator_type const& a = typename C::allocator_type ())
{
#if TEST_STD_VER >= 14
C c(n, a);
LIBCPP_ASSERT(c.__invariants());
assert(c.size() == n);
assert(c.get_allocator() == a);
LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e; ++i)
assert(*i == typename C::value_type());
#else
((void)n);
((void)a);
#endif
}
template <class C>
void
test1(typename C::size_type n)
{
C c(n);
LIBCPP_ASSERT(c.__invariants());
assert(c.size() == n);
assert(c.get_allocator() == typename C::allocator_type());
LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
#if TEST_STD_VER >= 11
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e; ++i)
assert(*i == typename C::value_type());
#endif
}
template <class C>
void
test(typename C::size_type n)
{
test1<C> ( n );
test2<C> ( n );
}
int main()
{
test<std::vector<int> >(50);
test<std::vector<DefaultOnly> >(500);
assert(DefaultOnly::count == 0);
#if TEST_STD_VER >= 11
test<std::vector<int, min_allocator<int>> >(50);
test<std::vector<DefaultOnly, min_allocator<DefaultOnly>> >(500);
test2<std::vector<DefaultOnly, test_allocator<DefaultOnly>> >( 100, test_allocator<DefaultOnly>(23));
assert(DefaultOnly::count == 0);
#endif
}
| 814 |
526 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.dataengine.rest;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
/**
* DataEngineOMASAPIRequestBody provides a common header for Data Engine OMAS request bodies for its REST API.
*/
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSubTypes(
{
@JsonSubTypes.Type(value = DataEngineRegistrationRequestBody.class, name = "dataEngine"),
@JsonSubTypes.Type(value = PortImplementationRequestBody.class, name = "port"),
@JsonSubTypes.Type(value = PortAliasRequestBody.class, name = "portAlias"),
@JsonSubTypes.Type(value = ProcessRequestBody.class, name = "process"),
@JsonSubTypes.Type(value = SchemaTypeRequestBody.class, name = "schema"),
@JsonSubTypes.Type(value = DatabaseRequestBody.class, name = "database"),
@JsonSubTypes.Type(value = DatabaseRequestBody.class, name = "table"),
@JsonSubTypes.Type(value = DataFileRequestBody.class, name = "dataFile")
})
@EqualsAndHashCode
@ToString(callSuper = true)
@NoArgsConstructor
@Getter
@Setter
public abstract class DataEngineOMASAPIRequestBody implements Serializable {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
/* unique name for the external source */
private String externalSourceName;
}
| 799 |
601 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests to cover the ad_manager module."""
import datetime
import unittest
import mock
import pytz
import io
import googleads.ad_manager
import googleads.common
import googleads.errors
from . import testing
CURRENT_VERSION = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
class BaseValue(object):
def __init__(self, original_object):
self.original_object = original_object
def __getitem__(self, key):
return self.original_object[key]
def __contains__(self, key):
if key in self.original_object:
return True
return False
class TextValue(BaseValue):
def __init__(self, original_object):
BaseValue.__init__(self, original_object)
class NumberValue(BaseValue):
def __init__(self, original_object):
BaseValue.__init__(self, original_object)
class DateValue(BaseValue):
def __init__(self, original_object):
BaseValue.__init__(self, original_object)
class DateTimeValue(BaseValue):
def __init__(self, original_object):
BaseValue.__init__(self, original_object)
class BooleanValue(BaseValue):
def __init__(self, original_object):
BaseValue.__init__(self, original_object)
class SetValue(object):
def __init__(self, original_object):
packed_objects = [DecideValue(obj_to_pack) for obj_to_pack
in original_object['values']]
self.original_object = {'values': packed_objects}
def __getitem__(self, key):
return self.original_object[key]
def __contains__(self, key):
if key in self.original_object:
return True
return False
def DecideValue(original_object):
class_type = original_object['xsi_type']
if class_type == 'TextValue':
return TextValue(original_object)
elif class_type == 'NumberValue':
return NumberValue(original_object)
elif class_type == 'DateValue':
return DateValue(original_object)
elif class_type == 'DateTimeValue':
return DateTimeValue(original_object)
elif class_type == 'SetValue':
return SetValue(original_object)
else:
return BooleanValue(original_object)
class AdManagerHeaderHandlerTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the googleads.ad_manager._AdManagerHeaderHandler class."""
def setUp(self):
self.ad_manager_client = mock.Mock()
self.enable_compression = False
self.custom_headers = ()
self.header_handler = googleads.ad_manager._AdManagerHeaderHandler(
self.ad_manager_client, self.enable_compression, self.custom_headers)
self.utility_name = 'TestUtility'
self.default_sig_template = ' (%s, %s, %s)'
self.util_sig_template = ' (%s, %s, %s, %s)'
self.network_code = 'my network code is code'
self.app_name = 'application name'
self.oauth_header = {'oauth': 'header'}
@googleads.common.RegisterUtility(self.utility_name)
class TestUtility(object):
def Test(self):
pass
self.test_utility = TestUtility()
def testGetHTTPHeaders(self):
self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = (
self.oauth_header)
header_result = self.header_handler.GetHTTPHeaders()
# Check that the returned headers have the correct values.
self.assertEqual(header_result, self.oauth_header)
def testGetHTTPHeadersWithCustomHeaders(self):
self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = (
self.oauth_header)
self.header_handler.custom_http_headers = {'X-My-Header': 'abc'}
header_result = self.header_handler.GetHTTPHeaders()
# Check that the returned headers have the correct values.
self.assertEqual(header_result, {'oauth': 'header', 'X-My-Header': 'abc'})
def testGetSOAPHeaders(self):
create_method = mock.Mock()
self.ad_manager_client.network_code = self.network_code
self.ad_manager_client.application_name = self.app_name
header_result = self.header_handler.GetSOAPHeaders(create_method)
# Check that the SOAP header has the correct values.
create_method.assert_called_once_with('ns0:SoapRequestHeader')
self.assertEqual(self.network_code, header_result.networkCode)
self.assertEqual(
''.join([
self.app_name,
googleads.common.GenerateLibSig(
googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG)]),
header_result.applicationName)
def testGetSOAPHeadersUserAgentWithUtility(self):
create_method = mock.Mock()
self.ad_manager_client.network_code = self.network_code
self.ad_manager_client.application_name = self.app_name
with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
self.test_utility.Test() # This will register TestUtility.
soap_header = self.header_handler.GetSOAPHeaders(create_method)
self.assertEqual(
''.join([
self.app_name,
self.util_sig_template % (
googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
mock_common_sig,
mock_py_ver,
self.utility_name)]),
soap_header.applicationName)
def testGetHeadersUserAgentWithAndWithoutUtility(self):
create_method = mock.Mock()
self.ad_manager_client.network_code = self.network_code
self.ad_manager_client.application_name = self.app_name
with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig:
with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver:
# Check headers when utility registered.
self.test_utility.Test() # This will register TestUtility.
soap_header = self.header_handler.GetSOAPHeaders(create_method)
self.assertEqual(
''.join([
self.app_name,
self.util_sig_template % (
googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
mock_common_sig,
mock_py_ver,
self.utility_name)]),
soap_header.applicationName)
# Check headers when no utility should be registered.
soap_header = self.header_handler.GetSOAPHeaders(create_method)
self.assertEqual(
''.join([
self.app_name,
self.default_sig_template % (
googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
mock_common_sig,
mock_py_ver)]),
soap_header.applicationName)
# Verify that utility is registered in subsequent uses.
self.test_utility.Test() # This will register TestUtility.
soap_header = self.header_handler.GetSOAPHeaders(create_method)
self.assertEqual(
''.join([
self.app_name,
self.util_sig_template % (
googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG,
mock_common_sig,
mock_py_ver,
self.utility_name)]),
soap_header.applicationName)
class AdManagerClientTest(unittest.TestCase):
"""Tests for the googleads.ad_manager.AdManagerClient class."""
def setUp(self):
self.network_code = '12345'
self.application_name = 'application name'
self.oauth2_client = mock.Mock()
self.oauth2_client.CreateHttpHeader.return_value = {}
self.proxy_host = 'myproxy'
self.proxy_port = 443
self.https_proxy = 'http://myproxy:443'
self.proxy_config = googleads.common.ProxyConfig(
https_proxy=self.https_proxy)
self.cache = None
self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
def CreateAdManagerClient(self, **kwargs):
if 'proxy_config' not in kwargs:
kwargs['proxy_config'] = self.proxy_config
if 'cache' not in kwargs:
kwargs['cache'] = self.cache
return googleads.ad_manager.AdManagerClient(
self.oauth2_client, self.application_name, self.network_code,
**kwargs)
def testLoadFromString(self):
with mock.patch('googleads.common.LoadFromString') as mock_load:
mock_load.return_value = {
'network_code': 'abcdEFghIjkLMOpqRs',
'oauth2_client': True,
'application_name': 'unit testing'
}
self.assertIsInstance(
googleads.ad_manager.AdManagerClient.LoadFromString(''),
googleads.ad_manager.AdManagerClient)
def testLoadFromStorage(self):
with mock.patch('googleads.common.LoadFromStorage') as mock_load:
mock_load.return_value = {
'network_code': 'abcdEFghIjkLMOpqRs',
'oauth2_client': True,
'application_name': 'unit testing'
}
self.assertIsInstance(
googleads.ad_manager.AdManagerClient.LoadFromStorage(),
googleads.ad_manager.AdManagerClient)
def testLoadFromStorageWithCompressionEnabled(self):
enable_compression = True
application_name_gzip_template = '%s (gzip)'
default_app_name = 'unit testing'
custom_headers = {'X-My-Header': 'abc'}
with mock.patch('googleads.common.LoadFromStorage') as mock_load:
with mock.patch('googleads.ad_manager._AdManagerHeaderHandler') as mock_h:
mock_load.return_value = {
'network_code': 'abcdEFghIjkLMOpqRs',
'oauth2_client': True,
'application_name': default_app_name,
'enable_compression': enable_compression,
'custom_http_headers': custom_headers
}
ad_manager = googleads.ad_manager.AdManagerClient.LoadFromStorage()
self.assertEqual(
application_name_gzip_template % default_app_name,
ad_manager.application_name)
mock_h.assert_called_once_with(
ad_manager, enable_compression, custom_headers)
def testInitializeWithDefaultApplicationName(self):
self.application_name = 'INSERT_APPLICATION_NAME_HERE'
self.assertRaises(
googleads.errors.GoogleAdsValueError,
googleads.ad_manager.AdManagerClient, self.oauth2_client,
self.application_name, self.network_code, self.https_proxy, self.cache)
def testInitializeWithUselessApplicationName(self):
self.application_name = 'try_to_trick_me_INSERT_APPLICATION_NAME_HERE'
self.assertRaises(
googleads.errors.GoogleAdsValueError,
googleads.ad_manager.AdManagerClient, self.oauth2_client,
self.application_name, self.network_code, self.https_proxy, self.cache)
def testGetService_success(self):
ad_manager = self.CreateAdManagerClient(
cache='cache', proxy_config='proxy', timeout='timeout')
service_name = googleads.ad_manager._SERVICE_MAP[self.version][0]
# Use a custom server. Also test what happens if the server ends with a
# trailing slash
server = 'https://testing.test.com/'
with mock.patch('googleads.common.'
'GetServiceClassForLibrary') as mock_get_service:
impl = mock.Mock()
mock_service = mock.Mock()
impl.return_value = mock_service
mock_get_service.return_value = impl
service = ad_manager.GetService(service_name, self.version, server)
impl.assert_called_once_with(
'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl'
% (self.version, service_name), ad_manager._header_handler,
googleads.ad_manager._AdManagerPacker, 'proxy', 'timeout',
self.version, cache='cache')
self.assertEqual(service, mock_service)
def testGetService_badService(self):
ad_manager = self.CreateAdManagerClient()
with mock.patch('googleads.common.'
'GetServiceClassForLibrary') as mock_get_service:
mock_get_service.side_effect = (
googleads.errors.GoogleAdsSoapTransportError('', ''))
self.assertRaises(
googleads.errors.GoogleAdsValueError, ad_manager.GetService,
'GYIVyievfyiovslf', self.version)
def testGetService_badVersion(self):
ad_manager = self.CreateAdManagerClient()
with mock.patch('googleads.common.'
'GetServiceClassForLibrary') as mock_get_service:
mock_get_service.side_effect = (
googleads.errors.GoogleAdsSoapTransportError('', ''))
self.assertRaises(
googleads.errors.GoogleAdsValueError, ad_manager.GetService,
'CampaignService', '11111')
def testGetService_transportError(self):
service = googleads.ad_manager._SERVICE_MAP[self.version][0]
ad_manager = self.CreateAdManagerClient()
with mock.patch('googleads.common.'
'GetServiceClassForLibrary') as mock_get_service:
mock_get_service.side_effect = (
googleads.errors.GoogleAdsSoapTransportError('', ''))
self.assertRaises(googleads.errors.GoogleAdsSoapTransportError,
ad_manager.GetService, service, self.version)
class AdManagerPackerTest(unittest.TestCase):
"""Tests for the googleads.ad_manager._AdManagerPacker class."""
def setUp(self):
self.packer = googleads.ad_manager._AdManagerPacker
def testPackDate(self):
input_date = datetime.date(2017, 1, 2)
result = self.packer.Pack(input_date, CURRENT_VERSION)
self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2})
def testPackDateTime(self):
input_date = datetime.datetime(2017, 1, 2, 3, 4, 5)
input_date = pytz.timezone('America/New_York').localize(input_date)
result = self.packer.Pack(input_date, CURRENT_VERSION)
self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2},
'hour': 3, 'minute': 4, 'second': 5,
'timeZoneId': 'America/New_York'})
def testPackDateTimeNeedsTimeZone(self):
input_date = datetime.datetime(2017, 1, 2, 3, 4, 5)
self.assertRaises(googleads.errors.GoogleAdsValueError,
self.packer.Pack, input_date, CURRENT_VERSION)
def testPackUnsupportedObjectType(self):
obj = object()
self.assertEqual(googleads.ad_manager._AdManagerPacker.
Pack(obj, CURRENT_VERSION), obj)
class DataDownloaderTest(unittest.TestCase):
"""Tests for the googleads.ad_manager.AdManagerClient class."""
def setUp(self):
network_code = '12345'
application_name = 'application name'
oauth2_client = 'unused'
self.https_proxy = 'myproxy.com:443'
self.ad_manager = googleads.ad_manager.AdManagerClient(
oauth2_client, application_name, network_code, self.https_proxy)
self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1]
self.report_downloader = self.ad_manager.GetDataDownloader()
self.pql_service = mock.Mock()
self.report_service = mock.Mock()
self.report_downloader._pql_service = self.pql_service
self.report_downloader._report_service = self.report_service
self.generic_header = [{'labelName': 'Some random header...'},
{'labelName': 'Another header...'}]
row1_field1 = {
'value': 'Some random PQL response...',
'xsi_type': 'TextValue'
}
row1_field2 = {
'value': {
'date': {
'year': '1999', 'month': '04', 'day': '03'}
},
'xsi_type': 'DateValue'
}
row1_field3 = {
'value': '123',
'xsi_type': 'NumberValue'
}
row1_field4 = {
'value': {
'date': {
'year': '2012',
'month': '11',
'day': '05'
},
'hour': '12',
'minute': '12',
'second': '12',
'timeZoneId': 'PST8PDT'},
'xsi_type': 'DateTimeValue'
}
row1_field5 = {
'value': None,
'xsi_type': 'NumberValue'
}
row1_field6 = {
'values': [{
'value': 'Whatcha thinkin about?',
'xsi_type': 'TextValue'
}, {
'value': 'Oh nothing, just String stuff...',
'xsi_type': 'TextValue'
}],
'xsi_type': 'SetValue'
}
row2_field1 = {
'value': 'A second row of PQL response!',
'xsi_type': 'TextValue'
}
row2_field2 = {
'value': {
'date': {
'year': '2009',
'month': '02',
'day': '05'
}
},
'xsi_type': 'DateValue'
}
row2_field3 = {
'value': '345',
'xsi_type': 'NumberValue'
}
row2_field4 = {
'value': {
'date': {
'year': '2013',
'month': '01',
'day': '03'
},
'hour': '02',
'minute': '02',
'second': '02',
'timeZoneId': 'GMT'
},
'xsi_type': 'DateTimeValue'
}
row2_field5 = {
'value': '123456',
'xsi_type': 'NumberValue'
}
row2_field6 = {
'values': [{
'value': 'Look at how many commas and "s there are',
'xsi_type': 'TextValue'
}, {
'value': 'this,is...how,<NAME>, talks',
'xsi_type': 'TextValue'
}],
'xsi_type': 'SetValue'
}
row1 = [row1_field1, row1_field2, row1_field3, row1_field4, row1_field5,
row1_field6]
row2 = [row2_field1, row2_field2, row2_field3, row2_field4, row2_field5,
row2_field6]
self.generic_rval = [{
'values': [DecideValue(value) for value in row1]
}, {
'values': [DecideValue(value) for value in row2]
}]
def testDownloadPqlResultSetToCsv(self):
csv_file = io.StringIO()
self.pql_service.select.return_value = {'rows': self.generic_rval,
'columnTypes': self.generic_header}
self.report_downloader.DownloadPqlResultToCsv(
'SELECT Id, Name FROM Line_Item', csv_file)
csv_file.seek(0)
self.assertEqual(csv_file.readline(),
('"Some random header...",'
'"Another header..."\r\n'))
self.assertEqual(csv_file.readline(),
('"Some random PQL response...",'
'"1999-04-03",'
'"123",'
'"2012-11-05T12:12:12-08:00",'
'"-","""Whatcha thinkin about?"",""Oh nothing, '
'just String stuff..."""\r\n'))
self.assertEqual(csv_file.readline(),
('"A second row of PQL response!",'
'"2009-02-05",'
'"345",'
'"2013-01-03T02:02:02Z",'
'"123456","""Look at how many commas and """"s there are'
'"",""this,is...how,<NAME>, talks"""\r\n'))
csv_file.close()
self.pql_service.select.assert_called_once_with(
{'values': None,
'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
def testDownloadPqlResultToList(self):
self.pql_service.select.return_value = {'rows': self.generic_rval,
'columnTypes': self.generic_header}
result_set = self.report_downloader.DownloadPqlResultToList(
'SELECT Id, Name FROM Line_Item')
row1 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[0]['values']]
row2 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[1]['values']]
self.pql_service.select.assert_called_once_with(
{'values': None,
'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
self.assertEqual([[self.generic_header[0]['labelName'],
self.generic_header[1]['labelName']],
row1, row2], result_set)
def testDownloadPqlResultToListWithOldValuesList(self):
self.pql_service.select.return_value = {'rows': self.generic_rval,
'columnTypes': self.generic_header}
result_set = self.report_downloader.DownloadPqlResultToList(
'SELECT Id, Name FROM Line_Item WHERE Id = :id',
[{'key': 'id', 'value': {'xsi_type': 'NumberValue', 'value': 1}}])
row1 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[0]['values']]
row2 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[1]['values']]
self.pql_service.select.assert_called_once_with(
{'values': [{'key': 'id',
'value': {'xsi_type': 'NumberValue', 'value': 1}}],
'query': ('SELECT Id, Name FROM Line_Item '
'WHERE Id = :id LIMIT 500 OFFSET 0')})
self.assertEqual([[self.generic_header[0]['labelName'],
self.generic_header[1]['labelName']],
row1, row2], result_set)
def testDownloadPqlResultToListWithDict(self):
self.pql_service.select.return_value = {'rows': self.generic_rval,
'columnTypes': self.generic_header}
result_set = self.report_downloader.DownloadPqlResultToList(
'SELECT Id, Name FROM Line_Item WHERE Id = :id',
{'id': 1})
row1 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[0]['values']]
row2 = [self.report_downloader._ConvertValueForCsv(field)
for field in self.generic_rval[1]['values']]
self.pql_service.select.assert_called_once_with(
{'values': [{'key': 'id',
'value': {'xsi_type': 'NumberValue', 'value': 1}}],
'query': ('SELECT Id, Name FROM Line_Item '
'WHERE Id = :id LIMIT 500 OFFSET 0')})
self.assertEqual([[self.generic_header[0]['labelName'],
self.generic_header[1]['labelName']],
row1, row2], result_set)
def testDownloadPqlResultToList_NoRows(self):
self.pql_service.select.return_value = {}
result_set = self.report_downloader.DownloadPqlResultToList(
'SELECT Id, Name FROM Line_Item')
self.pql_service.select.assert_called_once_with(
{'values': None,
'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')})
self.assertEqual([], result_set)
def testWaitForReport_success(self):
id_ = '1g684'
input_ = {'reportQuery': 'something', 'id': id_}
self.report_service.getReportJobStatus.side_effect = ['IN_PROGRESS',
'COMPLETED']
self.report_service.runReportJob.return_value = input_
with mock.patch('time.sleep') as mock_sleep:
rval = self.report_downloader.WaitForReport(input_)
mock_sleep.assert_called_once_with(30)
self.assertEqual(id_, rval)
self.report_service.getReportJobStatus.assert_any_call(id_)
def testWaitForReport_failure(self):
self.report_service.getReportJobStatus.return_value = 'FAILED'
self.report_service.runReportJob.return_value = {'id': '782yt97r2'}
self.assertRaises(
googleads.errors.AdManagerReportError,
self.report_downloader.WaitForReport, {'id': 'obj'})
def testDownloadReportToFile(self):
report_format = 'CSV_DUMP'
report_job_id = 't68t3278y429'
report_download_url = 'http://google.com/something'
report_data = 'THIS IS YOUR REPORT!'
report_contents = io.StringIO()
report_contents.write(report_data)
report_contents.seek(0)
fake_response = mock.Mock()
fake_response.read = report_contents.read
fake_response.msg = 'fake message'
fake_response.code = '200'
outfile = io.StringIO()
download_func = self.report_service.getReportDownloadUrlWithOptions
download_func.return_value = report_download_url
with mock.patch('urllib.request.OpenerDirector.open') as mock_open:
mock_open.return_value = fake_response
self.report_downloader.DownloadReportToFile(
report_job_id, report_format, outfile)
default_opts = {
'exportFormat': report_format,
'includeReportProperties': False,
'includeTotalsRow': False,
'useGzipCompression': True,
}
download_func.assert_called_once_with(report_job_id, default_opts)
mock_open.assert_called_once_with(report_download_url)
self.assertEqual(report_data, outfile.getvalue())
def testGetReportService(self):
self.report_downloader._ad_manager_client = mock.Mock()
self.report_downloader._report_service = None
self.report_downloader._GetReportService()
client = self.report_downloader._ad_manager_client
client.GetService.assert_called_once_with(
'ReportService', self.version, 'https://ads.google.com')
def testGetPqlService(self):
self.report_downloader._ad_manager_client = mock.Mock()
self.report_downloader._pql_service = None
self.report_downloader._GetPqlService()
client = self.report_downloader._ad_manager_client
client.GetService.assert_called_once_with(
'PublisherQueryLanguageService', self.version, 'https://ads.google.com')
def testDownloadHasCustomHeaders(self):
self.ad_manager.custom_http_headers = {'X-My-Headers': 'abc'}
class MyOpener(object):
addheaders = [('a', 'b')]
opener = MyOpener()
with mock.patch('googleads.ad_manager.build_opener') as mock_build_opener:
mock_build_opener.return_value = opener
self.ad_manager.GetDataDownloader()
self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')])
class StatementBuilderTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the StatementBuilder class."""
def testBuildBasicSelectFrom(self):
test_statement = googleads.ad_manager.StatementBuilder()
select_call_result = test_statement.Select('Id')
from_call_result = test_statement.From('Line_Item')
self.assertEqual(select_call_result, test_statement)
self.assertEqual(from_call_result, test_statement)
self.assertEqual(test_statement.ToStatement(),
{'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 0' %
googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': None})
def testLimitClause(self):
test_statement = googleads.ad_manager.StatementBuilder()
limit_call_result = (test_statement
.Select('Id')
.From('Line_Item')
.Limit(5))
self.assertEqual(limit_call_result, test_statement)
self.assertEqual(test_statement.ToStatement(),
{'query': 'SELECT Id FROM Line_Item LIMIT 5 OFFSET 0',
'values': None})
limit_call_result.Limit(None)
self.assertEqual(test_statement.ToStatement(),
{'query': 'SELECT Id FROM Line_Item OFFSET 0',
'values': None})
def testOffsetClause(self):
test_statement = googleads.ad_manager.StatementBuilder()
offset_call_result = (
test_statement
.Select('Id')
.From('Line_Item')
.Offset(100)
)
self.assertEqual(offset_call_result, test_statement)
self.assertEqual(test_statement.ToStatement(),
{'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 100' %
googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': None})
def testOrderByClause(self):
test_statement = googleads.ad_manager.StatementBuilder()
order_call_result = (
test_statement
.Select('Id')
.From('Line_Item')
.OrderBy('Id')
)
self.assertEqual(order_call_result, test_statement)
self.assertEqual(test_statement.ToStatement(),
{'query': ('SELECT Id FROM Line_Item '
'ORDER BY Id ASC '
'LIMIT %s OFFSET 0' %
googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': None})
test_statement.OrderBy('Id', ascending=False)
self.assertEqual(test_statement.ToStatement(),
{'query': ('SELECT Id FROM Line_Item '
'ORDER BY Id DESC '
'LIMIT %s OFFSET 0' %
googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': None})
def testConstructorArgs(self):
test_statement = googleads.ad_manager.StatementBuilder(
select_columns='Id', from_table='Line_Item', where='abc = 123',
order_by='Id', order_ascending=False)
self.assertEqual(test_statement.ToStatement(),
{'query': ('SELECT Id FROM Line_Item '
'WHERE abc = 123 '
'ORDER BY Id DESC '
'LIMIT %s OFFSET 0' %
googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': None})
def testWhereWithStringVariable(self):
test_statement = googleads.ad_manager.StatementBuilder()
where_call_result = (
test_statement
.Select('Id')
.From('Line_Item')
.Where('key = :test_key')
)
bind_call_result = test_statement.WithBindVariable('test_key', 'test_value')
target_values = [{
'key': 'test_key',
'value': {
'xsi_type': 'TextValue',
'value': 'test_value'
}
}]
self.assertEqual(where_call_result, test_statement)
self.assertEqual(bind_call_result, test_statement)
self.assertEqual(
test_statement.ToStatement(),
{'query': (
'SELECT Id FROM Line_Item '
'WHERE key = :test_key '
'LIMIT %s '
'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT),
'values': target_values})
def testWhereWithOtherTypes(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Where((
'bool_key = :test_bool_key '
'AND number_key = :test_number_key '
'AND date_key = :test_date_key '
'AND datetime_key = :test_datetime_key '
'AND set_key = :test_set_key'
))
test_statement.WithBindVariable('test_bool_key', True)
test_statement.WithBindVariable('test_number_key', 5)
test_statement.WithBindVariable('test_date_key', datetime.date(2017, 1, 2))
test_dt = datetime.datetime(2017, 1, 2,
hour=3, minute=4, second=5,
)
test_dt = pytz.timezone('America/New_York').localize(test_dt)
test_statement.WithBindVariable('test_datetime_key', test_dt)
test_statement.WithBindVariable('test_set_key', [1, 2])
target_values = [{
'key': 'test_bool_key',
'value': {
'xsi_type': 'BooleanValue',
'value': True,
}
}, {
'key': 'test_number_key',
'value': {
'xsi_type': 'NumberValue',
'value': 5,
}
}, {
'key': 'test_date_key',
'value': {
'xsi_type': 'DateValue',
'value': {
'year': 2017,
'month': 1,
'day': 2,
},
}
}, {
'key': 'test_datetime_key',
'value': {
'xsi_type': 'DateTimeValue',
'value': {
'date': {
'year': 2017,
'month': 1,
'day': 2,
},
'hour': 3,
'minute': 4,
'second': 5,
'timeZoneId': 'America/New_York'
},
}
}, {
'key': 'test_set_key',
'value': {
'xsi_type': 'SetValue',
'values': [
{'xsi_type': 'NumberValue', 'value': 1},
{'xsi_type': 'NumberValue', 'value': 2},
],
}
}]
target_values.sort(key=lambda v: v['key'])
statement_result = test_statement.ToStatement()
self.assertEqual(statement_result['query'],
('WHERE bool_key = :test_bool_key '
'AND number_key = :test_number_key '
'AND date_key = :test_date_key '
'AND datetime_key = :test_datetime_key '
'AND set_key = :test_set_key '
'LIMIT %s '
'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT
))
# The output order doesn't matter, and it's stored internally as a dict
# until rendered, which is fine, but we need to lock it down for this test.
self.assertEqual(
sorted(statement_result['values'], key=lambda v: v['key']),
target_values
)
def testBreakWithSetOfMultipleTypes(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Where('key = :test_key')
self.assertRaises(
googleads.errors.GoogleAdsValueError,
test_statement.WithBindVariable,
'key', [1, 'a']
)
def testMutateVar(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Where('key = :test_key')
test_statement.WithBindVariable('key', 'abc')
test_statement.WithBindVariable('key', '123')
statement_result = test_statement.ToStatement()
self.assertEqual(len(statement_result['values']), 1)
self.assertEqual(statement_result['values'][0]['value']['value'], '123')
def testBreakWithNoTZ(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Where('key = :test_key')
self.assertRaises(
googleads.errors.GoogleAdsValueError,
test_statement.WithBindVariable,
'key', datetime.datetime.now().replace(tzinfo=None)
)
def testBreakWithUnknownType(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Where('key = :test_key')
class RandomType(object):
pass
self.assertRaises(
googleads.errors.GoogleAdsValueError,
test_statement.WithBindVariable,
'key', RandomType()
)
def testBreakWithBadSelectFrom(self):
test_statement = googleads.ad_manager.StatementBuilder()
test_statement.Select('Id')
self.assertRaises(googleads.errors.GoogleAdsError,
test_statement.ToStatement)
test_statement.Select(None).From('Line_Item')
self.assertRaises(googleads.errors.GoogleAdsError,
test_statement.ToStatement)
class FilterStatementTest(testing.CleanUtilityRegistryTestCase):
"""Tests for the FilterStatement class."""
def testFilterStatement(self):
values = [{
'key': 'test_key',
'value': {
'xsi_type': 'TextValue',
'value': 'test_value'
}
}]
test_statement = googleads.ad_manager.FilterStatement()
self.assertEqual(test_statement.ToStatement(),
{'query': ' LIMIT 500 OFFSET 0', 'values': None})
test_statement.offset += 30
self.assertEqual(test_statement.ToStatement(),
{'query': ' LIMIT 500 OFFSET 30', 'values': None})
test_statement.offset = 123
test_statement.limit = 5
self.assertEqual(test_statement.ToStatement(),
{'query': ' LIMIT 5 OFFSET 123', 'values': None})
test_statement = googleads.ad_manager.FilterStatement(
'SELECT Id FROM Line_Item WHERE key = :test_key', limit=300, offset=20,
values=values)
self.assertEqual(test_statement.ToStatement(),
{'query': 'SELECT Id FROM Line_Item WHERE key = '
':test_key LIMIT 300 OFFSET 20',
'values': values})
if __name__ == '__main__':
unittest.main()
| 16,370 |
8,586 | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include <gtest/gtest.h>
#include "graph/visitor/DeduceTypeVisitor.h"
#include "graph/visitor/test/VisitorTestBase.h"
namespace nebula {
namespace graph {
class DeduceTypeVisitorTest : public VisitorTestBase {
protected:
static ColsDef emptyInput_;
};
ColsDef DeduceTypeVisitorTest::emptyInput_;
TEST_F(DeduceTypeVisitorTest, SubscriptExpr) {
{
auto* items = ExpressionList::make(pool);
items->add(ConstantExpression::make(pool, 1));
auto expr = SubscriptExpression::make(
pool, ListExpression::make(pool, items), ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(
pool, ConstantExpression::make(pool, Value::kNullValue), ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok()) << std::move(visitor).status();
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(
pool, ConstantExpression::make(pool, Value::kEmpty), ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(pool,
ConstantExpression::make(pool, Value::kNullValue),
ConstantExpression::make(pool, Value::kNullValue));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(
pool,
ConstantExpression::make(pool, Value(Map({{"k", "v"}, {"k1", "v1"}}))),
ConstantExpression::make(pool, "test"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(pool,
ConstantExpression::make(pool, Value::kEmpty),
ConstantExpression::make(pool, "test"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = SubscriptExpression::make(pool,
ConstantExpression::make(pool, Value::kNullValue),
ConstantExpression::make(pool, "test"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok()) << std::move(visitor).status();
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
// exceptions
{
auto expr = SubscriptExpression::make(
pool, ConstantExpression::make(pool, "test"), ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_FALSE(visitor.ok());
}
{
auto* items = ExpressionList::make(pool);
items->add(ConstantExpression::make(pool, 1));
auto expr = SubscriptExpression::make(
pool, ListExpression::make(pool, items), ConstantExpression::make(pool, "test"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_FALSE(visitor.ok());
}
{
auto expr = SubscriptExpression::make(
pool,
ConstantExpression::make(pool, Value(Map({{"k", "v"}, {"k1", "v1"}}))),
ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_FALSE(visitor.ok());
}
}
TEST_F(DeduceTypeVisitorTest, Attribute) {
{
auto expr = AttributeExpression::make(
pool,
ConstantExpression::make(pool, Value(Map({{"k", "v"}, {"k1", "v1"}}))),
ConstantExpression::make(pool, "a"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = AttributeExpression::make(pool,
ConstantExpression::make(pool, Value(Vertex("vid", {}))),
ConstantExpression::make(pool, "a"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = AttributeExpression::make(
pool,
ConstantExpression::make(pool, Value(Edge("v1", "v2", 1, "edge", 0, {}))),
ConstantExpression::make(pool, "a"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = AttributeExpression::make(pool,
ConstantExpression::make(pool, Value::kNullValue),
ConstantExpression::make(pool, "a"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
{
auto expr = AttributeExpression::make(pool,
ConstantExpression::make(pool, Value::kNullValue),
ConstantExpression::make(pool, Value::kNullValue));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_TRUE(visitor.ok());
EXPECT_EQ(visitor.type(), Value::Type::__EMPTY__);
}
// exceptions
{
auto expr = AttributeExpression::make(
pool, ConstantExpression::make(pool, "test"), ConstantExpression::make(pool, "a"));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_FALSE(visitor.ok());
}
{
auto expr = AttributeExpression::make(
pool,
ConstantExpression::make(pool, Value(Map({{"k", "v"}, {"k1", "v1"}}))),
ConstantExpression::make(pool, 1));
DeduceTypeVisitor visitor(emptyInput_, -1);
expr->accept(&visitor);
EXPECT_FALSE(visitor.ok());
}
}
} // namespace graph
} // namespace nebula
| 2,874 |
1,848 | <gh_stars>1000+
// bindgen-flags: --with-derive-hash --with-derive-partialeq --with-derive-eq
class MyClass {
public:
static const int* example;
static const int* example_check_no_collision;
};
static const int* example_check_no_collision;
| 89 |
711 | import sys
import os
import logging
import unittest
import pickle
import shutil
import numpy as np
from ConfigSpace import Configuration
from ConfigSpace.hyperparameters import UniformIntegerHyperparameter
from smac.scenario.scenario import Scenario
from smac.configspace import ConfigurationSpace
from smac.utils.merge_foreign_data import merge_foreign_data
from smac.utils.io.cmd_reader import truthy as _is_truthy
from smac.utils.io.input_reader import InputReader
from smac.runhistory.runhistory import RunHistory
from smac.tae import StatusType
__copyright__ = "Copyright 2021, AutoML.org Freiburg-Hannover"
__license__ = "3-clause BSD"
in_reader = InputReader()
if sys.version_info[0] == 2:
import mock
else:
from unittest import mock
class InitFreeScenario(Scenario):
def __init__(self):
pass
class ScenarioTest(unittest.TestCase):
def setUp(self):
logging.basicConfig()
self.logger = logging.getLogger(
self.__module__ + '.' + self.__class__.__name__)
self.logger.setLevel(logging.DEBUG)
base_directory = os.path.split(__file__)[0]
base_directory = os.path.abspath(
os.path.join(base_directory, '..', '..'))
self.current_dir = os.getcwd()
os.chdir(base_directory)
self.cs = ConfigurationSpace()
self.test_scenario_dict = {'algo': 'echo Hello',
'paramfile':
'test/test_files/scenario_test/param.pcs',
'execdir': '.',
'deterministic': 0,
'run_obj': 'runtime',
'overall_obj': 'mean10',
'cutoff_time': 5,
'wallclock-limit': 18000,
'instance_file':
'test/test_files/scenario_test/training.txt',
'test_instance_file':
'test/test_files/scenario_test/test.txt',
'feature_file':
'test/test_files/scenario_test/features.txt',
'output_dir':
'test/test_files/scenario_test/tmp_output'}
self.output_dirs = []
self.output_files = []
self.output_dirs.append(self.test_scenario_dict['output_dir'])
def tearDown(self):
for output_dir in self.output_dirs:
if output_dir:
shutil.rmtree(output_dir, ignore_errors=True)
for output_file in self.output_files:
if output_file:
try:
os.remove(output_file)
except FileNotFoundError:
pass
os.chdir(self.current_dir)
def test_Exception(self):
with self.assertRaises(TypeError):
_ = Scenario(['a', 'b'])
def test_string_scenario(self):
scenario = Scenario('test/test_files/scenario_test/scenario.txt')
self.assertEqual(scenario.ta, ['echo', 'Hello'])
self.assertEqual(scenario.execdir, '.')
self.assertFalse(scenario.deterministic)
self.assertEqual(
scenario.pcs_fn, 'test/test_files/scenario_test/param.pcs')
self.assertEqual(scenario.overall_obj, 'mean10')
self.assertEqual(scenario.cutoff, 5.)
self.assertEqual(scenario.algo_runs_timelimit, np.inf)
self.assertEqual(scenario.wallclock_limit, 18000)
self.assertEqual(scenario.par_factor, 10)
self.assertEqual(scenario.train_insts, ['d', 'e', 'f'])
self.assertEqual(scenario.test_insts, ['a', 'b', 'c'])
test_dict = {'d': 1, 'e': 2, 'f': 3}
self.assertEqual(scenario.feature_dict, test_dict)
self.assertEqual(scenario.feature_array[0], 1)
def test_dict_scenario(self):
scenario = Scenario(self.test_scenario_dict)
self.assertEqual(scenario.ta, ['echo', 'Hello'])
self.assertEqual(scenario.execdir, '.')
self.assertFalse(scenario.deterministic)
self.assertEqual(
scenario.pcs_fn, 'test/test_files/scenario_test/param.pcs')
self.assertEqual(scenario.overall_obj, 'mean10')
self.assertEqual(scenario.cutoff, 5.)
self.assertEqual(scenario.algo_runs_timelimit, np.inf)
self.assertEqual(scenario.wallclock_limit, 18000)
self.assertEqual(scenario.par_factor, 10)
self.assertEqual(scenario.train_insts, ['d', 'e', 'f'])
self.assertEqual(scenario.test_insts, ['a', 'b', 'c'])
test_dict = {'d': 1, 'e': 2, 'f': 3}
self.assertEqual(scenario.feature_dict, test_dict)
self.assertEqual(scenario.feature_array[0], 1)
def unknown_parameter_in_scenario(self):
self.assertRaisesRegex(ValueError,
'Could not parse the following arguments: '
'duairznbvulncbzpneairzbnuqdae',
Scenario,
{'wallclock-limit': '12345',
'duairznbvulncbzpneairzbnuqdae': 'uqpab'})
def test_merge_foreign_data(self):
''' test smac.utils.merge_foreign_data '''
scenario = Scenario(self.test_scenario_dict)
scenario_2 = Scenario(self.test_scenario_dict)
scenario_2.feature_dict = {"inst_new": [4]}
# init cs
cs = ConfigurationSpace()
cs.add_hyperparameter(UniformIntegerHyperparameter(name='a',
lower=0,
upper=100))
cs.add_hyperparameter(UniformIntegerHyperparameter(name='b',
lower=0,
upper=100))
# build runhistory
rh_merge = RunHistory()
config = Configuration(cs, values={'a': 1, 'b': 2})
rh_merge.add(config=config, instance_id="inst_new", cost=10, time=20,
status=StatusType.SUCCESS,
seed=None,
additional_info=None)
# "d" is an instance in <scenario>
rh_merge.add(config=config, instance_id="d", cost=5, time=20,
status=StatusType.SUCCESS,
seed=None,
additional_info=None)
# build empty rh
rh_base = RunHistory()
merge_foreign_data(scenario=scenario, runhistory=rh_base,
in_scenario_list=[scenario_2], in_runhistory_list=[rh_merge])
# both runs should be in the runhistory
# but we should not use the data to update the cost of config
self.assertTrue(len(rh_base.data) == 2)
self.assertTrue(np.isnan(rh_base.get_cost(config)))
# we should not get direct access to external run data
runs = rh_base.get_runs_for_config(config, only_max_observed_budget=True)
self.assertTrue(len(runs) == 0)
rh_merge.add(config=config, instance_id="inst_new_2", cost=10, time=20,
status=StatusType.SUCCESS,
seed=None,
additional_info=None)
self.assertRaises(ValueError, merge_foreign_data, **{
"scenario": scenario, "runhistory": rh_base,
"in_scenario_list": [scenario_2], "in_runhistory_list": [rh_merge]})
def test_pickle_dump(self):
scenario = Scenario(self.test_scenario_dict)
packed_scenario = pickle.dumps(scenario)
self.assertIsNotNone(packed_scenario)
unpacked_scenario = pickle.loads(packed_scenario)
self.assertIsNotNone(unpacked_scenario)
self.assertIsNotNone(unpacked_scenario.logger)
self.assertEqual(scenario.logger.name, unpacked_scenario.logger.name)
def test_write(self):
""" Test whether a reloaded scenario still holds all the necessary
information. A subset of parameters might change, such as the paths to
pcs- or instance-files, so they are checked manually. """
def check_scen_eq(scen1, scen2):
print('check_scen_eq')
""" Customized check for scenario-equality, ignoring file-paths """
for name in scen1._arguments:
dest = scen1._arguments[name]['dest']
name = dest if dest else name # if 'dest' is None, use 'name'
if name in ["pcs_fn", "train_inst_fn", "test_inst_fn",
"feature_fn", "output_dir"]:
continue # Those values are allowed to change when writing to disk
elif name == 'cs':
# Using repr because of cs-bug
# (https://github.com/automl/ConfigSpace/issues/25)
self.assertEqual(repr(scen1.cs), repr(scen2.cs))
elif name == 'feature_dict':
self.assertEqual(len(scen1.feature_dict),
len(scen2.feature_dict))
for key in scen1.feature_dict:
self.assertTrue((scen1.feature_dict[key] == scen2.feature_dict[key]).all())
else:
print(name, getattr(scen1, name), getattr(scen2, name))
self.assertEqual(getattr(scen1, name),
getattr(scen2, name))
# First check with file-paths defined
feature_filename = 'test/test_files/scenario_test/features_multiple.txt'
feature_filename = os.path.abspath(feature_filename)
self.test_scenario_dict['feature_file'] = feature_filename
scenario = Scenario(self.test_scenario_dict)
# This injection would usually happen by the facade object!
scenario.output_dir_for_this_run = scenario.output_dir
scenario.write()
path = os.path.join(scenario.output_dir, 'scenario.txt')
scenario_reloaded = Scenario(path)
check_scen_eq(scenario, scenario_reloaded)
# Test whether json is the default pcs_fn
self.assertTrue(os.path.exists(os.path.join(scenario.output_dir, 'param.pcs')))
self.assertTrue(os.path.exists(os.path.join(scenario.output_dir, 'param.json')))
self.assertEqual(scenario_reloaded.pcs_fn, os.path.join(scenario.output_dir, 'param.json'))
# Now create new scenario without filepaths
self.test_scenario_dict.update({
'paramfile': None, 'cs': scenario.cs,
'feature_file': None, 'features': scenario.feature_dict,
'feature_names': scenario.feature_names,
'instance_file': None, 'instances': scenario.train_insts,
'test_instance_file': None, 'test_instances': scenario.test_insts})
logging.debug(scenario_reloaded)
scenario_no_fn = Scenario(self.test_scenario_dict)
scenario_reloaded = Scenario(path)
check_scen_eq(scenario_no_fn, scenario_reloaded)
# Test whether json is the default pcs_fn
self.assertTrue(os.path.exists(os.path.join(scenario.output_dir, 'param.pcs')))
self.assertTrue(os.path.exists(os.path.join(scenario.output_dir, 'param.json')))
self.assertEqual(scenario_reloaded.pcs_fn, os.path.join(scenario.output_dir, 'param.json'))
@mock.patch.object(os, 'makedirs')
@mock.patch.object(os.path, 'isdir')
def test_write_except(self, patch_isdir, patch_mkdirs):
patch_isdir.return_value = False
patch_mkdirs.side_effect = OSError()
scenario = Scenario(self.test_scenario_dict)
# This injection would usually happen by the facade object!
scenario.output_dir_for_this_run = scenario.output_dir
with self.assertRaises(OSError):
scenario.write()
def test_no_output_dir(self):
self.test_scenario_dict['output_dir'] = ""
scenario = Scenario(self.test_scenario_dict)
self.assertFalse(scenario.out_writer.write_scenario_file(scenario))
def test_par_factor(self):
# Test setting the default value of 1 if no factor is given
scenario_dict = self.test_scenario_dict
scenario_dict['overall_obj'] = 'mean'
scenario = Scenario(scenario_dict)
self.assertEqual(scenario.par_factor, 1)
scenario_dict['overall_obj'] = 'par'
scenario = Scenario(scenario_dict)
self.assertEqual(scenario.par_factor, 1)
def test_truth_value(self):
self.assertTrue(_is_truthy("1"))
self.assertTrue(_is_truthy("true"))
self.assertTrue(_is_truthy(True))
self.assertFalse(_is_truthy("0"))
self.assertFalse(_is_truthy("false"))
self.assertFalse(_is_truthy(False))
self.assertRaises(ValueError, _is_truthy, "something")
def test_str_cast_instances(self):
self.scen = Scenario({'cs': None,
'instances': [[1], [2]],
'run_obj': 'quality'})
self.assertIsInstance(self.scen.train_insts[0], str)
self.assertIsInstance(self.scen.train_insts[1], str)
def test_features(self):
cmd_options = {
'feature_file': 'test/test_files/features_example.csv',
'instance_file': 'test/test_files/train_insts_example.txt'
}
scenario = Scenario(self.test_scenario_dict,
cmd_options=cmd_options)
self.assertEqual(scenario.feature_names,
['feature1', 'feature2', 'feature3'])
if __name__ == "__main__":
unittest.main()
| 6,787 |
1,102 | <gh_stars>1000+
// Copyright (c) 2006, 2007 <NAME>
// Copyright (c) 2008 <NAME>, <NAME>
// Copyright (c) 2009 <NAME>
// Copyright (c) 2010 <NAME>, <NAME>
// Copyright (c) 2011, 2012 <NAME>, <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PROCESS_POSIX_INITIALIZERS_SET_ARGS_HPP
#define BOOST_PROCESS_POSIX_INITIALIZERS_SET_ARGS_HPP
#include <boost/process/posix/initializers/initializer_base.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <boost/shared_array.hpp>
#include <string>
namespace boost { namespace process { namespace posix { namespace initializers {
template <class Range>
class set_args_ : public initializer_base
{
private:
static char *c_str(const std::string &s)
{
return const_cast<char*>(s.c_str());
}
public:
explicit set_args_(const Range &args)
{
args_.reset(new char*[args.size() + 1]);
boost::transform(args, args_.get(), c_str);
args_[args.size()] = 0;
}
template <class PosixExecutor>
void on_exec_setup(PosixExecutor &e) const
{
e.cmd_line = args_.get();
if (!e.exe && *args_[0])
e.exe = args_[0];
}
private:
boost::shared_array<char*> args_;
};
template <class Range>
set_args_<Range> set_args(const Range &range)
{
return set_args_<Range>(range);
}
}}}}
#endif
| 593 |
1,405 | <filename>sample4/recompiled_java/sources/com/lenovo/safecenter/systeminfo/service/CallerlocQueryService.java
package com.lenovo.safecenter.systeminfo.service;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.lenovo.safecenter.systeminfo.db.DBHelper;
public class CallerlocQueryService {
private static final String a = CallerlocQueryService.class.getSimpleName();
private static CallerlocQueryService b = new CallerlocQueryService();
private CallerlocQueryService() {
}
public static CallerlocQueryService getInstance() {
return b;
}
public String queryByAreaCode(String areaCode) {
String result = null;
if (areaCode == null || "".equals(areaCode)) {
return null;
}
SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
Cursor cursor = db.query(" numdata ", null, " area_code=? ", new String[]{areaCode}, null, null, null);
if (cursor.moveToNext()) {
result = cursor.getString(cursor.getColumnIndex("province")) + cursor.getString(cursor.getColumnIndex("city"));
}
cursor.close();
db.close();
return result;
}
public String queryByNumberSegment(String numberSegment) {
String result = null;
if (numberSegment == null || "".equals(numberSegment) || numberSegment.length() < 7) {
return null;
}
if (numberSegment.length() > 7) {
numberSegment = numberSegment.substring(0, 7);
Log.i(a, numberSegment);
}
SQLiteDatabase db = DBHelper.getInstance().getReadableDatabase();
Cursor cursor = db.query(" numdata ", null, " num_segment=? ", new String[]{numberSegment}, null, null, null);
if (cursor.moveToNext()) {
result = (cursor.getString(cursor.getColumnIndex("province")) + " " + cursor.getString(cursor.getColumnIndex("city"))) + cursor.getString(cursor.getColumnIndex("carry"));
}
cursor.close();
db.close();
return result;
}
}
| 822 |
2,151 | <reponame>zipated/src
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_COMMON_API_DECLARATIVE_NET_REQUEST_CONSTANTS_H_
#define EXTENSIONS_COMMON_API_DECLARATIVE_NET_REQUEST_CONSTANTS_H_
namespace extensions {
namespace declarative_net_request {
// Permission name.
extern const char kAPIPermission[];
// Minimum valid value of a declarative rule ID.
constexpr int kMinValidID = 1;
// Minimum valid value of a declarative rule priority.
constexpr int kMinValidPriority = 1;
// Default priority used for rules when the priority is not explicity provided
// by an extension.
constexpr int kDefaultPriority = 1;
// Keys used in rules.
extern const char kIDKey[];
extern const char kPriorityKey[];
extern const char kRuleConditionKey[];
extern const char kRuleActionKey[];
extern const char kUrlFilterKey[];
extern const char kIsUrlFilterCaseSensitiveKey[];
extern const char kDomainsKey[];
extern const char kExcludedDomainsKey[];
extern const char kResourceTypesKey[];
extern const char kExcludedResourceTypesKey[];
extern const char kDomainTypeKey[];
extern const char kRuleActionTypeKey[];
extern const char kRedirectUrlKey[];
} // namespace declarative_net_request
} // namespace extensions
#endif // EXTENSIONS_COMMON_API_DECLARATIVE_NET_REQUEST_CONSTANTS_H_
| 443 |
662 | /**
* @author <NAME>
* Copyright (C) 2010 <NAME>
* Imperial College London
**/
#include <pangolin/pangolin.h>
void SetGlFormat(GLint& glformat, GLenum& gltype, const pangolin::PixelFormat& fmt)
{
switch( fmt.channels) {
case 1: glformat = GL_LUMINANCE; break;
case 3: glformat = GL_RGB; break;
case 4: glformat = GL_RGBA; break;
default: throw std::runtime_error("Unable to display video format");
}
switch (fmt.channel_bits[0]) {
case 8: gltype = GL_UNSIGNED_BYTE; break;
case 16: gltype = GL_UNSIGNED_SHORT; break;
case 32: gltype = GL_FLOAT; break;
default: throw std::runtime_error("Unknown channel format");
}
}
void VideoSample(const std::string uri)
{
// Setup Video Source
pangolin::VideoInput video(uri);
const pangolin::PixelFormat vid_fmt = video.PixFormat();
const unsigned w = video.Width();
const unsigned h = video.Height();
// Work out appropriate GL channel and format options
GLint glformat;
GLenum gltype;
SetGlFormat(glformat, gltype, vid_fmt);
// Create OpenGL window
pangolin::CreateWindowAndBind("Main",w,h);
// Create viewport for video with fixed aspect
pangolin::View& vVideo = pangolin::Display("Video").SetAspect((float)w/h);
// OpenGl Texture for video frame.
pangolin::GlTexture texVideo(w,h,glformat,false,0,glformat,gltype);
unsigned char* img = new unsigned char[video.SizeBytes()];
for(int frame=0; !pangolin::ShouldQuit(); ++frame)
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
if( video.GrabNext(img,true) ) {
texVideo.Upload( img, glformat, gltype );
}
// Activate video viewport and render texture
vVideo.Activate();
texVideo.RenderToViewportFlipY();
// Swap back buffer with front and process window events
pangolin::FinishFrame();
}
delete[] img;
}
int main( int argc, char* argv[] )
{
std::string uris[] = {
"dc1394:[fps=30,dma=10,size=640x480,iso=400]//0",
"convert:[fmt=RGB24]//v4l:///dev/video0",
"convert:[fmt=RGB24]//v4l:///dev/video1",
"openni:[img1=rgb]//",
"pleora:[sn=00000215,size=640x480,pos=64x64]//",
"test:[size=160x120,n=1,fmt=RGB24]//"
""
};
if( argc > 1 ) {
const std::string uri = std::string(argv[1]);
VideoSample(uri);
}else{
std::cout << "Usage : SimpleRecord [video-uri]" << std::endl << std::endl;
std::cout << "Where video-uri describes a stream or file resource, e.g." << std::endl;
std::cout << "\tfile:[realtime=1]///home/user/video/movie.pvn" << std::endl;
std::cout << "\tfile:///home/user/video/movie.avi" << std::endl;
std::cout << "\tfiles:///home/user/seqiemce/foo%03d.jpeg" << std::endl;
std::cout << "\tdc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]//0" << std::endl;
std::cout << "\tdc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]//0" << std::endl;
std::cout << "\tv4l:///dev/video0" << std::endl;
std::cout << "\tconvert:[fmt=RGB24]//v4l:///dev/video0" << std::endl;
std::cout << "\tmjpeg://http://127.0.0.1/?action=stream" << std::endl;
std::cout << "\topenni:[img1=rgb]//" << std::endl;
std::cout << std::endl;
// Try to open some video device
for(int i=0; !uris[i].empty(); ++i )
{
try{
std::cout << "Trying: " << uris[i] << std::endl;
VideoSample(uris[i]);
return 0;
}catch(const pangolin::VideoException&) { }
}
}
return 0;
}
| 1,688 |
348 | {"nom":"Pannecières","circ":"5ème circonscription","dpt":"Loiret","inscrits":84,"abs":49,"votants":35,"blancs":2,"nuls":1,"exp":32,"res":[{"nuance":"LR","nom":"<NAME>","voix":27},{"nuance":"REM","nom":"<NAME>","voix":5}]} | 91 |
1,993 | /*
* Copyright 2013-2020 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package brave;
import brave.propagation.TraceContext;
import brave.sampler.SamplerFunction;
/**
* Abstract request type used for parsing and sampling. When implemented, it will be the parameter
* of {@link SamplerFunction} or {@link TraceContext.Extractor}.
*
* <h3>No extensions outside Brave</h3>
* While this is an abstract type, it should not be subclassed outside the Brave repository. In
* other words, subtypes are sealed within this source tree.
*
* @see SamplerFunction
* @see TraceContext.Extractor
* @see TraceContext.Injector
* @see Response
* @since 5.9
*/
public abstract class Request {
/** The remote {@link Span.Kind} describing the direction and type of the request. */
public abstract Span.Kind spanKind();
/**
* Returns the underlying request object or {@code null} if there is none. Here are some request
* objects: {@code org.apache.http.HttpRequest}, {@code org.apache.dubbo.rpc.Invocation}, {@code
* org.apache.kafka.clients.consumer.ConsumerRecord}.
*
* <p>Note: Some implementations are composed of multiple types, such as a request and a socket
* address of the client. Moreover, an implementation may change the type returned due to
* refactoring. Unless you control the implementation, cast carefully (ex using {@code
* instanceof}) instead of presuming a specific type will always be returned.
*
* @since 5.9
*/
public abstract Object unwrap();
@Override public String toString() {
Object unwrapped = unwrap();
// handles case where unwrap() returning this or null: don't NPE or stack overflow!
if (unwrapped == null || unwrapped == this) return getClass().getSimpleName();
return getClass().getSimpleName() + "{" + unwrapped + "}";
}
protected Request() { // no instances of this type: only subtypes
}
}
| 668 |
403 | <filename>snippets/camunda-openapi-client/camunda-openapi-client-spring/src/main/java/com/camunda/consulting/openapi/client/model/ExternalTaskBpmnErrorAllOf.java<gh_stars>100-1000
/*
* Camunda Platform REST API
* OpenApi Spec for Camunda Platform REST API.
*
* The version of the OpenAPI document: 7.16.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.camunda.consulting.openapi.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* ExternalTaskBpmnErrorAllOf
*/
@JsonPropertyOrder({
ExternalTaskBpmnErrorAllOf.JSON_PROPERTY_WORKER_ID
})
@JsonTypeName("ExternalTaskBpmnError_allOf")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-11-19T11:53:20.948992+01:00[Europe/Berlin]")
public class ExternalTaskBpmnErrorAllOf {
public static final String JSON_PROPERTY_WORKER_ID = "workerId";
private String workerId;
public ExternalTaskBpmnErrorAllOf workerId(String workerId) {
this.workerId = workerId;
return this;
}
/**
* The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task.
* @return workerId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The id of the worker that reports the failure. Must match the id of the worker who has most recently locked the task.")
@JsonProperty(JSON_PROPERTY_WORKER_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getWorkerId() {
return workerId;
}
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExternalTaskBpmnErrorAllOf externalTaskBpmnErrorAllOf = (ExternalTaskBpmnErrorAllOf) o;
return Objects.equals(this.workerId, externalTaskBpmnErrorAllOf.workerId);
}
@Override
public int hashCode() {
return Objects.hash(workerId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ExternalTaskBpmnErrorAllOf {\n");
sb.append(" workerId: ").append(toIndentedString(workerId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 1,102 |
793 | <filename>lib/APINotes/APINotesReader.cpp
//===--- APINotesReader.cpp - Side Car Reader --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c APINotesReader class that reads source
// API notes data providing additional information about source code as
// a separate input, such as the non-nil/nilable annotations for
// method parameters.
//
//===----------------------------------------------------------------------===//
#include "clang/APINotes/APINotesReader.h"
#include "APINotesFormat.h"
#include "llvm/Bitcode/BitstreamReader.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/StringExtras.h"
using namespace clang;
using namespace api_notes;
using namespace llvm::support;
using namespace llvm;
namespace {
/// Deserialize a version tuple.
VersionTuple readVersionTuple(const uint8_t *&data) {
uint8_t numVersions = (*data++) & 0x03;
unsigned major = endian::readNext<uint32_t, little, unaligned>(data);
if (numVersions == 0)
return VersionTuple(major);
unsigned minor = endian::readNext<uint32_t, little, unaligned>(data);
if (numVersions == 1)
return VersionTuple(major, minor);
unsigned subminor = endian::readNext<uint32_t, little, unaligned>(data);
if (numVersions == 2)
return VersionTuple(major, minor, subminor);
unsigned build = endian::readNext<uint32_t, little, unaligned>(data);
return VersionTuple(major, minor, subminor, build);
}
/// An on-disk hash table whose data is versioned based on the Swift version.
template<typename Derived, typename KeyType, typename UnversionedDataType>
class VersionedTableInfo {
public:
using internal_key_type = KeyType;
using external_key_type = KeyType;
using data_type = SmallVector<std::pair<VersionTuple, UnversionedDataType>, 1>;
using hash_value_type = size_t;
using offset_type = unsigned;
internal_key_type GetInternalKey(external_key_type key) {
return key;
}
external_key_type GetExternalKey(internal_key_type key) {
return key;
}
hash_value_type ComputeHash(internal_key_type key) {
return static_cast<size_t>(llvm::hash_value(key));
}
static bool EqualKey(internal_key_type lhs, internal_key_type rhs) {
return lhs == rhs;
}
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const uint8_t *&data) {
unsigned keyLength = endian::readNext<uint16_t, little, unaligned>(data);
unsigned dataLength = endian::readNext<uint16_t, little, unaligned>(data);
return { keyLength, dataLength };
}
static data_type ReadData(internal_key_type key, const uint8_t *data,
unsigned length) {
unsigned numElements = endian::readNext<uint16_t, little, unaligned>(data);
data_type result;
result.reserve(numElements);
for (unsigned i = 0; i != numElements; ++i) {
auto version = readVersionTuple(data);
auto dataBefore = data; (void)dataBefore;
auto unversionedData = Derived::readUnversioned(key, data);
assert(data != dataBefore
&& "Unversioned data reader didn't move pointer");
result.push_back({version, unversionedData});
}
return result;
}
};
/// Read serialized CommonEntityInfo.
void readCommonEntityInfo(const uint8_t *&data, CommonEntityInfo &info) {
uint8_t unavailableBits = *data++;
info.Unavailable = (unavailableBits >> 1) & 0x01;
info.UnavailableInSwift = unavailableBits & 0x01;
if ((unavailableBits >> 2) & 0x01)
info.setSwiftPrivate(static_cast<bool>((unavailableBits >> 3) & 0x01));
unsigned msgLength = endian::readNext<uint16_t, little, unaligned>(data);
info.UnavailableMsg
= std::string(reinterpret_cast<const char *>(data),
reinterpret_cast<const char *>(data) + msgLength);
data += msgLength;
unsigned swiftNameLength
= endian::readNext<uint16_t, little, unaligned>(data);
info.SwiftName
= std::string(reinterpret_cast<const char *>(data),
reinterpret_cast<const char *>(data) + swiftNameLength);
data += swiftNameLength;
}
/// Read serialized CommonTypeInfo.
void readCommonTypeInfo(const uint8_t *&data, CommonTypeInfo &info) {
readCommonEntityInfo(data, info);
unsigned swiftBridgeLength =
endian::readNext<uint16_t, little, unaligned>(data);
if (swiftBridgeLength > 0) {
info.setSwiftBridge(
std::string(reinterpret_cast<const char *>(data), swiftBridgeLength-1));
data += swiftBridgeLength-1;
}
unsigned errorDomainLength =
endian::readNext<uint16_t, little, unaligned>(data);
if (errorDomainLength > 0) {
info.setNSErrorDomain(
std::string(reinterpret_cast<const char *>(data), errorDomainLength-1));
data += errorDomainLength-1;
}
}
/// Used to deserialize the on-disk identifier table.
class IdentifierTableInfo {
public:
using internal_key_type = StringRef;
using external_key_type = StringRef;
using data_type = IdentifierID;
using hash_value_type = uint32_t;
using offset_type = unsigned;
internal_key_type GetInternalKey(external_key_type key) {
return key;
}
external_key_type GetExternalKey(internal_key_type key) {
return key;
}
hash_value_type ComputeHash(internal_key_type key) {
return llvm::djbHash(key);
}
static bool EqualKey(internal_key_type lhs, internal_key_type rhs) {
return lhs == rhs;
}
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const uint8_t *&data) {
unsigned keyLength = endian::readNext<uint16_t, little, unaligned>(data);
unsigned dataLength = endian::readNext<uint16_t, little, unaligned>(data);
return { keyLength, dataLength };
}
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
return StringRef(reinterpret_cast<const char *>(data), length);
}
static data_type ReadData(internal_key_type key, const uint8_t *data,
unsigned length) {
return endian::readNext<uint32_t, little, unaligned>(data);
}
};
/// Used to deserialize the on-disk Objective-C class table.
class ObjCContextIDTableInfo {
public:
// identifier ID, is-protocol
using internal_key_type = std::pair<unsigned, char>;
using external_key_type = internal_key_type;
using data_type = unsigned;
using hash_value_type = size_t;
using offset_type = unsigned;
internal_key_type GetInternalKey(external_key_type key) {
return key;
}
external_key_type GetExternalKey(internal_key_type key) {
return key;
}
hash_value_type ComputeHash(internal_key_type key) {
return static_cast<size_t>(llvm::hash_value(key));
}
static bool EqualKey(internal_key_type lhs, internal_key_type rhs) {
return lhs == rhs;
}
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const uint8_t *&data) {
unsigned keyLength = endian::readNext<uint16_t, little, unaligned>(data);
unsigned dataLength = endian::readNext<uint16_t, little, unaligned>(data);
return { keyLength, dataLength };
}
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID
= endian::readNext<uint32_t, little, unaligned>(data);
auto isProtocol = endian::readNext<uint8_t, little, unaligned>(data);
return { nameID, isProtocol };
}
static data_type ReadData(internal_key_type key, const uint8_t *data,
unsigned length) {
return endian::readNext<uint32_t, little, unaligned>(data);
}
};
/// Used to deserialize the on-disk Objective-C property table.
class ObjCContextInfoTableInfo
: public VersionedTableInfo<ObjCContextInfoTableInfo,
unsigned,
ObjCContextInfo>
{
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
return endian::readNext<uint32_t, little, unaligned>(data);
}
static ObjCContextInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
ObjCContextInfo info;
readCommonTypeInfo(data, info);
uint8_t payload = *data++;
if (payload & 0x01)
info.setHasDesignatedInits(true);
payload = payload >> 1;
if (payload & 0x4)
info.setDefaultNullability(static_cast<NullabilityKind>(payload&0x03));
payload >>= 3;
if (payload & (1 << 1))
info.setSwiftObjCMembers(payload & 1);
payload >>= 2;
if (payload & (1 << 1))
info.setSwiftImportAsNonGeneric(payload & 1);
return info;
}
};
/// Read serialized VariableInfo.
void readVariableInfo(const uint8_t *&data, VariableInfo &info) {
readCommonEntityInfo(data, info);
if (*data++) {
info.setNullabilityAudited(static_cast<NullabilityKind>(*data));
}
++data;
auto typeLen
= endian::readNext<uint16_t, little, unaligned>(data);
info.setType(std::string(data, data + typeLen));
data += typeLen;
}
/// Used to deserialize the on-disk Objective-C property table.
class ObjCPropertyTableInfo
: public VersionedTableInfo<ObjCPropertyTableInfo,
std::tuple<unsigned, unsigned, char>,
ObjCPropertyInfo>
{
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto classID = endian::readNext<uint32_t, little, unaligned>(data);
auto nameID = endian::readNext<uint32_t, little, unaligned>(data);
char isInstance = endian::readNext<uint8_t, little, unaligned>(data);
return std::make_tuple(classID, nameID, isInstance);
}
static ObjCPropertyInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
ObjCPropertyInfo info;
readVariableInfo(data, info);
uint8_t flags = *data++;
if (flags & (1 << 0))
info.setSwiftImportAsAccessors(flags & (1 << 1));
return info;
}
};
/// Read serialized ParamInfo.
void readParamInfo(const uint8_t *&data, ParamInfo &info) {
readVariableInfo(data, info);
uint8_t payload = endian::readNext<uint8_t, little, unaligned>(data);
if (auto rawConvention = payload & 0x7) {
auto convention = static_cast<RetainCountConventionKind>(rawConvention-1);
info.setRetainCountConvention(convention);
}
payload >>= 3;
if (payload & 0x01) {
info.setNoEscape(payload & 0x02);
}
payload >>= 2; assert(payload == 0 && "Bad API notes");
}
/// Read serialized FunctionInfo.
void readFunctionInfo(const uint8_t *&data, FunctionInfo &info) {
readCommonEntityInfo(data, info);
uint8_t payload = endian::readNext<uint8_t, little, unaligned>(data);
if (auto rawConvention = payload & 0x7) {
auto convention = static_cast<RetainCountConventionKind>(rawConvention-1);
info.setRetainCountConvention(convention);
}
payload >>= 3;
info.NullabilityAudited = payload & 0x1;
payload >>= 1; assert(payload == 0 && "Bad API notes");
info.NumAdjustedNullable
= endian::readNext<uint8_t, little, unaligned>(data);
info.NullabilityPayload
= endian::readNext<uint64_t, little, unaligned>(data);
unsigned numParams = endian::readNext<uint16_t, little, unaligned>(data);
while (numParams > 0) {
ParamInfo pi;
readParamInfo(data, pi);
info.Params.push_back(pi);
--numParams;
}
unsigned resultTypeLen
= endian::readNext<uint16_t, little, unaligned>(data);
info.ResultType = std::string(data, data + resultTypeLen);
data += resultTypeLen;
}
/// Used to deserialize the on-disk Objective-C method table.
class ObjCMethodTableInfo
: public VersionedTableInfo<ObjCMethodTableInfo,
std::tuple<unsigned, unsigned, char>,
ObjCMethodInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto classID = endian::readNext<uint32_t, little, unaligned>(data);
auto selectorID = endian::readNext<uint32_t, little, unaligned>(data);
auto isInstance = endian::readNext<uint8_t, little, unaligned>(data);
return internal_key_type{ classID, selectorID, isInstance };
}
static ObjCMethodInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
ObjCMethodInfo info;
uint8_t payload = *data++;
info.Required = payload & 0x01;
payload >>= 1;
info.DesignatedInit = payload & 0x01;
payload >>= 1;
readFunctionInfo(data, info);
return info;
}
};
/// Used to deserialize the on-disk Objective-C selector table.
class ObjCSelectorTableInfo {
public:
using internal_key_type = StoredObjCSelector;
using external_key_type = internal_key_type;
using data_type = SelectorID;
using hash_value_type = unsigned;
using offset_type = unsigned;
internal_key_type GetInternalKey(external_key_type key) {
return key;
}
external_key_type GetExternalKey(internal_key_type key) {
return key;
}
hash_value_type ComputeHash(internal_key_type key) {
return llvm::DenseMapInfo<StoredObjCSelector>::getHashValue(key);
}
static bool EqualKey(internal_key_type lhs, internal_key_type rhs) {
return llvm::DenseMapInfo<StoredObjCSelector>::isEqual(lhs, rhs);
}
static std::pair<unsigned, unsigned>
ReadKeyDataLength(const uint8_t *&data) {
unsigned keyLength = endian::readNext<uint16_t, little, unaligned>(data);
unsigned dataLength = endian::readNext<uint16_t, little, unaligned>(data);
return { keyLength, dataLength };
}
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
internal_key_type key;
key.NumPieces = endian::readNext<uint16_t, little, unaligned>(data);
unsigned numIdents = (length - sizeof(uint16_t)) / sizeof(uint32_t);
for (unsigned i = 0; i != numIdents; ++i) {
key.Identifiers.push_back(
endian::readNext<uint32_t, little, unaligned>(data));
}
return key;
}
static data_type ReadData(internal_key_type key, const uint8_t *data,
unsigned length) {
return endian::readNext<uint32_t, little, unaligned>(data);
}
};
/// Used to deserialize the on-disk global variable table.
class GlobalVariableTableInfo
: public VersionedTableInfo<GlobalVariableTableInfo, unsigned,
GlobalVariableInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID = endian::readNext<uint32_t, little, unaligned>(data);
return nameID;
}
static GlobalVariableInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
GlobalVariableInfo info;
readVariableInfo(data, info);
return info;
}
};
/// Used to deserialize the on-disk global function table.
class GlobalFunctionTableInfo
: public VersionedTableInfo<GlobalFunctionTableInfo, unsigned,
GlobalFunctionInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID = endian::readNext<uint32_t, little, unaligned>(data);
return nameID;
}
static GlobalFunctionInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
GlobalFunctionInfo info;
readFunctionInfo(data, info);
return info;
}
};
/// Used to deserialize the on-disk enumerator table.
class EnumConstantTableInfo
: public VersionedTableInfo<EnumConstantTableInfo, unsigned,
EnumConstantInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID = endian::readNext<uint32_t, little, unaligned>(data);
return nameID;
}
static EnumConstantInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
EnumConstantInfo info;
readCommonEntityInfo(data, info);
return info;
}
};
/// Used to deserialize the on-disk tag table.
class TagTableInfo
: public VersionedTableInfo<TagTableInfo, unsigned, TagInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID = endian::readNext<IdentifierID, little, unaligned>(data);
return nameID;
}
static TagInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
TagInfo info;
uint8_t payload = *data++;
if (payload & 1) {
info.setFlagEnum(payload & 2);
}
payload >>= 2;
if (payload > 0) {
info.EnumExtensibility =
static_cast<EnumExtensibilityKind>((payload & 0x3) - 1);
}
readCommonTypeInfo(data, info);
return info;
}
};
/// Used to deserialize the on-disk typedef table.
class TypedefTableInfo
: public VersionedTableInfo<TypedefTableInfo, unsigned, TypedefInfo> {
public:
static internal_key_type ReadKey(const uint8_t *data, unsigned length) {
auto nameID = endian::readNext<IdentifierID, little, unaligned>(data);
return nameID;
}
static TypedefInfo readUnversioned(internal_key_type key,
const uint8_t *&data) {
TypedefInfo info;
uint8_t payload = *data++;
if (payload > 0) {
info.SwiftWrapper = static_cast<SwiftWrapperKind>((payload & 0x3) - 1);
}
readCommonTypeInfo(data, info);
return info;
}
};
} // end anonymous namespace
class APINotesReader::Implementation {
public:
/// The input buffer for the API notes data.
llvm::MemoryBuffer *InputBuffer;
/// Whether we own the input buffer.
bool OwnsInputBuffer;
/// The Swift version to use for filtering.
VersionTuple SwiftVersion;
/// The name of the module that we read from the control block.
std::string ModuleName;
// The size and modification time of the source file from
// which this API notes file was created, if known.
Optional<std::pair<off_t, time_t>> SourceFileSizeAndModTime;
/// Various options and attributes for the module
ModuleOptions ModuleOpts;
using SerializedIdentifierTable =
llvm::OnDiskIterableChainedHashTable<IdentifierTableInfo>;
/// The identifier table.
std::unique_ptr<SerializedIdentifierTable> IdentifierTable;
using SerializedObjCContextIDTable =
llvm::OnDiskIterableChainedHashTable<ObjCContextIDTableInfo>;
/// The Objective-C context ID table.
std::unique_ptr<SerializedObjCContextIDTable> ObjCContextIDTable;
using SerializedObjCContextInfoTable =
llvm::OnDiskIterableChainedHashTable<ObjCContextInfoTableInfo>;
/// The Objective-C context info table.
std::unique_ptr<SerializedObjCContextInfoTable> ObjCContextInfoTable;
using SerializedObjCPropertyTable =
llvm::OnDiskIterableChainedHashTable<ObjCPropertyTableInfo>;
/// The Objective-C property table.
std::unique_ptr<SerializedObjCPropertyTable> ObjCPropertyTable;
using SerializedObjCMethodTable =
llvm::OnDiskIterableChainedHashTable<ObjCMethodTableInfo>;
/// The Objective-C method table.
std::unique_ptr<SerializedObjCMethodTable> ObjCMethodTable;
using SerializedObjCSelectorTable =
llvm::OnDiskIterableChainedHashTable<ObjCSelectorTableInfo>;
/// The Objective-C selector table.
std::unique_ptr<SerializedObjCSelectorTable> ObjCSelectorTable;
using SerializedGlobalVariableTable =
llvm::OnDiskIterableChainedHashTable<GlobalVariableTableInfo>;
/// The global variable table.
std::unique_ptr<SerializedGlobalVariableTable> GlobalVariableTable;
using SerializedGlobalFunctionTable =
llvm::OnDiskIterableChainedHashTable<GlobalFunctionTableInfo>;
/// The global function table.
std::unique_ptr<SerializedGlobalFunctionTable> GlobalFunctionTable;
using SerializedEnumConstantTable =
llvm::OnDiskIterableChainedHashTable<EnumConstantTableInfo>;
/// The enumerator table.
std::unique_ptr<SerializedEnumConstantTable> EnumConstantTable;
using SerializedTagTable =
llvm::OnDiskIterableChainedHashTable<TagTableInfo>;
/// The tag table.
std::unique_ptr<SerializedTagTable> TagTable;
using SerializedTypedefTable =
llvm::OnDiskIterableChainedHashTable<TypedefTableInfo>;
/// The typedef table.
std::unique_ptr<SerializedTypedefTable> TypedefTable;
/// Retrieve the identifier ID for the given string, or an empty
/// optional if the string is unknown.
Optional<IdentifierID> getIdentifier(StringRef str);
/// Retrieve the selector ID for the given selector, or an empty
/// optional if the string is unknown.
Optional<SelectorID> getSelector(ObjCSelectorRef selector);
bool readControlBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readIdentifierBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readObjCContextBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readObjCPropertyBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readObjCMethodBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readObjCSelectorBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readGlobalVariableBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readGlobalFunctionBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readEnumConstantBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readTagBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
bool readTypedefBlock(llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch);
};
Optional<IdentifierID> APINotesReader::Implementation::getIdentifier(
StringRef str) {
if (!IdentifierTable)
return None;
if (str.empty())
return IdentifierID(0);
auto known = IdentifierTable->find(str);
if (known == IdentifierTable->end())
return None;
return *known;
}
Optional<SelectorID> APINotesReader::Implementation::getSelector(
ObjCSelectorRef selector) {
if (!ObjCSelectorTable || !IdentifierTable)
return None;
// Translate the identifiers.
StoredObjCSelector key;
key.NumPieces = selector.NumPieces;
for (auto ident : selector.Identifiers) {
if (auto identID = getIdentifier(ident)) {
key.Identifiers.push_back(*identID);
} else {
return None;
}
}
auto known = ObjCSelectorTable->find(key);
if (known == ObjCSelectorTable->end())
return None;
return *known;
}
bool APINotesReader::Implementation::readControlBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(CONTROL_BLOCK_ID))
return true;
bool sawMetadata = false;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown metadata sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case control_block::METADATA:
// Already saw metadata.
if (sawMetadata)
return true;
if (scratch[0] != VERSION_MAJOR || scratch[1] != VERSION_MINOR)
return true;
sawMetadata = true;
break;
case control_block::MODULE_NAME:
ModuleName = blobData.str();
break;
case control_block::MODULE_OPTIONS:
ModuleOpts.SwiftInferImportAsMember = (scratch.front() & 1) != 0;
break;
case control_block::SOURCE_FILE:
SourceFileSizeAndModTime = { scratch[0], scratch[1] };
break;
default:
// Unknown metadata record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return !sawMetadata;
}
bool APINotesReader::Implementation::readIdentifierBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(IDENTIFIER_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case identifier_block::IDENTIFIER_DATA: {
// Already saw identifier table.
if (IdentifierTable)
return true;
uint32_t tableOffset;
identifier_block::IdentifierDataLayout::readRecord(scratch, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
IdentifierTable.reset(
SerializedIdentifierTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readObjCContextBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(OBJC_CONTEXT_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case objc_context_block::OBJC_CONTEXT_ID_DATA: {
// Already saw Objective-C context ID table.
if (ObjCContextIDTable)
return true;
uint32_t tableOffset;
objc_context_block::ObjCContextIDLayout::readRecord(scratch, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
ObjCContextIDTable.reset(
SerializedObjCContextIDTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
case objc_context_block::OBJC_CONTEXT_INFO_DATA: {
// Already saw Objective-C context info table.
if (ObjCContextInfoTable)
return true;
uint32_t tableOffset;
objc_context_block::ObjCContextInfoLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
ObjCContextInfoTable.reset(
SerializedObjCContextInfoTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readObjCPropertyBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(OBJC_PROPERTY_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case objc_property_block::OBJC_PROPERTY_DATA: {
// Already saw Objective-C property table.
if (ObjCPropertyTable)
return true;
uint32_t tableOffset;
objc_property_block::ObjCPropertyDataLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
ObjCPropertyTable.reset(
SerializedObjCPropertyTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readObjCMethodBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(OBJC_METHOD_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case objc_method_block::OBJC_METHOD_DATA: {
// Already saw Objective-C method table.
if (ObjCMethodTable)
return true;
uint32_t tableOffset;
objc_method_block::ObjCMethodDataLayout::readRecord(scratch, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
ObjCMethodTable.reset(
SerializedObjCMethodTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readObjCSelectorBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(OBJC_SELECTOR_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case objc_selector_block::OBJC_SELECTOR_DATA: {
// Already saw Objective-C selector table.
if (ObjCSelectorTable)
return true;
uint32_t tableOffset;
objc_selector_block::ObjCSelectorDataLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
ObjCSelectorTable.reset(
SerializedObjCSelectorTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readGlobalVariableBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(GLOBAL_VARIABLE_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case global_variable_block::GLOBAL_VARIABLE_DATA: {
// Already saw global variable table.
if (GlobalVariableTable)
return true;
uint32_t tableOffset;
global_variable_block::GlobalVariableDataLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
GlobalVariableTable.reset(
SerializedGlobalVariableTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readGlobalFunctionBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(GLOBAL_FUNCTION_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case global_function_block::GLOBAL_FUNCTION_DATA: {
// Already saw global function table.
if (GlobalFunctionTable)
return true;
uint32_t tableOffset;
global_function_block::GlobalFunctionDataLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
GlobalFunctionTable.reset(
SerializedGlobalFunctionTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readEnumConstantBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(ENUM_CONSTANT_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case enum_constant_block::ENUM_CONSTANT_DATA: {
// Already saw enumerator table.
if (EnumConstantTable)
return true;
uint32_t tableOffset;
enum_constant_block::EnumConstantDataLayout::readRecord(scratch,
tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
EnumConstantTable.reset(
SerializedEnumConstantTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readTagBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(TAG_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case tag_block::TAG_DATA: {
// Already saw tag table.
if (TagTable)
return true;
uint32_t tableOffset;
tag_block::TagDataLayout::readRecord(scratch, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
TagTable.reset(
SerializedTagTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
bool APINotesReader::Implementation::readTypedefBlock(
llvm::BitstreamCursor &cursor,
SmallVectorImpl<uint64_t> &scratch) {
if (cursor.EnterSubBlock(TYPEDEF_BLOCK_ID))
return true;
auto next = cursor.advance();
while (next.Kind != llvm::BitstreamEntry::EndBlock) {
if (next.Kind == llvm::BitstreamEntry::Error)
return true;
if (next.Kind == llvm::BitstreamEntry::SubBlock) {
// Unknown sub-block, possibly for use by a future version of the
// API notes format.
if (cursor.SkipBlock())
return true;
next = cursor.advance();
continue;
}
scratch.clear();
StringRef blobData;
unsigned kind = cursor.readRecord(next.ID, scratch, &blobData);
switch (kind) {
case typedef_block::TYPEDEF_DATA: {
// Already saw typedef table.
if (TypedefTable)
return true;
uint32_t tableOffset;
typedef_block::TypedefDataLayout::readRecord(scratch, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
TypedefTable.reset(
SerializedTypedefTable::Create(base + tableOffset,
base + sizeof(uint32_t),
base));
break;
}
default:
// Unknown record, possibly for use by a future version of the
// module format.
break;
}
next = cursor.advance();
}
return false;
}
APINotesReader::APINotesReader(llvm::MemoryBuffer *inputBuffer,
bool ownsInputBuffer,
VersionTuple swiftVersion,
bool &failed)
: Impl(*new Implementation)
{
failed = false;
// Initialize the input buffer.
Impl.InputBuffer = inputBuffer;
Impl.OwnsInputBuffer = ownsInputBuffer;
Impl.SwiftVersion = swiftVersion;
llvm::BitstreamCursor cursor(*Impl.InputBuffer);
// Validate signature.
for (auto byte : API_NOTES_SIGNATURE) {
if (cursor.AtEndOfStream() || cursor.Read(8) != byte) {
failed = true;
return;
}
}
// Look at all of the blocks.
bool hasValidControlBlock = false;
SmallVector<uint64_t, 64> scratch;
while (!cursor.AtEndOfStream()) {
auto topLevelEntry = cursor.advance();
if (topLevelEntry.Kind != llvm::BitstreamEntry::SubBlock)
break;
switch (topLevelEntry.ID) {
case llvm::bitc::BLOCKINFO_BLOCK_ID:
if (!cursor.ReadBlockInfoBlock()) {
failed = true;
break;
}
break;
case CONTROL_BLOCK_ID:
// Only allow a single control block.
if (hasValidControlBlock || Impl.readControlBlock(cursor, scratch)) {
failed = true;
return;
}
hasValidControlBlock = true;
break;
case IDENTIFIER_BLOCK_ID:
if (!hasValidControlBlock || Impl.readIdentifierBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case OBJC_CONTEXT_BLOCK_ID:
if (!hasValidControlBlock || Impl.readObjCContextBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case OBJC_PROPERTY_BLOCK_ID:
if (!hasValidControlBlock ||
Impl.readObjCPropertyBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case OBJC_METHOD_BLOCK_ID:
if (!hasValidControlBlock || Impl.readObjCMethodBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case OBJC_SELECTOR_BLOCK_ID:
if (!hasValidControlBlock ||
Impl.readObjCSelectorBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case GLOBAL_VARIABLE_BLOCK_ID:
if (!hasValidControlBlock ||
Impl.readGlobalVariableBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case GLOBAL_FUNCTION_BLOCK_ID:
if (!hasValidControlBlock ||
Impl.readGlobalFunctionBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case ENUM_CONSTANT_BLOCK_ID:
if (!hasValidControlBlock ||
Impl.readEnumConstantBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case TAG_BLOCK_ID:
if (!hasValidControlBlock || Impl.readTagBlock(cursor, scratch)) {
failed = true;
return;
}
break;
case TYPEDEF_BLOCK_ID:
if (!hasValidControlBlock || Impl.readTypedefBlock(cursor, scratch)) {
failed = true;
return;
}
break;
default:
// Unknown top-level block, possibly for use by a future version of the
// module format.
if (cursor.SkipBlock()) {
failed = true;
return;
}
break;
}
}
if (!cursor.AtEndOfStream()) {
failed = true;
return;
}
}
APINotesReader::~APINotesReader() {
if (Impl.OwnsInputBuffer)
delete Impl.InputBuffer;
delete &Impl;
}
std::unique_ptr<APINotesReader>
APINotesReader::get(std::unique_ptr<llvm::MemoryBuffer> inputBuffer,
VersionTuple swiftVersion) {
bool failed = false;
std::unique_ptr<APINotesReader>
reader(new APINotesReader(inputBuffer.release(), /*ownsInputBuffer=*/true,
swiftVersion, failed));
if (failed)
return nullptr;
return reader;
}
std::unique_ptr<APINotesReader>
APINotesReader::getUnmanaged(llvm::MemoryBuffer *inputBuffer,
VersionTuple swiftVersion) {
bool failed = false;
std::unique_ptr<APINotesReader>
reader(new APINotesReader(inputBuffer, /*ownsInputBuffer=*/false,
swiftVersion, failed));
if (failed)
return nullptr;
return reader;
}
StringRef APINotesReader::getModuleName() const {
return Impl.ModuleName;
}
Optional<std::pair<off_t, time_t>>
APINotesReader::getSourceFileSizeAndModTime() const {
return Impl.SourceFileSizeAndModTime;
}
ModuleOptions APINotesReader::getModuleOptions() const {
return Impl.ModuleOpts;
}
template<typename T>
APINotesReader::VersionedInfo<T>::VersionedInfo(
VersionTuple version,
SmallVector<std::pair<VersionTuple, T>, 1> results)
: Results(std::move(results)) {
assert(!Results.empty());
assert(std::is_sorted(Results.begin(), Results.end(),
[](const std::pair<VersionTuple, T> &left,
const std::pair<VersionTuple, T> &right) -> bool {
assert(left.first != right.first && "two entries for the same version");
return left.first < right.first;
}));
Selected = Results.size();
for (unsigned i = 0, n = Results.size(); i != n; ++i) {
if (version && Results[i].first >= version) {
// If the current version is "4", then entries for 4 are better than
// entries for 5, but both are valid. Because entries are sorted, we get
// that behavior by picking the first match.
Selected = i;
break;
}
}
// If we didn't find a match but we have an unversioned result, use the
// unversioned result. This will always be the first entry because we encode
// it as version 0.
if (Selected == Results.size() && Results[0].first.empty())
Selected = 0;
}
auto APINotesReader::lookupObjCClassID(StringRef name) -> Optional<ContextID> {
if (!Impl.ObjCContextIDTable)
return None;
Optional<IdentifierID> classID = Impl.getIdentifier(name);
if (!classID)
return None;
auto knownID = Impl.ObjCContextIDTable->find({*classID, '\0'});
if (knownID == Impl.ObjCContextIDTable->end())
return None;
return ContextID(*knownID);
}
auto APINotesReader::lookupObjCClassInfo(StringRef name)
-> VersionedInfo<ObjCContextInfo> {
if (!Impl.ObjCContextInfoTable)
return None;
Optional<ContextID> contextID = lookupObjCClassID(name);
if (!contextID)
return None;
auto knownInfo = Impl.ObjCContextInfoTable->find(contextID->Value);
if (knownInfo == Impl.ObjCContextInfoTable->end())
return None;
return { Impl.SwiftVersion, *knownInfo };
}
auto APINotesReader::lookupObjCProtocolID(StringRef name)
-> Optional<ContextID> {
if (!Impl.ObjCContextIDTable)
return None;
Optional<IdentifierID> classID = Impl.getIdentifier(name);
if (!classID)
return None;
auto knownID = Impl.ObjCContextIDTable->find({*classID, '\1'});
if (knownID == Impl.ObjCContextIDTable->end())
return None;
return ContextID(*knownID);
}
auto APINotesReader::lookupObjCProtocolInfo(StringRef name)
-> VersionedInfo<ObjCContextInfo> {
if (!Impl.ObjCContextInfoTable)
return None;
Optional<ContextID> contextID = lookupObjCProtocolID(name);
if (!contextID)
return None;
auto knownInfo = Impl.ObjCContextInfoTable->find(contextID->Value);
if (knownInfo == Impl.ObjCContextInfoTable->end())
return None;
return { Impl.SwiftVersion, *knownInfo };
}
auto APINotesReader::lookupObjCProperty(ContextID contextID,
StringRef name,
bool isInstance)
-> VersionedInfo<ObjCPropertyInfo> {
if (!Impl.ObjCPropertyTable)
return None;
Optional<IdentifierID> propertyID = Impl.getIdentifier(name);
if (!propertyID)
return None;
auto known = Impl.ObjCPropertyTable->find(std::make_tuple(contextID.Value,
*propertyID,
(char)isInstance));
if (known == Impl.ObjCPropertyTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupObjCMethod(
ContextID contextID,
ObjCSelectorRef selector,
bool isInstanceMethod)
-> VersionedInfo<ObjCMethodInfo> {
if (!Impl.ObjCMethodTable)
return None;
Optional<SelectorID> selectorID = Impl.getSelector(selector);
if (!selectorID)
return None;
auto known = Impl.ObjCMethodTable->find(
ObjCMethodTableInfo::internal_key_type{
contextID.Value, *selectorID, isInstanceMethod});
if (known == Impl.ObjCMethodTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupGlobalVariable(
StringRef name)
-> VersionedInfo<GlobalVariableInfo> {
if (!Impl.GlobalVariableTable)
return None;
Optional<IdentifierID> nameID = Impl.getIdentifier(name);
if (!nameID)
return None;
auto known = Impl.GlobalVariableTable->find(*nameID);
if (known == Impl.GlobalVariableTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupGlobalFunction(StringRef name)
-> VersionedInfo<GlobalFunctionInfo> {
if (!Impl.GlobalFunctionTable)
return None;
Optional<IdentifierID> nameID = Impl.getIdentifier(name);
if (!nameID)
return None;
auto known = Impl.GlobalFunctionTable->find(*nameID);
if (known == Impl.GlobalFunctionTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupEnumConstant(StringRef name)
-> VersionedInfo<EnumConstantInfo> {
if (!Impl.EnumConstantTable)
return None;
Optional<IdentifierID> nameID = Impl.getIdentifier(name);
if (!nameID)
return None;
auto known = Impl.EnumConstantTable->find(*nameID);
if (known == Impl.EnumConstantTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupTag(StringRef name) -> VersionedInfo<TagInfo> {
if (!Impl.TagTable)
return None;
Optional<IdentifierID> nameID = Impl.getIdentifier(name);
if (!nameID)
return None;
auto known = Impl.TagTable->find(*nameID);
if (known == Impl.TagTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
auto APINotesReader::lookupTypedef(StringRef name)
-> VersionedInfo<TypedefInfo> {
if (!Impl.TypedefTable)
return None;
Optional<IdentifierID> nameID = Impl.getIdentifier(name);
if (!nameID)
return None;
auto known = Impl.TypedefTable->find(*nameID);
if (known == Impl.TypedefTable->end())
return None;
return { Impl.SwiftVersion, *known };
}
| 21,529 |
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.rs.security.saml;
import java.io.InputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import org.apache.cxf.common.util.CompressionUtils;
import org.apache.cxf.common.util.PropertyUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.PhaseInterceptorChain;
public class DeflateEncoderDecoder {
public InputStream inflateToken(byte[] deflatedToken)
throws DataFormatException {
return CompressionUtils.inflate(deflatedToken);
}
public byte[] deflateToken(byte[] tokenBytes) {
return deflateToken(tokenBytes, true);
}
public byte[] deflateToken(byte[] tokenBytes, boolean nowrap) {
return deflateToken(tokenBytes, getDeflateLevel(), nowrap);
}
public byte[] deflateToken(byte[] tokenBytes, int level, boolean nowrap) {
return CompressionUtils.deflate(tokenBytes, level, nowrap);
}
private static int getDeflateLevel() {
Integer level = null;
Message m = PhaseInterceptorChain.getCurrentMessage();
if (m != null) {
level = PropertyUtils.getInteger(m, "deflate.level");
}
if (level == null) {
level = Deflater.DEFLATED;
}
return level;
}
}
| 678 |
1,694 | <reponame>CrackerCat/iWeChat
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <MMCommon/WXPBGeneratedMessage.h>
@class AppStoreControl, BaseResponse, BestSellingGameListModule, DownloadGuidance, FeedBackEntrance, GameIndexMyGame, GameIndexNav, GameManagementEntrance, GetGameIndex2Response_Recommendation, IndexTheme, Installed, LibraryEntranceInfo, NSString, TypeNavModule;
@interface GetGameIndex2Response : WXPBGeneratedMessage
{
}
+ (void)initialize;
// Remaining properties
@property(retain, nonatomic) AppStoreControl *appStoreControl; // @dynamic appStoreControl;
@property(retain, nonatomic) NSString *appStoreGoodsId; // @dynamic appStoreGoodsId;
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(retain, nonatomic) BestSellingGameListModule *bestSellingGameList; // @dynamic bestSellingGameList;
@property(retain, nonatomic) FeedBackEntrance *feedBackEntrance; // @dynamic feedBackEntrance;
@property(nonatomic) unsigned int gameDetailJumpType; // @dynamic gameDetailJumpType;
@property(retain, nonatomic) NSString *gameDetailUrl; // @dynamic gameDetailUrl;
@property(retain, nonatomic) GameManagementEntrance *gameManagement; // @dynamic gameManagement;
@property(retain, nonatomic) GetGameIndex2Response_Recommendation *gameRecommendation; // @dynamic gameRecommendation;
@property(retain, nonatomic) DownloadGuidance *googlePlayTips; // @dynamic googlePlayTips;
@property(retain, nonatomic) Installed *installed; // @dynamic installed;
@property(nonatomic) _Bool isForeigner; // @dynamic isForeigner;
@property(retain, nonatomic) LibraryEntranceInfo *libraryEntrance; // @dynamic libraryEntrance;
@property(retain, nonatomic) GameIndexMyGame *myGame; // @dynamic myGame;
@property(retain, nonatomic) GameIndexNav *nav; // @dynamic nav;
@property(retain, nonatomic) IndexTheme *theme; // @dynamic theme;
@property(retain, nonatomic) TypeNavModule *typeNav; // @dynamic typeNav;
@end
| 642 |
1,362 | from powerfulseal.k8s import Pod
EXAMPLE_POD_ARGS1 = dict(
uid="someid",
name="name of some kind",
namespace="default",
)
EXAMPLE_POD_ARGS2 = dict(
name="name of some kind",
namespace="default",
)
def test_pods_are_deduplicated_with_uids():
collection = set()
collection.add(Pod(**EXAMPLE_POD_ARGS1))
collection.add(Pod(**EXAMPLE_POD_ARGS1))
assert len(collection) == 1
def test_pods_are_deduplicated_without_uids():
collection = set()
collection.add(Pod(**EXAMPLE_POD_ARGS2))
collection.add(Pod(**EXAMPLE_POD_ARGS2))
assert len(collection) == 1
| 258 |
679 | <filename>main/framework/inc/uielement/toolbarmerger.hxx
/**************************************************************
*
* 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 __FRAMEWORK_UIELEMENT_TOOLBARMERGER_HXX_
#define __FRAMEWORK_UIELEMENT_TOOLBARMERGER_HXX_
#include <uielement/comboboxtoolbarcontroller.hxx>
#include <uielement/imagebuttontoolbarcontroller.hxx>
#include <uielement/togglebuttontoolbarcontroller.hxx>
#include <uielement/buttontoolbarcontroller.hxx>
#include <uielement/spinfieldtoolbarcontroller.hxx>
#include <uielement/edittoolbarcontroller.hxx>
#include <uielement/dropdownboxtoolbarcontroller.hxx>
#include <uielement/commandinfo.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <svtools/toolboxcontroller.hxx>
#include <rtl/ustring.hxx>
#include <vcl/toolbox.hxx>
namespace framework
{
struct AddonsParams
{
::rtl::OUString aImageId;
::rtl::OUString aTarget;
::rtl::OUString aControlType;
};
struct AddonToolbarItem
{
::rtl::OUString aCommandURL;
::rtl::OUString aLabel;
::rtl::OUString aImageIdentifier;
::rtl::OUString aTarget;
::rtl::OUString aContext;
::rtl::OUString aControlType;
sal_uInt16 nWidth;
};
typedef ::std::vector< AddonToolbarItem > AddonToolbarItemContainer;
struct ReferenceToolbarPathInfo
{
ToolBox* pToolbar;
sal_uInt16 nPos;
bool bResult;
};
class ToolBarMerger
{
public:
static bool IsCorrectContext( const ::rtl::OUString& aContext, const ::rtl::OUString& aModuleIdentifier );
static bool ConvertSeqSeqToVector( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > rSequence,
AddonToolbarItemContainer& rContainer );
static void ConvertSequenceToValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > rSequence,
::rtl::OUString& rCommandURL,
::rtl::OUString& rLabel,
::rtl::OUString& rImageIdentifier,
::rtl::OUString& rTarget,
::rtl::OUString& rContext,
::rtl::OUString& rControlType,
sal_uInt16& rWidth );
static ReferenceToolbarPathInfo FindReferencePoint( ToolBox* pToolbar,
const ::rtl::OUString& rReferencePoint );
static bool ProcessMergeOperation( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
ToolBox* pToolbar,
sal_uInt16 nPos,
sal_uInt16& rItemId,
CommandToInfoMap& rCommandMap,
const ::rtl::OUString& rModuleIdentifier,
const ::rtl::OUString& rMergeCommand,
const ::rtl::OUString& rMergeCommandParameter,
const AddonToolbarItemContainer& rItems );
static bool ProcessMergeFallback( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
ToolBox* pToolbar,
sal_uInt16 nPos,
sal_uInt16& rItemId,
CommandToInfoMap& rCommandMap,
const ::rtl::OUString& rModuleIdentifier,
const ::rtl::OUString& rMergeCommand,
const ::rtl::OUString& rMergeFallback,
const AddonToolbarItemContainer& rItems );
static bool MergeItems( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
ToolBox* pToolbar,
sal_uInt16 nPos,
sal_uInt16 nModIndex,
sal_uInt16& rItemId,
CommandToInfoMap& rCommandMap,
const ::rtl::OUString& rModuleIdentifier,
const AddonToolbarItemContainer& rAddonToolbarItems );
static bool ReplaceItem( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
ToolBox* pToolbar,
sal_uInt16 nPos,
sal_uInt16& rItemId,
CommandToInfoMap& rCommandMap,
const ::rtl::OUString& rModuleIdentifier,
const AddonToolbarItemContainer& rAddonToolbarItems );
static bool RemoveItems( ToolBox* pToolbar,
sal_uInt16 nPos,
const ::rtl::OUString& rMergeCommandParameter );
static ::cppu::OWeakObject* CreateController(
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMGR,
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame,
ToolBox* pToolbar,
const ::rtl::OUString& rCommandURL,
sal_uInt16 nId,
sal_uInt16 nWidth,
const ::rtl::OUString& rControlType );
static void CreateToolbarItem( ToolBox* pToolbox,
CommandToInfoMap& rCommandMap,
sal_uInt16 nPos,
sal_uInt16 nItemId,
const AddonToolbarItem& rAddonToolbarItem );
private:
ToolBarMerger();
ToolBarMerger( const ToolBarMerger& );
ToolBarMerger& operator=( const ToolBarMerger& );
};
} // namespace framework
#endif // __FRAMEWORK_UIELEMENT_TOOLBARMERGER_HXX_
| 4,376 |
2,073 | /**
* 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.transport.https;
import org.apache.activemq.transport.http.HttpTransportHttpTraceTest;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class HttpsTransportHttpTraceTest extends HttpTransportHttpTraceTest {
public HttpsTransportHttpTraceTest(String enableTraceParam, int expectedStatus) {
super(enableTraceParam, expectedStatus);
}
@Override
protected String getConnectorUri() {
return "https://localhost:0?" + enableTraceParam;
}
@Override
public void additionalConfig() {
System.setProperty("javax.net.ssl.trustStore", "src/test/resources/client.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", "src/test/resources/server.keystore");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.keyStoreType", "jks");
}
}
| 593 |
634 | /*
* Copyright 2013-2017 consulo.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.ui.ex;
import consulo.disposer.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.WindowInfo;
import com.intellij.openapi.wm.impl.InternalDecoratorListener;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* @author VISTALL
* @since 12-Oct-17
*/
public interface ToolWindowInternalDecorator extends Disposable {
/**
* Catches all event from tool window and modifies decorator's appearance.
*/
String HIDE_ACTIVE_WINDOW_ACTION_ID = "HideActiveWindow";
String TOGGLE_PINNED_MODE_ACTION_ID = "TogglePinnedMode";
String TOGGLE_DOCK_MODE_ACTION_ID = "ToggleDockMode";
String TOGGLE_FLOATING_MODE_ACTION_ID = "ToggleFloatingMode";
String TOGGLE_WINDOWED_MODE_ACTION_ID = "ToggleWindowedMode";
String TOGGLE_SIDE_MODE_ACTION_ID = "ToggleSideMode";
String TOGGLE_CONTENT_UI_TYPE_ACTION_ID = "ToggleContentUiTypeMode";
@Nonnull
WindowInfo getWindowInfo();
void apply(@Nonnull WindowInfo windowInfo);
@Nonnull
ToolWindow getToolWindow();
void addInternalDecoratorListener(InternalDecoratorListener l);
void removeInternalDecoratorListener(InternalDecoratorListener l);
void fireActivated();
void fireHidden();
void fireHiddenSide();
@Nonnull
ActionGroup createPopupGroup();
boolean isFocused();
boolean hasFocus();
default void setTitleActions(AnAction... actions) {
}
default void setTabActions(AnAction... actions) {
}
default void setAdditionalGearActions(@Nullable ActionGroup gearActions) {
}
}
| 694 |
1,168 | /**
* The MIT License
* Copyright © 2010 JmxTrans team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.jmxtrans.model.output;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.googlecode.jmxtrans.exceptions.LifecycleException;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.Server;
import com.googlecode.jmxtrans.model.ValidationException;
import com.googlecode.jmxtrans.model.output.support.opentsdb.OpenTSDBMessageFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import static com.google.common.collect.ImmutableList.copyOf;
/**
* Originally written by <NAME> <bko<EMAIL>>. Common base class for OpenTSDBWriter and TCollectorWriter.
* Date: 4/4/13
* Time: 6:00 PM
* <p/>
* Updates by <NAME>
*/
public abstract class OpenTSDBGenericWriter extends BaseOutputWriter {
public static final boolean DEFAULT_MERGE_TYPE_NAMES_TAGS = true;
private static final Logger log = LoggerFactory.getLogger(OpenTSDBGenericWriter.class);
protected final String host;
protected final Integer port;
protected final OpenTSDBMessageFormatter messageFormatter;
@JsonCreator
public OpenTSDBGenericWriter(
@JsonProperty("typeNames") ImmutableList<String> typeNames,
@JsonProperty("booleanAsNumber") boolean booleanAsNumber,
@JsonProperty("debug") Boolean debugEnabled,
@JsonProperty("host") String host,
@JsonProperty("port") Integer port,
@JsonProperty("tags") Map<String, String> tags,
@JsonProperty("tagName") String tagName,
@JsonProperty("mergeTypeNamesTags") Boolean mergeTypeNamesTags,
@JsonProperty("metricNamingExpression") String metricNamingExpression,
@JsonProperty("addHostnameTag") Boolean addHostnameTag,
@JsonProperty("settings") Map<String, Object> settings) throws LifecycleException {
super(typeNames, booleanAsNumber, debugEnabled, settings);
this.host = MoreObjects.firstNonNull(host, (String) getSettings().get(HOST));
this.port = MoreObjects.firstNonNull(port, Settings.getIntegerSetting(getSettings(), PORT, null));
if (metricNamingExpression == null) {
metricNamingExpression = Settings.getStringSetting(this.getSettings(), "metricNamingExpression", null);
}
ImmutableList<String> nonNullTypeNames = copyOf(MoreObjects.firstNonNull(typeNames, Collections.<String>emptyList()));
messageFormatter = new OpenTSDBMessageFormatter(nonNullTypeNames, ImmutableMap.copyOf(
firstNonNull(
tags,
(Map<String, String>) getSettings().get("tags"),
ImmutableMap.<String, String>of())),
firstNonNull(tagName, (String) getSettings().get("tagName"), "type"),
metricNamingExpression,
MoreObjects.firstNonNull(
mergeTypeNamesTags,
Settings.getBooleanSetting(this.getSettings(), "mergeTypeNamesTags", DEFAULT_MERGE_TYPE_NAMES_TAGS)),
addHostnameTag);
}
/**
* Prepare for sending metrics, if needed. For use by subclasses.
*/
protected void prepareSender() throws LifecycleException {
}
/**
* Shutdown the sender, if needed. For use by subclasses.
*/
protected void shutdownSender() throws LifecycleException {
}
/**
* Prepare a batch of results output, if needed. For use by subclasses.
*/
protected void startOutput() throws IOException {
}
/**
* Subclass responsibility: specify the default value for the "addHostnameTag" setting.
*/
protected abstract boolean getAddHostnameTagDefault();
/**
* Subcall responsibility: method to perform the actual output for the given metric line. Every subclass
* <b>must</b> implement this method.
*
* @param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the
* "put" keyword expected by OpenTSDB and the trailing newline character.
*/
protected abstract void sendOutput(String metricLine) throws IOException;
/**
* Complete a batch of results output, if needed. For use by subclasses.
*/
protected void finishOutput() throws IOException {
}
/**
* Write the results of the query.
*
* @param server
* @param query - the query and its results.
* @param results
*/
@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
this.startOutput();
for (String formattedResult : messageFormatter.formatResults(results, server)) {
log.debug("Sending result: {}", formattedResult);
this.sendOutput(formattedResult);
}
this.finishOutput();
}
/**
* Validation per query, after the writer has been start()ed
*/
@Override
public void validateSetup(Server server, Query query) throws ValidationException {
}
/**
* Start the output writer. At this time, the settings are read from the configuration file and saved for later
* use.
*/
@Override
public void start() throws LifecycleException {
this.prepareSender();
}
@Override
public void close() throws LifecycleException {
this.shutdownSender();
}
}
| 1,927 |
1,282 | /* Copyright (C) 1995-1998 <NAME> (<EMAIL>)
* All rights reserved.
*
* This package is an SSL implementation written
* by <NAME>ung (<EMAIL>).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is <NAME> (<EMAIL>).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* <NAME> (<EMAIL>)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by <NAME> (t<EMAIL>)"
*
* THIS SOFTWARE IS PROVIDED BY <NAME> ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <openssl/sha.h>
#include <string.h>
#include <openssl/mem.h>
#include "internal.h"
#include "../../internal.h"
// The 32-bit hash algorithms share a common byte-order neutral collector and
// padding function implementations that operate on unaligned data,
// ../digest/md32_common.h. SHA-512 is the only 64-bit hash algorithm, as of
// this writing, so there is no need for a common collector/padding
// implementation yet.
static int sha512_final_impl(uint8_t *out, SHA512_CTX *sha);
int SHA384_Init(SHA512_CTX *sha) {
sha->h[0] = UINT64_C(0xcbbb9d5dc1059ed8);
sha->h[1] = UINT64_C(0x629a292a367cd507);
sha->h[2] = UINT64_C(0x9159015a3070dd17);
sha->h[3] = UINT64_C(0x152fecd8f70e5939);
sha->h[4] = UINT64_C(0x67332667ffc00b31);
sha->h[5] = UINT64_C(0x8eb44a8768581511);
sha->h[6] = UINT64_C(0xdb0c2e0d64f98fa7);
sha->h[7] = UINT64_C(0x47b5481dbefa4fa4);
sha->Nl = 0;
sha->Nh = 0;
sha->num = 0;
sha->md_len = SHA384_DIGEST_LENGTH;
return 1;
}
int SHA512_Init(SHA512_CTX *sha) {
sha->h[0] = UINT64_C(0x6a09e667f3bcc908);
sha->h[1] = UINT64_C(0xbb67ae8584caa73b);
sha->h[2] = UINT64_C(0x3c6ef372fe94f82b);
sha->h[3] = UINT64_C(0xa54ff53a5f1d36f1);
sha->h[4] = UINT64_C(0x510e527fade682d1);
sha->h[5] = UINT64_C(0x9b05688c2b3e6c1f);
sha->h[6] = UINT64_C(0x1f83d9abfb41bd6b);
sha->h[7] = UINT64_C(0x5be0cd19137e2179);
sha->Nl = 0;
sha->Nh = 0;
sha->num = 0;
sha->md_len = SHA512_DIGEST_LENGTH;
return 1;
}
int SHA512_256_Init(SHA512_CTX *sha) {
sha->h[0] = UINT64_C(0x22312194fc2bf72c);
sha->h[1] = UINT64_C(0x9f555fa3c84c64c2);
sha->h[2] = UINT64_C(0x2393b86b6f53b151);
sha->h[3] = UINT64_C(0x963877195940eabd);
sha->h[4] = UINT64_C(0x96283ee2a88effe3);
sha->h[5] = UINT64_C(0xbe5e1e2553863992);
sha->h[6] = UINT64_C(0x2b0199fc2c85b8aa);
sha->h[7] = UINT64_C(0x0eb72ddc81c52ca2);
sha->Nl = 0;
sha->Nh = 0;
sha->num = 0;
sha->md_len = SHA512_256_DIGEST_LENGTH;
return 1;
}
uint8_t *SHA384(const uint8_t *data, size_t len,
uint8_t out[SHA384_DIGEST_LENGTH]) {
SHA512_CTX ctx;
SHA384_Init(&ctx);
SHA384_Update(&ctx, data, len);
SHA384_Final(out, &ctx);
OPENSSL_cleanse(&ctx, sizeof(ctx));
return out;
}
uint8_t *SHA512(const uint8_t *data, size_t len,
uint8_t out[SHA512_DIGEST_LENGTH]) {
SHA512_CTX ctx;
SHA512_Init(&ctx);
SHA512_Update(&ctx, data, len);
SHA512_Final(out, &ctx);
OPENSSL_cleanse(&ctx, sizeof(ctx));
return out;
}
uint8_t *SHA512_256(const uint8_t *data, size_t len,
uint8_t out[SHA512_256_DIGEST_LENGTH]) {
SHA512_CTX ctx;
SHA512_256_Init(&ctx);
SHA512_256_Update(&ctx, data, len);
SHA512_256_Final(out, &ctx);
OPENSSL_cleanse(&ctx, sizeof(ctx));
return out;
}
#if !defined(SHA512_ASM)
static void sha512_block_data_order(uint64_t *state, const uint8_t *in,
size_t num_blocks);
#endif
int SHA384_Final(uint8_t out[SHA384_DIGEST_LENGTH], SHA512_CTX *sha) {
// |SHA384_Init| sets |sha->md_len| to |SHA384_DIGEST_LENGTH|, so this has a
// smaller output.
assert(sha->md_len == SHA384_DIGEST_LENGTH);
return sha512_final_impl(out, sha);
}
int SHA384_Update(SHA512_CTX *sha, const void *data, size_t len) {
return SHA512_Update(sha, data, len);
}
int SHA512_256_Update(SHA512_CTX *sha, const void *data, size_t len) {
return SHA512_Update(sha, data, len);
}
int SHA512_256_Final(uint8_t out[SHA512_256_DIGEST_LENGTH], SHA512_CTX *sha) {
// |SHA512_256_Init| sets |sha->md_len| to |SHA512_256_DIGEST_LENGTH|, so this
// has a |smaller output.
assert(sha->md_len == SHA512_256_DIGEST_LENGTH);
return sha512_final_impl(out, sha);
}
void SHA512_Transform(SHA512_CTX *c, const uint8_t block[SHA512_CBLOCK]) {
sha512_block_data_order(c->h, block, 1);
}
int SHA512_Update(SHA512_CTX *c, const void *in_data, size_t len) {
uint64_t l;
uint8_t *p = c->p;
const uint8_t *data = in_data;
if (len == 0) {
return 1;
}
l = (c->Nl + (((uint64_t)len) << 3)) & UINT64_C(0xffffffffffffffff);
if (l < c->Nl) {
c->Nh++;
}
if (sizeof(len) >= 8) {
c->Nh += (((uint64_t)len) >> 61);
}
c->Nl = l;
if (c->num != 0) {
size_t n = sizeof(c->p) - c->num;
if (len < n) {
OPENSSL_memcpy(p + c->num, data, len);
c->num += (unsigned int)len;
return 1;
} else {
OPENSSL_memcpy(p + c->num, data, n), c->num = 0;
len -= n;
data += n;
sha512_block_data_order(c->h, p, 1);
}
}
if (len >= sizeof(c->p)) {
sha512_block_data_order(c->h, data, len / sizeof(c->p));
data += len;
len %= sizeof(c->p);
data -= len;
}
if (len != 0) {
OPENSSL_memcpy(p, data, len);
c->num = (int)len;
}
return 1;
}
int SHA512_Final(uint8_t out[SHA512_DIGEST_LENGTH], SHA512_CTX *sha) {
// Ideally we would assert |sha->md_len| is |SHA512_DIGEST_LENGTH| to match
// the size hint, but calling code often pairs |SHA384_Init| with
// |SHA512_Final| and expects |sha->md_len| to carry the size over.
//
// TODO(davidben): Add an assert and fix code to match them up.
return sha512_final_impl(out, sha);
}
static int sha512_final_impl(uint8_t *out, SHA512_CTX *sha) {
uint8_t *p = sha->p;
size_t n = sha->num;
p[n] = 0x80; // There always is a room for one
n++;
if (n > (sizeof(sha->p) - 16)) {
OPENSSL_memset(p + n, 0, sizeof(sha->p) - n);
n = 0;
sha512_block_data_order(sha->h, p, 1);
}
OPENSSL_memset(p + n, 0, sizeof(sha->p) - 16 - n);
CRYPTO_store_u64_be(p + sizeof(sha->p) - 16, sha->Nh);
CRYPTO_store_u64_be(p + sizeof(sha->p) - 8, sha->Nl);
sha512_block_data_order(sha->h, p, 1);
if (out == NULL) {
// TODO(davidben): This NULL check is absent in other low-level hash 'final'
// functions and is one of the few places one can fail.
return 0;
}
assert(sha->md_len % 8 == 0);
const size_t out_words = sha->md_len / 8;
for (size_t i = 0; i < out_words; i++) {
CRYPTO_store_u64_be(out, sha->h[i]);
out += 8;
}
return 1;
}
#ifndef SHA512_ASM
static const uint64_t K512[80] = {
UINT64_C(0x428a2f98d728ae22), UINT64_C(0x7137449123ef65cd),
UINT64_C(0xb5c0fbcfec4d3b2f), UINT64_C(0xe9b5dba58189dbbc),
UINT64_C(0x3956c25bf348b538), UINT64_C(0x59f111f1b605d019),
UINT64_C(0x923f82a4af194f9b), UINT64_C(0xab1c5ed5da6d8118),
UINT64_C(0xd807aa98a3030242), UINT64_C(0x12835b0145706fbe),
UINT64_C(0x243185be4ee4b28c), UINT64_C(0x550c7dc3d5ffb4e2),
UINT64_C(0x72be5d74f27b896f), UINT64_C(0x80deb1fe3b1696b1),
UINT64_C(0x9bdc06a725c71235), UINT64_C(0xc19bf174cf692694),
UINT64_C(0xe49b69c19ef14ad2), UINT64_C(0xefbe4786384f25e3),
UINT64_C(0x0fc19dc68b8cd5b5), UINT64_C(0x240ca1cc77ac9c65),
UINT64_C(0x2de92c6f592b0275), UINT64_C(0x4a7484aa6ea6e483),
UINT64_C(0x5cb0a9dcbd41fbd4), UINT64_C(0x76f988da831153b5),
UINT64_C(0x983e5152ee66dfab), UINT64_C(0xa831c66d2db43210),
UINT64_C(0xb00327c898fb213f), UINT64_C(0xbf597fc7beef0ee4),
UINT64_C(0xc6e00bf33da88fc2), UINT64_C(0xd5a79147930aa725),
UINT64_C(0x06ca6351e003826f), UINT64_C(0x142929670a0e6e70),
UINT64_C(0x27b70a8546d22ffc), UINT64_C(0x2e1b21385c26c926),
UINT64_C(0x4d2c6dfc5ac42aed), UINT64_C(0x53380d139d95b3df),
UINT64_C(0x650a73548baf63de), UINT64_C(0x766a0abb3c77b2a8),
UINT64_C(0x81c2c92e47edaee6), UINT64_C(0x92722c851482353b),
UINT64_C(0xa2bfe8a14cf10364), UINT64_C(0xa81a664bbc423001),
UINT64_C(0xc24b8b70d0f89791), UINT64_C(0xc76c51a30654be30),
UINT64_C(0xd192e819d6ef5218), UINT64_C(0xd69906245565a910),
UINT64_C(0xf40e35855771202a), UINT64_C(0x106aa07032bbd1b8),
UINT64_C(0x19a4c116b8d2d0c8), UINT64_C(0x1e376c085141ab53),
UINT64_C(0x2748774cdf8eeb99), UINT64_C(0x34b0bcb5e19b48a8),
UINT64_C(0x391c0cb3c5c95a63), UINT64_C(0x4ed8aa4ae3418acb),
UINT64_C(0x5b9cca4f7763e373), UINT64_C(0x682e6ff3d6b2b8a3),
UINT64_C(0x748f82ee5defb2fc), UINT64_C(0x78a5636f43172f60),
UINT64_C(0x84c87814a1f0ab72), UINT64_C(0x8cc702081a6439ec),
UINT64_C(0x90befffa23631e28), UINT64_C(0xa4506cebde82bde9),
UINT64_C(0xbef9a3f7b2c67915), UINT64_C(0xc67178f2e372532b),
UINT64_C(0xca273eceea26619c), UINT64_C(0xd186b8c721c0c207),
UINT64_C(0xeada7dd6cde0eb1e), UINT64_C(0xf57d4f7fee6ed178),
UINT64_C(0x06f067aa72176fba), UINT64_C(0x0a637dc5a2c898a6),
UINT64_C(0x113f9804bef90dae), UINT64_C(0x1b710b35131c471b),
UINT64_C(0x28db77f523047d84), UINT64_C(0x32caab7b40c72493),
UINT64_C(0x3c9ebe0a15c9bebc), UINT64_C(0x431d67c49c100d4c),
UINT64_C(0x4cc5d4becb3e42b6), UINT64_C(0x597f299cfc657e2a),
UINT64_C(0x5fcb6fab3ad6faec), UINT64_C(0x6c44198c4a475817),
};
#define Sigma0(x) \
(CRYPTO_rotr_u64((x), 28) ^ CRYPTO_rotr_u64((x), 34) ^ \
CRYPTO_rotr_u64((x), 39))
#define Sigma1(x) \
(CRYPTO_rotr_u64((x), 14) ^ CRYPTO_rotr_u64((x), 18) ^ \
CRYPTO_rotr_u64((x), 41))
#define sigma0(x) \
(CRYPTO_rotr_u64((x), 1) ^ CRYPTO_rotr_u64((x), 8) ^ ((x) >> 7))
#define sigma1(x) \
(CRYPTO_rotr_u64((x), 19) ^ CRYPTO_rotr_u64((x), 61) ^ ((x) >> 6))
#define Ch(x, y, z) (((x) & (y)) ^ ((~(x)) & (z)))
#define Maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
// This code should give better results on 32-bit CPU with less than
// ~24 registers, both size and performance wise...
static void sha512_block_data_order(uint64_t *state, const uint8_t *in,
size_t num) {
uint64_t A, E, T;
uint64_t X[9 + 80], *F;
int i;
while (num--) {
F = X + 80;
A = state[0];
F[1] = state[1];
F[2] = state[2];
F[3] = state[3];
E = state[4];
F[5] = state[5];
F[6] = state[6];
F[7] = state[7];
for (i = 0; i < 16; i++, F--) {
T = CRYPTO_load_u64_be(in + i * 8);
F[0] = A;
F[4] = E;
F[8] = T;
T += F[7] + Sigma1(E) + Ch(E, F[5], F[6]) + K512[i];
E = F[3] + T;
A = T + Sigma0(A) + Maj(A, F[1], F[2]);
}
for (; i < 80; i++, F--) {
T = sigma0(F[8 + 16 - 1]);
T += sigma1(F[8 + 16 - 14]);
T += F[8 + 16] + F[8 + 16 - 9];
F[0] = A;
F[4] = E;
F[8] = T;
T += F[7] + Sigma1(E) + Ch(E, F[5], F[6]) + K512[i];
E = F[3] + T;
A = T + Sigma0(A) + Maj(A, F[1], F[2]);
}
state[0] += A;
state[1] += F[1];
state[2] += F[2];
state[3] += F[3];
state[4] += E;
state[5] += F[5];
state[6] += F[6];
state[7] += F[7];
in += 16 * 8;
}
}
#else
#define ROUND_00_15(i, a, b, c, d, e, f, g, h) \
do { \
T1 += h + Sigma1(e) + Ch(e, f, g) + K512[i]; \
h = Sigma0(a) + Maj(a, b, c); \
d += T1; \
h += T1; \
} while (0)
#define ROUND_16_80(i, j, a, b, c, d, e, f, g, h, X) \
do { \
s0 = X[(j + 1) & 0x0f]; \
s0 = sigma0(s0); \
s1 = X[(j + 14) & 0x0f]; \
s1 = sigma1(s1); \
T1 = X[(j) & 0x0f] += s0 + s1 + X[(j + 9) & 0x0f]; \
ROUND_00_15(i + j, a, b, c, d, e, f, g, h); \
} while (0)
static void sha512_block_data_order(uint64_t *state, const uint8_t *in,
size_t num) {
uint64_t a, b, c, d, e, f, g, h, s0, s1, T1;
uint64_t X[16];
int i;
while (num--) {
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
T1 = X[0] = CRYPTO_load_u64_be(in);
ROUND_00_15(0, a, b, c, d, e, f, g, h);
T1 = X[1] = CRYPTO_load_u64_be(in + 8);
ROUND_00_15(1, h, a, b, c, d, e, f, g);
T1 = X[2] = CRYPTO_load_u64_be(in + 2 * 8);
ROUND_00_15(2, g, h, a, b, c, d, e, f);
T1 = X[3] = CRYPTO_load_u64_be(in + 3 * 8);
ROUND_00_15(3, f, g, h, a, b, c, d, e);
T1 = X[4] = CRYPTO_load_u64_be(in + 4 * 8);
ROUND_00_15(4, e, f, g, h, a, b, c, d);
T1 = X[5] = CRYPTO_load_u64_be(in + 5 * 8);
ROUND_00_15(5, d, e, f, g, h, a, b, c);
T1 = X[6] = CRYPTO_load_u64_be(in + 6 * 8);
ROUND_00_15(6, c, d, e, f, g, h, a, b);
T1 = X[7] = CRYPTO_load_u64_be(in + 7 * 8);
ROUND_00_15(7, b, c, d, e, f, g, h, a);
T1 = X[8] = CRYPTO_load_u64_be(in + 8 * 8);
ROUND_00_15(8, a, b, c, d, e, f, g, h);
T1 = X[9] = CRYPTO_load_u64_be(in + 9 * 8);
ROUND_00_15(9, h, a, b, c, d, e, f, g);
T1 = X[10] = CRYPTO_load_u64_be(in + 10 * 8);
ROUND_00_15(10, g, h, a, b, c, d, e, f);
T1 = X[11] = CRYPTO_load_u64_be(in + 11 * 8);
ROUND_00_15(11, f, g, h, a, b, c, d, e);
T1 = X[12] = CRYPTO_load_u64_be(in + 12 * 8);
ROUND_00_15(12, e, f, g, h, a, b, c, d);
T1 = X[13] = CRYPTO_load_u64_be(in + 13 * 8);
ROUND_00_15(13, d, e, f, g, h, a, b, c);
T1 = X[14] = CRYPTO_load_u64_be(in + 14 * 8);
ROUND_00_15(14, c, d, e, f, g, h, a, b);
T1 = X[15] = CRYPTO_load_u64_be(in + 15 * 8);
ROUND_00_15(15, b, c, d, e, f, g, h, a);
for (i = 16; i < 80; i += 16) {
ROUND_16_80(i, 0, a, b, c, d, e, f, g, h, X);
ROUND_16_80(i, 1, h, a, b, c, d, e, f, g, X);
ROUND_16_80(i, 2, g, h, a, b, c, d, e, f, X);
ROUND_16_80(i, 3, f, g, h, a, b, c, d, e, X);
ROUND_16_80(i, 4, e, f, g, h, a, b, c, d, X);
ROUND_16_80(i, 5, d, e, f, g, h, a, b, c, X);
ROUND_16_80(i, 6, c, d, e, f, g, h, a, b, X);
ROUND_16_80(i, 7, b, c, d, e, f, g, h, a, X);
ROUND_16_80(i, 8, a, b, c, d, e, f, g, h, X);
ROUND_16_80(i, 9, h, a, b, c, d, e, f, g, X);
ROUND_16_80(i, 10, g, h, a, b, c, d, e, f, X);
ROUND_16_80(i, 11, f, g, h, a, b, c, d, e, X);
ROUND_16_80(i, 12, e, f, g, h, a, b, c, d, X);
ROUND_16_80(i, 13, d, e, f, g, h, a, b, c, X);
ROUND_16_80(i, 14, c, d, e, f, g, h, a, b, X);
ROUND_16_80(i, 15, b, c, d, e, f, g, h, a, X);
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
in += 16 * 8;
}
}
#endif
#endif // !SHA512_ASM
#undef Sigma0
#undef Sigma1
#undef sigma0
#undef sigma1
#undef Ch
#undef Maj
#undef ROUND_00_15
#undef ROUND_16_80
| 9,066 |
770 | // Copyright (C) 2013 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Please contact the author of this library if you have any questions.
// Author: <NAME> (<EMAIL>)
#ifndef THEIA_SFM_TRIANGULATION_TRIANGULATION_H_
#define THEIA_SFM_TRIANGULATION_TRIANGULATION_H_
#include <Eigen/Core>
#include <vector>
#include "theia/alignment/alignment.h"
#include "theia/sfm/types.h"
namespace theia {
struct FeatureCorrespondence;
// Triangulates 2 posed views using the "Triangulation Made Easy" by Lindstrom
// (CVPR 2010)". The inputs are the projection matrices and image points. For
// two view reconstructions where only an essential matrix or fundamental matrix
// is available you can use ProjectionMatricesFromFundamentalMatrix in
// theia/sfm/pose/fundamental_matrix_utils.h
bool Triangulate(const Matrix3x4d& pose1,
const Matrix3x4d& pose2,
const Eigen::Vector2d& point1,
const Eigen::Vector2d& point2,
Eigen::Vector4d* triangulated_point);
// Triangulates a 3D point by determining the closest point between the
// rays. This method is known to be suboptimal in terms of reprojection error
// but it is extremely fast. We assume that the directions are unit vectors.
bool TriangulateMidpoint(const std::vector<Eigen::Vector3d>& origins,
const std::vector<Eigen::Vector3d>& ray_directions,
Eigen::Vector4d* triangulated_point);
// Triangulates 2 posed views using the DLT method from HZZ 12.2 p 312. The
// inputs are the projection matrices and the image observations. Returns true
// on success and false on failure.
bool TriangulateDLT(const Matrix3x4d& pose1,
const Matrix3x4d& pose2,
const Eigen::Vector2d& point1,
const Eigen::Vector2d& point2,
Eigen::Vector4d* triangulated_point);
// Computes n-view triangulation by computing the SVD that wil approximately
// minimize reprojection error. The inputs are the projection matrices and the
// image observations. Returns true on success and false on failure.
bool TriangulateNViewSVD(
const std::vector<Matrix3x4d>& poses,
const std::vector<Eigen::Vector2d>& points,
Eigen::Vector4d* triangulated_point);
// Computes n-view triangulation by an efficient L2 minimization of the
// algebraic error. This minimization is independent of the number of points, so
// it is extremely scalable. It gives better reprojection errors in the results
// and is significantly faster. The inputs are the projection matrices and the
// image observations. Returns true on success and false on failure.
bool TriangulateNView(const std::vector<Matrix3x4d>& poses,
const std::vector<Eigen::Vector2d>& points,
Eigen::Vector4d* triangulated_point);
// Determines if the 3D point is in front of the camera or not. We can simply
// compute the homogeneous ray intersection (closest point to two rays) and
// determine if the depth of the point is positive for both camera.
bool IsTriangulatedPointInFrontOfCameras(
const FeatureCorrespondence& correspondence,
const Eigen::Matrix3d& rotation,
const Eigen::Vector3d& position);
// Returns true if the triangulation angle between any two observations is
// sufficient.
bool SufficientTriangulationAngle(
const std::vector<Eigen::Vector3d>& ray_directions,
const double min_triangulation_angle_degrees);
} // namespace theia
#endif // THEIA_SFM_TRIANGULATION_TRIANGULATION_H_
| 1,690 |
3,631 | <filename>drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BackwardChainingTest.java
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.compiler.integrationtests;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.drools.compiler.integrationtests.incrementalcompilation.TestUtil;
import org.drools.core.InitialFact;
import org.drools.core.base.ClassObjectType;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseImpl;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.drools.core.reteoo.AccumulateNode;
import org.drools.core.reteoo.BetaMemory;
import org.drools.core.reteoo.BetaNode;
import org.drools.core.reteoo.ExistsNode;
import org.drools.core.reteoo.FromNode;
import org.drools.core.reteoo.NotNode;
import org.drools.core.reteoo.ObjectTypeNode;
import org.drools.core.reteoo.QueryElementNode;
import org.drools.core.reteoo.RightInputAdapterNode;
import org.drools.testcoverage.common.model.Address;
import org.drools.testcoverage.common.model.Person;
import org.drools.testcoverage.common.util.KieBaseTestConfiguration;
import org.drools.testcoverage.common.util.KieBaseUtil;
import org.drools.testcoverage.common.util.KieSessionTestConfiguration;
import org.drools.testcoverage.common.util.KieUtil;
import org.drools.testcoverage.common.util.SerializationHelper;
import org.drools.testcoverage.common.util.TestParametersUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.ReleaseId;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.LiveQuery;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import org.kie.api.runtime.rule.Row;
import org.kie.api.runtime.rule.Variable;
import org.kie.api.runtime.rule.ViewChangedEventListener;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.conf.PropertySpecificOption;
import org.kie.internal.io.ResourceFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.kie.api.runtime.rule.Variable.v;
@RunWith(Parameterized.class)
public class BackwardChainingTest extends AbstractBackwardChainingTest {
public BackwardChainingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) {
super(kieBaseTestConfiguration);
}
@Parameterized.Parameters(name = "KieBase type={0}")
public static Collection<Object[]> getParameters() {
return TestParametersUtil.getKieBaseCloudConfigurations(true);
}
@Test(timeout = 10000)
public void testQueryPatternBindingAsResult() throws IOException, ClassNotFoundException {
String str = "" +
"package org.drools.compiler.test \n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global java.util.List list\n" +
"query peeps( Person $p, String $name, String $likes, int $age ) \n" +
" $p := Person( $name := name, $likes := likes, $age := age; ) \n" +
"end\n";
str += "rule x1\n" +
"when\n" +
" String( this == \"go1\" )\n" +
// output, output, output ,output
" ?peeps($p, $name1; $likes1 : $likes, $age1 : $age )\n" +
"then\n" +
" list.add( $p );\n" +
" list.add( $name1 + \" : \" + $age1 );\n" +
"end \n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, str);
KieSession ksession = kbase.newKieSession();
try {
final List list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p1 = new Person("darth",
"stilton",
100);
final Person p2 = new Person("darth",
"stilton",
200);
final Person p3 = new Person("yoda",
"stilton",
300);
final Person p4 = new Person("luke",
"brie",
300);
final Person p5 = new Person("bobba",
"cheddar",
300);
ksession.insert(p1);
ksession.insert(p2);
ksession.insert(p3);
ksession.insert(p4);
ksession.insert(p5);
ksession.insert("go1");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
if (kieBaseTestConfiguration.isIdentity()) {
assertEquals(10, list.size());
assertEquals(p1, list.get(list.indexOf("darth : 100") - 1));
assertTrue(list.contains("darth : 100"));
assertEquals(p2, list.get(list.indexOf("darth : 200") - 1));
assertTrue(list.contains("darth : 200"));
assertEquals(p3, list.get(list.indexOf("yoda : 300") - 1));
assertTrue(list.contains("yoda : 300"));
assertEquals(p4, list.get(list.indexOf("luke : 300") - 1));
assertTrue(list.contains("luke : 300"));
assertEquals(p5, list.get(list.indexOf("bobba : 300") - 1));
assertTrue(list.contains("bobba : 300"));
} else {
assertEquals(8, list.size());
assertEquals(p1, list.get(list.indexOf("darth : 100") - 1));
assertTrue(list.contains("darth : 100"));
assertEquals(p3, list.get(list.indexOf("yoda : 300") - 1));
assertTrue(list.contains("yoda : 300"));
assertEquals(p4, list.get(list.indexOf("luke : 300") - 1));
assertTrue(list.contains("luke : 300"));
assertEquals(p5, list.get(list.indexOf("bobba : 300") - 1));
assertTrue(list.contains("bobba : 300"));
}
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueriesWithNestedAccessorsAllOutputs() throws IOException, ClassNotFoundException {
String drl = "" +
"package org.drools.compiler.test \n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global java.util.List list\n" +
"query peeps( String $name, String $likes, String $street ) \n" +
" Person( $name := name, $likes := likes, $street := address.street ) \n" +
"end\n";
drl += "rule x1\n" +
"when\n" +
" String( this == \"go1\" )\n" +
// output, output, ,output
" ?peeps($name1; $likes1 : $likes, $street1 : $street )\n" +
"then\n" +
" list.add( $name1 + \" : \" + $likes1 + \" : \" + $street1 );\n" +
"end \n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p1 = new Person("darth",
"stilton",
100);
p1.setAddress(new Address("s1"));
final Person p2 = new Person("yoda",
"stilton",
300);
p2.setAddress(new Address("s2"));
ksession.insert(p1);
ksession.insert(p2);
ksession.insert("go1");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
assertEquals(2, list.size());
assertTrue(list.contains("darth : stilton : s1"));
assertTrue(list.contains("yoda : stilton : s2"));
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueriesWithNestedAcecssorsMixedArgs() {
String drl = "" +
"package org.drools.compiler.test \n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global java.util.List list\n" +
"query peeps( String $name, String $likes, String $street ) \n" +
" Person( $name := name, $likes := likes, $street := address.street ) \n" +
"end\n";
drl += "rule x1\n" +
"when\n" +
" $s : String()\n" +
// output, output, ,input
" ?peeps($name1; $likes1 : $likes, $street : $s )\n" +
"then\n" +
" list.add( $name1 + \" : \" + $likes1 + \" : \" + $s );\n" +
"end \n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p1 = new Person("darth",
"stilton",
100);
p1.setAddress(new Address("s1"));
final Person p2 = new Person("yoda",
"stilton",
300);
p2.setAddress(new Address("s2"));
ksession.insert(p1);
ksession.insert(p2);
ksession.insert("s1");
ksession.fireAllRules();
assertEquals(1, list.size());
assertTrue(list.contains("darth : stilton : s1"));
list.clear();
ksession.insert("s2");
ksession.fireAllRules();
assertEquals(1, list.size());
assertTrue(list.contains("yoda : stilton : s2"));
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryWithDynamicData() throws IOException, ClassNotFoundException {
String drl = "" +
"package org.drools.compiler.test \n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global java.util.List list\n" +
"query peeps( Person $p, String $name, String $likes, int $age ) \n" +
" $p := Person( ) from new Person( $name, $likes, $age ) \n" +
"end\n";
drl += "rule x1\n" +
"when\n" +
" $n1 : String( )\n" +
// output, input ,input ,input
" ?peeps($p; $name : $n1, $likes : \"stilton\", $age : 100 )\n" +
"then\n" +
" list.add( $p );\n" +
"end \n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p1 = new Person("darth",
"stilton",
100);
final Person p2 = new Person("yoda",
"stilton",
100);
ksession.insert("darth");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
assertEquals(1, list.size());
assertEquals(p1, list.get(0));
list.clear();
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.insert("yoda");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
assertEquals(1, list.size());
assertEquals(p2, list.get(0));
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundException {
String drl = "" +
"package org.drools.compiler.test \n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global java.util.List list\n" +
"query peeps( Person $p, String $name, String $likes, int $age ) \n" +
" $p := Person( ) from new Person( $name, $likes, $age ) \n" +
"end\n";
drl += "rule x1\n" +
"when\n" +
" $n1 : String( )\n" +
" not Person( name == 'darth' )\n " +
// output, input ,input ,input
" ?peeps($p; $name : $n1, $likes : \"stilton\", $age : 100 )\n" +
"then\n" +
" insert( $p );\n" +
"end \n";
drl += "rule x2\n" +
"when\n" +
" $p : Person( )\n" +
"then\n" +
" list.add( $p );\n" +
"end \n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p1 = new Person("darth",
"stilton",
100);
ksession.insert("darth");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
ksession.insert("yoda"); // darth exists, so yoda won't get created
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
assertEquals(1, list.size());
assertEquals(p1, list.get(0));
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryWithOr() {
final String drl = "" +
"package org.drools.compiler.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import " + BackwardChainingTest.class.getName() + ".Q\n" +
"import " + BackwardChainingTest.class.getName() + ".R\n" +
"import " + BackwardChainingTest.class.getName() + ".S\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"\n" +
"query q(int x)\n" +
" Q( x := value )\n" +
"end\n" +
"\n" +
"query r(int x)\n" +
" R( x := value )\n" +
"end\n" +
"\n" +
"query s(int x)\n" +
" S( x := value ) \n" +
"end\n" +
"\n" +
"query p(int x)\n" +
" (?q(x;) and ?r(x;) ) \n" +
" or\n" +
" ?s(x;)\n" +
"end\n" +
"rule init when\n" +
"then\n" +
" insert( new Q(1) );\n " +
" insert( new Q(5) );\n " +
" insert( new Q(6) );\n " +
" insert( new R(1) );\n " +
" insert( new R(4) );\n " +
" insert( new R(6) );\n " +
" insert( new R(2) );\n " +
" insert( new S(2) );\n " +
" insert( new S(3) );\n " +
" insert( new S(6) );\n " +
"end\n" +
"";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List<Integer> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
QueryResults results;
list.clear();
results = ksession.getQueryResults("p", new Integer[]{0});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(0, list.size());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{1});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(1, list.size());
assertEquals(1, list.get(0).intValue());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{2});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(1, list.size());
assertEquals(2, list.get(0).intValue());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{3});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(1, list.size());
assertEquals(3, list.get(0).intValue());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{4});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(0, list.size());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{5});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(0, list.size());
list.clear();
results = ksession.getQueryResults("p", new Integer[]{6});
for (final QueryResultsRow result : results) {
list.add((Integer) result.get("x"));
}
assertEquals(2, list.size());
assertEquals(6, list.get(0).intValue());
assertEquals(6, list.get(1).intValue());
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testGeneology() throws IOException, ClassNotFoundException {
// from http://kti.mff.cuni.cz/~bartak/prolog/genealogy.html
final String drl = "" +
"package org.drools.compiler.test2 \n" +
"global java.util.List list\n" +
"dialect \"mvel\"\n" +
"query man( String name ) \n" +
" " + BackwardChainingTest.class.getName() + ".Man( name := name ) \n" +
"end\n" +
"query woman( String name ) \n" +
" " + BackwardChainingTest.class.getName() + ".Woman( name := name ) \n" +
"end\n" +
"query parent( String parent, String child ) \n" +
" " + BackwardChainingTest.class.getName() + ".Parent( parent := parent, child := child ) \n" +
"end\n" +
"query father( String father, String child ) \n" +
" ?man( father; ) \n" +
" ?parent( father, child; ) \n" +
"end\n" +
"query mother( String mother, String child ) \n" +
" ?woman( mother; ) \n" +
" ?parent( mother, child; ) \n" +
"end\n" +
"query son( String son, String parent ) \n" +
" ?man( son; ) \n" +
" ?parent( parent, son; ) \n" +
"end\n" +
"query daughter( String daughter, String parent ) \n" +
" ?woman( daughter; ) \n" +
" ?parent( parent, daughter; ) \n" +
"end\n" +
"query siblings( String c1, String c2 ) \n" +
" ?parent( $p, c1; ) \n" +
" ?parent( $p, c2; ) \n" +
" eval( !c1.equals( c2 ) )\n" +
"end\n" +
"query fullSiblings( String c1, String c2 )\n" +
" ?parent( $p1, c1; ) ?parent( $p1, c2; )\n" +
" ?parent( $p2, c1; ) ?parent( $p2, c2; )\n" +
" eval( !c1.equals( c2 ) && !$p1.equals( $p2 ) )\n" +
"end\n" +
"query fullSiblings2( String c1, String c2 )\n" +
" ?father( $p1, c1; ) ?father( $p1, c2; )\n" +
" ?mother( $p2, c1; ) ?mother( $p2, c2; )\n" +
" eval( !c1.equals( c2 ) )\n" +
"end\n" +
"query uncle( String uncle, String n )\n" +
" ?man( uncle; ) ?siblings( uncle, parent; )\n" +
" ?parent( parent, n; )\n " +
"end\n" +
"query aunt( String aunt, String n )\n" +
" ?woman( aunt; ) ?siblings( aunt, parent; )\n" +
" ?parent( parent, n; )\n " +
"end\n" +
"query grantParents( String gp, String gc )\n" +
" ?parent( gp, p; ) ?parent( p, gc; )\n" +
"end\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
// grand parents
ksession.insert(new Man("john"));
ksession.insert(new Woman("janet"));
// parent
ksession.insert(new Man("adam"));
ksession.insert(new Parent("john",
"adam"));
ksession.insert(new Parent("janet",
"adam"));
ksession.insert(new Man("stan"));
ksession.insert(new Parent("john",
"stan"));
ksession.insert(new Parent("janet",
"stan"));
// grand parents
ksession.insert(new Man("carl"));
ksession.insert(new Woman("tina"));
//
// parent
ksession.insert(new Woman("eve"));
ksession.insert(new Parent("carl",
"eve"));
ksession.insert(new Parent("tina",
"eve"));
//
// parent
ksession.insert(new Woman("mary"));
ksession.insert(new Parent("carl",
"mary"));
ksession.insert(new Parent("tina",
"mary"));
ksession.insert(new Man("peter"));
ksession.insert(new Parent("adam",
"peter"));
ksession.insert(new Parent("eve",
"peter"));
ksession.insert(new Man("paul"));
ksession.insert(new Parent("adam",
"paul"));
ksession.insert(new Parent("mary",
"paul"));
ksession.insert(new Woman("jill"));
ksession.insert(new Parent("adam",
"jill"));
ksession.insert(new Parent("eve",
"jill"));
QueryResults results = null;
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
list.clear();
results = ksession.getQueryResults("woman", v);
for (final QueryResultsRow result : results) {
list.add((String) result.get("name"));
}
assertEquals(5, list.size());
assertContains(new String[]{"janet", "mary", "tina", "eve", "jill"}, list);
list.clear();
results = ksession.getQueryResults("man", v);
for (final QueryResultsRow result : results) {
list.add((String) result.get("name"));
}
assertEquals(6, list.size());
assertContains(new String[]{"stan", "john", "peter", "carl", "adam", "paul"}, list);
list.clear();
results = ksession.getQueryResults("father", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("father") + ", " + result.get("child"));
}
assertEquals(7, list.size());
assertContains(new String[]{"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("mother", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("mother") + ", " + result.get("child"));
}
assertEquals(7, list.size());
assertContains(new String[]{"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>"},
list);
list.clear();
results = ksession.getQueryResults("son",
v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("son") + ", " + result.get("parent"));
}
assertEquals(8,
list.size());
assertContains(new String[]{"stan, john", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("daughter", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("daughter") + ", " + result.get("parent"));
}
assertEquals(6, list.size());
assertContains(new String[]{"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("siblings", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("c1") + ", " + result.get("c2"));
}
assertEquals(16, list.size());
assertContains(new String[]{"<NAME>", "<NAME>",
"<NAME>", "stan, adam",
"adam, stan", "stan, adam",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>",
"<NAME>", "<NAME>"}, list);
list.clear();
list.clear();
results = ksession.getQueryResults("parent", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("parent") + ":" + result.get("child"));
}
System.out.println(list);
// "query fullSiblings( String c1, String c2 )\n" +
// " ?parent( $p1, c1; ) ?parent( $p1, c2; )\n" +
// " ?parent( $p2, c1; ) ?parent( $p2, c2; )\n" +
// " eval( !c1.equals( c2 ) && !$p1.equals( $p2 ) )\n" +
// "end\n" +
list.clear();
results = ksession.getQueryResults("fullSiblings", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("c1") + ", " + result.get("c2"));
}
System.out.println(list);
assertEquals(12, list.size());
assertContains(new String[]{"eve, mary", "<NAME>",
"adam, stan", "stan, adam",
"adam, stan", "stan, adam",
"peter, jill", "jill, peter",
"peter, jill", "jill, peter",
"eve, mary", "<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("fullSiblings", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("c1") + ", " + result.get("c2"));
}
assertEquals(12, list.size());
assertContains(new String[]{"eve, mary", "<NAME>",
"adam, stan", "stan, adam",
"adam, stan", "stan, adam",
"<NAME>", "<NAME>",
"<NAME>", "jill, peter",
"eve, mary", "<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("uncle", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("uncle") + ", " + result.get("n"));
}
assertEquals(6, list.size());
assertContains(new String[]{"stan, peter",
"stan, paul",
"stan, jill",
"stan, peter",
"stan, paul",
"stan, jill"}, list);
list.clear();
results = ksession.getQueryResults("aunt", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("aunt") + ", " + result.get("n"));
}
assertEquals(6, list.size());
assertContains(new String[]{"mary, peter",
"<NAME>",
"<NAME>",
"<NAME>",
"eve, paul",
"<NAME>"}, list);
list.clear();
results = ksession.getQueryResults("grantParents", v, v);
for (final QueryResultsRow result : results) {
list.add(result.get("gp") + ", " + result.get("gc"));
}
assertEquals(12, list.size());
assertContains(new String[]{"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"john, paul",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",}, list);
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testDynamicRulesWithSharing() {
String drl = "" +
"package org.drools.compiler.test1 \n" +
"\n" +
"declare Location\n" +
" thing : String \n" +
" location : String \n" +
"end" +
"\n" +
"declare Edible\n" +
" thing : String\n" +
"end" +
"\n" +
"query whereFood( String x, String y ) \n" +
" Location(x, y;) Edible(x;) \n" +
"end\n" +
"\n" +
"rule init when\n" +
"then\n" +
" \n" +
" insert( new Location(\"apple\", \"kitchen\") );\n" +
" insert( new Location(\"crackers\", \"kitchen\") );\n" +
" insert( new Location(\"broccoli\", \"kitchen\") );\n" +
" insert( new Location(\"computer\", \"office\") );\n" +
" insert( new Edible(\"apple\") );\n" +
" insert( new Edible(\"crackers\") );\n" +
"end\n" +
"";
final KieBase kieBase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration);
final KnowledgeBuilder knowledgeBuilder = TestUtil.createKnowledgeBuilder(kieBase, drl);
drl = "" +
"package org.drools.compiler.test2 \n" +
"import org.drools.compiler.test1.*\n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import java.util.Map\n" +
"import java.util.HashMap\n" +
"global List list\n" +
"\n" +
"rule look2 when\n" +
" $place : String() // just here to give a OTN lookup point\n" +
" whereFood(thing, $place;)\n" +
"then\n" +
" list.add( \"2:\" + thing );\n" +
"end\n";
knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
if (knowledgeBuilder.hasErrors()) {
fail(knowledgeBuilder.getErrors().toString());
}
drl = "" +
"package org.drools.compiler.test3 \n" +
"import org.drools.compiler.test1.*\n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import java.util.Map\n" +
"import java.util.HashMap\n" +
"global List list\n" +
"\n" +
"rule look3 when\n" +
" $place : String() // just here to give a OTN lookup point\n" +
" whereFood(thing, $place;)\n" +
"then\n" +
" list.add( \"3:\" + thing );\n" +
"end\n";
knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
if (knowledgeBuilder.hasErrors()) {
fail(knowledgeBuilder.getErrors().toString());
}
drl = "" +
"package org.drools.compiler.test4 \n" +
"import org.drools.compiler.test1.*\n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import java.util.Map\n" +
"import java.util.HashMap\n" +
"global List list\n" +
"\n" +
"rule look4 when\n" +
" $place : String() // just here to give a OTN lookup point\n" +
" whereFood(thing, $place;)\n" +
"then\n" +
" list.add( \"4:\" + thing );\n" +
"end\n";
knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
if (knowledgeBuilder.hasErrors()) {
fail(knowledgeBuilder.getErrors().toString());
}
final Map<String, KiePackage> pkgs = new HashMap<>();
for (final KiePackage pkg : knowledgeBuilder.getKnowledgePackages()) {
pkgs.put(pkg.getName(), pkg);
}
final InternalKnowledgeBase kbase =
(InternalKnowledgeBase) KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration);
kbase.addPackages(Arrays.asList(pkgs.get("org.drools.compiler.test1"), pkgs.get("org.drools.compiler.test2")));
final KieSession ksession = kbase.newKieSession();
try {
final List<Map<String, Object>> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.insert("kitchen");
ksession.fireAllRules();
assertEquals(2, list.size());
assertContains(new String[]{"2:crackers", "2:apple"}, list);
list.clear();
kbase.addPackages(Collections.singletonList(pkgs.get("org.drools.compiler.test3")));
ksession.fireAllRules();
assertEquals(2, list.size());
assertContains(new String[]{"3:crackers", "3:apple"}, list);
list.clear();
kbase.addPackages(Collections.singletonList(pkgs.get("org.drools.compiler.test4")));
ksession.fireAllRules();
assertEquals(2, list.size());
assertContains(new String[]{"4:crackers", "4:apple"}, list);
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testOpenBackwardChain() {
// http://www.amzi.com/AdventureInProlog/advtop.php
final String drl = "" +
"package org.drools.compiler.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import " + Person.class.getCanonicalName() + "\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"declare Location\n" +
" thing : String \n" +
" location : String \n" +
"end" +
"\n" +
"query isContainedIn( String x, String y ) \n" +
" Location(x, y;)\n" +
" or \n" +
" ( Location(z, y;) and isContainedIn(x, z;) )\n" +
"end\n" +
"\n" +
"rule look when \n" +
" Person( $l : likes ) \n" +
" isContainedIn( $l, 'office'; )\n" +
"then\n" +
" insertLogical( 'blah' );" +
"end\n" +
"rule existsBlah when \n" +
" exists String( this == 'blah') \n" +
"then\n" +
" list.add( 'exists blah' );" +
"end\n" +
"\n" +
"rule notBlah when \n" +
" not String( this == 'blah') \n" +
"then\n" +
" list.add( 'not blah' );" +
"end\n" +
"\n" +
"rule init when\n" +
"then\n" +
" insert( new Location(\"desk\", \"office\") );\n" +
" insert( new Location(\"envelope\", \"desk\") );\n" +
" insert( new Location(\"key\", \"envelope\") );\n" +
"end\n" +
"\n" +
"rule go1 when \n" +
" String( this == 'go1') \n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" insert( new Location('lamp', 'desk') );\n" +
"end\n" +
"\n" +
"rule go2 when \n" +
" String( this == 'go2') \n" +
" $l : Location('lamp', 'desk'; )\n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" retract( $l );\n" +
"end\n" +
"\n" +
"rule go3 when \n" +
" String( this == 'go3') \n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" insert( new Location('lamp', 'desk') );\n" +
"end\n" +
"\n" +
"rule go4 when \n" +
" String( this == 'go4') \n" +
" $l : Location('lamp', 'desk'; )\n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" modify( $l ) { thing = 'book' };\n" +
"end\n" +
"\n" +
"rule go5 when \n" +
" String( this == 'go5') \n" +
" $l : Location('book', 'desk'; )\n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" modify( $l ) { thing = 'lamp' };\n" +
"end\n" +
"\n" +
"rule go6 when \n" +
" String( this == 'go6') \n" +
" $l : Location( 'lamp', 'desk'; )\n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" modify( $l ) { thing = 'book' };\n" +
"end\n" +
"\n" +
"rule go7 when \n" +
" String( this == 'go7') \n" +
" $p : Person( likes == 'lamp' ) \n" +
"then\n" +
" list.add( drools.getRule().getName() ); \n" +
" modify( $p ) { likes = 'key' };\n" +
"end\n" +
"\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
final Person p = new Person();
p.setLikes("lamp");
ksession.insert(p);
ksession.fireAllRules();
assertEquals("not blah", list.get(0));
list.clear();
InternalFactHandle fh = (InternalFactHandle) ksession.insert("go1");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go1", list.get(0));
assertEquals("exists blah", list.get(1));
fh = (InternalFactHandle) ksession.insert("go2");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go2", list.get(2));
assertEquals("not blah", list.get(3));
fh = (InternalFactHandle) ksession.insert("go3");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go3", list.get(4));
assertEquals("exists blah", list.get(5));
fh = (InternalFactHandle) ksession.insert("go4");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go4", list.get(6));
assertEquals("not blah", list.get(7));
fh = (InternalFactHandle) ksession.insert("go5");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go5", list.get(8));
assertEquals("exists blah", list.get(9));
// This simulates a modify of the root DroolsQuery object, but first we break it
fh = (InternalFactHandle) ksession.insert("go6");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go6", list.get(10));
assertEquals("not blah", list.get(11));
// now fix it
fh = (InternalFactHandle) ksession.insert("go7");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
assertEquals("go7", list.get(12));
assertEquals("exists blah", list.get(13));
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testCompile() {
final String drl = "declare Location\n"
+ "thing : String\n"
+ "location : String\n"
+ "end\n\n"
+ "query isContainedIn( String x, String y )\n"
+ "Location( x := thing, y := location)\n"
+ "or \n"
+ "( Location(z := thing, y := location) and ?isContainedIn( x := x, z := y ) )\n"
+ "end\n";
KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
}
@Test(timeout = 10000)
public void testInsertionOrder() {
final String drl = "" +
"package org.drools.compiler.integrationtests \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"declare Person\n" +
" name : String\n" +
" likes : String\n" +
"end\n" +
"\n" +
"declare Location\n" +
" thing : String \n" +
" location : String \n" +
"end\n" +
"\n" +
"declare Edible\n" +
" thing : String\n" +
"end\n" +
"\n" +
"\n" +
"query hasFood( String x, String y ) \n" +
" Location(x, y;) " +
" or \n " +
" ( Location(z, y;) and hasFood(x, z;) )\n" +
"end\n" +
"\n" +
"rule look when \n" +
" Person( $l : likes ) \n" +
" hasFood( $l, 'kitchen'; )\n" +
"then\n" +
" list.add( 'kitchen has ' + $l );" +
"end\n" +
"rule go1 when\n" +
" String( this == 'go1') \n" +
"then\n" +
" insert( new Person('zool', 'peach') );\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
"end\n" +
"rule go2 when\n" +
" String( this == 'go2') \n" +
"then\n" +
" insert( new Person('zool', 'peach') );\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
"end\n" +
"\n" +
"rule go3 when\n" +
" String( this == 'go3') \n" +
"then\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
" insert( new Person('zool', 'peach') );\n" +
"end\n" +
"\n" +
"rule go4 when\n" +
" String( this == 'go4') \n" +
"then\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
" insert( new Person('zool', 'peach') );\n" +
"end\n" +
"rule go5 when\n" +
" String( this == 'go5') \n" +
"then\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
" insert( new Person('zool', 'peach') );\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
"end\n" +
"rule go6 when\n" +
" String( this == 'go6') \n" +
"then\n" +
" insert( new Location(\"table\", \"kitchen\") );\n" +
" insert( new Person('zool', 'peach') );\n" +
" insert( new Location(\"peach\", \"table\") );\n" +
"end\n" +
"\n" +
"\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
for (int i = 1; i <= 6; i++) {
final KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
list.clear();
final FactHandle fh = ksession.insert("go" + i);
ksession.fireAllRules();
ksession.delete(fh);
assertEquals(1, list.size());
assertEquals("kitchen has peach", list.get(0));
} finally {
ksession.dispose();
}
}
}
@Test(timeout = 10000)
public void testQueryFindAll() {
final Object[] objects = new Object[]{42, "a String", 100};
final int oCount = objects.length;
final List<Object> queryList = new ArrayList<>();
final List<Object> ruleList = new ArrayList<>();
// expect all inserted objects + InitialFact
runTestQueryFindAll(0, queryList, ruleList, objects);
assertEquals(oCount, queryList.size());
assertContains(objects, queryList);
// expect inserted objects + InitialFact
queryList.clear();
ruleList.clear();
runTestQueryFindAll(1, queryList, ruleList, objects);
assertEquals(oCount * oCount, queryList.size());
queryList.clear();
ruleList.clear();
runTestQueryFindAll(2, queryList, ruleList, objects);
assertEquals(oCount * oCount, queryList.size());
}
private void runTestQueryFindAll(final int iCase,
final List<Object> queryList,
final List<Object> ruleList,
final Object[] objects) {
String drl = "" +
"package org.drools.compiler.test \n" +
"global java.util.List queryList \n" +
"global java.util.List ruleList \n" +
"query object( Object o ) \n" +
" o := Object( ) \n" +
"end \n" +
"rule findObjectByQuery \n" +
"when \n";
switch (iCase) {
case 0:
// omit Object()
drl += " object( $a ; ) \n";
break;
case 1:
drl += " Object() ";
drl += " object( $a ; ) \n";
break;
case 2:
drl += " object( $a ; ) \n";
drl += " Object() ";
break;
}
drl +=
"then \n" +
"// System.out.println( \"Object by query: \" + $a );\n" +
" queryList.add( $a ); \n" +
"end \n" +
"rule findObject \n" +
"salience 10 \n" +
"when \n" +
" $o: Object() \n" +
"then " +
"// System.out.println( \"Object: \" + $o );\n" +
" ruleList.add( $o ); \n" +
"end \n" +
"";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
ksession.setGlobal("queryList", queryList);
ksession.setGlobal("ruleList", ruleList);
for (final Object o : objects) {
ksession.insert(o);
}
ksession.fireAllRules();
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryWithObject() {
final String drl = "" +
"package org.drools.compiler.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"\n" +
"import " + BackwardChainingTest.class.getName() + ".Q\n" +
"import " + BackwardChainingTest.class.getName() + ".R\n" +
"import " + BackwardChainingTest.class.getName() + ".S\n" +
"query object(Object o)\n" +
" o := Object() \n" +
"end\n" +
"rule collectObjects when\n" +
" String( this == 'go1' )\n" +
" object( o; )\n" +
"then\n" +
" list.add( o );\n" +
"end\n" +
"rule init when\n" +
" String( this == 'init' )\n" +
"then\n" +
" insert( new Q(1) );\n " +
" insert( new Q(5) );\n " +
" insert( new Q(6) );\n " +
" insert( new R(1) );\n " +
" insert( new R(4) );\n " +
" insert( new R(6) );\n " +
" insert( new R(2) );\n " +
" insert( new S(2) );\n " +
" insert( new S(3) );\n " +
" insert( new S(6) );\n " +
"end\n" +
"";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
KieSession ksession = kbase.newKieSession();
List<Integer> list = new ArrayList<>();
try {
ksession.setGlobal("list", list);
ksession.insert("init");
ksession.fireAllRules();
ksession.insert("go1");
ksession.fireAllRules();
assertEquals(12, list.size());
assertContains(new Object[]{
"go1", "init", new Q(6), new R(6), new S(3),
new R(2), new R(1), new R(4), new S(2),
new S(6), new Q(1), new Q(5)},
list);
} finally {
ksession.dispose();
}
// now reverse the go1 and init order
ksession = kbase.newKieSession();
try {
list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.insert("go1");
ksession.fireAllRules();
ksession.insert("init");
ksession.fireAllRules();
assertEquals(12, list.size());
assertContains(new Object[]{
"go1", "init", new Q(6), new R(6), new S(3),
new R(2), new R(1), new R(4), new S(2),
new S(6), new Q(1), new Q(5)},
list);
} finally {
ksession.dispose();
}
}
public static void assertContains(final Object[] objects,
final List list) {
for (final Object object : objects) {
if (!list.contains(object)) {
fail("does not contain:" + object);
}
}
}
public static void assertContains(final List objects,
final List list) {
if (!list.contains(objects)) {
fail("does not contain:" + objects);
}
}
public static InternalFactHandle getFactHandle(final FactHandle factHandle,
final KieSession ksession) {
final Map<Long, FactHandle> handles = new HashMap<>();
ksession.getFactHandles().forEach(fh -> handles.put(((InternalFactHandle) fh).getId(), fh));
return (InternalFactHandle) handles.get(((InternalFactHandle) factHandle).getId());
}
public static class Man
implements
Serializable {
private String name;
public Man(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
return "Man [name=" + name + "]";
}
}
public static class Woman
implements
Serializable {
private String name;
public Woman(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
return "Woman [name=" + name + "]";
}
}
public static class Parent
implements
Serializable {
private String parent;
private String child;
public Parent(final String parent,
final String child) {
this.parent = parent;
this.child = child;
}
public String getParent() {
return parent;
}
public void setParent(final String parent) {
this.parent = parent;
}
public String getChild() {
return child;
}
public void setChild(final String child) {
this.child = child;
}
@Override
public String toString() {
return "Parent [parent=" + parent + ", child=" + child + "]";
}
}
public static class Q {
int value;
public Q(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(final int value) {
this.value = value;
}
public String toString() {
return "Q" + value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Q other = (Q) obj;
return value == other.value;
}
}
public static class R {
int value;
public R(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(final int value) {
this.value = value;
}
public String toString() {
return "R" + value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final R other = (R) obj;
return value == other.value;
}
}
public static class S {
int value;
public S(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(final int value) {
this.value = value;
}
public String toString() {
return "S" + value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final S other = (S) obj;
return value == other.value;
}
}
@Test(timeout = 10000)
public void testQueryWithClassLiterals() {
final String drl = "" +
"package org.drools.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"global List list\n" +
"declare Foo end \n" +
"query klass( Class $c )\n" +
" Object( this.getClass() == $c ) \n" +
"end\n" +
"rule R when\n" +
" o : String( this == 'go1' )\n" +
" klass( String.class ; )\n" +
"then\n" +
" list.add( o );\n" +
" insert( new Foo() ); \n" +
"end\n" +
"rule S when\n" +
" o : Foo()\n" +
" klass( Foo.class ; )\n" +
"then\n" +
" list.add( o );\n" +
"end\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List list = new ArrayList();
ksession.setGlobal("list", list);
ksession.insert("go1");
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("go1", list.get(0));
assertEquals("org.drools.test.Foo", list.get(1).getClass().getName());
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryIndexingWithUnification() {
final String drl = "" +
"package org.drools.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"global List list\n" +
"declare Foo id : int end \n" +
"declare Bar " +
" name : String " +
" val : int " +
"end \n" +
"query fooffa( String $name, Foo $f )\n" +
" Bar( name == $name, $id : val )\n" +
" $f := Foo( id == $id ) \n" +
"end\n" +
"rule R when\n" +
" o : String( this == 'go' )\n" +
" fooffa( \"x\", $f ; )\n" +
"then\n" +
" list.add( $f );\n" +
"end\n" +
"rule S when\n" +
"then\n" +
" insert( new Foo( 1 ) );\n" +
" insert( new Bar( \"x\", 1 ) );\n" +
"end\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final List<Integer> list = new ArrayList<>();
ksession.setGlobal("list",
list);
ksession.fireAllRules();
ksession.insert("go");
ksession.fireAllRules();
assertEquals(1, list.size());
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testQueryWithEvents() {
final String drl = "global java.util.List list; " +
"" +
"declare Inner\n" +
" @role(event)\n" +
"end\n" +
"rule \"Input\"\n" +
"when\n" +
"then\n" +
" insert( \"X\" );\n" +
" insert( new Inner( ) );\n" +
"end\n" +
"\n" +
"query myAgg( )\n" +
" Inner( )\n" +
"end\n" +
"\n" +
"rule \"React\"\n" +
"when\n" +
" String()\n" +
" myAgg( )\n" +
"then\n" +
" list.add( 42 );\n" +
"end";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final ArrayList list = new ArrayList();
ksession.setGlobal("list", list);
ksession.fireAllRules();
assertEquals(Collections.singletonList(42), list);
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testNpeOnQuery() {
final String drl =
"global java.util.List list; " +
"query foo( Integer $i ) " +
" $i := Integer( this < 10 ) " +
"end\n" +
"\n" +
"rule r1 when " +
" foo( $i ; ) " +
" Integer( this == 10 ) " +
"then " +
" System.out.println(\"10 \" + $i);" +
" list.add( 10 );\n" +
"end\n" +
"\n" +
"rule r2 when " +
" foo( $i; ) " +
" Integer( this == 20 ) " +
"then " +
" System.out.println(\"20 \" + $i);" +
" list.add( 20 );\n" +
"end\n" +
"rule r3 when " +
" $i : Integer( this == 1 ) " +
"then " +
" System.out.println($i);" +
" update( kcontext.getKieRuntime().getFactHandle( $i ), $i + 1 );" +
"end\n" +
"\n";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession kieSession = kbase.newKieSession();
try {
final List<Integer> list = new ArrayList<>();
kieSession.setGlobal("list", list);
kieSession.insert(1);
kieSession.insert(20);
kieSession.fireAllRules();
assertEquals(1, list.size());
assertEquals(20, (int) list.get(0));
} finally {
kieSession.dispose();
}
}
@Test
public void testQueryWithEvalAndTypeBoxingUnboxing() {
final String drl = "package org.drools.test;\n" +
"\n" +
"global java.util.List list \n;" +
"\n" +
"query primitiveInt( int $a )\n" +
" Integer( intValue == $a )\n" +
" eval( $a == 178 )\n" +
"end\n" +
"\n" +
"query boxedInteger( Integer $a )\n" +
" Integer( this == $a )\n" +
" eval( $a == 178 )\n" +
"end\n" +
"\n" +
"query boxInteger( int $a )\n" +
" Integer( this == $a )\n" +
" eval( $a == 178 )\n" +
"end\n" +
"\n" +
"query unboxInteger( Integer $a )\n" +
" Integer( intValue == $a )\n" +
" eval( $a == 178 )\n" +
"end\n" +
"\n" +
"query cast( int $a )\n" +
" Integer( intValue == $a )\n" +
" eval( $a == 178 )\n" +
"end\n" +
"" +
"rule Init when then insert( 178 ); end\n" +
"\n" +
"rule Check\n" +
"when\n" +
" String()\n" +
" ?primitiveInt( 178 ; )\n" +
" ?boxedInteger( $x ; )\n" +
" ?boxInteger( $x ; )\n" +
" ?unboxInteger( $y ; )\n" +
" ?cast( $z ; )\n" +
"then\n" +
" list.add( $x ); \n" +
" list.add( $y ); \n" +
" list.add( $z ); \n" +
"end";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
final KieSession ksession = kbase.newKieSession();
try {
final ArrayList list = new ArrayList();
ksession.setGlobal("list", list);
ksession.fireAllRules();
assertTrue(list.isEmpty());
ksession.insert("go");
ksession.fireAllRules();
assertEquals(Arrays.asList(178, 178, 178), list);
} finally {
ksession.dispose();
}
}
@Test
public void testNaniSearchsNoPropReactivity() throws IOException, ClassNotFoundException {
testNaniSearchs( PropertySpecificOption.ALLOWED);
}
@Test
public void testNaniSearchsWithPropReactivity() throws IOException, ClassNotFoundException {
// DROOLS-1453
testNaniSearchs(PropertySpecificOption.ALWAYS);
}
private void testNaniSearchs(final PropertySpecificOption propertySpecificOption) throws IOException, ClassNotFoundException {
// http://www.amzi.com/AdventureInProlog/advtop.php
final String drl = "" +
"package org.drools.compiler.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import java.util.Map\n" +
"import java.util.HashMap\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"declare Room" +
" name : String\n" +
"end\n" +
"\n" +
"declare Location\n" +
" thing : String \n" +
" location : String \n" +
"end" +
"\n" +
"declare Door\n" +
" fromLocation : String\n" +
" toLocation : String\n" +
"end" +
"\n" +
"declare Edible\n" +
" thing : String\n" +
"end" +
"\n" +
"declare TastesYucky\n" +
" thing : String\n" +
"end\n" +
"\n" +
"declare Here\n" +
" place : String \n" +
"end\n" +
"\n" +
"query whereFood( String x, String y ) \n" +
" ( Location(x, y;) and\n" +
" Edible(x;) ) " +
" or \n " +
" ( Location(z, y;) and ?whereFood(x, z;) )\n" +
"end\n" +
"query connect( String x, String y ) \n" +
" Door(x, y;)\n" +
" or \n" +
" Door(y, x;)\n" +
"end\n" +
"\n" +
"query isContainedIn( String x, String y ) \n" +
" Location(x, y;)\n" +
" or \n" +
" ( Location(z, y;) and ?isContainedIn(x, z;) )\n" +
"end\n" +
"\n" +
"query look(String place, List things, List food, List exits ) \n" +
" Here(place;)\n" +
" things := List() from accumulate( Location(thing, place;),\n" +
" collectList( thing ) )\n" +
" food := List() from accumulate( ?whereFood(thing, place;) ," +
" collectList( thing ) )\n" +
" exits := List() from accumulate( ?connect(place, exit;),\n" +
" collectList( exit ) )\n" +
"end\n" +
"\n" +
"rule reactiveLook when\n" +
" Here( place : place) \n" +
" ?look(place, things, food, exits;)\n" +
"then\n" +
" Map map = new HashMap();" +
" list.add(map);" +
" map.put( 'place', place); " +
" map.put( 'things', things); " +
" map.put( 'food', food); " +
" map.put( 'exits', exits); " +
" System.out.println( \"You are in the \" + place);\n" +
" System.out.println( \" You can see \" + things );\n" +
" System.out.println( \" You can eat \" + food );\n" +
" System.out.println( \" You can go to \" + exits );\n" +
"end\n" +
"\n" +
"rule init when\n" +
"then\n" +
" insert( new Room(\"kitchen\") );\n" +
" insert( new Room(\"office\") );\n" +
" insert( new Room(\"hall\") );\n" +
" insert( new Room(\"dining room\") );\n" +
" insert( new Room(\"cellar\") );\n" +
" \n" +
" insert( new Location(\"apple\", \"kitchen\") );\n" +
" insert( new Location(\"desk\", \"office\") );\n" +
" insert( new Location(\"apple\", \"desk\") );\n" +
" insert( new Location(\"flashlight\", \"desk\") );\n" +
" insert( new Location(\"envelope\", \"desk\") );\n" +
" insert( new Location(\"key\", \"envelope\") );\n" +
" insert( new Location(\"washing machine\", \"cellar\") );\n" +
" insert( new Location(\"nani\", \"washing machine\") );\n" +
" insert( new Location(\"broccoli\", \"kitchen\") );\n" +
" insert( new Location(\"crackers\", \"kitchen\") );\n" +
" insert( new Location(\"computer\", \"office\") );\n" +
" \n" +
" insert( new Door(\"office\", \"hall\") );\n" +
" insert( new Door(\"kitchen\", \"office\") );\n" +
" insert( new Door(\"hall\", \"dining room\") );\n" +
" insert( new Door(\"kitchen\", \"cellar\") );\n" +
" insert( new Door(\"dining room\", \"kitchen\") );\n" +
" \n" +
" insert( new Edible(\"apple\") );\n" +
" insert( new Edible(\"crackers\") );\n" +
" \n" +
" insert( new TastesYucky(\"broccoli\") ); " +
"end\n" +
"" +
"rule go1 when\n" +
" String( this == 'go1' )\n" +
"then\n" +
" insert( new Here(\"kitchen\") );\n" +
"end\n" +
"\n" +
"rule go2 when\n" +
" String( this == 'go2' )\n" +
" $h : Here( place == \"kitchen\")" +
"then\n" +
" modify( $h ) { place = \"office\" };\n" +
"end\n" +
"";
final ReleaseId releaseId1 = KieServices.get().newReleaseId("org.kie", "backward-chaining-test", "1");
final Map<String, String> kieModuleConfigurationProperties = new HashMap<>();
kieModuleConfigurationProperties.put(PropertySpecificOption.PROPERTY_NAME, propertySpecificOption.toString());
final KieModule kieModule = KieUtil.getKieModuleFromDrls(releaseId1,
kieBaseTestConfiguration,
KieSessionTestConfiguration.STATEFUL_REALTIME,
kieModuleConfigurationProperties,
drl);
final KieContainer kieContainer = KieServices.get().newKieContainer(kieModule.getReleaseId());
final KieBase kbase = kieContainer.getKieBase();
KieSession ksession = kbase.newKieSession();
try {
final List<Map<String, Object>> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
ksession.insert("go1");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
Map<String, Object> map = list.get(0);
assertEquals("kitchen", map.get("place"));
List<String> items = (List<String>) map.get("things");
assertEquals(3, items.size());
assertContains(new String[]{"apple", "broccoli", "crackers"}, items);
items = (List<String>) map.get("food");
assertEquals(2, items.size());
assertContains(new String[]{"apple", "crackers"}, items);
items = (List<String>) map.get("exits");
assertEquals(3, items.size());
assertContains(new String[]{"office", "cellar", "dining room"}, items);
ksession.insert("go2");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
map = list.get(1);
assertEquals("office", map.get("place"));
items = (List<String>) map.get("things");
assertEquals(2, items.size());
assertContains(new String[]{"computer", "desk",}, items);
items = (List<String>) map.get("food");
assertEquals(1, items.size());
assertContains(new String[]{"apple"}, items); // notice the apple is on the desk in the office
items = (List<String>) map.get("exits");
assertEquals(2, items.size());
assertContains(new String[]{"hall", "kitchen"}, items);
QueryResults results = ksession.getQueryResults("isContainedIn", "key", "office");
assertEquals(1, results.size());
final QueryResultsRow result = results.iterator().next();
assertEquals("key", result.get("x"));
assertEquals("office", result.get("y"));
results = ksession.getQueryResults("isContainedIn", "key", Variable.v);
List<List<String>> l = new ArrayList<>();
for (final QueryResultsRow r : results) {
l.add(Arrays.asList((String) r.get("x"), (String) r.get("y")));
}
assertEquals(3, results.size());
assertContains(Arrays.asList("key", "desk"), l);
assertContains(Arrays.asList("key", "office"), l);
assertContains(Arrays.asList("key", "envelope"), l);
results = ksession.getQueryResults("isContainedIn", Variable.v, "office");
l = new ArrayList<>();
for (final QueryResultsRow r : results) {
l.add(Arrays.asList((String) r.get("x"), (String) r.get("y")));
}
assertEquals(6, results.size());
assertContains(Arrays.asList("desk", "office"), l);
assertContains(Arrays.asList("computer", "office"), l);
assertContains(Arrays.asList("apple", "office"), l);
assertContains(Arrays.asList("envelope", "office"), l);
assertContains(Arrays.asList("flashlight", "office"), l);
assertContains(Arrays.asList("key", "office"), l);
results = ksession.getQueryResults("isContainedIn", Variable.v, Variable.v);
l = new ArrayList<>();
for (final QueryResultsRow r : results) {
l.add(Arrays.asList((String) r.get("x"), (String) r.get("y")));
}
assertEquals(17, results.size());
assertContains(Arrays.asList("apple", "kitchen"), l);
assertContains(Arrays.asList("apple", "desk"), l);
assertContains(Arrays.asList("envelope", "desk"), l);
assertContains(Arrays.asList("desk", "office"), l);
assertContains(Arrays.asList("computer", "office"), l);
assertContains(Arrays.asList("washing machine", "cellar"), l);
assertContains(Arrays.asList("key", "envelope"), l);
assertContains(Arrays.asList("broccoli", "kitchen"), l);
assertContains(Arrays.asList("nani", "washing machine"), l);
assertContains(Arrays.asList("crackers", "kitchen"), l);
assertContains(Arrays.asList("flashlight", "desk"), l);
assertContains(Arrays.asList("nani", "cellar"), l);
assertContains(Arrays.asList("apple", "office"), l);
assertContains(Arrays.asList("envelope", "office"), l);
assertContains(Arrays.asList("flashlight", "office"), l);
assertContains(Arrays.asList("key", "office"), l);
assertContains(Arrays.asList("key", "desk"), l);
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testSubNetworksAndQueries() {
final String drl = "" +
"package org.drools.compiler.test \n" +
"import java.util.List\n" +
"import java.util.ArrayList\n" +
"import java.util.Map\n" +
"import java.util.HashMap\n" +
"global List list\n" +
"dialect \"mvel\"\n" +
"\n" +
"declare Location\n" +
" thing : String \n" +
" location : String \n" +
"end" +
"\n" +
"declare Edible\n" +
" thing : String\n" +
"end" +
"\n" +
"query whereFood( String x, String y ) \n" +
" Location(x, y;) Edible(x;) \n" +
"end\n" +
"\n" +
"query look(String place, List food ) \n" +
" $s : String() // just here to give a OTN lookup point\n" +
" food := List() from accumulate( whereFood(thing, place;) ," +
" collectList( thing ) )\n" +
" exists( whereFood(thing, place;) )\n" +
" not( whereFood(thing, place;) and\n " +
" String( this == $s ) from thing )\n" +
"end\n" +
"\n" +
"rule init when\n" +
"then\n" +
" \n" +
" insert( new Location(\"apple\", \"kitchen\") );\n" +
" insert( new Location(\"crackers\", \"kitchen\") );\n" +
" insert( new Location(\"broccoli\", \"kitchen\") );\n" +
" insert( new Location(\"computer\", \"office\") );\n" +
" insert( new Edible(\"apple\") );\n" +
" insert( new Edible(\"crackers\") );\n" +
"end\n" +
"";
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drl);
// Get the accumulate node, so we can test it's memory later
// now check beta memory was correctly cleared
final List<ObjectTypeNode> nodes = (( KnowledgeBaseImpl ) kbase).getRete().getObjectTypeNodes();
ObjectTypeNode node = null;
for (final ObjectTypeNode n : nodes) {
if ((( ClassObjectType ) n.getObjectType()).getClassType() == String.class) {
node = n;
break;
}
}
assertNotNull(node);
final BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
final QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
final RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
final AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
final QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
final RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
final ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
final QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
final FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
final RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
final NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
final KieSession ksession = kbase.newKieSession();
try {
final InternalWorkingMemory wm = (( StatefulKnowledgeSessionImpl ) ksession);
final AccumulateNode.AccumulateMemory accMemory = (AccumulateNode.AccumulateMemory ) wm.getNodeMemory(accNode);
final BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
final FromNode.FromMemory fromMemory = (FromNode.FromMemory ) wm.getNodeMemory(fromNode);
final BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
final List<Map<String, Object>> list = new ArrayList<>();
ksession.setGlobal("list", list);
final FactHandle fh = ksession.insert("bread");
ksession.fireAllRules();
final List food = new ArrayList();
// Execute normal query and check no subnetwork tuples are left behind
QueryResults results = ksession.getQueryResults("look", "kitchen", Variable.v);
assertEquals(1, results.size());
for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
food.addAll((Collection) row.get("food"));
}
assertEquals(2, food.size());
assertContains(new String[]{"crackers", "apple"}, food);
assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size());
assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
// Now execute an open query and ensure the memory is left populated
food.clear();
final List foodUpdated = new ArrayList();
final LiveQuery query = ksession.openLiveQuery("look",
new Object[]{"kitchen", Variable.v},
new ViewChangedEventListener() {
public void rowUpdated(final Row row) {
foodUpdated.addAll((Collection) row.get("food"));
}
public void rowDeleted(final Row row) {
}
public void rowInserted(final Row row) {
food.addAll((Collection) row.get("food"));
}
});
assertEquals(2, food.size());
assertContains(new String[]{"crackers", "apple"}, food);
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size()); // This is zero, as it's held directly on the LeftTuple context
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
food.clear();
// Now try again, make sure it only delete's it's own tuples
results = ksession.getQueryResults("look", "kitchen", Variable.v);
assertEquals(1, results.size());
for (final org.kie.api.runtime.rule.QueryResultsRow row : results) {
food.addAll((Collection) row.get("food"));
}
assertEquals(2, food.size());
assertContains(new String[]{"crackers", "apple"}, food);
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size()); // This is zero, as it's held directly on the LeftTuple context
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
food.clear();
// do an update and check it's still memory size 2
// however this time the food should be empty, as 'crackers' now blocks the not.
ksession.update(fh, "crackers");
ksession.fireAllRules();
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(1, existsMemory.getLeftTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size()); // This is zero, as it's held directly on the LeftTuple context
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size()); // This is zero, as it's held directly on the LeftTuple context
assertEquals(0, foodUpdated.size());
// do an update and check it's still memory size 2
// this time
ksession.update(fh, "oranges");
ksession.fireAllRules();
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(1, existsMemory.getLeftTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size()); // This is zero, as it's held directly on the LeftTuple context
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
assertEquals(2, food.size());
assertContains(new String[]{"crackers", "apple"}, food);
// Close the open
query.close();
assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size());
assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
} finally {
ksession.dispose();
}
}
@Test(timeout = 10000)
public void testInsertionOrderTwo() {
final StringBuilder drlBuilder = new StringBuilder("" +
"package org.drools.compiler.test \n" +
"import java.util.List \n" +
"global List list \n" +
"declare Thing \n" +
" thing : String @key \n" +
"end \n" +
"declare Edible extends Thing \n" +
"end \n" +
"declare Location extends Thing \n" +
" location : String @key \n" +
"end \n" +
"declare Here \n" +
" place : String \n" +
"end \n" +
"rule kickOff \n" +
"when \n" +
" Integer( $i: intValue ) \n" +
"then \n" +
" switch( $i ){ \n");
String[] facts = new String[]{"new Edible( 'peach' )", "new Location( 'peach', 'table' )", "new Here( 'table' )"};
int f = 0;
for (final String fact : facts) {
for (final String fact1 : facts) {
for (final String fact2 : facts) {
// use a Set to make sure we only include 3 unique values
final Set<String> set = new HashSet<>();
set.add(fact);
set.add(fact1);
set.add(fact2);
if (set.size() == 3) {
drlBuilder.append(" case ").append(f++).append(": \n")
.append(" insert( ").append(fact).append(" ); \n")
.append(" insert( ").append(fact1).append(" ); \n")
.append(" insert( ").append(fact2).append(" ); \n")
.append(" break; \n");
}
}
}
}
facts = new String[]{"new Edible( 'peach' )", "new Location( 'table', 'office' )", "new Location( 'peach', 'table' )", "new Here( 'office' )"};
int h = f;
for (final String fact : facts) {
for (final String fact1 : facts) {
for (final String fact3 : facts) {
for (final String fact2 : facts) {
// use a Set to make sure we only include 3 unique values
final Set<String> set = new HashSet<>();
set.add(fact);
set.add(fact1);
set.add(fact3);
set.add(fact2);
if (set.size() == 4) {
drlBuilder.append(" case ").append(h++).append(": \n")
.append(" insert( ").append(fact).append(" ); \n")
.append(" insert( ").append(fact1).append(" ); \n")
.append(" insert( ").append(fact3).append(" ); \n")
.append(" insert( ").append(fact2).append(" ); \n")
.append(" break; \n");
}
}
}
}
}
drlBuilder.append(" } \n" + "end \n" + "\n"
+ "query whereFood( String x, String y ) \n"
+ " ( Location(x, y;) and Edible(x;) ) \n "
+ " or \n"
+ " ( Location(z, y;) and whereFood(x, z;) ) \n"
+ "end "
+ "query look(String place, List things, List food) \n" + " Here(place;) \n"
+ " things := List() from accumulate( Location(thing, place;), \n"
+ " collectList( thing ) ) \n"
+ " food := List() from accumulate( whereFood(thing, place;), \n"
+ " collectList( thing ) ) \n"
+ "end \n" + "rule reactiveLook \n" + "when \n" + " Here( $place : place) \n"
+ " look($place, $things, $food;) \n"
+ "then \n"
+ " list.addAll( $things ); \n"
+ " list.addAll( $food ); \n"
+ "end \n" + "");
final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("backward-chaining-test", kieBaseTestConfiguration, drlBuilder.toString());
for (int i = 0; i < f; i++) {
final KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
list.clear();
InternalFactHandle fh = (InternalFactHandle) ksession.insert(i);
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("peach", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
final InternalFactHandle[] handles = ksession.getFactHandles().toArray(new InternalFactHandle[0]);
for (int j = 0; j < handles.length; j++) {
if (handles[j].getObject() instanceof InitialFact || handles[j].getObject() instanceof Integer) {
continue;
}
handles[j] = getFactHandle(handles[j], ksession);
final Object o = handles[j].getObject();
// first retract + assert
ksession.delete(handles[j]);
handles[j] = (InternalFactHandle) ksession.insert(o);
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("peach", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
// now try update
// session was serialised so need to get factHandle
handles[j] = getFactHandle(handles[j], ksession);
ksession.update(handles[j], handles[j].getObject());
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("peach", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
}
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
} finally {
ksession.dispose();
}
}
for (int i = f; i < h; i++) {
final KieSession ksession = kbase.newKieSession();
try {
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);
ksession.fireAllRules();
list.clear();
InternalFactHandle fh = (InternalFactHandle) ksession.insert(i);
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("table", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
final InternalFactHandle[] handles = ksession.getFactHandles().toArray(new InternalFactHandle[0]);
for (int j = 0; j < handles.length; j++) {
if (handles[j].getObject() instanceof InitialFact || handles[j].getObject() instanceof Integer) {
continue;
}
handles[j] = getFactHandle(handles[j], ksession);
final Object o = handles[j].getObject();
ksession.delete(handles[j]);
handles[j] = (InternalFactHandle) ksession.insert(o);
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("table", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
// now try update
handles[j] = getFactHandle(handles[j], ksession);
ksession.update(handles[j], handles[j].getObject());
ksession.fireAllRules();
assertEquals(2, list.size());
assertEquals("table", list.get(0));
assertEquals("peach", list.get(1));
list.clear();
}
fh = getFactHandle(fh, ksession);
ksession.delete(fh);
} finally {
ksession.dispose();
}
}
}
}
| 55,947 |
668 | <filename>fineract-provider/src/main/java/org/apache/fineract/infrastructure/core/config/CacheConfig.java
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.core.config;
import java.time.Duration;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.jsr107.Eh107Configuration;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheConfig {
@Bean
public JCacheCacheManager ehCacheManager() {
JCacheCacheManager jCacheCacheManager = new JCacheCacheManager();
jCacheCacheManager.setCacheManager(getCustomCacheManager());
return jCacheCacheManager;
}
private CacheManager getCustomCacheManager() {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
javax.cache.configuration.Configuration<Object, Object> defaultTemplate = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(10000))
.withExpiry(ExpiryPolicyBuilder.noExpiration()).build());
cacheManager.createCache("users", defaultTemplate);
cacheManager.createCache("usersByUsername", defaultTemplate);
cacheManager.createCache("tenantsById", defaultTemplate);
cacheManager.createCache("offices", defaultTemplate);
cacheManager.createCache("officesForDropdown", defaultTemplate);
cacheManager.createCache("officesById", defaultTemplate);
cacheManager.createCache("charges", defaultTemplate);
cacheManager.createCache("funds", defaultTemplate);
cacheManager.createCache("code_values", defaultTemplate);
cacheManager.createCache("codes", defaultTemplate);
cacheManager.createCache("hooks", defaultTemplate);
cacheManager.createCache("tfConfig", defaultTemplate);
javax.cache.configuration.Configuration<Object, Object> accessTokenTemplate = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(10000))
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofHours(2))).build());
cacheManager.createCache("userTFAccessToken", accessTokenTemplate);
return cacheManager;
}
}
| 1,090 |
2,164 | //
// KSDynamicLinker.h
//
// Created by <NAME> on 2013-10-02.
//
// Copyright (c) 2012 <NAME>. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall remain in place
// in this source code.
//
// 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.
//
#ifndef HDR_BSG_KSDynamicLinker_h
#define HDR_BSG_KSDynamicLinker_h
#ifdef __cplusplus
extern "C" {
#endif
#include <dlfcn.h>
#include <mach-o/dyld.h>
/** Find a loaded binary image with the specified name.
*
* @param imageName The image name to look for.
*
* @param exactMatch If true, look for an exact match instead of a partial one.
*
* @return the index of the matched image, or UINT32_MAX if not found.
*/
uint32_t bsg_ksdlimageNamed(const char *const imageName, bool exactMatch);
/** Get the UUID of a loaded binary image with the specified name.
*
* @param imageName The image name to look for.
*
* @param exactMatch If true, look for an exact match instead of a partial one.
*
* @return A pointer to the binary (16 byte) UUID of the image, or NULL if it
* wasn't found.
*/
const uint8_t *bsg_ksdlimageUUID(const char *const imageName, bool exactMatch);
/** Get the address of the first command following a header (which will be of
* type struct load_command).
*
* @param header The header to get commands for.
*
* @return The address of the first command, or NULL if none was found (which
* should not happen unless the header or image is corrupt).
*/
uintptr_t bsg_ksdlfirstCmdAfterHeader(const struct mach_header *header);
/** Get the image index that the specified address is part of.
*
* @param address The address to examine.
* @return The index of the image it is part of, or UINT_MAX if none was found.
*/
uint32_t bsg_ksdlimageIndexContainingAddress(const uintptr_t address);
/** Get the segment base address of the specified image.
*
* This is required for any symtab command offsets.
*
* @param idx The image index.
* @return The image's base address, or 0 if none was found.
*/
uintptr_t bsg_ksdlsegmentBaseOfImageIndex(const uint32_t idx);
/** async-safe version of dladdr.
*
* This method searches the dynamic loader for information about any image
* containing the specified address. It may not be entirely successful in
* finding information, in which case any fields it could not find will be set
* to NULL.
*
* Unlike dladdr(), this method does not make use of locks, and does not call
* async-unsafe functions.
*
* @param address The address to search for.
* @param info Gets filled out by this function.
* @return true if at least some information was found.
*/
bool bsg_ksdldladdr(const uintptr_t address, Dl_info *const info);
/** Get the address of a symbol in the specified image.
*
* @param imageIdx The index of the image to search.
* @param symbolName The symbol to search for.
* @return The address of the symbol or NULL if not found.
*/
const void *bsg_ksdlgetSymbolAddrInImage(uint32_t imageIdx,
const char *symbolName);
/** Get the address of a symbol in any image.
* Searches all images starting at index 0.
*
* @param symbolName The symbol to search for.
* @return The address of the symbol or NULL if not found.
*/
const void *bsg_ksdlgetSymbolAddrInAnyImage(const char *symbolName);
#ifdef __cplusplus
}
#endif
#endif // HDR_KSDynamicLinker_h
| 1,285 |
665 | /*
* 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.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.isis.commons.internal.collections._Lists;
import org.apache.isis.core.metamodel.interactions.managed.nonscalar.DataRow;
import org.apache.isis.core.runtime.context.IsisAppCommonContext;
import org.apache.isis.viewer.wicket.ui.components.widgets.checkbox.ContainedToggleboxPanel;
import org.apache.isis.viewer.wicket.ui.util.CssClassAppender;
import lombok.val;
public final class GenericToggleboxColumn
extends GenericColumnAbstract {
private static final long serialVersionUID = 1L;
public static enum BulkToggle {
CLEAR_ALL, SET_ALL;
static BulkToggle valueOf(final boolean b) {
return b ? SET_ALL : CLEAR_ALL;
}
public boolean isSetAll() { return this == SET_ALL; }
}
public GenericToggleboxColumn(
final IsisAppCommonContext commonContext) {
super(commonContext, "");
}
@Override
public Component getHeader(final String componentId) {
val bulkToggle = new ContainedToggleboxPanel(componentId) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit(final AjaxRequestTarget target) {
val bulkToggle = BulkToggle.valueOf(!this.isChecked());
//System.err.printf("bulkToggle: %s%n", bulkToggle);
for (ContainedToggleboxPanel rowToggle : rowToggles) {
rowToggle.smartSet(bulkToggle, target);
}
}
};
bulkToggle.add(new CssClassAppender("title-column"));
return bulkToggle;
}
private final List<ContainedToggleboxPanel> rowToggles = _Lists.newArrayList();
@Override
public void populateItem(
final Item<ICellPopulator<DataRow>> cellItem,
final String componentId,
final IModel<DataRow> rowModel) {
cellItem.add(new CssClassAppender("togglebox-column"));
final MarkupContainer row = cellItem.getParent().getParent();
row.setOutputMarkupId(true);
val rowToggle = new ContainedToggleboxPanel(componentId) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit(final AjaxRequestTarget target) {
val isChecked = rowModel.getObject().getSelectToggle().toggleThenGet();
// no matter what, the underlying backend model must be reflected by the UI
setModel(isChecked);
}
};
rowToggles.add(rowToggle);
rowToggle.setOutputMarkupId(true);
cellItem.add(rowToggle);
}
public void removeToggles() {
rowToggles.clear();
}
} | 1,484 |
1,233 | package com.github.mustachejava;
import org.junit.Test;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Reproduction test case
*/
public class Issue75Test {
@Test
public void testDotNotationWithNull() throws IOException {
DefaultMustacheFactory mf = new DefaultMustacheFactory();
Mustache m = mf.compile(new StringReader("[{{category.name}}]"), "test");
StringWriter sw = new StringWriter();
Map map = new HashMap();
map.put("category", null);
m.execute(sw, map).close();
}
}
| 203 |
1,804 | <filename>dateparser/data/date_translation_data/lu.py
info = {
"name": "lu",
"date_order": "DMY",
"january": [
"cio",
"ciongo"
],
"february": [
"lui",
"lùishi"
],
"march": [
"lus",
"lusòlo"
],
"april": [
"muu",
"mùuyà"
],
"may": [
"lum",
"lumùngùlù"
],
"june": [
"luf",
"lufuimi"
],
"july": [
"kab",
"kabàlàshìpù"
],
"august": [
"lush",
"lùshìkà"
],
"september": [
"lut",
"lutongolo"
],
"october": [
"lun",
"lungùdi"
],
"november": [
"kas",
"kaswèkèsè"
],
"december": [
"cis",
"ciswà"
],
"monday": [
"nko",
"nkodya"
],
"tuesday": [
"ndy",
"ndàayà"
],
"wednesday": [
"ndangù",
"ndg"
],
"thursday": [
"njw",
"njòwa"
],
"friday": [
"ngv",
"ngòvya"
],
"saturday": [
"lub",
"lubingu"
],
"sunday": [
"lum",
"lumingu"
],
"am": [
"dinda"
],
"pm": [
"dilolo"
],
"year": [
"tshidimu"
],
"month": [
"ngondo"
],
"week": [
"lubingu"
],
"day": [
"dituku"
],
"hour": [
"diba"
],
"minute": [
"kasunsu"
],
"second": [
"kasunsukusu"
],
"relative-type": {
"0 day ago": [
"lelu"
],
"0 hour ago": [
"this hour"
],
"0 minute ago": [
"this minute"
],
"0 month ago": [
"this month"
],
"0 second ago": [
"now"
],
"0 week ago": [
"this week"
],
"0 year ago": [
"this year"
],
"1 day ago": [
"makelela"
],
"1 month ago": [
"last month"
],
"1 week ago": [
"last week"
],
"1 year ago": [
"last year"
],
"in 1 day": [
"malaba"
],
"in 1 month": [
"next month"
],
"in 1 week": [
"next week"
],
"in 1 year": [
"next year"
]
},
"locale_specific": {},
"skip": [
" ",
"'",
",",
"-",
".",
"/",
";",
"@",
"[",
"]",
"|",
","
]
}
| 1,813 |
593 | <reponame>Awais75/Linq
/*=============================================================================
Copyright (c) 2012 <NAME>
join.h
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef LINQ_GUARD_EXTENSIONS_JOIN_H
#define LINQ_GUARD_EXTENSIONS_JOIN_H
#include <linq/extensions/extension.h>
#include <linq/extensions/group_join.h>
#include <linq/extensions/select_many.h>
#include <linq/extensions/select.h>
#include <linq/utility.h>
namespace linq {
namespace detail {
struct join_t
{
template<class ResultSelector, class Key>
struct apply_result_selector
{
ResultSelector rs;
Key k;
apply_result_selector(ResultSelector rs, Key k)
: rs(rs), k(k)
{}
template<class T>
auto operator()(T && x) const -> decltype(declval<const ResultSelector>()(declval<const Key>(), std::forward<T>(x)))
{
return rs(k, std::forward<T>(x));
}
};
template<class ResultSelector, class Key>
static apply_result_selector < ResultSelector, Key >
make_apply_result_selector (ResultSelector rs, Key k)
{
return apply_result_selector < ResultSelector, Key >
(rs, k);
}
template<class ResultSelector>
struct result_selector
{
ResultSelector rs;
result_selector(ResultSelector rs)
: rs(rs)
{}
template<class>
struct result;
template<class X, class Key, class Value>
struct result<X(Key, Value)>
{
typedef decltype(declval<Value>() | linq::select(make_apply_result_selector(declval<const ResultSelector>(), declval<Key>()))) type;
};
template<class Key, class Value>
typename result<result_selector(Key&&, Value&&)>::type
operator()(Key && k, Value && v) const // -> decltype(v | linq::select(make_apply_result_selector(declval<const ResultSelector>(), k)))
{
return v | linq::select(make_apply_result_selector(rs, k));
};
};
template<class ResultSelector>
static result_selector< function_object<ResultSelector> >
make_result_selector (ResultSelector rs)
{
return result_selector < function_object<ResultSelector> >
(make_function_object(rs));
}
template<class>
struct result;
template<class X, class Outer, class Inner, class OuterKeySelector, class InnerKeySelector, class ResultSelector>
struct result<X(Outer, Inner, OuterKeySelector, InnerKeySelector, ResultSelector)>
{
static Outer && outer;
static Inner && inner;
static OuterKeySelector&& outer_key_selector;
static InnerKeySelector&& inner_key_selector;
static ResultSelector&& rs;
typedef decltype
(
outer | linq::group_join(std::forward<Inner>(inner), outer_key_selector, inner_key_selector, make_result_selector(rs))
| linq::select_many(linq::detail::identity_selector())
) type;
};
template<class Outer, class Inner, class OuterKeySelector, class InnerKeySelector, class ResultSelector>
typename result<join_t(Outer&&, Inner&&, OuterKeySelector, InnerKeySelector, ResultSelector)>::type
operator()(Outer && outer, Inner && inner, OuterKeySelector outer_key_selector, InnerKeySelector inner_key_selector, ResultSelector rs) const
{
return outer | linq::group_join(std::forward<Inner>(inner), outer_key_selector, inner_key_selector, make_result_selector(rs))
| linq::select_many(linq::detail::identity_selector());
}
};
}
namespace {
range_extension<detail::join_t> join = {};
}
}
#endif
| 1,515 |
1,072 | <reponame>li-ziang/cogdl<filename>cogdl/data/dataloader.py
from abc import ABCMeta
import torch.utils.data
from torch.utils.data.dataloader import default_collate
from cogdl.data import Batch, Graph
try:
from typing import GenericMeta # python 3.6
except ImportError:
# in 3.7, genericmeta doesn't exist but we don't need it
class GenericMeta(type):
pass
class RecordParameters(ABCMeta):
def __call__(cls, *args, **kwargs):
obj = type.__call__(cls, *args, **kwargs)
obj.record_parameters([args, kwargs])
return obj
class GenericRecordParameters(GenericMeta, RecordParameters):
pass
class DataLoader(torch.utils.data.DataLoader, metaclass=GenericRecordParameters):
r"""Data loader which merges data objects from a
:class:`cogdl.data.dataset` to a mini-batch.
Args:
dataset (Dataset): The dataset from which to load the data.
batch_size (int, optional): How may samples per batch to load.
(default: :obj:`1`)
shuffle (bool, optional): If set to :obj:`True`, the data will be
reshuffled at every epoch (default: :obj:`True`)
"""
def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):
if "collate_fn" not in kwargs or kwargs["collate_fn"] is None:
kwargs["collate_fn"] = self.collate_fn
super(DataLoader, self).__init__(
dataset,
batch_size,
shuffle,
**kwargs,
)
@staticmethod
def collate_fn(batch):
item = batch[0]
if isinstance(item, Graph):
return Batch.from_data_list(batch)
elif isinstance(item, torch.Tensor):
return default_collate(batch)
elif isinstance(item, float):
return torch.tensor(batch, dtype=torch.float)
raise TypeError("DataLoader found invalid type: {}".format(type(item)))
def get_parameters(self):
return self.default_kwargs
def record_parameters(self, params):
self.default_kwargs = params
| 855 |
360 | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* regioninfo.cpp
* support the obs foreign table, we get the region info from
* the region_map file, and clean the region info in database.
*
* IDENTIFICATION
* src/gausskernel/cbb/extension/foreign/regioninfo.cpp
*
* -------------------------------------------------------------------------
*/
#include <sys/stat.h>
#include "access/cstore_am.h"
#include "access/heapam.h"
#include "access/htup.h"
#include "access/tableam.h"
#include "access/reloptions.h"
#include "catalog/catalog.h"
#include "catalog/pg_foreign_server.h"
#include "fmgr.h"
#include "foreign/regioninfo.h"
#include "lib/stringinfo.h"
#include "pgxc/pgxc.h"
#include "pgxc/execRemote.h"
#include "utils/builtins.h"
#include "utils/snapmgr.h"
#include "storage/dfs/dfs_connector.h"
#include "cjson/cJSON.h"
static Datum pgxc_clean_region_info();
static bool clean_region_info();
/**
* @Description: get the region string from the region map file.
* if the region is empty, we will get the value of defaultRegion.
* @in region, the given region.
* @return return the region string.
*/
char* readDataFromJsonFile(char* region)
{
const char* regionMapfileName = "region_map";
StringInfo regionURL = makeStringInfo();
ereport(DEBUG1,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Get the region value from the %s file", regionMapfileName)));
if (NULL == region) {
region = "defaultRegion";
}
StringInfo regionMapfilePath = makeStringInfo();
const char* gausshome = gs_getenv_r("GAUSSHOME");
char real_gausshome[PATH_MAX + 1] = {'\0'};
if (NULL != gausshome && 0 != strcmp(gausshome, "\0") && realpath(gausshome, real_gausshome) != NULL) {
if (backend_env_valid(real_gausshome, "GAUSSHOME") == false) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("Incorrect backend environment variable $GAUSSHOME"),
errdetail("Please refer to the backend instance log for the detail")));
}
appendStringInfo(regionMapfilePath, "%s/etc/%s", real_gausshome, regionMapfileName);
} else {
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Failed to get enviroment parameter $GAUSSHOME or it is NULL, "
"please set $GAUSSHOME as your installation directory!")));
}
FILE* fp = NULL;
if ((fp = fopen(regionMapfilePath->data, "rb")) == NULL) {
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Failed to open file %s, errno = %d, reason = %s.", regionMapfileName, errno, strerror(errno))));
}
int32 nFileLength;
if (fseek(fp, 0, SEEK_END)) {
(void)fclose(fp);
ereport(ERROR, (errcode_for_file_access(), errmsg("unable to fseek file \"%s\"", regionMapfileName)));
}
nFileLength = ftell(fp);
if (nFileLength <= 0) {
(void)fclose(fp);
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR), errmodule(MOD_OBS), errmsg("The %s file is empty.", regionMapfileName)));
}
rewind(fp);
char* fileContext = (char*)palloc0((nFileLength + 1) * sizeof(char));
int nReadSize;
nReadSize = fread(fileContext, 1, nFileLength, fp);
if (nReadSize != nFileLength) {
(void)fclose(fp);
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR), errmodule(MOD_OBS), errmsg("Failed to read file %s.", regionMapfileName)));
}
(void)fclose(fp);
cJSON* region_jsons = cJSON_Parse(fileContext);
const cJSON* region_json = NULL;
bool found = false;
if (region_jsons == NULL) {
const char* error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Failed to parse %s file: %s.", regionMapfileName, error_ptr)));
} else {
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Failed to parse %s file: unkonwn error.", regionMapfileName)));
}
}
if (cJSON_IsArray(region_jsons)) {
cJSON_ArrayForEach(region_json, region_jsons)
{
if (region_json != NULL && region_json->child != NULL && region_json->child->string != NULL && !found &&
0 == pg_strcasecmp(region_json->child->string, region)) {
found = true;
appendStringInfo(regionURL, "%s", region_json->child->valuestring);
ereport(DEBUG1,
(errcode(ERRCODE_FDW_ERROR), errmodule(MOD_OBS), errmsg("The region URL is %s.", regionURL->data)));
}
}
} else {
cJSON_Delete(region_jsons);
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("Must exist array format in the %s json file.", regionMapfileName)));
}
cJSON_Delete(region_jsons);
if (!found) {
ereport(ERROR,
(errcode(ERRCODE_FDW_ERROR),
errmodule(MOD_OBS),
errmsg("No such region name: %s in %s file.", region, regionMapfileName)));
}
pfree_ext(regionMapfilePath->data);
pfree_ext(regionMapfilePath);
return regionURL->data;
}
static bool clean_region_info()
{
Relation rel;
TableScanDesc scan;
HeapTuple tuple;
int cleanNum = 0;
bool ret = true;
rel = heap_open(ForeignServerRelationId, AccessShareLock);
scan = tableam_scan_begin(rel, GetActiveSnapshot(), 0, NULL);
while ((tuple = (HeapTuple) tableam_scan_getnexttuple(scan, ForwardScanDirection)) != NULL) {
Oid srvOid = HeapTupleGetOid(tuple);
PG_TRY();
{
if (dfs::InvalidOBSConnectorCache(srvOid)) {
cleanNum++;
}
}
PG_CATCH();
{
FlushErrorState();
Form_pg_foreign_server server = (Form_pg_foreign_server)GETSTRUCT(tuple);
tableam_scan_end(scan);
heap_close(rel, AccessShareLock);
ereport(LOG, (errmodule(MOD_DFS), errmsg("Failed to clean region info of %s.", NameStr(server->srvname))));
ret = false;
}
PG_END_TRY();
}
tableam_scan_end(scan);
heap_close(rel, AccessShareLock);
ereport(LOG, (errmodule(MOD_DFS), errmsg("clean %d region info.", cleanNum)));
return ret;
}
/**
* @Description: clean the region map info for obs server.
* @in none.
* @return return true if clean it successfully, otherwise return false.
*/
Datum pg_clean_region_info(PG_FUNCTION_ARGS)
{
#ifdef PGXC
if (IS_PGXC_COORDINATOR && !IsConnFromCoord()) {
PG_RETURN_DATUM(pgxc_clean_region_info());
}
#endif
if (!superuser())
ereport(
ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("must be system admin to clean obs region info")));
VarChar* result = NULL;
if (clean_region_info()) {
result = (VarChar*)cstring_to_text_with_len("success", strlen("success"));
} else {
result = (VarChar*)cstring_to_text_with_len("failure", strlen("failure"));
}
PG_RETURN_VARCHAR_P(result);
}
static Datum pgxc_clean_region_info()
{
StringInfoData buf;
ParallelFunctionState* state = NULL;
VarChar* result = NULL;
initStringInfo(&buf);
appendStringInfo(&buf, "SELECT pg_catalog.pg_clean_region_info()");
state = RemoteFunctionResultHandler(buf.data, NULL, StrategyFuncSum);
FreeParallelFunctionState(state);
if (clean_region_info()) {
result = (VarChar*)cstring_to_text_with_len("success", strlen("success"));
} else {
result = (VarChar*)cstring_to_text_with_len("failure", strlen("failure"));
}
PG_RETURN_VARCHAR_P(result);
}
| 3,711 |
352 | /**
* Testcase package.
*/
package com.crawljax.plugins.testcasegenerator; | 25 |
348 | <filename>docs/data/leg-t1/062/06208328.json<gh_stars>100-1000
{"nom":"Ferfay","circ":"8ème circonscription","dpt":"Pas-de-Calais","inscrits":675,"abs":282,"votants":393,"blancs":8,"nuls":2,"exp":383,"res":[{"nuance":"FN","nom":"Mme <NAME>","voix":133},{"nuance":"REM","nom":"<NAME>","voix":77},{"nuance":"COM","nom":"<NAME>","voix":68},{"nuance":"FI","nom":"<NAME>","voix":41},{"nuance":"UDI","nom":"Mme <NAME>","voix":28},{"nuance":"SOC","nom":"M. <NAME>","voix":15},{"nuance":"DVD","nom":"M. <NAME>","voix":7},{"nuance":"ECO","nom":"M. <NAME>","voix":5},{"nuance":"DIV","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"Mme <NAME>","voix":4},{"nuance":"ECO","nom":"M. <NAME>","voix":1}]} | 289 |
678 | <reponame>bzxy/cydia<gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iLifeSlideshow.framework/iLifeSlideshow
*/
#import <iLifeSlideshow/MCSlide.h>
#import <iLifeSlideshow/MCAnimationPathSupport.h>
#import <iLifeSlideshow/iLifeSlideshow-Structs.h>
#import <iLifeSlideshow/MCFilterSupport.h>
#import <iLifeSlideshow/MCObject.h>
@class NSMutableSet, NSRecursiveLock, MCSong, NSMutableDictionary, MCAssetVideo, NSDictionary, MCContainerEffect, NSSet, NSString, NSArray;
@interface MCSlide : MCObject {
MCAssetVideo *mAsset; // 12 = 0xc
MCSong *mSong; // 16 = 0x10
unsigned mIndex; // 20 = 0x14
float mAudioVolume; // 24 = 0x18
double mAudioFadeInDuration; // 28 = 0x1c
double mAudioFadeOutDuration; // 36 = 0x24
float mAudioDuckLevel; // 44 = 0x2c
double mAudioDuckInDuration; // 48 = 0x30
double mAudioDuckOutDuration; // 56 = 0x38
double mStartTime; // 64 = 0x40
double mDuration; // 72 = 0x48
BOOL mStartTimeIsDefined; // 80 = 0x50
BOOL mDurationIsDefined; // 81 = 0x51
NSString *mFrameID; // 84 = 0x54
NSMutableDictionary *mFrameAttributes; // 88 = 0x58
NSString *mKenBurnsType; // 92 = 0x5c
CGPoint mCenter; // 96 = 0x60
float mScale; // 104 = 0x68
float mRotation; // 108 = 0x6c
NSMutableSet *mAnimationPaths; // 112 = 0x70
NSRecursiveLock *mAnimationPathsLock; // 116 = 0x74
NSMutableSet *mFilters; // 120 = 0x78
NSRecursiveLock *mFiltersLock; // 124 = 0x7c
NSArray *mCachedOrderedFilters; // 128 = 0x80
MCContainerEffect *mContainer; // 132 = 0x84
}
@property(retain) MCAssetVideo *asset; // G=0x176fd; S=0x17565; @synthesize=mAsset
@property(readonly, assign) MCSong *song; // G=0x17491; @synthesize=mSong
@property(assign) unsigned index; // G=0x1606d; S=0x1607d; @synthesize=mIndex
@property(assign) float audioVolume; // G=0x1604d; S=0x1605d; @synthesize=mAudioVolume
@property(assign) double audioFadeInDuration; // G=0x164b9; S=0x16485; @synthesize=mAudioFadeInDuration
@property(assign) double audioFadeOutDuration; // G=0x16521; S=0x164ed; @synthesize=mAudioFadeOutDuration
@property(assign) float audioDuckLevel; // G=0x1602d; S=0x1603d; @synthesize=mAudioDuckLevel
@property(assign) double audioDuckInDuration; // G=0x16589; S=0x16555; @synthesize=mAudioDuckInDuration
@property(assign) double audioDuckOutDuration; // G=0x165f1; S=0x165bd; @synthesize=mAudioDuckOutDuration
@property(assign, nonatomic) double startTime; // G=0x16015; S=0x17171; @synthesize=mStartTime
@property(readonly, assign) BOOL startTimeIsDefined; // G=0x16005; @synthesize=mStartTimeIsDefined
@property(assign, nonatomic) double duration; // G=0x15fed; S=0x17115; @synthesize=mDuration
@property(readonly, assign) BOOL durationIsDefined; // G=0x15fdd; @synthesize=mDurationIsDefined
@property(copy) NSString *frameID; // G=0x1664d; S=0x16625; @synthesize=mFrameID
@property(copy) NSString *kenBurnsType; // G=0x1668d; S=0x16665; @synthesize=mKenBurnsType
@property(assign) CGPoint center; // G=0x166d9; S=0x166a5; @synthesize=mCenter
@property(assign) float scale; // G=0x15fbd; S=0x15fcd; @synthesize=mScale
@property(assign) float rotation; // G=0x15f9d; S=0x15fad; @synthesize=mRotation
@property(assign) MCContainerEffect *container; // G=0x15f7d; S=0x15f8d; @synthesize=mContainer
@property(copy) NSDictionary *frameAttributes; // G=0x16e1d; S=0x16cf5;
+ (id)keyPathsForValuesAffectingValueForKey:(id)key; // 0x162c9
- (id)init; // 0x1608d
- (id)initWithImprint:(id)imprint andMontage:(id)montage; // 0x18005
- (void)demolish; // 0x17ead
- (id)imprint; // 0x17889
- (void)observeValueForKeyPath:(id)keyPath ofObject:(id)object change:(id)change context:(void *)context; // 0x177d1
// declared property getter: - (id)asset; // 0x176fd
// declared property setter: - (void)setAsset:(id)asset; // 0x17565
// declared property getter: - (id)song; // 0x17491
- (void)setSongForAsset:(id)asset; // 0x171cd
- (void)undefineStartTime; // 0x15f55
// declared property setter: - (void)setStartTime:(double)time; // 0x17171
- (void)undefineDuration; // 0x15f69
// declared property setter: - (void)setDuration:(double)duration; // 0x17115
- (id)frameAttributeForKey:(id)key; // 0x17029
- (void)setFrameAttribute:(id)attribute forKey:(id)key; // 0x16ee9
// declared property getter: - (id)frameAttributes; // 0x16e1d
// declared property setter: - (void)setFrameAttributes:(id)attributes; // 0x16cf5
- (id)snapshot; // 0x16c95
- (void)_copySelfToSnapshot:(id)snapshot; // 0x166fd
// declared property getter: - (id)container; // 0x15f7d
// declared property setter: - (void)setContainer:(id)container; // 0x15f8d
// declared property getter: - (float)rotation; // 0x15f9d
// declared property setter: - (void)setRotation:(float)rotation; // 0x15fad
// declared property getter: - (float)scale; // 0x15fbd
// declared property setter: - (void)setScale:(float)scale; // 0x15fcd
// declared property getter: - (CGPoint)center; // 0x166d9
// declared property setter: - (void)setCenter:(CGPoint)center; // 0x166a5
// declared property getter: - (id)kenBurnsType; // 0x1668d
// declared property setter: - (void)setKenBurnsType:(id)type; // 0x16665
// declared property getter: - (id)frameID; // 0x1664d
// declared property setter: - (void)setFrameID:(id)anId; // 0x16625
// declared property getter: - (BOOL)durationIsDefined; // 0x15fdd
// declared property getter: - (double)duration; // 0x15fed
// declared property getter: - (BOOL)startTimeIsDefined; // 0x16005
// declared property getter: - (double)startTime; // 0x16015
// declared property getter: - (double)audioDuckOutDuration; // 0x165f1
// declared property setter: - (void)setAudioDuckOutDuration:(double)duration; // 0x165bd
// declared property getter: - (double)audioDuckInDuration; // 0x16589
// declared property setter: - (void)setAudioDuckInDuration:(double)duration; // 0x16555
// declared property getter: - (float)audioDuckLevel; // 0x1602d
// declared property setter: - (void)setAudioDuckLevel:(float)level; // 0x1603d
// declared property getter: - (double)audioFadeOutDuration; // 0x16521
// declared property setter: - (void)setAudioFadeOutDuration:(double)duration; // 0x164ed
// declared property getter: - (double)audioFadeInDuration; // 0x164b9
// declared property setter: - (void)setAudioFadeInDuration:(double)duration; // 0x16485
// declared property getter: - (float)audioVolume; // 0x1604d
// declared property setter: - (void)setAudioVolume:(float)volume; // 0x1605d
// declared property getter: - (unsigned)index; // 0x1606d
// declared property setter: - (void)setIndex:(unsigned)index; // 0x1607d
@end
@interface MCSlide (MCFilterSupport) <MCFilterSupport>
@property(readonly, assign) NSSet *filters; // G=0x1895d;
@property(readonly, assign) NSArray *orderedFilters; // G=0x18819;
- (void)initFiltersWithImprints:(id)imprints; // 0x196e1
- (void)demolishFilters; // 0x19861
- (id)imprintsForFilters; // 0x199f5
// declared property getter: - (id)orderedFilters; // 0x18819
// declared property getter: - (id)filters; // 0x1895d
- (unsigned)countOfFilters; // 0x18a0d
- (id)filterAtIndex:(unsigned)index; // 0x19ae1
- (id)addFilterWithFilterID:(id)filterID; // 0x18a69
- (id)insertFilterWithFilterID:(id)filterID atIndex:(unsigned)index; // 0x19c35
- (void)removeFiltersAtIndices:(id)indices; // 0x19ea1
- (void)removeAllFilters; // 0x18a9d
- (void)moveFiltersAtIndices:(id)indices toIndex:(unsigned)index; // 0x1a101
- (void)observeFilter:(id)filter; // 0x18afd
- (void)unobserveFilter:(id)filter; // 0x18b91
@end
@interface MCSlide (MCAnimationPathSupport) <MCAnimationPathSupport>
@property(readonly, assign) NSSet *animationPaths; // G=0x186f9;
@property(readonly, assign) unsigned countOfAnimationPaths; // G=0x187a9;
- (void)initAnimationPathsWithImprints:(id)imprints; // 0x18bf9
- (void)demolishAnimationPaths; // 0x18d89
- (id)imprintsForAnimationPaths; // 0x18f29
// declared property getter: - (id)animationPaths; // 0x186f9
// declared property getter: - (unsigned)countOfAnimationPaths; // 0x187a9
- (id)animationPathForKey:(id)key createIfNeeded:(BOOL)needed; // 0x19015
- (id)animationPathForKey:(id)key; // 0x18805
- (void)removeAnimationPathForKey:(id)key; // 0x192c1
- (void)removeAllAnimationPaths; // 0x194f1
@end
| 3,228 |
1,104 | /*
* Copyright (c) 2010 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Time Series
* Forecasting. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/*
* JFreeChartDriver.java
* Copyright (C) 2010 Pentaho Corporation
*/
package weka.classifiers.timeseries.eval.graph;
import java.awt.BasicStroke;
import java.awt.Image;
import java.io.File;
import java.util.List;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYErrorRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYIntervalSeries;
import org.jfree.data.xy.XYIntervalSeriesCollection;
import weka.classifiers.evaluation.NumericPrediction;
import weka.classifiers.timeseries.AbstractForecaster;
import weka.classifiers.timeseries.TSForecaster;
import weka.classifiers.timeseries.WekaForecaster;
import weka.classifiers.timeseries.core.TSLagMaker;
import weka.classifiers.timeseries.core.TSLagUser;
import weka.classifiers.timeseries.eval.ErrorModule;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
/**
* A Graph driver that uses the JFreeChart library.
*
* @author <NAME> (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 50889 $
*/
public class JFreeChartDriver extends GraphDriver {
protected JFreeChart getPredictedTargetsChart(TSForecaster forecaster,
ErrorModule preds, List<String> targetNames, int stepNumber,
int instanceNumOffset, Instances data) {
if (forecaster instanceof TSLagUser && data != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (lagMaker.getAdjustForTrends()
&& !lagMaker.isUsingAnArtificialTimeIndex()) {
// fill in any missing time stamps only
data = new Instances(data);
data = weka.classifiers.timeseries.core.Utils.replaceMissing(data,
null, lagMaker.getTimeStampField(), true,
lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
}
}
// set up a collection of predicted and actual series
XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();
for (String target : targetNames) {
XYIntervalSeries targetSeries = new XYIntervalSeries(target + "-actual",
false, false);
xyDataset.addSeries(targetSeries);
targetSeries = new XYIntervalSeries(target + "-predicted", false, false);
xyDataset.addSeries(targetSeries);
}
ValueAxis timeAxis = null;
NumberAxis valueAxis = new NumberAxis("");
valueAxis.setAutoRangeIncludesZero(false);
int timeIndex = -1;
boolean timeAxisIsDate = false;
if (forecaster instanceof TSLagUser && data != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (!lagMaker.isUsingAnArtificialTimeIndex()
&& lagMaker.getAdjustForTrends()) {
String timeName = lagMaker.getTimeStampField();
if (data.attribute(timeName).isDate()) {
timeAxis = new DateAxis("");
timeAxisIsDate = true;
timeIndex = data.attribute(timeName).index();
}
}
}
if (timeAxis == null) {
timeAxis = new NumberAxis("");
((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
}
// now populate the series
boolean hasConfidenceIntervals = false;
for (int i = 0; i < targetNames.size(); i++) {
String targetName = targetNames.get(i);
List<NumericPrediction> predsForI = preds
.getPredictionsForTarget(targetName);
int predIndex = xyDataset.indexOf(targetName + "-predicted");
int actualIndex = xyDataset.indexOf(targetName + "-actual");
XYIntervalSeries predSeries = xyDataset.getSeries(predIndex);
XYIntervalSeries actualSeries = xyDataset.getSeries(actualIndex);
for (int j = 0; j < predsForI.size(); j++) {
double x = Utils.missingValue();
if (timeAxisIsDate) {
if (instanceNumOffset + j + stepNumber - 1 < data.numInstances()) {
x = data.instance(instanceNumOffset + j + stepNumber - 1).value(
timeIndex);
}
} else {
x = instanceNumOffset + j + stepNumber;
}
double yPredicted = predsForI.get(j).predicted();
double yHigh = yPredicted;
double yLow = yPredicted;
double[][] conf = predsForI.get(j).predictionIntervals();
if (conf.length > 0) {
yLow = conf[0][0];
yHigh = conf[0][1];
hasConfidenceIntervals = true;
}
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) {
if (predSeries != null) {
predSeries.add(x, x, x, yPredicted, yLow, yHigh);
}
// System.err.println("* " + yPredicted + " " + x);
}
double yActual = predsForI.get(j).actual();
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) {
if (actualSeries != null) {
actualSeries.add(x, x, x, yActual, yActual, yActual);
}
}
}
}
// set up the chart
String title = "" + stepNumber + " step-ahead predictions for: ";
for (String s : targetNames) {
title += s + ",";
}
title = title.substring(0, title.lastIndexOf(","));
/*
* String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
* + ")";
*/
if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
}
XYErrorRenderer renderer = new XYErrorRenderer();
renderer.setBaseLinesVisible(true);
renderer.setDrawXError(false);
renderer.setDrawYError(true);
// renderer.setShapesFilled(true);
XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,
plot, true);
chart.setBackgroundPaint(java.awt.Color.white);
TextTitle chartTitle = chart.getTitle();
String fontName = chartTitle.getFont().getFontName();
java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
chartTitle.setFont(newFont);
return chart;
}
/**
* Save a chart to a file.
*
* @param chart the chart to save
* @param filename the filename to save to
* @param width width of the saved image
* @param height height of the saved image
* @throws Exception if the chart can't be saved for some reason
*/
@Override
public void saveChartToFile(JPanel chart, String filename, int width,
int height) throws Exception {
if (!(chart instanceof ChartPanel)) {
throw new Exception("Chart is not a JFreeChart!");
}
if (filename.toLowerCase().lastIndexOf(".png") < 0) {
filename = filename + ".png";
}
ChartUtilities.saveChartAsPNG(new File(filename),
((ChartPanel) chart).getChart(), width, height);
}
/**
* Get an image representation of the supplied chart.
*
* @param chart the chart to get an image of.
* @param width width of the chart
* @param height height of the chart
* @return an Image of the chart
* @throws Exception if the image can't be created for some reason
*/
@Override
public Image getImageFromChart(JPanel chart, int width, int height)
throws Exception {
if (!(chart instanceof ChartPanel)) {
throw new Exception("Chart is not a JFreeChart!");
}
Image result = ((ChartPanel) chart).getChart().createBufferedImage(width,
height);
return result;
}
/**
* Return the graph encapsulated in a panel.
*
* @param width the width in pixels of the graph
* @param height the height in pixels of the graph
* @param forecaster the forecaster
* @param preds an ErrorModule that contains predictions for all targets for
* the specified step ahead. Targets are in the same order returned
* by TSForecaster.getFieldsToForecast()
* @param targetNames the list of target names to plot
* @param stepNumber which step ahead to graph for specified targets
* @param instanceNumOffset how far into the data the predictions start from
* @param data the instances that these predictions correspond to (may be
* null)
* @return an image of the graph
*/
@Override
public JPanel getGraphPanelTargets(TSForecaster forecaster,
ErrorModule preds, List<String> targetNames, int stepNumber,
int instanceNumOffset, Instances data) throws Exception {
JFreeChart chart = getPredictedTargetsChart(forecaster, preds, targetNames,
stepNumber, instanceNumOffset, data);
ChartPanel result = new ChartPanel(chart, false, true, true, true, false);
return result;
}
protected JFreeChart getPredictedStepsChart(TSForecaster forecaster,
List<ErrorModule> preds, String targetName, List<Integer> stepsToPlot,
int instanceNumOffset, Instances data) {
if (forecaster instanceof TSLagUser && data != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (lagMaker.getAdjustForTrends()
&& !lagMaker.isUsingAnArtificialTimeIndex()) {
// fill in any missing time stamps only
data = new Instances(data);
data = weka.classifiers.timeseries.core.Utils.replaceMissing(data,
null, lagMaker.getTimeStampField(), true,
lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
}
}
// set up a collection of predicted series
XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();
XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false,
false);
xyDataset.addSeries(targetSeries);
// for (int i = 0; i < preds.size(); i++) {
for (int z = 0; z < stepsToPlot.size(); z++) {
int i = stepsToPlot.get(z);
i--;
// ignore out of range steps
if (i < 0 || i >= preds.size()) {
continue;
}
String step = "-steps";
if (i == 0) {
step = "-step";
}
targetSeries = new XYIntervalSeries(targetName + "_" + (i + 1) + step
+ "-ahead", false, false);
xyDataset.addSeries(targetSeries);
}
ValueAxis timeAxis = null;
NumberAxis valueAxis = new NumberAxis("");
valueAxis.setAutoRangeIncludesZero(false);
int timeIndex = -1;
boolean timeAxisIsDate = false;
if (forecaster instanceof TSLagUser && data != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (!lagMaker.isUsingAnArtificialTimeIndex()
&& lagMaker.getAdjustForTrends()) {
String timeName = lagMaker.getTimeStampField();
if (data.attribute(timeName).isDate()) {
timeAxis = new DateAxis("");
timeAxisIsDate = true;
timeIndex = data.attribute(timeName).index();
}
}
}
if (timeAxis == null) {
timeAxis = new NumberAxis("");
((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
}
// now populate the series
// for (int i = 0; i < preds.size(); i++) {
boolean doneActual = false;
boolean hasConfidenceIntervals = false;
for (int z = 0; z < stepsToPlot.size(); z++) {
int i = stepsToPlot.get(z);
i--;
// ignore out of range steps
if (i < 0 || i >= preds.size()) {
continue;
}
ErrorModule predsForStepI = preds.get(i);
List<NumericPrediction> predsForTargetAtI = predsForStepI
.getPredictionsForTarget(targetName);
String step = "-steps";
if (i == 0) {
step = "-step";
}
int predIndex = xyDataset.indexOf(targetName + "_" + (i + 1) + step
+ "-ahead");
XYIntervalSeries predSeries = xyDataset.getSeries(predIndex);
XYIntervalSeries actualSeries = null;
if (!doneActual) {
int actualIndex = xyDataset.indexOf(targetName);
actualSeries = xyDataset.getSeries(actualIndex);
}
for (int j = 0; j < predsForTargetAtI.size(); j++) {
double x = Utils.missingValue();
if (timeAxisIsDate) {
if (instanceNumOffset + j + i < data.numInstances()) {
x = data.instance(instanceNumOffset + j + i).value(timeIndex);
}
} else {
x = instanceNumOffset + j + i;
}
double yPredicted = predsForTargetAtI.get(j).predicted();
double yHigh = yPredicted;
double yLow = yPredicted;
double[][] conf = predsForTargetAtI.get(j).predictionIntervals();
if (conf.length > 0) {
yLow = conf[0][0];
yHigh = conf[0][1];
hasConfidenceIntervals = true;
}
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) {
if (predSeries != null) {
predSeries.add(x, x, x, yPredicted, yLow, yHigh);
}
// System.err.println("* " + yPredicted + " " + x);
}
if (!doneActual && actualSeries != null) {
double yActual = predsForTargetAtI.get(j).actual();
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) {
actualSeries.add(x, x, x, yActual, yActual, yActual);
}
}
}
if (actualSeries != null) {
doneActual = true;
}
}
// set up the chart
String title = "";
for (int i : stepsToPlot) {
title += i + ",";
}
title = title.substring(0, title.lastIndexOf(","));
title += " step-ahead predictions for " + targetName;
/*
* String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
* + ")";
*/
if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
}
XYErrorRenderer renderer = new XYErrorRenderer();
renderer.setBaseLinesVisible(true);
// renderer.setShapesFilled(true);
XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,
plot, true);
chart.setBackgroundPaint(java.awt.Color.white);
TextTitle chartTitle = chart.getTitle();
String fontName = chartTitle.getFont().getFontName();
java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
chartTitle.setFont(newFont);
return chart;
}
/**
* Return the graph encapsulated in a JPanel.
*
* @param forecaster the forecaster
* @param preds a list of ErrorModules, one for each consecutive step ahead
* prediction set
* @param targetName the name of the target field to plot
* @param stepsToPlot a list of step numbers for the step-ahead prediction
* sets to plot to plot for the specified target.
* @param instanceNumOffset how far into the data the predictions start from
* @param data the instances that these predictions correspond to (may be
* null)
* @return an image of the graph.
*/
@Override
public JPanel getGraphPanelSteps(TSForecaster forecaster,
List<ErrorModule> preds, String targetName, List<Integer> stepsToPlot,
int instanceNumOffset, Instances data) throws Exception {
JFreeChart chart = getPredictedStepsChart(forecaster, preds, targetName,
stepsToPlot, instanceNumOffset, data);
ChartPanel result = new ChartPanel(chart, false, true, true, true, false);
return result;
}
protected JFreeChart getFutureForecastChart(TSForecaster forecaster,
List<List<NumericPrediction>> preds, List<String> targetNames,
Instances history) {
if (forecaster instanceof TSLagUser && history != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (lagMaker.getAdjustForTrends()
&& !lagMaker.isUsingAnArtificialTimeIndex()) {
// fill in any missing time stamps only
history = new Instances(history);
history = weka.classifiers.timeseries.core.Utils.replaceMissing(
history, null, lagMaker.getTimeStampField(), true,
lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
}
}
// set up a collection of series
XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();
if (history != null) {
// add actual historical data values
for (String targetName : targetNames) {
XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false,
false);
xyDataset.addSeries(targetSeries);
}
}
// add predicted series
for (String targetName : targetNames) {
XYIntervalSeries targetSeries = new XYIntervalSeries(targetName
+ "-predicted", false, false);
xyDataset.addSeries(targetSeries);
}
ValueAxis timeAxis = null;
NumberAxis valueAxis = new NumberAxis("");
valueAxis.setAutoRangeIncludesZero(false);
int timeIndex = -1;
boolean timeAxisIsDate = false;
double artificialTimeStart = 0;
double lastRealTimeValue = Utils.missingValue();
if (forecaster instanceof TSLagUser && history != null) {
TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
if (!lagMaker.isUsingAnArtificialTimeIndex()
&& lagMaker.getAdjustForTrends()) {
String timeName = lagMaker.getTimeStampField();
if (history.attribute(timeName).isDate()) {
timeAxis = new DateAxis("");
timeAxisIsDate = true;
timeIndex = history.attribute(timeName).index();
}
} else {
try {
artificialTimeStart = (history != null) ? 1 : lagMaker
.getArtificialTimeStartValue() + 1;
} catch (Exception ex) {
}
}
}
if (timeAxis == null) {
timeAxis = new NumberAxis("");
((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
}
boolean hasConfidenceIntervals = false;
// now populate the series
if (history != null) {
// do the actuals first
for (int i = 0; i < history.numInstances(); i++) {
Instance current = history.instance(i);
for (String targetName : targetNames) {
int dataIndex = history.attribute(targetName.trim()).index();
if (dataIndex >= 0) {
XYIntervalSeries actualSeries = null;
int actualIndex = xyDataset.indexOf(targetName);
actualSeries = xyDataset.getSeries(actualIndex);
double x = Utils.missingValue();
if (timeAxisIsDate) {
x = current.value(timeIndex);
if (!Utils.isMissingValue(x)) {
lastRealTimeValue = x;
}
} else {
x = artificialTimeStart;
}
double y = Utils.missingValue();
y = current.value(dataIndex);
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
if (actualSeries != null) {
actualSeries.add(x, x, x, y, y, y);
}
}
}
}
if (!timeAxisIsDate) {
artificialTimeStart++;
}
}
}
// now do the futures
List<String> forecasterTargets = AbstractForecaster.stringToList(forecaster
.getFieldsToForecast());
// loop over the steps
for (int j = 0; j < preds.size(); j++) {
List<NumericPrediction> predsForStepJ = preds.get(j);
// advance the real time index (if appropriate)
if (timeAxisIsDate) {
lastRealTimeValue = ((TSLagUser) forecaster).getTSLagMaker()
.advanceSuppliedTimeValue(lastRealTimeValue);
}
for (String targetName : targetNames) {
// look up this requested target in the list that the forecaster
// has predicted
int predIndex = forecasterTargets.indexOf(targetName.trim());
if (predIndex >= 0) {
NumericPrediction predsForTargetAtStepJ = predsForStepJ
.get(predIndex);
XYIntervalSeries predSeries = null;
int datasetIndex = xyDataset.indexOf(targetName + "-predicted");
predSeries = xyDataset.getSeries(datasetIndex);
if (predSeries != null) {
double y = predsForTargetAtStepJ.predicted();
double x = Utils.missingValue();
double yHigh = y;
double yLow = y;
double[][] conf = predsForTargetAtStepJ.predictionIntervals();
if (conf.length > 0) {
yLow = conf[0][0];
yHigh = conf[0][1];
hasConfidenceIntervals = true;
}
if (!timeAxisIsDate) {
x = artificialTimeStart;
} else {
x = lastRealTimeValue;
}
if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
predSeries.add(x, x, x, y, yLow, yHigh);
}
}
}
}
// advance the artificial time index (if appropriate)
if (!timeAxisIsDate) {
artificialTimeStart++;
}
}
String title = "Future forecast for: ";
for (String s : targetNames) {
title += s + ",";
}
title = title.substring(0, title.lastIndexOf(","));
/*
* String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
* + ")";
*/
if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
}
XYErrorRenderer renderer = new XYErrorRenderer();
// renderer.setShapesFilled(true);
XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
// renderer = (XYErrorRenderer)plot.getRenderer();
if (history != null) {
for (String targetName : targetNames) {
XYIntervalSeries predSeries = null;
int predIndex = xyDataset.indexOf(targetName + "-predicted");
predSeries = xyDataset.getSeries(predIndex);
XYIntervalSeries actualSeries = null;
int actualIndex = xyDataset.indexOf(targetName);
actualSeries = xyDataset.getSeries(actualIndex);
if (actualSeries != null && predSeries != null) {
// match the color of the actual series
java.awt.Paint actualPaint = renderer.lookupSeriesPaint(actualIndex);
renderer.setSeriesPaint(predIndex, actualPaint);
// now set the line style to dashed
BasicStroke dashed = new BasicStroke(1.5f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, new float[] { 5.0f }, 0.0f);
renderer.setSeriesStroke(predIndex, dashed);
}
}
}
renderer.setBaseLinesVisible(true);
renderer.setDrawXError(false);
renderer.setDrawYError(true);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT,
plot, true);
chart.setBackgroundPaint(java.awt.Color.white);
TextTitle chartTitle = chart.getTitle();
String fontName = chartTitle.getFont().getFontName();
java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
chartTitle.setFont(newFont);
return chart;
}
/**
* Return the graph encapsulated in a JPanel
*
* @param forecaster the forecaster
* @param preds a list of list of predictions for *all* targets. The outer
* list is indexed by step number (i.e. the first entry is the 1-step
* ahead forecasts, the second is the 2-steps ahead forecasts etc.)
* and the inner list is indexed by target in the same order as the
* list of targets returned by TSForecaster.getFieldsToForecast().
* @param targetNames the list of target names to plot
* @param history a set of instances from which predictions are assumed to
* follow on from. May be null, in which case just the predictions
* are plotted.
* @return an image of the graph
*/
@Override
public JPanel getPanelFutureForecast(TSForecaster forecaster,
List<List<NumericPrediction>> preds, List<String> targetNames,
Instances history) throws Exception {
JFreeChart chart = getFutureForecastChart(forecaster, preds, targetNames,
history);
ChartPanel result = new ChartPanel(chart, false, true, true, true, false);
return result;
}
}
| 10,098 |
1,565 | <reponame>morph3ux/async-storage
package com.reactnativecommunity.asyncstorage;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
// A utility class that migrates a scoped AsyncStorage database to RKStorage.
// This utility only runs if the RKStorage file has not been created yet.
public class AsyncStorageExpoMigration {
static final String LOG_TAG = "AsyncStorageExpoMigration";
public static void migrate(Context context) {
// Only migrate if the default async storage file does not exist.
if (isAsyncStorageDatabaseCreated(context)) {
return;
}
ArrayList<File> expoDatabases = getExpoDatabases(context);
File expoDatabase = getLastModifiedFile(expoDatabases);
if (expoDatabase == null) {
Log.v(LOG_TAG, "No scoped database found");
return;
}
try {
// Create the storage file
ReactDatabaseSupplier.getInstance(context).get();
copyFile(new FileInputStream(expoDatabase), new FileOutputStream(context.getDatabasePath(ReactDatabaseSupplier.DATABASE_NAME)));
Log.v(LOG_TAG, "Migrated most recently modified database " + expoDatabase.getName() + " to RKStorage");
} catch (Exception e) {
Log.v(LOG_TAG, "Failed to migrate scoped database " + expoDatabase.getName());
e.printStackTrace();
return;
}
try {
for (File file : expoDatabases) {
if (file.delete()) {
Log.v(LOG_TAG, "Deleted scoped database " + file.getName());
} else {
Log.v(LOG_TAG, "Failed to delete scoped database " + file.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
Log.v(LOG_TAG, "Completed the scoped AsyncStorage migration");
}
private static boolean isAsyncStorageDatabaseCreated(Context context) {
return context.getDatabasePath(ReactDatabaseSupplier.DATABASE_NAME).exists();
}
// Find all database files that the user may have created while using Expo.
private static ArrayList<File> getExpoDatabases(Context context) {
ArrayList<File> scopedDatabases = new ArrayList<>();
try {
File databaseDirectory = context.getDatabasePath("noop").getParentFile();
File[] directoryListing = databaseDirectory.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Find all databases matching the Expo scoped key, and skip any database journals.
if (child.getName().startsWith("RKStorage-scoped-experience-") && !child.getName().endsWith("-journal")) {
scopedDatabases.add(child);
}
}
}
} catch (Exception e) {
// Just in case anything happens catch and print, file system rules can tend to be different across vendors.
e.printStackTrace();
}
return scopedDatabases;
}
// Returns the most recently modified file.
// If a user publishes an app with Expo, then changes the slug
// and publishes again, a new database will be created.
// We want to select the most recent database and migrate it to RKStorage.
private static File getLastModifiedFile(ArrayList<File> files) {
if (files.size() == 0) {
return null;
}
long lastMod = -1;
File lastModFile = null;
for (File child : files) {
long modTime = getLastModifiedTimeInMillis(child);
if (modTime > lastMod) {
lastMod = modTime;
lastModFile = child;
}
}
if (lastModFile != null) {
return lastModFile;
}
return files.get(0);
}
private static long getLastModifiedTimeInMillis(File file) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return getLastModifiedTimeFromBasicFileAttrs(file);
} else {
return file.lastModified();
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@RequiresApi(Build.VERSION_CODES.O)
private static long getLastModifiedTimeFromBasicFileAttrs(File file) {
try {
return Files.readAttributes(file.toPath(), BasicFileAttributes.class).creationTime().toMillis();
} catch (Exception e) {
return -1;
}
}
private static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
}
| 2,444 |
852 | <filename>Alignment/CommonAlignmentAlgorithm/src/AlignmentIORoot.cc
#include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h"
#include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIORoot.h"
#include "Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIORoot.h"
// this class's header
#include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h"
// ----------------------------------------------------------------------------
// write alignment parameters
void AlignmentIORoot::writeAlignmentParameters(
const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) {
AlignmentParametersIORoot theIO;
ierr = 0;
int iret;
iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.write(alivec, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// read alignment parameters
align::Parameters AlignmentIORoot::readAlignmentParameters(const align::Alignables& alivec,
const char* filename,
int iter,
int& ierr) {
align::Parameters result;
AlignmentParametersIORoot theIO;
ierr = 0;
int iret;
iret = theIO.open(filename, iter, false);
if (iret != 0) {
ierr = -1;
return result;
}
result = theIO.read(alivec, iret);
if (iret != 0) {
ierr = -2;
return result;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return result;
}
return result;
}
// ----------------------------------------------------------------------------
// write alignment parameters
void AlignmentIORoot::writeOrigRigidBodyAlignmentParameters(
const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) {
AlignmentParametersIORoot theIO;
ierr = 0;
int iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.writeOrigRigidBody(alivec, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// write correlations
void AlignmentIORoot::writeCorrelations(
const align::Correlations& cormap, const char* filename, int iter, bool validCheck, int& ierr) {
AlignmentCorrelationsIORoot theIO;
ierr = 0;
int iret;
iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.write(cormap, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// read correlations
align::Correlations AlignmentIORoot::readCorrelations(const align::Alignables& alivec,
const char* filename,
int iter,
int& ierr) {
align::Correlations result;
AlignmentCorrelationsIORoot theIO;
ierr = 0;
int iret;
iret = theIO.open(filename, iter, false);
if (iret != 0) {
ierr = -1;
return result;
}
result = theIO.read(alivec, iret);
if (iret != 0) {
ierr = -2;
return result;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return result;
}
return result;
}
// ----------------------------------------------------------------------------
// write absolute position of alignable
void AlignmentIORoot::writeAlignableAbsolutePositions(
const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) {
AlignableDataIORoot theIO(AlignableDataIORoot::Abs);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.writeAbsPos(alivec, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// read absolute position of alignable
AlignablePositions AlignmentIORoot::readAlignableAbsolutePositions(const align::Alignables& alivec,
const char* filename,
int iter,
int& ierr) {
AlignablePositions result;
AlignableDataIORoot theIO(AlignableDataIORoot::Abs);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, false);
if (iret != 0) {
ierr = -1;
return result;
}
result = theIO.readAbsPos(alivec, iret);
if (iret != 0) {
ierr = -2;
return result;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return result;
}
return result;
}
// ----------------------------------------------------------------------------
// write original position of alignable
void AlignmentIORoot::writeAlignableOriginalPositions(
const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) {
AlignableDataIORoot theIO(AlignableDataIORoot::Org);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.writeOrgPos(alivec, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// read original position of alignable
AlignablePositions AlignmentIORoot::readAlignableOriginalPositions(const align::Alignables& alivec,
const char* filename,
int iter,
int& ierr) {
AlignablePositions result;
AlignableDataIORoot theIO(AlignableDataIORoot::Org);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, false);
if (iret != 0) {
ierr = -1;
return result;
}
result = theIO.readOrgPos(alivec, iret);
if (iret != 0) {
ierr = -2;
return result;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return result;
}
return result;
}
// ----------------------------------------------------------------------------
// write relative position of alignable
void AlignmentIORoot::writeAlignableRelativePositions(
const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) {
AlignableDataIORoot theIO(AlignableDataIORoot::Rel);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, true);
if (iret != 0) {
ierr = -1;
return;
}
iret = theIO.writeRelPos(alivec, validCheck);
if (iret != 0) {
ierr = -2;
return;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return;
}
}
// ----------------------------------------------------------------------------
// read relative position of alignable
AlignableShifts AlignmentIORoot::readAlignableRelativePositions(const align::Alignables& alivec,
const char* filename,
int iter,
int& ierr) {
AlignableShifts result;
AlignableDataIORoot theIO(AlignableDataIORoot::Rel);
ierr = 0;
int iret;
iret = theIO.open(filename, iter, false);
if (iret != 0) {
ierr = -1;
return result;
}
result = theIO.readRelPos(alivec, iret);
if (iret != 0) {
ierr = -2;
return result;
}
iret = theIO.close();
if (iret != 0) {
ierr = -3;
return result;
}
return result;
}
| 3,586 |
984 | <filename>mapper-processor/src/test/java/com/datastax/oss/driver/internal/mapper/processor/entity/EntityNamingStrategyTest.java
/*
* Copyright DataStax, 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.datastax.oss.driver.internal.mapper.processor.entity;
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy;
import com.datastax.oss.driver.api.mapper.entity.naming.NameConverter;
import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention;
import com.datastax.oss.driver.internal.mapper.processor.MapperProcessorTest;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import javax.lang.model.element.Modifier;
import org.junit.Test;
public class EntityNamingStrategyTest extends MapperProcessorTest {
private static final ClassName CUSTOM_CONVERTER_CLASS_NAME =
ClassName.get("test", "CustomConverter");
private static final TypeSpec CUSTOM_CONVERTER_CLASS =
TypeSpec.classBuilder(CUSTOM_CONVERTER_CLASS_NAME)
.addSuperinterface(NameConverter.class)
.addMethod(
MethodSpec.methodBuilder("toCassandraName")
.addModifiers(Modifier.PUBLIC)
.returns(String.class)
.addParameter(String.class, "javaName")
.addStatement("return null;") // doesn't matter, converter won't be invoked
.build())
.build();
// Common code for the entity class, to avoid repeating it in every test
private TypeSpec.Builder entityTemplate() {
return TypeSpec.classBuilder("TestEntity")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Entity.class)
.addField(TypeName.INT, "i", Modifier.PRIVATE)
.addMethod(
MethodSpec.methodBuilder("setI")
.addParameter(TypeName.INT, "i")
.addModifiers(Modifier.PUBLIC)
.build())
.addMethod(
MethodSpec.methodBuilder("getI")
.returns(TypeName.INT)
.addModifiers(Modifier.PUBLIC)
.addStatement("return 0")
.build());
}
@Test
public void should_fail_if_both_convention_and_converter_specified() {
should_fail_with_expected_error(
"Invalid annotation configuration: "
+ "NamingStrategy must have either a 'convention' or 'customConverterClass' argument, "
+ "but not both",
"test",
CUSTOM_CONVERTER_CLASS,
entityTemplate()
.addAnnotation(
AnnotationSpec.builder(NamingStrategy.class)
.addMember("convention", "$T.CASE_INSENSITIVE", NamingConvention.class)
.addMember("customConverterClass", "$T.class", CUSTOM_CONVERTER_CLASS_NAME)
.build())
.build());
}
@Test
public void should_fail_if_neither_convention_nor_converter_specified() {
should_fail_with_expected_error(
"Invalid annotation configuration: "
+ "NamingStrategy must have either a 'convention' or 'customConverterClass' argument",
"test",
CUSTOM_CONVERTER_CLASS,
entityTemplate().addAnnotation(NamingStrategy.class).build());
}
@Test
public void should_warn_if_multiple_conventions_specified() {
should_succeed_with_expected_warning(
"Too many naming conventions: "
+ "NamingStrategy must have at most one 'convention' argument "
+ "(will use the first one: CASE_INSENSITIVE)",
"test",
CUSTOM_CONVERTER_CLASS,
entityTemplate()
.addAnnotation(
AnnotationSpec.builder(NamingStrategy.class)
.addMember(
"convention",
"{ $1T.CASE_INSENSITIVE, $1T.EXACT_CASE }",
NamingConvention.class)
.build())
.build());
}
@Test
public void should_warn_if_multiple_converters_specified() {
should_succeed_with_expected_warning(
"Too many custom converters: "
+ "NamingStrategy must have at most one 'customConverterClass' argument "
+ "(will use the first one: test.CustomConverter)",
"test",
CUSTOM_CONVERTER_CLASS,
entityTemplate()
.addAnnotation(
AnnotationSpec.builder(NamingStrategy.class)
.addMember(
"customConverterClass",
"{ $1T.class, $1T.class }",
CUSTOM_CONVERTER_CLASS_NAME)
.build())
.build());
}
}
| 2,313 |
1,338 | /*
* Copyright 2000, <NAME>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _AUTO_ICON_H_
#define _AUTO_ICON_H_
#include <SupportDefs.h>
class BBitmap;
class AutoIcon {
public:
AutoIcon(const char* signature)
:
fSignature(signature),
fbits(0),
fBitmap(0)
{
}
AutoIcon(const uchar* bits)
:
fSignature(0),
fbits(bits),
fBitmap(0)
{
}
~AutoIcon();
operator BBitmap*()
{
return Bitmap();
}
BBitmap* Bitmap();
private:
const char* fSignature;
const uchar* fbits;
BBitmap* fBitmap;
};
#endif // _AUTO_ICON_H_
| 296 |
9,959 | // version :9
// unchanged
import lombok.val;
public class ValErrors {
public void unresolvableExpression() {
val c = d;
}
public void arrayInitializer() {
val e = { "foo", "bar"};
}
} | 75 |
2,151 | // 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 CHROME_BROWSER_DEVTOOLS_PROTOCOL_TARGET_HANDLER_H_
#define CHROME_BROWSER_DEVTOOLS_PROTOCOL_TARGET_HANDLER_H_
#include <set>
#include "base/memory/weak_ptr.h"
#include "chrome/browser/devtools/protocol/forward.h"
#include "chrome/browser/devtools/protocol/target.h"
#include "chrome/browser/media/router/presentation/independent_otr_profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "net/base/host_port_pair.h"
using RemoteLocations = std::set<net::HostPortPair>;
class TargetHandler : public protocol::Target::Backend {
public:
explicit TargetHandler(protocol::UberDispatcher* dispatcher);
~TargetHandler() override;
RemoteLocations& remote_locations() { return remote_locations_; }
// Target::Backend:
protocol::Response SetRemoteLocations(
std::unique_ptr<protocol::Array<protocol::Target::RemoteLocation>>
in_locations) override;
protocol::Response CreateBrowserContext(std::string* out_context_id) override;
protocol::Response CreateTarget(
const std::string& url,
protocol::Maybe<int> width,
protocol::Maybe<int> height,
protocol::Maybe<std::string> browser_context_id,
protocol::Maybe<bool> enable_begin_frame_control,
std::string* out_target_id) override;
protocol::Response GetBrowserContexts(
std::unique_ptr<protocol::Array<protocol::String>>* browser_context_ids)
override;
void DisposeBrowserContext(
const std::string& context_id,
std::unique_ptr<DisposeBrowserContextCallback> callback) override;
private:
RemoteLocations remote_locations_;
DISALLOW_COPY_AND_ASSIGN(TargetHandler);
};
#endif // CHROME_BROWSER_DEVTOOLS_PROTOCOL_TARGET_HANDLER_H_
| 662 |
459 | /**
* @file oglplus/object/auto_rebind.hpp
* @brief Object-target binding utilities
*
* @author <NAME>
*
* Copyright 2010-2014 <NAME>. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_OBJECT_AUTO_REBIND_1107121519_HPP
#define OGLPLUS_OBJECT_AUTO_REBIND_1107121519_HPP
#include <oglplus/object/wrapper.hpp>
namespace oglplus {
template <typename Object>
class AutoRebind;
/// Class that remembers the currently bound Object and rebinds it when destroyed
template <typename OpsTag, typename ObjTag>
class AutoRebind<Object<ObjectOps<OpsTag, ObjTag>>>
{
private:
typedef typename ObjectOps<OpsTag, ObjTag>::Target Target;
ObjectName<ObjTag> _object;
Target _target;
public:
/// Remembers the object currently bound to target
AutoRebind(Target target)
: _object(ObjBindingOps<ObjTag>::Binding(target))
, _target(target)
{ }
/// Re-binds the object to the target specified in constructor
~AutoRebind(void)
{
ObjBindingOps<ObjTag>::Bind(_target, _object);
}
};
} // namespace oglplus
#endif // include guard
| 415 |
647 | #include <gtest/gtest.h>
#define private public
#include "arena.hh"
#include <algorithm>
TEST( ArenaTest , one ) {
// Attempt to create an arena
Arena * arena;
arena = new Arena(5,5);
EXPECT_NE( (void*)0, arena);
}
TEST( ArenaTest , two ) {
// Make sure that arena size is what we specified.
Arena arena(5,5);
EXPECT_EQ( arena.getWidth(), 5);
EXPECT_EQ( arena.getHeight(), 5);
}
TEST( ArenaTest , three ) {
// Make sure that arena size is what we specified.
//Checks that x is width and y is height
Arena arena(10,7);
EXPECT_EQ( arena.getWidth(), 10);
EXPECT_EQ( arena.getHeight(), 7);
}
TEST( ArenaTest , four ) {
// Make sure that arena size is what we specified.
unsigned char ARENA_bits[] = {
0x10, 0x00, 0x86, 0x00, 0xe8, 0x00, 0x28, 0x00, 0xe2, 0x00, 0x02, 0x00};
Arena arena(10,6,ARENA_bits);
EXPECT_EQ( arena.getWidth(), 10);
EXPECT_EQ( arena.getHeight(), 6);
}
TEST( ArenaTest , calcOffset_one ) {
// Make sure that calcOffset properly adds its value to the variable offset
Arena arena(10,7);
size_t sz;
arena.calcOffset(1,1, sz);
EXPECT_EQ( sz, (size_t)11);
}
TEST( ArenaTest, calcOffset_two )
{
//Checks to make sure calcOffset function returns 1 if the if-statements
//evaluate to false
Arena arena(10,7);
size_t sz;
EXPECT_EQ (arena.calcOffset(15,12,sz), 1);
}
TEST( ArenaTest, calcOffset_three )
{
//Checks to make sure calcOffset function returns 0 if the if-statements
//evaluate to true
Arena arena(10,7);
size_t sz;
EXPECT_EQ (arena.calcOffset(5,6,sz), 0);
}
TEST ( ArenaTest, getGridSquare_one)
{
//Tests to make sure getGridSquare gets the gridSquare pointer at the location specified
//Which in this case is the first gridSquare
Arena arena(10,7);
GridSquare *agridsquare = arena.getGridSquare(0,0);
EXPECT_EQ (agridsquare, arena.grid);
}
TEST ( ArenaTest, getGridSquare_two)
{
//Tests if the gridSquare that getGridSquare picked up is the correct gridSquare
//by counting the spaces in memory
Arena arena(10,7);
GridSquare *agridsquare = arena.getGridSquare(2,3);
EXPECT_EQ (agridsquare, arena.grid + 32);
}
TEST (ArenaTest, getGridSquare_three)
{
//failure case for if-statement within getGridSquare
Arena arena(10,7);
EXPECT_EQ (arena.getGridSquare(50,70), ((GridSquare*)0));
}
TEST( ArenaTest, calcOffset2_one )
{
//Checks to make sure calcOffset function returns 1 if the if-statements
//evaluate to false
//failure case for first if-statement in calcOffset function
Arena arena(10,7);
size_t sz;
GridSquare* gridSquare = (GridSquare*)(arena.grid-1);
EXPECT_EQ (arena.calcOffset(gridSquare,sz), 1);
}
TEST(ArenaTest, calcOffset2_two)
{
//Tests if calcOffset function returns 0 when all if statement conditions are met
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(2,3);
size_t sz;
EXPECT_EQ (arena.calcOffset(agridSquare, sz), 0);
}
TEST(ArenaTest, calcOffset2_three)
{
//Tests if offset value is calculated correctly and put in the correct memory location
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(9,6);
size_t sz;
arena.calcOffset(agridSquare, sz);
EXPECT_EQ (sz, 69);
}
TEST(ArenaTest, calcOffset2_four)
{
//failure case for second if-statement in calcOffset function
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(15,10);
size_t sz;
EXPECT_EQ (arena.calcOffset(agridSquare, sz), 1);
}
TEST(ArenaTest, getGridSquareCoordinates_one)
{
//failure case for if-statement in getGridSquareCoordinates function
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(15,10);
Point coordinate;
std::cout << std::endl;
std::cout << "The following error message is expected from this test." << std::endl;
EXPECT_EQ (arena.getGridSquareCoordinates(agridSquare, coordinate),1);
std::cout << std::endl;
}
TEST(ArenaTest, getGridSquareCoordinates_two)
{
//Tests if the if-statement evaluates to true that the remainder of code (for that function)
//runs through
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(9,6);
Point coordinate;
EXPECT_EQ (arena.getGridSquareCoordinates(agridSquare, coordinate),0);
}
TEST(ArenaTest, getGridSquareCoordinates_three)
{
//Tests the arithmetic within the getGridSquareCooordinates function
//once the first if-statement evaluates to true
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(9,6);
Point coordinate;
arena.getGridSquareCoordinates(agridSquare, coordinate);
EXPECT_EQ (coordinate.x, 9);
EXPECT_EQ (coordinate.y, 6);
}
TEST(ArenaTest, movementCostEstimate_one)
{
//Failure case for the if-statement
//Ensures that the movementCostEstimate function fails appropiately
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(11,3);
GridSquare *anothergridSquare = arena.getGridSquare(12,4);
int costestimate;
std::cout << std::endl;
std::cout << "The following error messages are expected from this test." << std::endl;
EXPECT_EQ (arena.movementCostEstimate(agridSquare,anothergridSquare,costestimate), 1);
std::cout << std::endl;
}
TEST(ArenaTest, movementCostEstimate_two)
{
//Tests the case that the if-statement evaluates to true and if the following lines of code
//get executed in their entirety
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
GridSquare *anothergridSquare = arena.getGridSquare(3,4);
int costestimate;
EXPECT_EQ (arena.movementCostEstimate(agridSquare,anothergridSquare,costestimate), 0);
}
TEST(ArenaTest, movementCostEstimate_three)
{
//Tests to ensure that movementCostEstimate function is calculating the movement cost correctly
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
GridSquare *anothergridSquare = arena.getGridSquare(3,4);
int costestimate;
arena.movementCostEstimate(agridSquare,anothergridSquare,costestimate);
EXPECT_EQ (costestimate, 40);
}
TEST(ArenaTest, distanceBetween_one)
{
//Failure case for the if-statement
//Ensures that the distanceBetween function fails appropiately
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(11,3);
GridSquare *anothergridSquare = arena.getGridSquare(12,4);
int dist;
std::cout << std::endl;
std::cout << "The following error messages are expected from this test." << std::endl;
EXPECT_EQ (arena.distanceBetween(agridSquare,anothergridSquare,dist), 1);
std::cout << std::endl;
}
TEST(ArenaTest, distanceBetween_two)
{
//Tests the case that the if-statement evaluates to true and if the following lines of code
//get executed in their entirety
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
GridSquare *anothergridSquare = arena.getGridSquare(3,4);
int dist;
EXPECT_EQ (arena.distanceBetween(agridSquare,anothergridSquare,dist), 0);
}
TEST(ArenaTest, distanceBetween_three)
{
//Tests that the distanceBetween function properly calculates the distance between two gridSquares
//using gridSquare pointers
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
GridSquare *anothergridSquare = arena.getGridSquare(3,4);
int dist;
arena.distanceBetween(agridSquare,anothergridSquare,dist);
EXPECT_EQ (dist, 28);
}
TEST(ArenaTest, blockunblock_one)
{
//Tests to ensure that the block and unblock functions change the isBlocked member
//respective to their names
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
arena.block(1,2);
EXPECT_EQ (agridSquare->isBlocked,true);
arena.unblock(1,2);
EXPECT_EQ (agridSquare->isBlocked,false);
}
TEST(ArenaTest, mark_one)
{
//Tests to make sure that the mark function places a mark in the gridSquare desired
Arena arena(10,7);
GridSquare *agridSquare = arena.getGridSquare(1,2);
arena.mark(1,2, 'c');
EXPECT_EQ (agridSquare->mark,'c');
}
TEST(ArenaTest, getNeighbors_one)
{
//Tests that error message displays when trying to
std::cout << std::endl;
std::cout << "The following error messages are expected from this test." << std::endl;
Arena arena(10,7);
std::vector<GridSquare*> neighbors;
GridSquare *agridSquare = arena.getGridSquare(11,22);
neighbors = arena.getNeighbors(agridSquare);
int length = neighbors.size();
std::cout << std::endl; std::cout << std::endl;
EXPECT_EQ (length, 0);
}
TEST(ArenaTest, getNeighbors_two)
{
//Tests that getNeighbors returns the correct amount of neighbors within the vector
Arena arena(3,3);
GridSquare *agridSquare = arena.getGridSquare(1,1);
std::vector<GridSquare*> neighbors;
neighbors = arena.getNeighbors(agridSquare);
int length = neighbors.size();
EXPECT_EQ (length, 8);
}
TEST(ArenaTest, getNeighbors_three)
{
//Tests that getNeighbors returns the correct amount of neighbors when
//certain neighbors are blocked
Arena arena(3,3);
GridSquare *agridSquare = arena.getGridSquare(1,1);
std::vector<GridSquare*> neighbors;
arena.block(0,0);
arena.block(2,0);
arena.block(2,2);
neighbors = arena.getNeighbors(agridSquare);
int length = neighbors.size();
EXPECT_EQ (length, 5);
}
TEST(ArenaTest, getNeighbors_four)
{
//Tests that getNeighbors returns the correct GridSquare pointers in the neighbors vector
Arena arena(3,3);
GridSquare *agridSquare = arena.getGridSquare(1,1);
std::vector<GridSquare*> neighbors;
arena.block(0,0);
GridSquare* n0_1 = arena.getGridSquare(0,1);//0,1
GridSquare* n0_2 = arena.getGridSquare(0,2);//0,2
GridSquare* n1_0 = arena.getGridSquare(1,0);//1,0
GridSquare* n1_2 = arena.getGridSquare(1,2);// 1,2
arena.block(2,0);
GridSquare* n2_1 = arena.getGridSquare(2,1);//2,1
arena.block(2,2);
neighbors = arena.getNeighbors(agridSquare);
std::vector<GridSquare*>::iterator neighborsIterator;
//Test for (0,1) gridSquare
bool n0_1_found_flag = false;
neighborsIterator = find (neighbors.begin(),neighbors.end(), n0_1); //search for neighbor (0,1) in neighbors
if (neighborsIterator != neighbors.end()) //if the value is found
n0_1_found_flag = true; //change the found flag to true
Point point;
arena.getGridSquareCoordinates(*neighborsIterator,point);
std::cout << point.x << " "<< point.y << std::endl;
EXPECT_EQ(n0_1_found_flag, true);
//Test for (0,2) gridSquare
bool n0_2_found_flag = false;
neighborsIterator = find (neighbors.begin(),neighbors.end(), n0_2); //search for neighbor (0,2) in neighbors
if (neighborsIterator != neighbors.end()) //if the value is found
n0_2_found_flag = true; //change the found flag to true
arena.getGridSquareCoordinates(*neighborsIterator,point);
std::cout << point.x << " "<< point.y << std::endl;
EXPECT_EQ(n0_2_found_flag, true);
//Test for (1,0) gridSquare
bool n1_0_found_flag = false;
neighborsIterator = find (neighbors.begin(),neighbors.end(), n1_0); //search for neighbor (0,2) in neighbors
if (neighborsIterator != neighbors.end()) //if the value is found
n1_0_found_flag = true; //change the found flag to true
arena.getGridSquareCoordinates(*neighborsIterator,point);
std::cout << point.x << " "<< point.y << std::endl;
EXPECT_EQ(n1_0_found_flag, true);
//Test for (1,2) gridSquare
bool n1_2_found_flag = false;
neighborsIterator = find (neighbors.begin(),neighbors.end(), n1_2); //search for neighbor (1,2) in neighbors
if (neighborsIterator != neighbors.end()) //if the value is found
n1_2_found_flag = true; //change the found flag to true
arena.getGridSquareCoordinates(*neighborsIterator,point);
std::cout << point.x << " "<< point.y << std::endl;
EXPECT_EQ(n1_2_found_flag, true);
//Test for (2,1) gridSquare
bool n2_1_found_flag = false;
neighborsIterator = find (neighbors.begin(),neighbors.end(), n2_1); //search for neighbor (2,1) in neighbors
if (neighborsIterator != neighbors.end()) //if the value is found
n2_1_found_flag = true; //change the found flag to true
arena.getGridSquareCoordinates(*neighborsIterator,point);
std::cout << point.x << " "<< point.y << std::endl;
EXPECT_EQ(n2_1_found_flag, true);
}
| 4,311 |
480 | /*
* Copyright [2013-2021], 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.polardbx.transaction.tso;
import com.alibaba.polardbx.common.model.lifecycle.AbstractLifecycle;
import com.alibaba.polardbx.optimizer.utils.ITimestampOracle;
import java.util.concurrent.atomic.AtomicLong;
public final class LocalTimestampOracle extends AbstractLifecycle implements ITimestampOracle {
private final AtomicLong localClock;
public LocalTimestampOracle() {
localClock = new AtomicLong();
}
public LocalTimestampOracle(final long init) {
localClock = new AtomicLong(init);
}
@Override
public void setTimeout(long timeout) {
}
private long next(long threshold) {
// Make sure localClock is beyond the threshold
long last = localClock.get();
while (last < threshold && !localClock.compareAndSet(last, threshold)) {
last = localClock.get();
}
return localClock.incrementAndGet();
}
@Override
public long nextTimestamp() {
return next(System.currentTimeMillis() << BITS_LOGICAL_TIME);
}
}
| 537 |
2,690 | <reponame>NoahR02/Odin<filename>src/libtommath/mp_init_u64.c<gh_stars>1000+
#include "tommath_private.h"
#ifdef MP_INIT_U64_C
/* LibTomMath, multiple-precision integer library -- <NAME> */
/* SPDX-License-Identifier: Unlicense */
MP_INIT_INT(mp_init_u64, mp_set_u64, uint64_t)
#endif
| 124 |
380 | #include "igl/readOBJ.h"
#include "igl/writeOBJ.h"
// #include "igl/decimate.h"
#include <Eigen/Core>
#include "pythonlike.h"
#include <cstdlib> // exit()
#include <iostream>
#include <cassert>
#include <cstdio> // printf()
#include <igl/seam_edges.h>
#include "decimate.h"
#include "quadric_error_metric.h"
#include <igl/writeDMAT.h>
// An anonymous namespace. This hides these symbols from other modules.
namespace {
void usage( const char* argv0 )
{
std::cerr << "Usage: " << argv0 << " <path/to/input.obj> num-vertices <target_number_of_vertices> [--strict] [<strictness>]" << std::endl;
std::cerr << "Usage: " << argv0 << " <path/to/input.obj> percent-vertices <target_percent_of_vertices> [--strict] [<strictness>]" << std::endl;
exit(-1);
}
int count_seam_edge_num(const EdgeMap& seam_vertex_edges)
{
int count = 0;
for(auto & v : seam_vertex_edges) {
count += v.second.size();
}
return count / 2;
}
enum SeamAwareDegree
{
NoUVShapePreserving,
UVShapePreserving,
Seamless
};
/*
Decimates a triangle mesh down to a target number of vertices,
preserving the UV parameterization.
TODO Q: Should we do a version that does not preserve the UV parameterization exactly,
but instead returns a sequence of TC/FTC that can be used to transform a UV
point between the parameterizations of the decimated and undecimated mesh?
Input parameters:
V: The 3D positions of the input mesh (3 columns)
TC: The 2D texture coordinates of the input mesh (2 columns)
F: Indices into `V` for the three vertices of each triangle.
FTC: Indices into `TC` for the three vertices of each triangle.
Output parameters:
Vout: The 3D positions of the decimated mesh (3 columns),
where #vertices is as close as possible to `target_num_vertices`)
TCout: The texture coordinates of the decimated mesh (2 columns)
Fout: Indices into `Vout` for the three vertices of each triangle.
FTCout: Indices into `TCout` for the three vertices of each triangle.
Returns:
True if the routine succeeded, false if an error occurred.
Notes:
The output mesh will a vertex count as close as possible to `target_num_vertices`.
The decimated mesh should never have fewer vertices than `target_num_vertices`.
*/
template <typename DerivedV, typename DerivedF, typename DerivedT>
bool decimate_down_to(
const Eigen::PlainObjectBase<DerivedV>& V,
const Eigen::PlainObjectBase<DerivedF>& F,
const Eigen::PlainObjectBase<DerivedT>& TC,
const Eigen::PlainObjectBase<DerivedF>& FT,
int target_num_vertices,
Eigen::MatrixXd& V_out,
Eigen::MatrixXi& F_out,
Eigen::MatrixXd& TC_out,
Eigen::MatrixXi& FT_out,
int seam_aware_degree
)
{
#define DEBUG_DECIMATE_DOWN_TO
assert( target_num_vertices > 0 );
assert( target_num_vertices < V.rows() );
/// 3D triangle mesh with UVs.
// 3D
assert( V.cols() == 3 );
// triangle mesh
assert( F.cols() == 3 );
// UVs
assert( TC.cols() == 2 );
assert( FT.cols() == 3 );
assert( FT.cols() == F.cols() );
// Print information about seams.
Eigen::MatrixXi seams, boundaries, foldovers;
igl::seam_edges( V, TC, F, FT, seams, boundaries, foldovers );
#ifdef DEBUG_DECIMATE_DOWN_TO
std::cout << "seams: " << seams.rows() << "\n";
std::cout << seams << std::endl;
std::cout << "boundaries: " << boundaries.rows() << "\n";
std::cout << boundaries << std::endl;
std::cout << "foldovers: " << foldovers.rows() << "\n";
std::cout << foldovers << std::endl;
#endif
// Collect all vertex indices involved in seams.
std::unordered_set< int > seam_vertex_indices;
// Also collect the edges in terms of position vertex indices themselves.
EdgeMap seam_vertex_edges;
{
for( int i = 0; i < seams.rows(); ++i ) {
const int v1 = F( seams( i, 0 ), seams( i, 1 ) );
const int v2 = F( seams( i, 0 ), ( seams( i, 1 ) + 1 ) % 3 );
seam_vertex_indices.insert( v1 );
seam_vertex_indices.insert( v2 );
insert_edge( seam_vertex_edges, v1, v2 );
// The vertices on both sides should match:
assert( seam_vertex_indices.count( F( seams( i, 2 ), seams( i, 3 ) ) ) );
assert( seam_vertex_indices.count( F( seams( i, 2 ), ( seams( i, 3 ) + 1 ) % 3 ) ) );
}
for( int i = 0; i < boundaries.rows(); ++i ) {
const int v1 = F( boundaries( i, 0 ), boundaries( i, 1 ) );
const int v2 = F( boundaries( i, 0 ), ( boundaries( i, 1 ) + 1 ) % 3 );
seam_vertex_indices.insert( v1 );
seam_vertex_indices.insert( v2 );
insert_edge( seam_vertex_edges, v1, v2 );
}
for( int i = 0; i < foldovers.rows(); ++i ) {
const int v1 = F( foldovers( i, 0 ), foldovers( i, 1 ) );
const int v2 = F( foldovers( i, 0 ), ( foldovers( i, 1 ) + 1 ) % 3 );
seam_vertex_indices.insert( v1 );
seam_vertex_indices.insert( v2 );
insert_edge( seam_vertex_edges, v1, v2 );
// The vertices on both sides should match:
assert( seam_vertex_indices.count( F( foldovers( i, 2 ), foldovers( i, 3 ) ) ) );
assert( seam_vertex_indices.count( F( foldovers( i, 2 ), ( foldovers( i, 3 ) + 1 ) % 3 ) ) );
}
std::cout << "# seam vertices: " << seam_vertex_indices.size() << std::endl;
std::cout << "# seam edges: " << count_seam_edge_num(seam_vertex_edges) << std::endl;
}
// Compute the per-vertex quadric error metric.
std::vector< Eigen::MatrixXd > Q;
bool success = false;
Eigen::VectorXi J;
MapV5d hash_Q;
half_edge_qslim_5d(V,F,TC,FT,hash_Q);
std::cout << "computing initial metrics finished\n" << std::endl;
success = decimate_halfedge_5d(
V, F,
TC, FT,
seam_vertex_edges,
hash_Q,
target_num_vertices,
seam_aware_degree,
V_out, F_out,
TC_out, FT_out
);
std::cout << "#seams after decimation: " << count_seam_edge_num(seam_vertex_edges) << std::endl;
std::cout << "#interior foldeover: " << interior_foldovers.size() << std::endl;
std::cout << "#exterior foldeover: " << exterior_foldovers.size() << std::endl;
return success;
}
}
int main( int argc, char* argv[] ) {
std::vector<std::string> args( argv + 1, argv + argc );
std::string strictness;
int seam_aware_degree = int( SeamAwareDegree::Seamless );
const bool found_strictness = pythonlike::get_optional_parameter( args, "--strict", strictness );
if ( found_strictness ) {
seam_aware_degree = atoi(strictness.c_str());
}
if( args.size() != 3 && args.size() != 4 ) usage( argv[0] );
std::string input_path, command, command_parameter;
pythonlike::unpack( args.begin(), input_path, command, command_parameter );
args.erase( args.begin(), args.begin() + 3 );
// Does the input path exist?
Eigen::MatrixXd V, TC, CN;
Eigen::MatrixXi F, FT, FN;
if( !igl::readOBJ( input_path, V, TC, CN, F, FT, FN ) ) {
std::cerr << "ERROR: Could not read OBJ: " << input_path << std::endl;
usage( argv[0] );
}
std::cout << "Loaded a mesh with " << V.rows() << " vertices and " << F.rows() << " faces: " << input_path << std::endl;
// Get the target number of vertices.
int target_num_vertices = 0;
if( command == "num-vertices" ) {
// strto<> returns 0 upon failure, which is fine, since that is invalid input for us.
target_num_vertices = pythonlike::strto< int >( command_parameter );
}
else if( command == "percent-vertices" ) {
const double percent = pythonlike::strto< double >( command_parameter );
target_num_vertices = lround( ( percent * V.rows() )/100. );
std::cout << command_parameter << "% of " << std::to_string( V.rows() ) << " input vertices is " << std::to_string( target_num_vertices ) << " output vertices." << std::endl;
// Ugh, printf() requires me to specify the types of integers versus longs.
// printf( "%.2f%% of %d input vertices is %d output vertices.", percent, V.rows(), target_num_vertices );
}
else {
std::cerr << "ERROR: Unknown command: " << command << std::endl;
usage( argv[0] );
}
// Check that the target number of vertices is positive and fewer than the input number of vertices.
if( target_num_vertices <= 0 ) {
std::cerr << "ERROR: Target number of vertices must be a positive integer: " << argv[4] << std::endl;
usage( argv[0] );
}
if( target_num_vertices >= V.rows() ) {
std::string output_path = pythonlike::os_path_splitext( input_path ).first + "-decimated_to_" + std::to_string( V.rows() ) + "_vertices.obj";
if( !igl::writeOBJ( output_path, V, F, CN, FN, TC, FT ) ) {
std::cerr << "ERROR: Could not write OBJ: " << output_path << std::endl;
usage( argv[0] );
}
std::cout << "Wrote: " << output_path << std::endl;
std::cerr << "ERROR: Target number of vertices must be smaller than the input number of vertices: " << argv[4] << std::endl;
return 0;
}
// Make the default output path.
std::string output_path = pythonlike::os_path_splitext( input_path ).first + "-decimated_to_" + std::to_string( target_num_vertices ) + "_vertices.obj";
if( !args.empty() ) {
output_path = args.front();
args.erase( args.begin() );
}
// We should have consumed all arguments.
if( !args.empty() ) usage( argv[0] );
// Decimate!
Eigen::MatrixXd V_out, TC_out, CN_out;
Eigen::MatrixXi F_out, FT_out, FN_out;
const bool success = decimate_down_to( V, F, TC, FT, target_num_vertices, V_out, F_out, TC_out, FT_out, seam_aware_degree );
if( !success ) {
std::cerr << "WARNING: decimate_down_to() returned false (target number of vertices may have been unachievable)." << std::endl;
}
if( !igl::writeOBJ( output_path, V_out, F_out, CN_out, FN_out, TC_out, FT_out ) ) {
std::cerr << "ERROR: Could not write OBJ: " << output_path << std::endl;
usage( argv[0] );
}
std::cout << "Wrote: " << output_path << std::endl;
return 0;
}
| 4,042 |
804 | <reponame>jiinpeng/fw-cloud-framework
package com.github.liuweijw.business.pay.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.github.liuweijw.business.pay.domain.TransOrder;
public interface TransOrderRepository extends JpaRepository<TransOrder, Long> {
}
| 103 |
519 | /*
* Copyright 2018 The GraphicsFuzz Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphicsfuzz.reducer.reductionopportunities;
import com.graphicsfuzz.common.ast.IAstNode;
import com.graphicsfuzz.common.ast.expr.Expr;
import com.graphicsfuzz.common.ast.visitors.VisitationDepth;
import com.graphicsfuzz.common.util.StatsVisitor;
public class SimplifyExprReductionOpportunity extends AbstractReductionOpportunity {
private final IAstNode parent;
private final Expr newChild;
private final Expr originalChild;
// This tracks the number of nodes that will be removed by applying the opportunity at its
// time of creation (this number may be different when the opportunity is actually applied,
// due to the effects of other opportunities).
private final int numRemovableNodes;
public SimplifyExprReductionOpportunity(IAstNode parent, Expr newChild, Expr originalChild,
VisitationDepth depth) {
super(depth);
this.parent = parent;
this.newChild = newChild;
this.originalChild = originalChild;
this.numRemovableNodes =
new StatsVisitor(originalChild).getNumNodes() - new StatsVisitor(newChild).getNumNodes();
}
@Override
public void applyReductionImpl() {
parent.replaceChild(originalChild, newChild);
}
@Override
public String toString() {
return getClass().getName() + ": " + originalChild;
}
@Override
public boolean preconditionHolds() {
if (!parent.hasChild(originalChild)) {
return false;
}
return true;
}
public int getNumRemovableNodes() {
return numRemovableNodes;
}
}
| 639 |
938 | //=====-- AArch64MCAsmInfo.h - AArch64 asm properties ---------*- C++ -*--====//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the AArch64MCAsmInfo class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_AARCH64_MCTARGETDESC_AARCH64MCASMINFO_H
#define LLVM_LIB_TARGET_AARCH64_MCTARGETDESC_AARCH64MCASMINFO_H
#include "llvm/MC/MCAsmInfoCOFF.h"
#include "llvm/MC/MCAsmInfoDarwin.h"
#include "llvm/MC/MCAsmInfoELF.h"
namespace llvm {
class MCStreamer;
class Target;
class Triple;
struct AArch64MCAsmInfoDarwin : public MCAsmInfoDarwin {
explicit AArch64MCAsmInfoDarwin();
const MCExpr *
getExprForPersonalitySymbol(const MCSymbol *Sym, unsigned Encoding,
MCStreamer &Streamer) const override;
};
struct AArch64MCAsmInfoELF : public MCAsmInfoELF {
explicit AArch64MCAsmInfoELF(const Triple &T);
};
struct AArch64MCAsmInfoMicrosoftCOFF : public MCAsmInfoMicrosoft {
explicit AArch64MCAsmInfoMicrosoftCOFF();
};
struct AArch64MCAsmInfoGNUCOFF : public MCAsmInfoGNUCOFF {
explicit AArch64MCAsmInfoGNUCOFF();
};
} // namespace llvm
#endif
| 503 |
1,909 | <gh_stars>1000+
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.item.file;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.LineTokenizer;
/**
* Interface for mapping lines (strings) to domain objects typically used to map lines read from a file to domain objects
* on a per line basis. Implementations of this interface perform the actual
* work of parsing a line without having to deal with how the line was
* obtained.
*
* @author <NAME>
* @param <T> type of the domain object
* @see FieldSetMapper
* @see LineTokenizer
* @since 2.0
*/
public interface LineMapper<T> {
/**
* Implementations must implement this method to map the provided line to
* the parameter type T. The line number represents the number of lines
* into a file the current line resides.
*
* @param line to be mapped
* @param lineNumber of the current line
* @return mapped object of type T
* @throws Exception if error occurred while parsing.
*/
T mapLine(String line, int lineNumber) throws Exception;
}
| 459 |
335 | {
"word": "Truth",
"definitions": [
"The quality or state of being true.",
"That which is true or in accordance with fact or reality.",
"A fact or belief that is accepted as true."
],
"parts-of-speech": "Noun"
} | 99 |
370 | /**
* @file video_capture.cpp
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*
* @ingroup vidcap
*/
/*
* Copyright (c) 2005-2019 CESNET, z. s. p. o.
* Copyright (c) 2001-2004 University of Southern California
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by the University of Southern
* California Information Sciences Institute. This product also includes
* software developed by CESNET z.s.p.o.
*
* 4. Neither the name of the University, Institute, CESNET nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESSED 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 AUTHORS 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.
*
*/
#include "config.h"
#include "config_unix.h"
#include "config_win32.h"
#include "capture_filter.h"
#include "debug.h"
#include "lib_common.h"
#include "module.h"
#include "utils/config_file.h"
#include "video_capture.h"
#include <string>
#include <iomanip>
using namespace std;
#define VIDCAP_MAGIC 0x76ae98f0
struct vidcap_params;
/**
* Defines parameters passed to video capture driver.
*/
struct vidcap_params {
char *driver; ///< driver name
char *fmt; ///< driver options
unsigned int flags; ///< one of @ref vidcap_flags
char *requested_capture_filter;
char *name; ///< input name (capture alias in config file or complete config if not alias)
struct vidcap_params *next; /**< Pointer to next vidcap params. Used by aggregate capture drivers.
* Last device in list has @ref driver set to NULL. */
struct module *parent;
};
/// @brief This struct represents video capture state.
struct vidcap {
struct module mod;
void *state; ///< state of the created video capture driver
const struct video_capture_info *funcs;
uint32_t magic; ///< For debugging. Conatins @ref VIDCAP_MAGIC
struct capture_filter *capture_filter; ///< capture_filter_state
};
/* API for probing capture devices ****************************************************************/
void list_video_capture_devices(bool full)
{
printf("Available capture devices:\n");
list_modules(LIBRARY_CLASS_VIDEO_CAPTURE, VIDEO_CAPTURE_ABI_VERSION, full);
}
void print_available_capturers()
{
const auto & vidcaps = get_libraries_for_class(LIBRARY_CLASS_VIDEO_CAPTURE, VIDEO_CAPTURE_ABI_VERSION);
for (auto && item : vidcaps) {
auto vci = static_cast<const struct video_capture_info *>(item.second);
void (*deleter)(void *) = nullptr;
struct vidcap_type *vt = vci->probe(true, &deleter);
if (vt == nullptr) {
continue;
}
std::cout << "[cap][capture] " << item.first << "\n";
for (int i = 0; i < vt->card_count; ++i) {
std::cout << "[capability][device] {"
"\"purpose\":\"video_cap\", "
"\"module\":" << std::quoted(vt->name) << ", "
"\"device\":" << std::quoted(vt->cards[i].dev) << ", "
"\"name\":" << std::quoted(vt->cards[i].name) << ", "
"\"extra\": {" << vt->cards[i].extra << "}, "
"\"modes\": [";
for (unsigned int j = 0; j < sizeof vt->cards[i].modes
/ sizeof vt->cards[i].modes[0]; j++) {
if (vt->cards[i].modes[j].id[0] == '\0') { // last item
break;
}
if (j > 0) {
printf(", ");
}
std::cout << "{\"name\":" << std::quoted(vt->cards[i].modes[j].name) << ", "
"\"opts\":" << vt->cards[i].modes[j].id << "}";
}
std::cout << "]}\n";
}
if(!deleter)
deleter = free;
deleter(vt->cards);
deleter(vt);
}
char buf[1024] = "";
struct config_file *conf = config_file_open(default_config_file(buf, sizeof buf));
if (conf) {
auto const & from_config_file = get_configured_capture_aliases(conf);
for (auto const & it : from_config_file) {
printf("[cap] (%s;%s)\n", it.first.c_str(), it.second.c_str());
}
}
config_file_close(conf);
}
/** @brief Initializes video capture
* @param[in] parent parent module
* @param[in] param driver parameters
* @param[out] state returned state
* @retval 0 if initialization was successful
* @retval <0 if initialization failed
* @retval >0 if initialization was successful but no state was returned (eg. only having shown help).
*/
int initialize_video_capture(struct module *parent,
struct vidcap_params *param,
struct vidcap **state)
{
/// check appropriate cmdline parameters order (--capture-filter and -t)
struct vidcap_params *t, *t0;
t = t0 = param;
while ((t = vidcap_params_get_next(t0))) {
t0 = t;
}
if (t0->driver == NULL && t0->requested_capture_filter != NULL) {
log_msg(LOG_LEVEL_ERROR, "Capture filter (--capture-filter) needs to be "
"specified before capture (-t)\n");
return -1;
}
const struct video_capture_info *vci = (const struct video_capture_info *)
load_library(vidcap_params_get_driver(param), LIBRARY_CLASS_VIDEO_CAPTURE, VIDEO_CAPTURE_ABI_VERSION);
if (vci == nullptr) {
log_msg(LOG_LEVEL_ERROR, "WARNING: Selected '%s' capture card "
"was not found.\n", vidcap_params_get_driver(param));
return -1;
}
struct vidcap *d =
(struct vidcap *)malloc(sizeof(struct vidcap));
d->magic = VIDCAP_MAGIC;
d->funcs = vci;
module_init_default(&d->mod);
d->mod.cls = MODULE_CLASS_CAPTURE;
module_register(&d->mod, parent);
param->parent = &d->mod;
int ret = vci->init(param, &d->state);
switch (ret) {
case VIDCAP_INIT_OK:
break;
case VIDCAP_INIT_NOERR:
break;
case VIDCAP_INIT_FAIL:
log_msg(LOG_LEVEL_ERROR,
"Unable to start video capture device %s\n",
vidcap_params_get_driver(param));
break;
case VIDCAP_INIT_AUDIO_NOT_SUPPOTED:
log_msg(LOG_LEVEL_ERROR,
"Video capture driver does not support selected embedded/analog/AESEBU audio.\n");
break;
}
if (ret != 0) {
module_done(&d->mod);
free(d);
return ret;
}
ret = capture_filter_init(&d->mod, param->requested_capture_filter,
&d->capture_filter);
if (ret < 0) {
log_msg(LOG_LEVEL_ERROR, "Unable to initialize capture filter: %s.\n",
param->requested_capture_filter);
}
if (ret != 0) {
module_done(&d->mod);
free(d);
return ret;
}
*state = d;
return 0;
}
/** @brief Destroys vidap state
* @param state state to be destroyed (must have been successfully initialized with vidcap_init()) */
void vidcap_done(struct vidcap *state)
{
assert(state->magic == VIDCAP_MAGIC);
state->funcs->done(state->state);
capture_filter_destroy(state->capture_filter);
module_done(&state->mod);
free(state);
}
/** @brief Grabs video frame.
* This function may block for a short period if waiting for incoming frame. This period, however,
* should not be longer than few frame times, a second at maximum.
*
* The decision of blocking behavior is on the vidcap driver.
*
* The returned video frame is valid only until next vidcap_grab() call.
*
* @param[in] state vidcap state
* @param[out] audio contains audio frame if driver is grabbing audio
* @returns video frame. If no frame was grabbed (or timeout passed) NULL is returned.
*/
struct video_frame *vidcap_grab(struct vidcap *state, struct audio_frame **audio)
{
assert(state->magic == VIDCAP_MAGIC);
struct video_frame *frame;
frame = state->funcs->grab(state->state, audio);
if (frame != NULL)
frame = capture_filter(state->capture_filter, frame);
return frame;
}
/**
* @brief Module doesn't have own FPS indicator -> use a generic one
*/
bool vidcap_generic_fps(struct vidcap *state)
{
assert(state->magic == VIDCAP_MAGIC);
return state->funcs->use_generic_fps_indicator;
}
| 4,869 |
336 | #include "TMCStepper.h"
#include "SW_SPI.h"
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS) :
_pinCS(pinCS),
Rsense(RS)
{}
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) :
_pinCS(pinCS),
Rsense(default_RS)
{
SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK);
TMC_SW_SPI = SW_SPI_Obj;
}
TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) :
_pinCS(pinCS),
Rsense(RS)
{
SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK);
TMC_SW_SPI = SW_SPI_Obj;
}
void TMC2660Stepper::switchCSpin(bool state) {
// Allows for overriding in child class to make use of fast io
digitalWrite(_pinCS, state);
}
uint32_t TMC2660Stepper::read() {
uint32_t response = 0UL;
uint32_t dummy = ((uint32_t)DRVCONF_register.address<<17) | DRVCONF_register.sr;
if (TMC_SW_SPI != nullptr) {
switchCSpin(LOW);
response |= TMC_SW_SPI->transfer((dummy >> 16) & 0xFF);
response <<= 8;
response |= TMC_SW_SPI->transfer((dummy >> 8) & 0xFF);
response <<= 8;
response |= TMC_SW_SPI->transfer(dummy & 0xFF);
} else {
SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3));
switchCSpin(LOW);
response |= SPI.transfer((dummy >> 16) & 0xFF);
response <<= 8;
response |= SPI.transfer((dummy >> 8) & 0xFF);
response <<= 8;
response |= SPI.transfer(dummy & 0xFF);
SPI.endTransaction();
}
switchCSpin(HIGH);
return response >> 4;
}
void TMC2660Stepper::write(uint8_t addressByte, uint32_t config) {
uint32_t data = (uint32_t)addressByte<<17 | config;
if (TMC_SW_SPI != nullptr) {
switchCSpin(LOW);
TMC_SW_SPI->transfer((data >> 16) & 0xFF);
TMC_SW_SPI->transfer((data >> 8) & 0xFF);
TMC_SW_SPI->transfer(data & 0xFF);
} else {
SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3));
switchCSpin(LOW);
SPI.transfer((data >> 16) & 0xFF);
SPI.transfer((data >> 8) & 0xFF);
SPI.transfer(data & 0xFF);
SPI.endTransaction();
}
switchCSpin(HIGH);
}
void TMC2660Stepper::begin() {
//set pins
pinMode(_pinCS, OUTPUT);
switchCSpin(HIGH);
//TODO: Push shadow registers
toff(8); //off_time(8);
tbl(1); //blank_time(24);
}
bool TMC2660Stepper::isEnabled() { return toff() > 0; }
uint8_t TMC2660Stepper::test_connection() {
uint32_t drv_status = DRVSTATUS();
switch (drv_status) {
case 0xFFCFF: return 1;
case 0: return 2;
default: return 0;
}
}
/*
Requested current = mA = I_rms/1000
Equation for current:
I_rms = (CS+1)/32 * V_fs/R_sense * 1/sqrt(2)
Solve for CS ->
CS = 32*sqrt(2)*I_rms*R_sense/V_fs - 1
Example:
vsense = 0b0 -> V_fs = 0.310V //Typical
mA = 1650mA = I_rms/1000 = 1.65A
R_sense = 0.100 Ohm
->
CS = 32*sqrt(2)*1.65*0.100/0.310 - 1 = 24,09
CS = 24
*/
uint16_t TMC2660Stepper::cs2rms(uint8_t CS) {
return (float)(CS+1)/32.0 * (vsense() ? 0.165 : 0.310)/(Rsense+0.02) / 1.41421 * 1000;
}
uint16_t TMC2660Stepper::rms_current() {
return cs2rms(cs());
}
void TMC2660Stepper::rms_current(uint16_t mA) {
uint8_t CS = 32.0*1.41421*mA/1000.0*Rsense/0.310 - 1;
// If Current Scale is too low, turn on high sensitivity R_sense and calculate again
if (CS < 16) {
vsense(true);
CS = 32.0*1.41421*mA/1000.0*Rsense/0.165 - 1;
} else { // If CS >= 16, turn off high_sense_r
vsense(false);
}
if (CS > 31)
CS = 31;
cs(CS);
//val_mA = mA;
}
void TMC2660Stepper::push() {
DRVCTRL( sdoff() ? DRVCTRL_1_register.sr : DRVCTRL_0_register.sr);
CHOPCONF(CHOPCONF_register.sr);
SMARTEN(SMARTEN_register.sr);
SGCSCONF(SGCSCONF_register.sr);
DRVCONF(DRVCONF_register.sr);
}
void TMC2660Stepper::hysteresis_end(int8_t value) { hend(value+3); }
int8_t TMC2660Stepper::hysteresis_end() { return hend()-3; };
void TMC2660Stepper::hysteresis_start(uint8_t value) { hstrt(value-1); }
uint8_t TMC2660Stepper::hysteresis_start() { return hstrt()+1; }
void TMC2660Stepper::microsteps(uint16_t ms) {
switch(ms) {
case 256: mres(0); break;
case 128: mres(1); break;
case 64: mres(2); break;
case 32: mres(3); break;
case 16: mres(4); break;
case 8: mres(5); break;
case 4: mres(6); break;
case 2: mres(7); break;
case 0: mres(8); break;
default: break;
}
}
uint16_t TMC2660Stepper::microsteps() {
switch(mres()) {
case 0: return 256;
case 1: return 128;
case 2: return 64;
case 3: return 32;
case 4: return 16;
case 5: return 8;
case 6: return 4;
case 7: return 2;
case 8: return 0;
}
return 0;
}
void TMC2660Stepper::blank_time(uint8_t value) {
switch (value) {
case 16: tbl(0b00); break;
case 24: tbl(0b01); break;
case 36: tbl(0b10); break;
case 54: tbl(0b11); break;
}
}
uint8_t TMC2660Stepper::blank_time() {
switch (tbl()) {
case 0b00: return 16;
case 0b01: return 24;
case 0b10: return 36;
case 0b11: return 54;
}
return 0;
}
| 2,358 |
14,668 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_
#define COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_
#include <string>
#include "base/callback.h"
#include "base/component_export.h"
#include "base/time/time.h"
#include "base/version.h"
#include "components/variations/proto/study.pb.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace variations {
// The values of the ChromeVariations policy. Those should be kept in sync
// with the values defined in policy_templates.json!
enum class RestrictionPolicy {
// No restrictions applied by policy. Default value when policy not set.
NO_RESTRICTIONS = 0,
// Only critical security variations should be applied.
CRITICAL_ONLY = 1,
// All variations disabled. Disables the variations framework altogether.
ALL = 2,
kMaxValue = ALL,
};
using IsEnterpriseFunction = base::OnceCallback<bool()>;
// A container for all of the client state which is used for filtering studies.
struct COMPONENT_EXPORT(VARIATIONS) ClientFilterableState {
static Study::Platform GetCurrentPlatform();
// base::Version used in {min,max}_os_version filtering.
static base::Version GetOSVersion();
explicit ClientFilterableState(IsEnterpriseFunction is_enterprise_function);
ClientFilterableState(const ClientFilterableState&) = delete;
ClientFilterableState& operator=(const ClientFilterableState&) = delete;
~ClientFilterableState();
// Whether this is an enterprise client. Always false on android, iOS, and
// linux. Determined by VariationsServiceClient::IsEnterprise for windows,
// chromeOs, and mac.
bool IsEnterprise() const;
// The system locale.
std::string locale;
// The date on which the variations seed was fetched.
base::Time reference_date;
// The Chrome version to filter on.
base::Version version;
// The OS version to filter on. See |min_os_version| in study.proto for
// details.
base::Version os_version;
// The Channel for this Chrome installation.
Study::Channel channel;
// The hardware form factor that Chrome is running on.
Study::FormFactor form_factor;
// The CPU architecture on which Chrome is running.
Study::CpuArchitecture cpu_architecture;
// The OS on which Chrome is running.
Study::Platform platform;
// The named hardware configuration that Chrome is running on -- used to
// identify models of devices.
std::string hardware_class;
// Whether this is a low-end device. Currently only supported on Android.
// Based on base::SysInfo::IsLowEndDevice().
bool is_low_end_device = false;
// The country code to use for studies configured with session consistency.
std::string session_consistency_country;
// The country code to use for studies configured with permanent consistency.
std::string permanent_consistency_country;
// The restriction applied to Chrome through the "ChromeVariations" policy.
RestrictionPolicy policy_restriction = RestrictionPolicy::NO_RESTRICTIONS;
private:
// Evaluating enterprise status negatively affects performance, so we only
// evaluate it if needed (i.e. if a study is filtering by enterprise) and at
// most once.
mutable IsEnterpriseFunction is_enterprise_function_;
mutable absl::optional<bool> is_enterprise_;
};
} // namespace variations
#endif // COMPONENTS_VARIATIONS_CLIENT_FILTERABLE_STATE_H_
| 978 |
382 | /*
* Copyright 2020 Netflix, 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.netflix.spinnaker.clouddriver.data.task;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class TaskDisplayStatus implements Status {
public static TaskDisplayStatus create(Status taskStatus) {
return new TaskDisplayStatus(taskStatus);
}
@JsonIgnore private final Status taskStatus;
public TaskDisplayStatus(Status taskStatus) {
this.taskStatus = taskStatus;
}
@Override
public String getStatus() {
return taskStatus.getStatus();
}
@Override
public String getPhase() {
return taskStatus.getPhase();
}
@JsonIgnore
public Boolean isCompleted() {
return taskStatus.isCompleted();
}
@JsonIgnore
public Boolean isFailed() {
return taskStatus.isFailed();
}
@JsonIgnore
@Override
public Boolean isRetryable() {
return taskStatus.isRetryable();
}
public final Status getTaskStatus() {
return taskStatus;
}
}
| 445 |
450 | /*
* Copyright (c) 2004, 2005, 2006 TADA AB - Taby Sweden
* Distributed under the terms shown in the file COPYRIGHT
* found in the root folder of this project or at
* http://eng.tada.se/osprojects/COPYRIGHT.html
*
* @author <NAME>
*/
#ifndef __pljava_HashMap_h
#define __pljava_HashMap_h
#include "pljava/PgObject.h"
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************
* The HashMap class. Maintains mappings between HashKey instances
* and values. The mappings are stored in hash bucket chains
* containing Entry instances.
*
* All Entries and HashKeys will be allocated using the same
* MemoryContext as the one used when creating the HashMap.
* A HashKey used for storing (HashKey_put) is cloned so that
* the HashMap maintains its own copy.
*
* @author <NAME>
*
*************************************************************/
struct HashKey_;
typedef struct HashKey_* HashKey;
struct Iterator_;
typedef struct Iterator_* Iterator;
struct Entry_;
typedef struct Entry_* Entry;
struct HashMap_;
typedef struct HashMap_* HashMap;
/*
* Creates a new HashMap with an initial capacity. If ctx is NULL, CurrentMemoryContext
* will be used.
*/
extern HashMap HashMap_create(uint32 initialCapacity, MemoryContext ctx);
/*
* Clears the HashMap.
*/
extern void HashMap_clear(HashMap self);
/*
* Returns an iterator that iterates over the entries of
* this HashMap.
*/
extern Iterator HashMap_entries(HashMap self);
/*
* Returns the object stored using the given key or NULL if no
* such object can be found.
*/
extern void* HashMap_get(HashMap self, HashKey key);
/*
* Returns the object stored using the given null
* terminated string or NULL if no such object can be found.
*/
extern void* HashMap_getByString(HashMap self, const char* key);
/*
* Returns the object stored using the given Oid or NULL
* if no such object can be found.
*/
extern void* HashMap_getByOid(HashMap self, Oid key);
/*
* Returns the object stored using the given Opaque pointer or NULL
* if no such object can be found.
*/
extern void* HashMap_getByOpaque(HashMap self, void* key);
/*
* Stores the given value under the given key. If
* an old value was stored using this key, the old value is returned.
* Otherwise this method returns NULL.
* This method will make a private copy of the key argument.
*/
extern void* HashMap_put(HashMap self, HashKey key, void* value);
/*
* Stores the given value under the given null terminated string. If
* an old value was stored using this key, the old value is returned.
* Otherwise this method returns NULL.
*/
extern void* HashMap_putByString(HashMap self, const char* key, void* value);
/*
* Stores the given value under the given Oid. If an old value
* was stored using this key, the old value is returned. Otherwise
* this method returns NULL.
*/
extern void* HashMap_putByOid(HashMap self, Oid key, void* value);
/*
* Stores the given value under the given Opaque pointer. If an old value
* was stored using this key, the old value is returned. Otherwise
* this method returns NULL.
*/
extern void* HashMap_putByOpaque(HashMap self, void* key, void* value);
/*
* Removes the value stored under the given key. The the old value
* (if any) is returned.
*/
extern void* HashMap_remove(HashMap self, HashKey key);
/*
* Removes the value stored under the given key. The the old value
* (if any) is returned. The key associated with the value is deleted.
*/
extern void* HashMap_removeByString(HashMap self, const char* key);
/*
* Removes the value stored under the given key. The the old value
* (if any) is returned.
*/
extern void* HashMap_removeByOid(HashMap self, Oid key);
/*
* Removes the value stored under the given key. The the old value
* (if any) is returned.
*/
extern void* HashMap_removeByOpaque(HashMap self, void* key);
/*
* Returns the number of entries currently in the HashMap
*/
extern uint32 HashMap_size(HashMap self);
/*************************************************************
* An instance of the Entry class holds a mapping between one
* HashKey and its associated value.
*************************************************************/
/*
* Returns the value of the Entry.
*/
extern void* Entry_getValue(Entry self);
/*
* Assigns a new value to the Entry. Returns the old value.
*/
extern void* Entry_setValue(Entry self, void* value);
/*
* Returns the key of the Entry. Can be used for removal.
*/
extern HashKey Entry_getKey(Entry self);
/*************************************************************
* The HashKey is an abstract class. Currently, three different
* implementations are used. Oid, Opaque (void*), and String.
*************************************************************/
/*
* Clone the key. The clone is allocated in the given context.
*/
extern HashKey HashKey_clone(HashKey self, MemoryContext ctx);
/*
* Return true if the key is equal to another key.
*/
extern bool HashKey_equals(HashKey self, HashKey other);
/*
* Return the hash code for the key
*/
extern uint32 HashKey_hashCode(HashKey self);
#ifdef __cplusplus
} /* end of extern "C" declaration */
#endif
#endif
| 1,474 |
460 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef FACEBOOKCLIENT_H
#define FACEBOOKCLIENT_H
#include "BT_FileTransferManager.h"
#define FACEBOOK_APPNAME "BumpTop"
class FacebookClient;
class JavaScriptAPI;
/*
*/
struct FacebookPhoto
{
public:
// legacy
QString filePath;
QString album;
// new
QString pid;
QString aid;
QString srcSmall;
int srcSmallWidth;
int srcSmallHeight;
QString srcBig;
int srcBigWidth;
int srcBigHeight;
QString src;
int srcWidth;
int srcHeight;
QString link;
QString caption;
QDateTime creationDate;
QDateTime modifiedDate;
public:
FacebookPhoto(QString path);
FacebookPhoto(QString path, QString cap);
FacebookPhoto(QString path, QString cap, QString alb);
};
/*
*/
class FacebookAlbum
{
public:
QString aid;
QString coverPid;
QString ownerUid;
QString name;
QString description;
QString location;
QDateTime creationDate;
QDateTime modificationDate;
QString link;
QString editLink;
QString visibility;
QString type;
int size;
};
/*
*/
class FacebookProfile
{
public:
QString uid;
QString profileLink;
QString name;
QString picSquare;
QString type;
};
/*
*/
class FacebookStreamMediaItem
{
public:
QString href;
QString alt;
QString type;
QString src;
};
class FacebookStreamPhoto : public FacebookStreamMediaItem
{
public:
QString aid;
QString pid;
QString ownerUid;
int index;
int width;
int height;
};
class FacebookStreamLink : public FacebookStreamMediaItem
{
public:
QString domain;
QString description;
};
class FacebookStreamAlbum
{
public:
QList<FacebookStreamPhoto *> photos;
QString name;
QString caption;
};
class FacebookStreamComments
{
public:
int count;
};
class FacebookStreamLikes
{
public:
int count;
};
class FacebookStreamPost
{
public:
QString sourceId;
QString postId;
QString actorUid;
QString message;
FacebookStreamAlbum album;
FacebookStreamLink link;
FacebookStreamComments comments;
FacebookStreamLikes likes;
QDateTime creationDate;
QDateTime updatedDate;
QString permalink;
int type;
};
/*
*/
class FacebookStatus
{
public:
QDateTime time;
QString message;
QString toJsonString();
};
/*
* Only used for the facebook widget, aggregates data from the other stream entries
* and pares it down into a single usable item
*/
class FacebookWidgetNewsFeedItem
{
public:
QString postId;
QString message;
QString sourceId;
QString title;
QString permalink;
QString extlink;
QString domain;
QString description;
QString ownerName;
QString ownerProfileLink;
QString ownerPicSquare;
QDateTime creationDate;
QString photoId;
QString imageAlt;
QString imageSrc;
int imageWidth;
int imageHeight;
int numComments;
int numLikes;
FacebookWidgetNewsFeedItem() : imageWidth(0), imageHeight(0), numComments(0),
numLikes(0) {}
Json::Value toJsonValue();
};
class FacebookWidgetNewsFeed
{
public:
QList<FacebookWidgetNewsFeedItem *> items;
QString toJsonString();
};
class FacebookWidgetAlbumItem
{
public:
QString aid;
QString uid;
QString title;
QString permalink;
QString albumCoverUrl;
int albumCoverWidth;
int albumCoverHeight;
int modifiedDate;
int numPhotos;
int numComments;
FacebookWidgetAlbumItem() : albumCoverWidth(0), albumCoverHeight(0),
modifiedDate(0), numPhotos(0), numComments(0) {}
Json::Value toJsonValue();
};
class FacebookWidgetPhotoAlbums
{
public:
QList<FacebookWidgetAlbumItem *> albums;
QString toJsonString();
};
class FacebookWidgetPhoto
{
public:
QString pid;
QString aid;
QString owner;
QString title;
QString permalink;
QString url;
int width;
int height;
int numComments;
int creationDate;
FacebookWidgetPhoto() : width(0), height(0), numComments(0), creationDate(0) {}
Json::Value toJsonValue();
};
class FacebookWidgetPhotos
{
public:
QList<FacebookWidgetPhoto *> photos;
QString toJsonString();
};
class FacebookWidgetPage
{
public:
QString pageId;
QString name;
QString pageUrl;
FacebookWidgetPage(){}
Json::Value toJsonValue();
};
class FacebookWidgetPages
{
public:
QList<FacebookWidgetPage *> pages;
QString toJsonString();
};
/*
*/
class FacebookClient : public FileTransferEventHandler
{
Q_DECLARE_TR_FUNCTIONS(FacebookClient);
QString _apiKey;
QString _secretKey;
QString _serverUrl;
QString _version;
Json::Reader _reader;
QHash<QString, QString> _supportedUploadExtensionsContentTypes;
// from auth_createToken
QString _authToken;
int _numPhotosUploaded;
int _numPhotosFailedUpload;
int _numPhotos;
// from auth_getSession
QString _userid;
QString _sessionKey;
QString _sessionSecretKey;
friend class FacebookAlbum;
private:
QString generateSignature(QHash<QString, QString> params, QString secretKey);
void prepareSessionParameters(QHash<QString, QString>& params);
void prepareSessionlessParameters(QHash<QString, QString>& params);
QString postHttpReqest(QString method, QHash<QString, QString> params);
void postHttpReqest(QString method, QHash<QString, QString> params, const QString& callback, FileTransferEventHandler * handler);
QString postHttpUploadRequest(QString method, QHash<QString, QString> params, QString filePath);
void postHttpUploadRequest(QString method, QHash<QString, QString> params, QString filePath, const QString& callback, FileTransferEventHandler * handler);
QString postHttpsRequest(QString method, QHash<QString, QString> params);
QString extractUidFromJsonResult(const QString& key, const QString& jsonSrc) const;
int extractIntFromJsonResult(const QString& key, const Json::Value& json) const;
QString extractStringFromJsonResult(const QString& key, const Json::Value& json) const;
bool hasAuthorized() const;
QHttp _http;
QHash<int,QString> _pendingHttpRequests;
void httpRequestFinished( int id, bool error );
public:
FacebookClient();
~FacebookClient();
// initialization
bool initialize(bool& usingSavedSession);
const QString& getUid() const;
// facebook api calls
bool fbconnect_login(JavaScriptAPI * jsApiRef);
bool validate_photos_upload(vector<FacebookPhoto>& photos, QString& errorReasonOut);
bool photos_upload(vector<FacebookPhoto>& photos);
bool photos_upload(const QString& aid, const QStringList& filePaths, const QString& callback, FileTransferEventHandler * api);
bool photos_getAlbums(QString filter, QString& albumLink);
bool photos_createAlbum(const QString& name, const QString& location, const QString& description);
bool users_hasAppPermission(QString permissionId, bool& hasPermission);
bool users_isAppUser(bool& isUserOut);
// bool users_getInfo_profileUrl(QString& urlOut);
QString hasNewsFeedFilter(const QList<QString>& filters);
bool stream_getFilters(QList<QString>& filterKeysOut);
bool status_get(FacebookStatus * statusOut);
bool status_set(const QString& status);
bool comments_get(const QString& id, int& numCommentsOut);
// widget specific calls (results are formatted specifically,
// feel free to refactor code out later as necessary)
bool widget_getPhotoAlbumsInfo(const QStringList& aidUids, const QString& callback, FileTransferEventHandler * handler);
bool onWidget_getPhotoAlbumsInfo(const QString& result, FacebookWidgetPhotoAlbums& albumsOut);
bool widget_getPhotoAlbums(bool includeProfile, const QString& callback, FileTransferEventHandler * handler);
bool onWidget_getPhotoAlbums(const QString& result, FacebookWidgetPhotoAlbums& albumsOut);
bool widget_getPhotoAlbumPhotos(const QString& aid, const QString& callback, FileTransferEventHandler * handler);
bool onWidget_getPhotoAlbumPhotos(const QString& result, FacebookWidgetPhotos& photosOut);
bool widget_getNewsFeed(const QString& callback, FileTransferEventHandler * handler, const QStringList& postTypes, int earliestPhotoTime);
bool onWidget_getNewsFeed(const QString& result, FacebookWidgetNewsFeed& entriesOut);
bool widget_getHighResolutionPhotos(const QList<QString>& pids, const QString& callback, FileTransferEventHandler * handler);
bool onWidget_getHighResolutionPhotos(const QString& result, FacebookWidgetPhotos& photosOut);
bool widget_getPageInfo(const QList<QString>& pageIds, const QString& callback, FileTransferEventHandler * handler);
bool onWidget_getPageInfo(const QString& result, FacebookWidgetPages& pagesOut);
// bool widget_getFriendsList(QList<FacebookWidgetFriend *>& friendsOut);
// bool widget_getFriendDetails(const QString& uid);
bool fql_multiquery(const QMap<QString, QString>& queries, QString& rawResultOut);
bool fql_multiquery(const QMap<QString, QString>& queries, const QString& callback, FileTransferEventHandler * handler);
// events
virtual void onTransferComplete(const FileTransfer& transfer);
virtual void onTransferError(const FileTransfer& transfer);
};
#endif // FACEBOOKCLIENT_H | 3,326 |
377 | /*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.client.es;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.impetus.kundera.client.Client;
/**
* @author vivek.mishra junit for {@link ESClientPropertyReader}
*/
public class ESClientPropertyReaderTest
{
private static final String PERSISTENCE_UNIT = "es-external-config";
/** The emf. */
private EntityManagerFactory emf;
/** The em. */
private EntityManager em;
@Before
public void setup()
{
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
em = emf.createEntityManager();
}
@Test
public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
Map<String, Client<ESQuery>> clients = (Map<String, Client<ESQuery>>) em.getDelegate();
ESClient client = (ESClient) clients.get(PERSISTENCE_UNIT);
Field factoryField = client.getClass().getDeclaredField("factory");
if (!factoryField.isAccessible())
{
factoryField.setAccessible(true);
}
ESClientFactory factory = (ESClientFactory) factoryField.get(client);
Field propertyReader = ((ESClientFactory) factory).getClass().getSuperclass()
.getDeclaredField("propertyReader");
if (!propertyReader.isAccessible())
{
propertyReader.setAccessible(true);
}
ESClientPropertyReader readerInstance = (ESClientPropertyReader) propertyReader.get(factory);
Properties props = readerInstance.getConnectionProperties();
Assert.assertEquals("true", props.get("client.transport.sniff"));
Assert.assertEquals("false", props.get("discovery.zen.ping.multicast.enabled"));
Assert.assertEquals("true", props.get("discovery.zen.ping.unicast.enabled"));
Assert.assertEquals("false", props.get("discovery.zen.multicast.enabled"));
Assert.assertEquals("true", props.get("discovery.zen.unicast.enabled"));
}
@After
public void tearDown()
{
if (em != null)
{
em.close();
}
if (emf != null)
{
emf.close();
}
}
}
| 1,166 |
2,338 | // BOLT test case
#include <stdio.h>
typedef unsigned long long (*FP)();
extern FP getCallback();
extern FP getCallback2();
extern FP getCallback3();
int main() {
printf("Case 1: Result is: %llX\n", (*getCallback())());
printf("Case 2: Result is: %llX\n", (*getCallback2())());
printf("Case 3: Result is: %llX\n", (*getCallback3())());
return 0;
}
| 131 |
711 | <gh_stars>100-1000
package com.java110.api.bmo.purchaseApply;
import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.IApiBaseBMO;
import com.java110.core.context.DataFlowContext;
/**
* @ClassName IPurchaseApplyBMO
* @Description TODO
* @Author wuxw
* @Date 2020/3/9 23:33
* @Version 1.0
* add by wuxw 2020/3/9
**/
public interface IPurchaseApplyBMO extends IApiBaseBMO {
/**
* 添加小区信息
*
* @param paramInJson 接口调用放传入入参
* @param dataFlowContext 数据上下文
* @return 订单服务能够接受的报文
*/
public void deletePurchaseApply(JSONObject paramInJson, DataFlowContext dataFlowContext);
/**
* 添加小区信息
*
* @param paramInJson 接口调用放传入入参
* @param dataFlowContext 数据上下文
* @return 订单服务能够接受的报文
*/
public void addPurchaseApply(JSONObject paramInJson, DataFlowContext dataFlowContext);
/**
* 添加采购申请信息
*
* @param paramInJson 接口调用放传入入参
* @param dataFlowContext 数据上下文
* @return 订单服务能够接受的报文
*/
public void updatePurchaseApply(JSONObject paramInJson, DataFlowContext dataFlowContext);
}
| 610 |
634 | <filename>zentral/contrib/monolith/migrations/0026_auto_20170919_1005.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-19 10:05
from __future__ import unicode_literals
from django.db import migrations, models
import zentral.contrib.monolith.models
class Migration(migrations.Migration):
dependencies = [
('monolith', '0025_auto_20170919_0932'),
]
operations = [
migrations.AlterField(
model_name='printerppd',
name='file',
field=models.FileField(blank=True, upload_to=zentral.contrib.monolith.models.ppd_path),
),
]
| 267 |
396 | <gh_stars>100-1000
package com.ibm.webapi.apis;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.json.Json;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.jwt.JsonWebToken;
@RequestScoped
@Path("/v1")
public class Manage {
@Inject
private JsonWebToken jwtPrincipal;
@POST
@Path("/manage")
@Produces(MediaType.APPLICATION_JSON)
@APIResponses(value = {
@APIResponse(responseCode = "200", description = "Manage application",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ManageResponse.class))),
@APIResponse(responseCode = "401", description = "Not authorized") })
@Operation(summary = "Manage application", description = "Manage application")
public Response manage() {
System.out.println("com.ibm.web-api.apis.Manage.manage");
System.out.println(this.jwtPrincipal);
String principalEmail = this.jwtPrincipal.getClaim("email");
if (principalEmail.equalsIgnoreCase("<EMAIL>")) {
JsonObject output = Json.createObjectBuilder().add("message", "success").build();
return Response.ok(output).build();
}
else {
JsonObject output = Json.createObjectBuilder().add("message", "failure").build();
return Response.status(Status.FORBIDDEN).entity(output).type(MediaType.APPLICATION_JSON).build();
}
}
}
| 646 |
357 | <reponame>yijianduanlang/n95-py
# python3.6.5
# coding:utf-8
# 天猫淘宝自动下单 用于定时抢购
import os
import sys
from selenium import webdriver
import requests
import time
from selenium.webdriver.chrome.options import Options
# 创建浏览器对象
chrome_options = Options()
# 关闭使用 ChromeDriver 打开浏览器时上部提示语 "Chrome正在受到自动软件的控制"
chrome_options.add_argument("disable-infobars")
# 允许浏览器重定向,Framebusting requires same-origin or a user gesture
chrome_options.add_argument("disable-web-security")
if sys.platform == "win32":
driver = webdriver.Chrome(os.path.join(os.path.abspath(os.path.dirname(__file__)) + "\\src", "chromedriver.exe"),
chrome_options=chrome_options)
else:
driver = webdriver.Chrome(os.path.join(os.path.dirname(__file__) + "/src", "chromedriver"),
chrome_options=chrome_options)
# 窗口最大化显示
driver.maximize_window()
def login(url, mall):
'''
登陆函数
url:商品的链接
mall:商城类别
'''
driver.get(url)
driver.implicitly_wait(10)
time.sleep(2)
# 淘宝和天猫的登陆链接文字不同
if mall == '1':
# 找到并点击淘宝的登陆按钮
driver.find_element_by_link_text("亲,请登录").click()
elif mall == '2':
# 找到并点击天猫的登陆按钮
driver.find_element_by_link_text("请登录").click()
print("请在30秒内完成登录")
# 用户扫码登陆
time.sleep(30)
def buy(buy_time, mall, time_dif):
'''
购买函数
buy_time:购买时间
mall:商城类别
'''
print("开始购买")
if mall == '1':
# "立即购买"的css_selector
btn_buy = '#J_juValid > div.tb-btn-buy > a'
# "立即下单"的css_selector
btn_order = '#submitOrder_1 > div.wrapper > a'
elif mall == '3':
btn_buy = '#J_Go'
btn_order = '#submitOrderPC_1 > div > a'
else:
btn_buy = '#J_LinkBuy'
btn_order = '#submitOrderPC_1 > div > a'
timeArray = time.strptime(buy_time, "%Y-%m-%d %H:%M:%S")
# 转为时间戳
timeStamp = int(time.mktime(timeArray))
print("开始准备购买")
while True:
# 现在时间大于预设时间则开售抢购
tmp_time = time.time()
if tmp_time >= (timeStamp - time_dif):
try:
print("开始购买" + str(time.time()))
# 找到“立即购买”,点击
if selector:
print("点击" + str(time.time()))
selector.click()
break
except:
pass
while True:
try:
# 找到“立即下单”,点击,
# print("尝试提交订单")
order_selector = driver.find_elements_by_css_selector(btn_order)
if order_selector:
print("购买" + str(time.time()))
order_selector[-1].click()
# 下单成功,跳转至支付页面
print("购买成功" + str(time.time() - tmp_time))
break
driver.refresh()
except:
driver.refresh()
time.sleep(0.01)
def get_server_time():
time_start = time.time()
r1 = requests.get(url='http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp',
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36'})
x = eval(r1.text)
tmp = time.time() - time_start
timeNum = int(x['data']['t'])
timeStamp = float(timeNum / 1000)
print(tmp)
# timeArray = time.localtime(timeStamp)
# otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
return timeStamp, tmp
# 使用方法
# 1 设置url
# 2 设置天猫还是淘宝
# 3 设置开抢时间
# 4 运行程序
# 5 扫码登录
# 6 选中要购买商品以及相应种类等(必须选中!!!)
# 7 自动下单
#
if __name__ == "__main__":
# 输入要购买物品 url
# 如果是天猫超市的抢购 请先加入购物车 此处为购物车链接
url = "https://cart.taobao.com/cart.htm"
# 请选择商城(淘宝 1 天猫 2 3 通过购物车 输入数字:
mall = '3'
# 输入开售时间
bt = "2020-03-01 15:00:00"
server_time, tmp = get_server_time()
time_dif = time.time() - server_time + tmp + tmp
login(url, mall)
buy(bt, mall, 2 * time_dif + 0.5)
# driver.quit()
| 2,689 |
Subsets and Splits