method2testcases
stringlengths 118
3.08k
|
---|
### Question:
DbManager { public ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getPrimaryKeys(localCatalog, localSchema, localTableName); } catch (SQLException e) { throw new RuntimeException("get primary key exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetPrimaryKeys() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getPrimaryKeys(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connection, null, resultSet); } |
### Question:
DbManager { public ResultSetMetaData getResultSetMetaData(ResultSet resultSet) { try { return resultSet.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get ResultSetMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetResultSetMetaData() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); ResultSetMetaData resultSetMetaData = dbManager.getResultSetMetaData(resultSet); assertNotNull(resultSetMetaData); assertEquals(resultSetMetaData.getColumnCount(), 1); } |
### Question:
DbManager { public DatabaseMetaData getDatabaseMetaData(Connection connection) { try { return connection.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get DatabaseMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetDatabaseMetaData() throws Exception { Connection connection = dbManager.getConnection(); DatabaseMetaData databaseMetaData = dbManager.getDatabaseMetaData(connection); assertNotNull(databaseMetaData); assertEquals(databaseMetaData.getDatabaseProductName().toLowerCase(), "mysql"); dbManager.close(connection); } |
### Question:
Coder { public static int ASCIIToEBCDIC(int ascii) { return ASCII.AToE[ascii & 0xff] & 0xff; } static int ASCIIToEBCDIC(int ascii); static int EBCDICToASCII(int ebcdic); static byte[] ASCIIToEBCDIC(byte[] ascii); static byte[] EBCDICToASCII(byte[] ebcdic); static String ASCIIToEBCDIC(String ascii); static String EBCDICToASCII(String ebcdic); static void ASCIIToEBCDIC(String fromFile, String toFile); static void EBCDICToASCII(String fromFile, String toFile); }### Answer:
@Test public void testASCIIToEBCDIC() { byte[]c = new byte[]{1,2,3,4}; byte[] a = Coder.ASCIIToEBCDIC(c); assertEquals(a[0], 1); assertEquals(a[1], 2); assertEquals(a[2], 3); assertEquals(a[3], 55); } |
### Question:
ValidateUtils { public static <T> void validate(T bean, Class<?>... groups) { validate(bean, true, groups); } static void validate(T bean, Class<?>... groups); static void validate(T bean, boolean flag, Class<?>... groups); }### Answer:
@Test public void testValidate() { User user = new User(); user.setRealName("a"); try { ValidateUtils.validate(user); } catch (Exception e) { String str = e.getMessage(); assertEquals(str, "用户id不能为空"); } }
@Test public void testFastValidate() { User user = new User(); try { ValidateUtils.validate(user, false); } catch (Exception e) { String str = e.getMessage(); String [] arrays = str.split(","); assertEquals(arrays.length, 2); } }
@Test public void testValidateSuccess() { User user = new User(); user.setId(1L); user.setRealName("a"); ValidateUtils.validate(user); } |
### Question:
PBE { public static byte[] initSalt() { byte[] salt = new byte[8]; Random random = new Random(); random.nextBytes(salt); return salt; } static byte[] encrypt(byte[] data, byte[] key, byte[] salt); static byte[] decrypt(byte[] data, byte[] key, byte[] salt); static Key generateRandomKey(byte[] key); static AlgorithmParameterSpec getAlgorithmParameterSpec(byte[] salt); static byte[] initSalt(); }### Answer:
@Test public void testInitSalt() { assertNotNull(PBE.initSalt()); } |
### Question:
AES { public static byte[] encrypt(byte[] data, byte[] key) { validation(data, key); Key secretKeySpec = Symmetry.generateRandomKey(key, AES_ALGORITHM); return Symmetry.encrypt(AES_ALGORITHM, secretKeySpec, data); } static byte[] encrypt(byte[] data, byte[] key); static byte[] decrypt(byte[] data, byte[] key); static void validation(byte[] data, byte[] key); }### Answer:
@Test public void encrypt() { String data = "root1"; byte[] key = "1111111111111111".getBytes(); byte[] encryption = AES.encrypt(data.getBytes(), key); assertEquals(Base64.getEncoder().encodeToString(encryption), "8/mudtZ/bQOhcV/K6JFrug=="); String decryptData = new String(AES.decrypt(encryption, key)); assertEquals(decryptData, data); } |
### Question:
HMAC { public static byte[] initMacKey() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(ISecurity.HMAC_ALGORITHM); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("获取自增密钥错误", e); } } static byte[] encrypt(byte[] data, byte[] key); static byte[] initMacKey(); }### Answer:
@Test public void testInitMacKey() { assertNotNull(HMAC.initMacKey()); } |
### Question:
HMAC { public static byte[] encrypt(byte[] data, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, ISecurity.HMAC_ALGORITHM); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此算法错误", e); } catch (InvalidKeyException e) { throw new RuntimeException("无效密钥错误", e); } } static byte[] encrypt(byte[] data, byte[] key); static byte[] initMacKey(); }### Answer:
@Test public void testEncrypt() { byte[] key = Base64.getDecoder().decode("aDoeS0jpEa7R6YssPU7gZvf95RYH4slqbQgr2gpijhviXyOa16xxOAYmlg0VqBKTE0QPYB26wySLruNJNsbO3A=="); byte[] data = "aaaa".getBytes(); byte[] encryptData = HMAC.encrypt(data, key); String result = Base64.getEncoder().encodeToString(encryptData); assertEquals(result, "omXf1QfFYGlZ+SshA2twjw=="); } |
### Question:
SHA { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.SHA_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.SHA_ALGORITHM + "]算法", e); } } static String digest(byte[] bytes); }### Answer:
@Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = SHA.digest(data); assertEquals(result, "7e240de74fb1ed08fa08d38063f6a6a91462a815"); } |
### Question:
MD5 { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.MD5_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.MD5_ALGORITHM + "]算法", e); } } static String digest(byte[] bytes); }### Answer:
@Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = MD5.digest(data); assertEquals(result, "47bce5c74f589f4867dbd57e9ca9f808"); } |
### Question:
WeatherSecurity { public static String standardURLEncoder(String data, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(spec); byte[] byteHMAC = mac.doFinal(data.getBytes()); if (byteHMAC != null) { String oauth = encode(byteHMAC); return URLEncoder.encode(oauth, "utf8"); } } catch (Exception e1) { e1.printStackTrace(); } return ""; } static String standardURLEncoder(String data, String key); static String encode(byte[] from); }### Answer:
@Test public void testExecuteGet() { try { String type = "forecast_f"; String appid = "0efe9e3c08151b8d"; String date = "201503030741"; String areaid = "101010100"; String key = "a0f6ac_SmartWeatherAPI_cd7e788"; String data = "http: String str = WeatherSecurity.standardURLEncoder(data + appid, key); assertEquals(str, "ocxOZEXG%2BM9aqzMKw0eZK0mXcaA%3D"); String result = data + appid.substring(0, 6) + "&key=" + str; assertEquals(result, "http: } catch (Exception e) { e.printStackTrace(); } } |
### Question:
RSAC { public static byte[] encryptByPublicKey(byte[] data, String ns, String es) { return encryptByPublicKey(data, ns, es, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds, String cipherS); }### Answer:
@Test public void testEncryptByPublicKey() { String data = "abc"; byte[] result = RSAC.encryptByPublicKey(data.getBytes(), ns, es); assertEquals(ISOUtil.hexString(result), "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"); } |
### Question:
RSAC { public static byte[] decryptByPrivateKey(byte[] data, String ns, String ds) { return decryptByPrivateKey(data, ns, ds, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds, String cipherS); }### Answer:
@Test public void testDecryptByPrivateKey() { String data = "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"; byte[] result = RSAC.decryptByPrivateKey(ISOUtil.hex2byte(data), ns, ds); assertEquals(new String(result).trim(), "abc"); } |
### Question:
CreditCardTypeConverter implements TypeConverter<String> { public String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors) { String cardNumber = input.replaceAll("\\D", ""); if (getCardType(cardNumber) != null) { return cardNumber; } errors.add(new ScopedLocalizableError("converter.creditCard", "invalidCreditCard")); return null; } void setLocale(Locale locale); String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors); static Type getCardType(String cardNumber); }### Answer:
@Test(groups = "fast") public void validNumber() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertEquals(c.convert("4111111111111111", String.class, new ArrayList<ValidationError>()), "4111111111111111"); }
@Test(groups = "fast") public void invalidNumber() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertNull(c.convert("4111111111111110", String.class, new ArrayList<ValidationError>())); }
@Test(groups = "fast") public void stripNonNumericCharacters() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertEquals(c.convert("4111-1111-1111-1111", String.class, new ArrayList<ValidationError>()), "4111111111111111"); } |
### Question:
UrlBuilder { @Override public String toString() { if (url == null) { url = build(); } if (this.anchor != null && this.anchor.length() > 0) { return url + "#" + StringUtil.uriFragmentEncode(this.anchor); } else { return url; } } UrlBuilder(Locale locale, String url, boolean isForPage); UrlBuilder(Locale locale, Class<? extends ActionBean> beanType, boolean isForPage); protected UrlBuilder(Locale locale, boolean isForPage); String getEvent(); UrlBuilder setEvent(String event); String getParameterSeparator(); void setParameterSeparator(String parameterSeparator); UrlBuilder addParameter(String name, Object... values); UrlBuilder addParameters(Map<? extends Object, ? extends Object> parameters); String getAnchor(); UrlBuilder setAnchor(String anchor); @Override String toString(); }### Answer:
@Test(groups = "fast") public void testBasicUrl() throws Exception { String path = "/test/page.jsp"; UrlBuilder builder = new UrlBuilder(Locale.getDefault(), path, false); String result = builder.toString(); Assert.assertEquals(result, path); } |
### Question:
HtmlUtil { public static String combineValues(Collection<String> values) { if (values == null || values.size() == 0) { return ""; } else { StringBuilder builder = new StringBuilder(values.size() * 30); for (String value : values) { builder.append(value).append(FIELD_DELIMITER_STRING); } return encode(builder.toString()); } } static String encode(String fragment); static String combineValues(Collection<String> values); static Collection<String> splitValues(String value); }### Answer:
@Test(groups = "fast") public void testJoinWithNoStrings() throws Exception { String combined = HtmlUtil.combineValues(null); Assert.assertEquals(combined, ""); combined = HtmlUtil.combineValues(new HashSet<String>()); Assert.assertEquals(combined, ""); } |
### Question:
HtmlUtil { public static Collection<String> splitValues(String value) { if (value == null || value.length() == 0) { return Collections.emptyList(); } else { String[] splits = FIELD_DELIMITER_PATTERN.split(value); return Arrays.asList(splits); } } static String encode(String fragment); static String combineValues(Collection<String> values); static Collection<String> splitValues(String value); }### Answer:
@Test(groups = "fast") public void testSplitWithNoValues() throws Exception { Collection<String> values = HtmlUtil.splitValues(null); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); values = HtmlUtil.splitValues(""); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); } |
### Question:
CollectionUtil { public static boolean empty(String[] arr) { if (arr == null || arr.length == 0) { return true; } for (String s : arr) { if (s != null && !"".equals(s)) { return false; } } return true; } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testEmptyOnNullCollection() { Assert.assertTrue(CollectionUtil.empty(null)); }
@Test(groups = "fast") public void testEmptyOnCollectionOfNulls() { Assert.assertTrue(CollectionUtil.empty(new String[]{null, null, null})); }
@Test(groups = "fast") public void testEmptyZeroLengthCollection() { Assert.assertTrue(CollectionUtil.empty(new String[]{})); }
@Test(groups = "fast") public void testEmptyOnCollectionOfEmptyStrings() { Assert.assertTrue(CollectionUtil.empty(new String[]{"", null, ""})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection1() { Assert.assertFalse(CollectionUtil.empty(new String[]{"", null, "foo"})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection2() { Assert.assertFalse(CollectionUtil.empty(new String[]{"bar"})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection3() { Assert.assertFalse(CollectionUtil.empty(new String[]{"bar", "splat", "foo"})); } |
### Question:
CollectionUtil { public static boolean applies(String events[], String event) { if (events == null || events.length == 0) { return true; } boolean isPositive = events[0].charAt(0) != '!'; if (isPositive) { return contains(events, event); } else { return !contains(events, "!" + event); } } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testApplies() { Assert.assertTrue(CollectionUtil.applies(null, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{}, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{"bar", "foo"}, "foo")); Assert.assertFalse(CollectionUtil.applies(new String[]{"bar", "f00"}, "foo")); Assert.assertFalse(CollectionUtil.applies(new String[]{"!bar", "!foo"}, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{"!bar", "!f00"}, "foo")); } |
### Question:
CollectionUtil { public static List<Object> asList(Object in) { if (in == null || !in.getClass().isArray()) { throw new IllegalArgumentException("Parameter to asObjectArray must be a non-null array."); } else { int length = Array.getLength(in); LinkedList<Object> list = new LinkedList<Object>(); for (int i = 0; i < length; ++i) { list.add(i, Array.get(in, i)); } return list; } } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testAsList() { List<Object> list = CollectionUtil.asList(new String[]{"foo", "bar"}); Assert.assertEquals(list.get(0), "foo"); Assert.assertEquals(list.get(1), "bar"); list = CollectionUtil.asList(new String[]{}); Assert.assertEquals(list.size(), 0); list = CollectionUtil.asList(new int[]{0, 1, 2, 3}); Assert.assertEquals(list.get(0), new Integer(0)); Assert.assertEquals(list.get(1), new Integer(1)); Assert.assertEquals(list.get(2), new Integer(2)); Assert.assertEquals(list.get(3), new Integer(3)); } |
### Question:
CryptoUtil { public static String encrypt(String input) { if (input == null) { input = ""; } Configuration configuration = StripesFilter.getConfiguration(); if (configuration != null && configuration.isDebugMode()) { return input; } try { byte[] inbytes = input.getBytes(); final int inputLength = inbytes.length; byte[] output = new byte[calculateCipherbytes(inputLength) + CIPHER_HMAC_LENGTH]; SecretKey key = getSecretKey(); byte[] iv = generateInitializationVector(); System.arraycopy(iv, 0, output, 0, CIPHER_BLOCK_LENGTH); Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE, iv, 0, CIPHER_BLOCK_LENGTH); cipher.doFinal(inbytes, 0, inbytes.length, output, CIPHER_BLOCK_LENGTH); hmac(key, output, 0, output.length - CIPHER_HMAC_LENGTH, output, output.length - CIPHER_HMAC_LENGTH); return Base64.encodeBytes(output, BASE64_OPTIONS); } catch (Exception e) { throw new StripesRuntimeException("Could not encrypt value.", e); } } static String encrypt(String input); static String decrypt(String input); static synchronized void setSecretKey(SecretKey key); static final String CONFIG_ENCRYPTION_KEY; }### Answer:
@Test(groups = "fast") public void failOnECB() throws Exception { String input1 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; String encrypted1 = CryptoUtil.encrypt(input1); String encrypted2 = CryptoUtil.encrypt(input1); for (int i = 0; i < encrypted1.length() - 4; i++) { Assert.assertFalse( encrypted2.contains(encrypted1.substring(i, i + 4)), "Predictable ECB detected: " + encrypted1 + " " + encrypted2); } } |
### Question:
ReflectUtil { public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property) { if (!propertyDescriptors.containsKey(clazz)) { getPropertyDescriptors(clazz); } return propertyDescriptors.get(clazz).get(property); } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarnings("rawtypes") // this allows us to assign without casting static Class findClass(String name); static String toString(Annotation ann); static Collection<Method> getMethods(Class<?> clazz); static Collection<Field> getFields(Class<?> clazz); static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property); static Method findAccessibleMethod(final Method m); static Field getField(Class<?> clazz, String property); static Object getDefaultValue(Class<?> clazz); static Set<Class<?>> getImplementedInterfaces(Class<?> clazz); static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static Method resolveBridgedReadMethod(PropertyDescriptor pd); static Method resolveBridgedWriteMethod(PropertyDescriptor pd); static Class<?> resolvePropertyType(PropertyDescriptor pd); }### Answer:
@Test(groups = "fast") public void testCovariantProperty() { abstract class Base { abstract Object getId(); } class ROSub extends Base { protected String id; @Override public String getId() { return id; } } class RWSub extends ROSub { @SuppressWarnings("unused") public void setId(String id) { this.id = id; } } PropertyDescriptor pd = ReflectUtil.getPropertyDescriptor(ROSub.class, "id"); Assert.assertNotNull(pd.getReadMethod(), "Read method is null"); Assert.assertNull(pd.getWriteMethod(), "Write method is not null"); pd = ReflectUtil.getPropertyDescriptor(RWSub.class, "id"); Assert.assertNotNull(pd.getReadMethod(), "Read method is null"); Assert.assertNotNull(pd.getWriteMethod(), "Write method is null"); } |
### Question:
AnnotatedClassActionResolver implements ActionResolver { public Class<? extends ActionBean> getActionBeanByName(String actionBeanName) { return actionBeansByName.get(actionBeanName); } @Override void init(Configuration configuration); UrlBindingFactory getUrlBindingFactory(); String getUrlBindingFromPath(String path); String getUrlBinding(Class<? extends ActionBean> clazz); String getHandledEvent(Method handler); Class<? extends ActionBean> getActionBeanType(String path); ActionBean getActionBean(ActionBeanContext context); ActionBean getActionBean(ActionBeanContext context, String path); String getEventName(Class<? extends ActionBean> bean, ActionBeanContext context); Method getHandler(Class<? extends ActionBean> bean, String eventName); Method getDefaultHandler(Class<? extends ActionBean> bean); Collection<Class<? extends ActionBean>> getActionBeanClasses(); Class<? extends ActionBean> getActionBeanByName(String actionBeanName); static final String PACKAGES; }### Answer:
@Test(groups = "fast") public void findByName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByName("SimpleActionBean"); Assert.assertNotNull(actionBean); }
@Test(groups = "fast") public void multipleActionBeansWithSameSimpleName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByName("OverloadedActionBean"); Assert.assertNull(actionBean); } |
### Question:
NameBasedActionResolver extends AnnotatedClassActionResolver { protected List<String> getFindViewAttempts(String urlBinding) { List<String> attempts = new ArrayList<String>(3); int lastPeriod = urlBinding.lastIndexOf('.'); String path = urlBinding.substring(0, urlBinding.lastIndexOf("/") + 1); String name = (lastPeriod >= path.length()) ? urlBinding.substring(path.length(), lastPeriod) : urlBinding.substring(path.length()); if (name.length() > 0) { attempts.add(path + name + ".jsp"); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); attempts.add(path + name + ".jsp"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < name.length(); ++i) { char ch = name.charAt(i); if (Character.isUpperCase(ch)) { builder.append("_"); builder.append(Character.toLowerCase(ch)); } else { builder.append(ch); } } attempts.add(path + builder.toString() + ".jsp"); } return attempts; } @Override void init(Configuration configuration); @Override String getUrlBinding(Class<? extends ActionBean> clazz); @Override String getHandledEvent(Method handler); static boolean isAsyncEventHandler(Method handler); @Override ActionBean getActionBean(ActionBeanContext context,
String urlBinding); static final Set<String> BASE_PACKAGES; static final String DEFAULT_BINDING_SUFFIX; static final List<String> DEFAULT_ACTION_BEAN_SUFFIXES; }### Answer:
@Test(groups = "fast") public void testGetFindViewAttempts() { String urlBinding = "/account/ViewAccount.action"; List<String> viewAttempts = this.resolver.getFindViewAttempts(urlBinding); Assert.assertEquals(viewAttempts.size(), 3); Assert.assertEquals(viewAttempts.get(0), "/account/ViewAccount.jsp"); Assert.assertEquals(viewAttempts.get(1), "/account/viewAccount.jsp"); Assert.assertEquals(viewAttempts.get(2), "/account/view_account.jsp"); } |
### Question:
LocalizationUtility { public static String getSimpleName(Class<?> c) { if (c.getEnclosingClass() == null) { return c.getSimpleName(); } else { return prefixSimpleName(new StringBuilder(), c).toString(); } } static String getLocalizedFieldName(String fieldName,
String actionPath,
Class<? extends ActionBean> beanclass,
Locale locale); static String makePseudoFriendlyName(String fieldNameKey); static String getErrorMessage(Locale locale, String key); static String getSimpleName(Class<?> c); }### Answer:
@Test(groups = "fast") public void testSimpleClassName() throws Exception { String output = LocalizationUtility.getSimpleName(TestEnum.class); Assert.assertEquals(output, "LocalizationUtilityTest.TestEnum"); output = LocalizationUtility.getSimpleName(A.B.C.class); Assert.assertEquals(output, "LocalizationUtilityTest.A.B.C"); } |
### Question:
MockRoundtrip { public void addParameter(String name, String... value) { if (this.request.getParameterValues(name) == null) { setParameter(name, value); } else { String[] oldValues = this.request.getParameterMap().get(name); String[] combined = new String[oldValues.length + value.length]; System.arraycopy(oldValues, 0, combined, 0, oldValues.length); System.arraycopy(value, 0, combined, oldValues.length, value.length); setParameter(name, combined); } } MockRoundtrip(MockServletContext context, Class<? extends ActionBean> beanType); MockRoundtrip(MockServletContext context,
Class<? extends ActionBean> beanType,
MockHttpSession session); MockRoundtrip(MockServletContext context, String actionBeanUrl); MockRoundtrip(MockServletContext context, String actionBeanUrl, MockHttpSession session); MockHttpServletRequest getRequest(); MockHttpServletResponse getResponse(); MockServletContext getContext(); void setParameter(String name, String... value); void addParameter(String name, String... value); void setSourcePage(String url); void execute(); void execute(String event); @SuppressWarnings("unchecked") A getActionBean(Class<A> type); ValidationErrors getValidationErrors(); List<Message> getMessages(); byte[] getOutputBytes(); String getOutputString(); String getDestination(); String getForwardUrl(); String getRedirectUrl(); static final String DEFAULT_SOURCE_PAGE; }### Answer:
@Test(groups = "fast") public void testAddParameter() throws Exception { MockRoundtrip trip = new MockRoundtrip(getMockServletContext(), TestMockRoundtrip.class); trip.addParameter("param", "a"); trip.addParameter("param", "b"); trip.execute(); TestMockRoundtrip bean = trip.getActionBean(TestMockRoundtrip.class); String[] params = bean.getContext().getRequest().getParameterValues("param"); Assert.assertEquals(2, params.length); Assert.assertEquals(new String[]{"a", "b"}, params); } |
### Question:
SimpleTextReader implements AutoCloseable { public LineIterator getLineIterator() throws IOException { return new LineIterator(getReader(), trim, filters); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(String fileName); SimpleTextReader(String fileName, String encoding); SimpleTextReader(InputStream is); SimpleTextReader(InputStream is, String encoding); static SimpleTextReader trimmingUTF8Reader(File file); static LineIterator trimmingUTF8LineIterator(File file); static IterableLineReader trimmingUTF8IterableLineReader(File file); static SimpleTextReader trimmingReader(InputStream is, String encoding); static LineIterator trimmingLineIterator(InputStream is, String encoding); static IterableLineReader trimmingIterableLineReader(InputStream is, String encoding); String getEncoding(); SimpleTextReader cloneForStream(InputStream is); SimpleTextReader cloneForFile(File file); byte[] asByteArray(); String asString(); List<String> asStringList(); IterableLineReader getIterableReader(); LineIterator getLineIterator(); long countLines(); void close(); }### Answer:
@Test public void lineIteratorTest2() throws IOException { try (LineIterator li = new SimpleTextReader(multi_line_text_file.getFile()).getLineIterator()) { while (li.hasNext()) { out.println(li.next().toUpperCase()); } } }
@Test public void lineIteratorWithConstraint() throws IOException { try (LineIterator li = new SimpleTextReader .Builder(multi_line_text_file.getFile()) .ignoreWhiteSpaceLines() .trim() .build().getLineIterator()) { int i = 0; while (li.hasNext()) { String s = li.next(); if (i == 0) { assertEquals(s, "uno"); } if (i == 1) { assertEquals(s, "dos"); } i++; } } } |
### Question:
LogMath { public static double log2(double input) { return Math.log(input) * INVERSE_LOG_TWO; } private LogMath(); static double logSum(double logA, double logB); static double logSum10(double log10A, double log10B); static double logSum(double... logValues); static double log(double base, double val); static double log2(double input); static double log10ToLog(double log10Value); static double toLogSphinx(double logValue); static void main(String[] args); static final double LOG_ZERO; static final double LOG_ONE; static final double LOG_TEN; static final double LOG_TWO; static final double INVERSE_LOG_TWO; static final float LOG_ZERO_FLOAT; static final float LOG_ONE_FLOAT; static final float LOG_TEN_FLOAT; static final float LOG_TWO_FLOAT; static final LogSumLookup LOG_SUM; static final LogSumLookupFloat LOG_SUM_FLOAT; static final LinearToLogConverter LINEAR_TO_LOG; static final LinearToLogConverterFloat LINEAR_TO_LOG_FLOAT; }### Answer:
@Test public void testLog2() { Assert.assertEquals(2, LogMath.log2(4), 0.0001); Assert.assertEquals(3, LogMath.log2(8), 0.0001); Assert.assertEquals(10, LogMath.log2(1024), 0.0001); Assert.assertEquals(-1, LogMath.log2(0.5), 0.0001); } |
### Question:
BlockTextLoader implements Iterable<TextChunk> { public static BlockTextLoader fromPath(Path corpus, int blockSize) { return new BlockTextLoader(Collections.singletonList(corpus), blockSize); } BlockTextLoader(List<Path> corpusPaths, int blockSize); List<Path> getCorpusPaths(); int getBlockSize(); int pathCount(); static BlockTextLoader fromPaths(List<Path> corpora); static BlockTextLoader fromDirectory(Path directoryPath); static BlockTextLoader fromPaths(List<Path> corpora, int blockSize); static BlockTextLoader fromPath(Path corpus, int blockSize); static BlockTextLoader fromDirectoryRoot(
Path corporaRoot,
Path folderListFile,
int blockSize); @Override Iterator<TextChunk> iterator(); static Iterator<TextChunk> singlePathIterator(Path path, int blockSize); static Iterator<TextChunk> iteratorFromCharIndex(
Path path,
int blockSize,
long charIndex); }### Answer:
@Test public void loadTest1() throws IOException { List<String> lines = new ArrayList<>(); for (int i = 0; i < 10000; i++) { lines.add(String.valueOf(i)); } Path path = TestUtil.tempFileWithData(lines); BlockTextLoader loader = BlockTextLoader.fromPath(path, 1000); int i = 0; List<String> read = new ArrayList<>(); for (TextChunk block : loader) { i++; read.addAll(block.getData()); } Assert.assertEquals(i, 10); Assert.assertEquals(lines, read); loader = BlockTextLoader.fromPath(path, 1001); i = 0; read = new ArrayList<>(); for (TextChunk block : loader) { i++; read.addAll(block.getData()); } Assert.assertEquals(i, 10); Assert.assertEquals(lines, read); loader = BlockTextLoader.fromPath(path, 100000); i = 0; read = new ArrayList<>(); for (TextChunk block : loader) { i++; read.addAll(block.getData()); } Assert.assertEquals(i, 1); Assert.assertEquals(lines, read); Files.delete(path); } |
### Question:
IntVector { public void add(int i) { if (size == data.length) { expand(); } data[size] = i; size++; } IntVector(); IntVector(int initialCapacity); IntVector(int[] values); void add(int i); void addAll(int[] arr); void addAll(IntVector vec); int get(int index); void set(int index, int value); void safeSet(int index, int value); int size(); int capacity(); void sort(); int[] copyOf(); void shuffle(Random random); boolean contains(int i); void shuffle(); void trimToSize(); boolean isempty(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testAdd() { IntVector darray = new IntVector(); for (int i = 0; i < 10000; i++) { darray.add(i); } Assert.assertEquals(10000, darray.size()); for (int i = 0; i < 10000; i++) { Assert.assertEquals(i, darray.get(i)); } } |
### Question:
IntVector { public void addAll(int[] arr) { if (size + arr.length >= data.length) { expand(arr.length); } System.arraycopy(arr, 0, data, size, arr.length); size += arr.length; } IntVector(); IntVector(int initialCapacity); IntVector(int[] values); void add(int i); void addAll(int[] arr); void addAll(IntVector vec); int get(int index); void set(int index, int value); void safeSet(int index, int value); int size(); int capacity(); void sort(); int[] copyOf(); void shuffle(Random random); boolean contains(int i); void shuffle(); void trimToSize(); boolean isempty(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testAddAll() { int[] d1 = {2, 4, 5, 17, -1, -2, 5, -123}; IntVector darray = new IntVector(); IntVector i = new IntVector(d1); darray.addAll(i); Assert.assertEquals(i, darray); } |
### Question:
IntVector { public void trimToSize() { data = Arrays.copyOf(data, size); } IntVector(); IntVector(int initialCapacity); IntVector(int[] values); void add(int i); void addAll(int[] arr); void addAll(IntVector vec); int get(int index); void set(int index, int value); void safeSet(int index, int value); int size(); int capacity(); void sort(); int[] copyOf(); void shuffle(Random random); boolean contains(int i); void shuffle(); void trimToSize(); boolean isempty(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testTrimToSize() { IntVector darray = new IntVector(); for (int i = 0; i < 10000; i++) { darray.add(i); } Assert.assertEquals(10000, darray.size()); Assert.assertNotEquals(darray.size(), darray.capacity()); darray.trimToSize(); Assert.assertEquals(10000, darray.size()); Assert.assertEquals(10000, darray.copyOf().length); Assert.assertEquals(darray.size(), darray.capacity()); } |
### Question:
LongBitVector { public void fill(boolean bitValue) { if (bitValue) { Arrays.fill(words, 0xffffffffffffffffL); int last = (int) (size / 64); words[last] &= cutMasks[(int) (size & mod64Mask)] >>> 1; } else { Arrays.fill(words, 0); } } LongBitVector(); LongBitVector(long initialCapcity); LongBitVector(long[] words, long size); LongBitVector(long initialCapcity, int capacityInterval); static LongBitVector deserialize(DataInputStream dis); long getLastBitIndex(boolean bitValue); void fill(boolean bitValue); long[] getLongArray(); long[] zeroIndexes(); int[] zeroIntIndexes(); long size(); void add(boolean b); void addFast(boolean b); long getLong(long start, int bitAmount); void add(int a, int bitLength); void add(int amount, boolean bit); void add(long a, int bitLength); long numberOfOnes(); long numberOfZeros(); void checkAndEnsureCapacity(int bitAmount); boolean get(long n); void set(long n); void set(long[] n); void clear(long n); void clear(long[] n); void serialize(DataOutputStream dos); static final long MAX_ARRAY_SIZE; }### Answer:
@Test public void fillTest() { LongBitVector vector = new LongBitVector(128); vector.add(128, false); for (int i = 0; i < 128; i++) { Assert.assertTrue(!vector.get(i)); } vector.fill(true); for (int i = 0; i < 128; i++) { Assert.assertTrue(vector.get(i)); } vector.fill(false); for (int i = 0; i < 128; i++) { Assert.assertTrue(!vector.get(i)); } vector = new LongBitVector(3); vector.add(3, false); vector.fill(true); assertEquals(vector.getLongArray()[0], 7); } |
### Question:
UIntMap extends UIntKeyHashBase implements Iterable<T> { public T get(int key) { if (key < 0) { throw new IllegalArgumentException("Key cannot be negative: " + key); } int slot = hash(key) & modulo; while (true) { final int t = keys[slot]; if (t == EMPTY) { return null; } if (t == DELETED) { slot = (slot + 1) & modulo; continue; } if (t == key) { return values[slot]; } slot = (slot + 1) & modulo; } } UIntMap(); UIntMap(int size); T get(int key); boolean containsKey(int key); void put(int key, T value); List<T> getValues(); @Override Iterator<T> iterator(); List<T> getValuesSortedByKey(); }### Answer:
@Test public void getTest() { UIntMap<String> map = new UIntMap<>(1); map.put(1, "2"); Assert.assertEquals("2", map.get(1)); Assert.assertNull(map.get(2)); map.put(1, "3"); Assert.assertEquals("3", map.get(1)); map = new UIntMap<>(); for (int i = 0; i < 100000; i++) { map.put(i, String.valueOf(i + 1)); } for (int i = 0; i < 100000; i++) { Assert.assertEquals(String.valueOf(i + 1), map.get(i)); } } |
### Question:
UIntMap extends UIntKeyHashBase implements Iterable<T> { public List<T> getValues() { List<T> result = new ArrayList<>(); for (int i = 0; i < keys.length; i++) { int key = keys[i]; if (key >= 0) { result.add(values[i]); } } return result; } UIntMap(); UIntMap(int size); T get(int key); boolean containsKey(int key); void put(int key, T value); List<T> getValues(); @Override Iterator<T> iterator(); List<T> getValuesSortedByKey(); }### Answer:
@Test public void getValuesTest() { UIntMap<String> map = new UIntMap<>(); int size = 1000; List<String> expected = new ArrayList<>(); for (int i = 0; i < size; i++) { String value = String.valueOf(i + 1); map.put(i, value); expected.add(value); } Assert.assertEquals(expected, map.getValuesSortedByKey()); } |
### Question:
IntIntMap extends CompactIntMapBase { public int get(int key) { checkKey(key); int slot = firstProbe(key); while (true) { final long entry = entries[slot]; final int t = (int) (entry & 0xFFFF_FFFFL); if (t == key) { return (int) (entry >>> 32); } if (t == EMPTY) { return NO_RESULT; } slot = probe(slot); } } IntIntMap(); IntIntMap(int capacity); void put(int key, int value); void increment(int key, int value); int get(int key); int[] getValues(); IntPair[] getAsPairs(); }### Answer:
@Test public void removeSpansWorksCorrectly2() { IntIntMap im = createMap(); int limit = 9999; insertSpan(im, 0, limit); int[] r = TestUtils.createRandomUintArray(1000, limit); for (int i : r) { im.remove(i); } for (int i : r) { assertEquals(im.get(i), IntIntMap.NO_RESULT); } insertSpan(im, 0, limit); checkSpan(im, 0, limit); removeSpan(im, 0, limit); assertEquals(im.size(), 0); insertSpan(im, -limit, limit); checkSpan(im, -limit, limit); } |
### Question:
IntIntMap extends CompactIntMapBase { public void put(int key, int value) { checkKey(key); expandIfNecessary(); int loc = locate(key); if (loc >= 0) { setValue(loc, value); } else { setKeyValue(-loc - 1, key, value); keyCount++; } } IntIntMap(); IntIntMap(int capacity); void put(int key, int value); void increment(int key, int value); int get(int key); int[] getValues(); IntPair[] getAsPairs(); }### Answer:
@Test public void removeTest2() { IntIntMap map = createMap(); for (int i = 0; i < 10000; i++) { map.put(i, i + 1); } for (int i = 0; i < 10000; i += 3) { map.remove(i); } for (int i = 0; i < 10000; i += 3) { Assert.assertTrue(!map.containsKey(i)); } for (int i = 0; i < 10000; i++) { map.put(i, i + 1); } for (int i = 0; i < 10000; i += 3) { Assert.assertTrue(map.containsKey(i)); } } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { public int addOrIncrement(T key) { return incrementByAmount(key, 1); } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void constructorTest2() { IntValueMap<String> set = new IntValueMap<>(1); set.addOrIncrement("foo"); Assert.assertEquals(1, set.size()); set.remove("foo"); Assert.assertEquals(0, set.size()); Assert.assertFalse(set.contains("foo")); } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { public void put(T key, int value) { if (key == null) { throw new IllegalArgumentException("Key cannot be null."); } if (keyCount + removeCount == threshold) { expand(); } int loc = locate(key); if (loc >= 0) { values[loc] = value; } else { loc = -loc - 1; keys[loc] = key; values[loc] = value; keyCount++; } } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void putTest() { IntValueMap<String> table = new IntValueMap<>(); table.put("foo", 1); Assert.assertEquals(1, table.size()); table.put("foo", 2); Assert.assertEquals(1, table.size()); table = new IntValueMap<>(); for (int i = 0; i < 1000; i++) { table.put(String.valueOf(i), i + 1); Assert.assertEquals(i + 1, table.size()); } table = new IntValueMap<>(); for (int i = 0; i < 1000; i++) { table.put(String.valueOf(i), i + 1); table.put(String.valueOf(i), i + 1); Assert.assertEquals(i + 1, table.size()); } } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { private void expand() { IntValueMap<T> h = new IntValueMap<>(newSize()); for (int i = 0; i < keys.length; i++) { if (hasValidKey(i)) { h.put(keys[i], values[i]); } } expandCopyParameters(h); this.values = h.values; } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void expandTest() { IntValueMap<String> table = new IntValueMap<>(); for (int i = 0; i < 10000; i++) { table.put(String.valueOf(i), i + 1); Assert.assertEquals(i + 1, table.size()); } for (int i = 0; i < 5000; i++) { table.remove(String.valueOf(i)); Assert.assertEquals(10000 - i - 1, table.size()); } for (int i = 5000; i < 10000; i++) { Assert.assertEquals(i + 1, table.get(String.valueOf(i))); } } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { public int get(T key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null."); } int slot = hash(key) & modulo; while (true) { final T t = keys[slot]; if (t == null) { return 0; } if (t == TOMB_STONE) { slot = (slot + 1) & modulo; continue; } if (t.equals(key)) { return values[slot]; } slot = (slot + 1) & modulo; } } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void getTest() { IntValueMap<Integer> table = new IntValueMap<>(); table.put(1, 2); Assert.assertEquals(2, table.get(1)); Assert.assertEquals(0, table.get(2)); table.put(1, 3); Assert.assertEquals(3, table.get(1)); table = new IntValueMap<>(); for (int i = 0; i < 1000; i++) { table.put(i, i + 1); } for (int i = 0; i < 1000; i++) { Assert.assertEquals(i + 1, table.get(i)); } } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { public int[] copyOfValues() { int[] result = new int[keyCount]; int k = 0; for (int i = 0; i < keys.length; i++) { if (hasValidKey(i)) { result[k] = values[i]; k++; } } return result; } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void copyOfValuesTest() { IntValueMap<String> set = new IntValueMap<>(); for (int i = 0; i < 1000; i++) { set.put(String.valueOf(i), i + 1); } int[] values = set.copyOfValues(); Assert.assertEquals(1000, values.length); Arrays.sort(values); for (int i = 0; i < 1000; i++) { Assert.assertEquals(i + 1, values[i]); } set.remove("768"); set.remove("0"); set.remove("999"); values = set.copyOfValues(); Assert.assertEquals(997, values.length); Arrays.sort(values); Assert.assertTrue(Arrays.binarySearch(values, 769) < 0); Assert.assertTrue(Arrays.binarySearch(values, 1) < 0); Assert.assertTrue(Arrays.binarySearch(values, 1000) < 0); } |
### Question:
IntValueMap extends HashBase<T> implements Iterable<T> { public void addOrIncrementAll(Iterable<T> keys) { for (T t : keys) { incrementByAmount(t, 1); } } IntValueMap(); IntValueMap(int size); int addOrIncrement(T key); void addOrIncrementAll(Iterable<T> keys); int get(T key); int decrement(T key); int incrementByAmount(T key, int amount); void put(T key, int value); int[] copyOfValues(); List<Entry<T>> getAsEntryList(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test @Ignore("Not a unit test") public void perfStrings() { for (int i = 0; i < 5; i++) { Set<String> strings = uniqueStrings(1000000, 7); Stopwatch sw = Stopwatch.createStarted(); Set<String> newSet = new HashSet<>(strings); System.out.println("Java Set : " + sw.elapsed(TimeUnit.MILLISECONDS)); System.out.println("Size = " + newSet.size()); sw.reset().start(); IntValueMap<String> cs = new IntValueMap<>(strings.size() * 2); cs.addOrIncrementAll(strings); System.out.println("Count Add : " + sw.elapsed(TimeUnit.MILLISECONDS)); } } |
### Question:
FixedBitVector { public boolean safeGet(int n) { check(n); return (words[n >> 5] & setMasks[n & 31]) != 0; } FixedBitVector(int length); boolean get(int n); boolean safeGet(int n); void set(int n); void safeSet(int n); void clear(int n); void safeClear(int n); int numberOfOnes(); int numberOfNewOneBitCount(FixedBitVector other); int differentBitCount(FixedBitVector other); int numberOfZeroes(); int[] zeroIndexes(); final int length; }### Answer:
@Test(expected = IllegalArgumentException.class) public void safeGet() { FixedBitVector vector = new FixedBitVector(10); vector.safeGet(10); } |
### Question:
FixedBitVector { public void safeSet(int n) { check(n); words[n >> 5] |= setMasks[n & 31]; } FixedBitVector(int length); boolean get(int n); boolean safeGet(int n); void set(int n); void safeSet(int n); void clear(int n); void safeClear(int n); int numberOfOnes(); int numberOfNewOneBitCount(FixedBitVector other); int differentBitCount(FixedBitVector other); int numberOfZeroes(); int[] zeroIndexes(); final int length; }### Answer:
@Test(expected = IllegalArgumentException.class) public void safeSet() { FixedBitVector vector = new FixedBitVector(10); vector.safeSet(10); } |
### Question:
FixedBitVector { public void safeClear(int n) { check(n); words[n >> 5] &= resetMasks[n & 31]; } FixedBitVector(int length); boolean get(int n); boolean safeGet(int n); void set(int n); void safeSet(int n); void clear(int n); void safeClear(int n); int numberOfOnes(); int numberOfNewOneBitCount(FixedBitVector other); int differentBitCount(FixedBitVector other); int numberOfZeroes(); int[] zeroIndexes(); final int length; }### Answer:
@Test(expected = IllegalArgumentException.class) public void safeClear() { FixedBitVector vector = new FixedBitVector(10); vector.safeClear(10); } |
### Question:
FloatValueMap extends HashBase<T> implements Iterable<T> { public float[] values() { float[] result = new float[size()]; int j = 0; for (int i = 0; i < keys.length; i++) { if (hasValidKey(i)) { result[j++] = values[i]; } } return result; } FloatValueMap(); FloatValueMap(int size); private FloatValueMap(FloatValueMap<T> other, T[] keys, float[] values); float get(T key); float incrementByAmount(T key, float amount); void set(T key, float value); float[] values(); List<Entry<T>> getAsEntryList(); FloatValueMap<T> copy(); Iterator<Entry<T>> entryIterator(); Iterable<Entry<T>> iterableEntries(); }### Answer:
@Test public void testValues() { FloatValueMap<String> set = new FloatValueMap<>(); set.set("a", 7); set.set("b", 2); set.set("c", 3); set.set("d", 4); set.set("d", 5); Assert.assertEquals(4, set.size()); float[] values = set.values(); Arrays.sort(values); Assert.assertTrue(Arrays.equals(new float[]{2f, 3f, 5f, 7f}, values)); } |
### Question:
LookupSet extends HashBase<T> implements Iterable<T> { public boolean add(T key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null."); } if (keyCount + removeCount == threshold) { expand(); } int loc = locate(key); if (loc >= 0) { return false; } else { loc = -loc - 1; keys[loc] = key; keyCount++; return true; } } LookupSet(); LookupSet(int size); T set(T key); @SafeVarargs final void addAll(T... t); void addAll(Iterable<T> it); boolean add(T key); T getOrAdd(T key); }### Answer:
@Test public void addTest() { Foo f1 = new Foo("abc", 1); Foo f2 = new Foo("abc", 2); LookupSet<Foo> fooSet = new LookupSet<>(); Assert.assertTrue(fooSet.add(f1)); Assert.assertFalse(fooSet.add(f2)); }
@Test public void lookupTest() { Foo f1 = new Foo("abc", 1); Foo f2 = new Foo("abc", 2); LookupSet<Foo> fooSet = new LookupSet<>(); Assert.assertNull(fooSet.lookup(f1)); Assert.assertNull(fooSet.lookup(f2)); fooSet.add(f1); Assert.assertEquals(1, fooSet.lookup(f1).b); Assert.assertEquals(1, fooSet.lookup(f2).b); fooSet.add(f2); Assert.assertEquals(1, fooSet.lookup(f1).b); Assert.assertEquals(1, fooSet.lookup(f2).b); } |
### Question:
LookupSet extends HashBase<T> implements Iterable<T> { public T getOrAdd(T key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null."); } if (keyCount + removeCount == threshold) { expand(); } int loc = locate(key); if (loc >= 0) { return keys[loc]; } else { loc = -loc - 1; keys[loc] = key; keyCount++; return key; } } LookupSet(); LookupSet(int size); T set(T key); @SafeVarargs final void addAll(T... t); void addAll(Iterable<T> it); boolean add(T key); T getOrAdd(T key); }### Answer:
@Test public void getOrAddTest() { Foo f1 = new Foo("abc", 1); Foo f2 = new Foo("abc", 2); LookupSet<Foo> fooSet = new LookupSet<>(); Assert.assertEquals(1, fooSet.getOrAdd(f1).b); Assert.assertEquals(1, fooSet.getOrAdd(f2).b); }
@Test public void removeTest() { Foo f1 = new Foo("abc", 1); Foo f2 = new Foo("abc", 2); LookupSet<Foo> fooSet = new LookupSet<>(); Assert.assertEquals(1, fooSet.getOrAdd(f1).b); Assert.assertEquals(1, fooSet.getOrAdd(f2).b); Assert.assertEquals(1, fooSet.remove(f2).b); Assert.assertEquals(2, fooSet.getOrAdd(f2).b); } |
### Question:
IntFloatMap extends CompactIntMapBase { public float get(int key) { checkKey(key); int slot = firstProbe(key); while (true) { final long entry = entries[slot]; final int t = (int) (entry & 0xFFFF_FFFFL); if (t == key) { return Float.intBitsToFloat((int) (entry >>> 32)); } if (t == EMPTY) { return NO_RESULT; } slot = probe(slot); } } IntFloatMap(); IntFloatMap(int capacity); void put(int key, float value); void increment(int key, float value); float get(int key); float[] getValues(); }### Answer:
@Test public void removeSpansWorksCorrectly2() { IntFloatMap im = createMap(); int limit = 9999; insertSpan(im, 0, limit); int[] r = TestUtils.createRandomUintArray(1000, limit); for (int i : r) { im.remove(i); } for (int i : r) { assertEqualsF(im.get(i), IntIntMap.NO_RESULT); } insertSpan(im, 0, limit); checkSpan(im, 0, limit); removeSpan(im, 0, limit); assertEqualsF(im.size(), 0); insertSpan(im, -limit, limit); checkSpan(im, -limit, limit); } |
### Question:
IntFloatMap extends CompactIntMapBase { public void put(int key, float value) { checkKey(key); expandIfNecessary(); int loc = locate(key); if (loc >= 0) { setValue(loc, value); } else { setKeyValue(-loc - 1, key, value); keyCount++; } } IntFloatMap(); IntFloatMap(int capacity); void put(int key, float value); void increment(int key, float value); float get(int key); float[] getValues(); }### Answer:
@Test public void removeTest2() { IntFloatMap map = createMap(); for (int i = 0; i < 10000; i++) { map.put(i, i + 1); } for (int i = 0; i < 10000; i += 3) { map.remove(i); } for (int i = 0; i < 10000; i += 3) { Assert.assertTrue(!map.containsKey(i)); } for (int i = 0; i < 10000; i++) { map.put(i, i + 1); } for (int i = 0; i < 10000; i += 3) { Assert.assertTrue(map.containsKey(i)); } } |
### Question:
Trie { public List<T> getAll() { List<T> items = new ArrayList<>(size); List<Node<T>> toWalk = Lists.newArrayList(root); while (toWalk.size() > 0) { List<Node<T>> n = new ArrayList<>(); for (Node<T> tNode : toWalk) { if (tNode.hasItem()) { items.addAll(tNode.items); } if (tNode.children != null && tNode.children.size() > 0) { n.addAll(tNode.children.getValues()); } } toWalk = n; } return items; } void add(String s, T item); void remove(String s, T item); int size(); boolean containsItem(String s, T item); List<T> getItems(String s); List<T> getAll(); List<T> getPrefixMatchingItems(String input); String toString(); }### Answer:
@Test public void getAllTest() { List<Item> items = createitems("elma", "el", "arm", "armut", "a", "elmas"); additems(items); List<Item> all = lt.getAll(); Assert.assertEquals(6, all.size()); } |
### Question:
Trie { public void remove(String s, T item) { Node node = walkToNode(s); if (node != null && node.hasItem()) { node.items.remove(item); size--; } } void add(String s, T item); void remove(String s, T item); int size(); boolean containsItem(String s, T item); List<T> getItems(String s); List<T> getAll(); List<T> getPrefixMatchingItems(String input); String toString(); }### Answer:
@Test public void removeStems() { List<Item> items = createitems("el", "elmas", "elma", "ela"); additems(items); checkitemsExist(items); checkitemsMatches("el", createitems("el")); checkitemsMatches("el", createitems()); lt.remove(items.get(1).surfaceForm, items.get(1)); checkitemsMatches("elmas", createitems()); checkitemsMatches("e", createitems()); checkitemsMatches("ela", createitems("ela")); checkitemsMatches("elastik", createitems("ela")); checkitemsMatches("elmas", createitems("el", "elma")); checkitemsMatches("elmaslar", createitems("el", "elma")); } |
### Question:
NerDataSet { public static NerDataSet load(Path path, AnnotationStyle style) throws IOException { switch (style) { case BRACKET: return loadBracketStyle(path); case ENAMEX: return loadEnamexStyle(path); case OPEN_NLP: return loadOpenNlpStyle(path); } throw new IOException(String.format("Cannot load data from %s with style %s", path, style)); } NerDataSet(List<NerSentence> sentences); List<NerSentence> getSentences(); void shuffle(); static NerDataSet load(Path path, AnnotationStyle style); static String normalizeForNer(String input); void addSet(NerDataSet set); NerDataSet getSubSet(int from, int to); String info(); static final String OUT_TOKEN_TYPE; }### Answer:
@Test public void testOpenNlpStyle() throws IOException { Path p = TestUtil.tempFileWithData( "<Start:ABC> Foo Bar <End> ivir zivir <Start:DEF> haha <End> . "); NerDataSet set = NerDataSet.load(p, AnnotationStyle.OPEN_NLP); System.out.println("types= " + set.types); Assert.assertTrue(TestUtil.containsAll(set.types, "ABC", "DEF", "OUT")); }
@Test public void testBracketStyle() throws IOException { Path p = TestUtil.tempFileWithData( "[ABC Foo Bar] ivir zivir [DEF haha] . "); NerDataSet set = NerDataSet.load(p, AnnotationStyle.BRACKET); System.out.println("types= " + set.types); Assert.assertTrue(TestUtil.containsAll(set.types, "ABC", "DEF", "OUT")); } |
### Question:
TurkishTokenizer { public static Builder builder() { return new Builder(); } private TurkishTokenizer(long acceptedTypeBits); static Builder builder(); boolean isTypeAccepted(Token.Type i); boolean isTypeIgnored(Token.Type i); List<Token> tokenize(File file); List<Token> tokenize(String input); List<Token> tokenize(Reader reader); List<String> tokenizeToStrings(String input); Iterator<Token> getTokenIterator(String input); Iterator<Token> getTokenIterator(File file); Iterator<Token> getTokenIterator(Reader reader); static Token convert(org.antlr.v4.runtime.Token token); static Token convert(org.antlr.v4.runtime.Token token, Token.Type type); static Token.Type convertType(org.antlr.v4.runtime.Token token); static final TurkishTokenizer ALL; static final TurkishTokenizer DEFAULT; }### Answer:
@Test public void testInstances() { TurkishTokenizer t = TurkishTokenizer.DEFAULT; matchToken(t, "a b \t c \n \r", "a", "b", "c"); t = TurkishTokenizer.ALL; matchToken(t, " a b\t\n\rc", " ", "a", " ", "b", "\t", "\n", "\r", "c"); t = TurkishTokenizer.builder().ignoreAll().acceptTypes(Type.Number).build(); matchToken(t, "www.foo.bar 12,4'ü [email protected] ; ^% 2 adf 12 \r \n ", "12,4'ü", "2", "12"); } |
### Question:
Span { public String getSubstring(String input) { return input.substring(start, end); } Span(int start, int end); int length(); int middleValue(); Span copy(int offset); String getSubstring(String input); boolean inSpan(int i); final int start; final int end; }### Answer:
@Test public void substringTest() { Assert.assertEquals("", new Span(0, 0).getSubstring("hello")); Assert.assertEquals("h", new Span(0, 1).getSubstring("hello")); Assert.assertEquals("ello", new Span(1, 5).getSubstring("hello")); } |
### Question:
Span { public int length() { return end - start; } Span(int start, int end); int length(); int middleValue(); Span copy(int offset); String getSubstring(String input); boolean inSpan(int i); final int start; final int end; }### Answer:
@Test public void lengthTest() { Assert.assertEquals(0, new Span(0, 0).length()); Assert.assertEquals(1, new Span(0, 1).length()); Assert.assertEquals(4, new Span(1, 5).length()); } |
### Question:
TurkishSentenceExtractor extends PerceptronSegmenter { public static Builder builder() { return new Builder(); } private TurkishSentenceExtractor(FloatValueMap<String> weights); private TurkishSentenceExtractor(FloatValueMap<String> weights,
boolean doNotSplitInDoubleQuotes); static Builder builder(); List<String> fromParagraphs(Collection<String> paragraphs); List<String> fromParagraph(String paragraph); List<String> fromDocument(String document); char[] getBoundaryCharacters(); static final TurkishSentenceExtractor DEFAULT; }### Answer:
@Test public void testDoubleQuotes() throws IOException { TurkishSentenceExtractor e = TurkishSentenceExtractor .builder() .doNotSplitInDoubleQuotes() .useDefaultModel().build(); Assert.assertEquals( "\"Merhaba! Bugün hava çok güzel. Ne dersin?\" dedi tavşan.|Havucu kemirirken.", markBoundariesParagraph( e, "\"Merhaba! Bugün hava çok güzel. Ne dersin?\" dedi tavşan. Havucu kemirirken.")); Assert.assertEquals( "\"Buna hakkı yok!\" diye öfkeyle konuşmaya başladı Baba Kurt.", markBoundariesParagraph( e, "\"Buna hakkı yok!\" diye öfkeyle konuşmaya başladı Baba Kurt.")); } |
### Question:
TurkishDictionaryLoader { public static RootLexicon loadDefaultDictionaries() throws IOException { return loadFromResources(DEFAULT_DICTIONARY_RESOURCES); } static RootLexicon loadDefaultDictionaries(); static RootLexicon loadFromResources(String... resourcePaths); static RootLexicon loadFromResources(Collection<String> resourcePaths); static RootLexicon load(File input); static RootLexicon loadInto(RootLexicon lexicon, File input); static DictionaryItem loadFromString(String dictionaryLine); static RootLexicon load(String... dictionaryLines); static RootLexicon load(Iterable<String> dictionaryLines); static final List<String> DEFAULT_DICTIONARY_RESOURCES; }### Answer:
@Test @Ignore("Not a unit test") public void saveFullAttributes() throws IOException { RootLexicon items = TurkishDictionaryLoader.loadDefaultDictionaries(); PrintWriter p = new PrintWriter(new File("dictionary-all-attributes.txt"), "utf-8"); for (DictionaryItem item : items) { p.println(item.toString()); } } |
### Question:
TurkishNumbers { public static String convertOrdinalNumberString(String input) { String numberPart = input; if (input.endsWith(".")) { numberPart = Strings.subStringUntilFirst(input, "."); } long number = Long.parseLong(numberPart); String text = convertToString(number); String[] words = text.trim().split("[ ]+"); String lastNumber = words[words.length - 1]; if (ordinalMap.containsKey(lastNumber)) { lastNumber = ordinalMap.get(lastNumber); } else { throw new RuntimeException("Cannot find ordinal reading for:" + lastNumber); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < words.length - 1; i++) { sb.append(words[i]).append(" "); } sb.append(lastNumber); return sb.toString(); } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static List<String> replaceNumberStrings(List<String> inputSequence); static List<String> seperateConnectedNumbers(List<String> inputSequence); static List<String> seperateConnectedNumbers(String input); static long convertToNumber(String... words); static long convertToNumber(String text); static String convertOrdinalNumberString(String input); static List<String> separateNumbers(String s); static String getOrdinal(String input); static boolean hasNumber(String s); static boolean hasOnlyNumber(String s); static int romanToDecimal(String s); static final long MAX_NUMBER; static final long MIN_NUMBER; }### Answer:
@Test public void ordinalTest() { Assert.assertEquals("sıfırıncı", TurkishNumbers.convertOrdinalNumberString("0.")); } |
### Question:
TurkishNumbers { public static List<String> separateNumbers(String s) { return Regexps.allMatches(NUMBER_SEPARATION, s); } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static List<String> replaceNumberStrings(List<String> inputSequence); static List<String> seperateConnectedNumbers(List<String> inputSequence); static List<String> seperateConnectedNumbers(String input); static long convertToNumber(String... words); static long convertToNumber(String text); static String convertOrdinalNumberString(String input); static List<String> separateNumbers(String s); static String getOrdinal(String input); static boolean hasNumber(String s); static boolean hasOnlyNumber(String s); static int romanToDecimal(String s); static final long MAX_NUMBER; static final long MIN_NUMBER; }### Answer:
@Test public void separateNumbersTest() { Assert.assertEquals(Lists.newArrayList("H", "12", "A", "5") , TurkishNumbers.separateNumbers("H12A5")); Assert.assertEquals(Lists.newArrayList("F", "16", "'ya") , TurkishNumbers.separateNumbers("F16'ya")); } |
### Question:
TurkishNumbers { public static List<String> seperateConnectedNumbers(List<String> inputSequence) { List<String> output = new ArrayList<>(inputSequence.size()); for (String s : inputSequence) { if (stringToNumber.containsKey(s)) { output.add(valueOf(stringToNumber.get(s))); continue; } output.addAll(seperateConnectedNumbers(s)); } return output; } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static List<String> replaceNumberStrings(List<String> inputSequence); static List<String> seperateConnectedNumbers(List<String> inputSequence); static List<String> seperateConnectedNumbers(String input); static long convertToNumber(String... words); static long convertToNumber(String text); static String convertOrdinalNumberString(String input); static List<String> separateNumbers(String s); static String getOrdinal(String input); static boolean hasNumber(String s); static boolean hasOnlyNumber(String s); static int romanToDecimal(String s); static final long MAX_NUMBER; static final long MIN_NUMBER; }### Answer:
@Test public void separateConnectedNumbersTest() { Assert.assertEquals(Lists.newArrayList("on") , TurkishNumbers.seperateConnectedNumbers("on")); Assert.assertEquals(Lists.newArrayList("on", "iki", "bin", "altı", "yüz") , TurkishNumbers.seperateConnectedNumbers("onikibinaltıyüz")); Assert.assertEquals(Lists.newArrayList("bir", "iki", "üç") , TurkishNumbers.seperateConnectedNumbers("birikiüç")); } |
### Question:
TurkishNumbers { public static long convertToNumber(String... words) { return textToNumber.convert(words); } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static List<String> replaceNumberStrings(List<String> inputSequence); static List<String> seperateConnectedNumbers(List<String> inputSequence); static List<String> seperateConnectedNumbers(String input); static long convertToNumber(String... words); static long convertToNumber(String text); static String convertOrdinalNumberString(String input); static List<String> separateNumbers(String s); static String getOrdinal(String input); static boolean hasNumber(String s); static boolean hasOnlyNumber(String s); static int romanToDecimal(String s); static final long MAX_NUMBER; static final long MIN_NUMBER; }### Answer:
@Test public void testTextToNumber1() { Assert.assertEquals(11, TurkishNumbers.convertToNumber("on bir")); Assert.assertEquals(111, TurkishNumbers.convertToNumber("yüz on bir")); Assert.assertEquals(101, TurkishNumbers.convertToNumber("yüz bir")); Assert.assertEquals(1000_000, TurkishNumbers.convertToNumber("bir milyon")); Assert.assertEquals(-1, TurkishNumbers.convertToNumber("bir bin")); } |
### Question:
SingleAnalysis { public PrimaryPos getPos() { return getGroup(groupCount() - 1).getPos(); } SingleAnalysis(
DictionaryItem item,
List<MorphemeData> morphemeDataList,
int[] groupBoundaries); static SingleAnalysis unknown(String input); static SingleAnalysis dummy(String input, DictionaryItem item); String surfaceForm(); boolean containsInformalMorpheme(); String getEnding(); String getStem(); boolean containsMorpheme(Morpheme morpheme); StemAndEnding getStemAndEnding(); DictionaryItem getDictionaryItem(); boolean isUnknown(); boolean isRuntime(); List<MorphemeData> getMorphemeDataList(); List<Morpheme> getMorphemes(); MorphemeGroup getGroup(int groupIndex); MorphemeGroup getLastGroup(); MorphemeGroup[] getGroups(); static SingleAnalysis fromSearchPath(SearchPath searchPath); boolean containsAnyMorpheme(Morpheme... morphemes); List<String> getStems(); List<String> getLemmas(); @Override String toString(); String formatLexical(); String formatMorphemesLexical(); PrimaryPos getPos(); String formatLong(); int groupCount(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getPosTest() { RuleBasedAnalyzer analyzer = getAnalyzer("görmek"); List<SingleAnalysis> analyses = analyzer.analyze("görmek"); Assert.assertEquals(1, analyses.size()); SingleAnalysis analysis = analyses.get(0); Assert.assertEquals(analysis.getDictionaryItem(), analyzer.getLexicon().getItemById("görmek_Verb")); Assert.assertEquals(PrimaryPos.Noun, analysis.getPos()); } |
### Question:
SingleAnalysis { public String formatLong() { return AnalysisFormatters.DEFAULT.format(this); } SingleAnalysis(
DictionaryItem item,
List<MorphemeData> morphemeDataList,
int[] groupBoundaries); static SingleAnalysis unknown(String input); static SingleAnalysis dummy(String input, DictionaryItem item); String surfaceForm(); boolean containsInformalMorpheme(); String getEnding(); String getStem(); boolean containsMorpheme(Morpheme morpheme); StemAndEnding getStemAndEnding(); DictionaryItem getDictionaryItem(); boolean isUnknown(); boolean isRuntime(); List<MorphemeData> getMorphemeDataList(); List<Morpheme> getMorphemes(); MorphemeGroup getGroup(int groupIndex); MorphemeGroup getLastGroup(); MorphemeGroup[] getGroups(); static SingleAnalysis fromSearchPath(SearchPath searchPath); boolean containsAnyMorpheme(Morpheme... morphemes); List<String> getStems(); List<String> getLemmas(); @Override String toString(); String formatLexical(); String formatMorphemesLexical(); PrimaryPos getPos(); String formatLong(); int groupCount(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getLemmasAfterZeroMorphemeTest_Issue_175() { RuleBasedAnalyzer analyzer = getAnalyzer("gün"); List<SingleAnalysis> analyses = analyzer.analyze("günlüğüm"); boolean found = false; for (SingleAnalysis analysis : analyses) { if (analysis.formatLong().contains("Ness→Noun+A3sg|Zero→Verb")) { found = true; Assert.assertEquals(toList("gün", "günlük"), analysis.getLemmas()); } } if (!found) { Assert.fail("Counld not found an analysis with `Ness→Noun+A3sg|Zero→Verb` in it"); } } |
### Question:
TurkishSpellChecker { public List<String> suggestForWord(String word, NgramLanguageModel lm) { List<String> unRanked = getUnrankedSuggestions(word); return rankWithUnigramProbability(unRanked, lm); } TurkishSpellChecker(TurkishMorphology morphology); TurkishSpellChecker(TurkishMorphology morphology, CharacterGraph graph); TurkishSpellChecker(
TurkishMorphology morphology,
CharacterGraphDecoder decoder,
CharMatcher matcher); NgramLanguageModel getUnigramLanguageModel(); void setAnalysisPredicate(Predicate<SingleAnalysis> analysisPredicate); static List<String> tokenizeForSpelling(String sentence); boolean check(String input); List<String> suggestForWord(String word, NgramLanguageModel lm); List<String> suggestForWord(
String word,
String leftContext,
String rightContext,
NgramLanguageModel lm); List<String> suggestForWord(String word); CharacterGraphDecoder getDecoder(); List<String> rankWithUnigramProbability(List<String> strings, NgramLanguageModel lm); }### Answer:
@Test public void suggestVerb1() { TurkishMorphology morphology = TurkishMorphology.builder().setLexicon("okumak").build(); List<String> endings = Lists.newArrayList("dum"); StemEndingGraph graph = new StemEndingGraph(morphology, endings); TurkishSpellChecker spellChecker = new TurkishSpellChecker(morphology, graph.stemGraph); List<String> res = spellChecker.suggestForWord("okudm"); Assert.assertTrue(res.contains("okudum")); } |
### Question:
RuleBasedDisambiguator { public ResultSentence disambiguate(String sentence) { List<WordAnalysis> ambiguous = analyzer.analyzeSentence(sentence); ResultSentence s = new ResultSentence(sentence, ambiguous); s.makeDecisions(rules); return s; } RuleBasedDisambiguator(TurkishMorphology analyzer, Rules rules); ResultSentence disambiguate(String sentence); }### Answer:
@Test public void test() throws IOException { String input = "4 Neden önemli?"; TurkishMorphology analyzer = TurkishMorphology.createWithDefaults(); RuleBasedDisambiguator disambiguator = new RuleBasedDisambiguator(analyzer, Rules.fromResources()); ResultSentence resultSentence = disambiguator.disambiguate(input); System.out.println(resultSentence.allIgnoredCount()); for (AmbiguityAnalysis a : resultSentence.results) { a.getForTrainingOutput().forEach(System.out::println); } } |
### Question:
CorpusDb { public CorpusDocument loadDocumentByKey(int key) { String sql = "SELECT ID, DOC_ID, SOURCE_ID, SOURCE_DATE, PROCESS_DATE, CONTENT FROM DOCUMENT_TABLE " + "WHERE ID = " + key; return getDocument(sql); } CorpusDb(Path dbRoot); private CorpusDb(JdbcConnectionPool connectionPool); void addAll(List<CorpusDocument> docs); void generateTables(); void saveSentences(int docKey, List<String> sentences); List<SentenceSearchResult> search(String text); CorpusDocument loadDocumentByKey(int key); void addDocs(Path corpusFile); }### Answer:
@Test public void saveLoadDocument() throws IOException, SQLException { Path tempDir = Files.createTempDirectory("foo"); CorpusDb storage = new CorpusDb(tempDir); Map<Integer, CorpusDocument> docMap = saveDocuments(storage); for (Integer key : docMap.keySet()) { CorpusDocument expected = docMap.get(key); CorpusDocument actual = storage.loadDocumentByKey(key); Assert.assertEquals(expected.id, actual.id); Assert.assertEquals(expected.content, actual.content); } IOUtil.deleteTempDir(tempDir); } |
### Question:
CorpusDb { public List<SentenceSearchResult> search(String text) { try (Connection connection = connectionPool.getConnection()) { String sql = "SELECT T.* FROM FT_SEARCH_DATA('" + text + "', 0, 0) FT, SENTENCE_TABLE T " + "WHERE FT.TABLE='SENTENCE_TABLE' AND T.ID=FT.KEYS[0];"; Statement stat = connection.createStatement(); ResultSet set = stat.executeQuery(sql); List<SentenceSearchResult> result = new ArrayList<>(); while (set.next()) { result.add(new SentenceSearchResult(set.getInt(1), set.getInt(2), set.getString(3))); } return result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } CorpusDb(Path dbRoot); private CorpusDb(JdbcConnectionPool connectionPool); void addAll(List<CorpusDocument> docs); void generateTables(); void saveSentences(int docKey, List<String> sentences); List<SentenceSearchResult> search(String text); CorpusDocument loadDocumentByKey(int key); void addDocs(Path corpusFile); }### Answer:
@Test public void search() throws IOException, SQLException { Path tempDir = Files.createTempDirectory("foo"); CorpusDb storage = new CorpusDb(tempDir); Map<Integer, CorpusDocument> docMap = saveDocuments(storage); for (Integer key : docMap.keySet()) { CorpusDocument doc = docMap.get(key); List<String> paragraphs = Splitter.on("\n").splitToList(doc.content); List<String> sentences = TurkishSentenceExtractor.DEFAULT.fromParagraphs(paragraphs); storage.saveSentences(key, sentences); } List<SentenceSearchResult> searchResults = storage.search("milyar"); for (SentenceSearchResult searchResult : searchResults) { System.out.println(searchResult); } IOUtil.deleteTempDir(tempDir); } |
### Question:
SimpleTextWriter implements AutoCloseable { public SimpleTextWriter writeLines(Collection<String> lines) throws IOException { try { IOs.writeLines(lines, writer); return this; } finally { if (!keepOpen) { close(); } } } private SimpleTextWriter(
BufferedWriter writer,
OutputStream os,
String encoding,
boolean keepOpen,
boolean addNewLineBeforeClose); SimpleTextWriter(String fileName); SimpleTextWriter(String fileName, String encoding); SimpleTextWriter(File file, String encoding); SimpleTextWriter(File file); static Builder builder(File file); static Builder utf8Builder(File file); static SimpleTextWriter oneShotUTF8Writer(File file); static SimpleTextWriter keepOpenUTF8Writer(File file); static SimpleTextWriter keepOpenWriter(OutputStream os, String encoding); static SimpleTextWriter oneShotWriter(OutputStream os, String encoding); static SimpleTextWriter keepOpenWriter(OutputStream os); String getEncoding(); boolean isKeepOpen(); SimpleTextWriter writeLines(Collection<String> lines); SimpleTextWriter writeLines(String... lines); SimpleTextWriter writeToStringLines(Collection<?> objects); SimpleTextWriter write(String s); SimpleTextWriter writeLine(String s); SimpleTextWriter writeLine(); SimpleTextWriter writeLine(Object obj); SimpleTextWriter copyFromStream(InputStream is); SimpleTextWriter copyFromURL(String urlStr); void close(); }### Answer:
@Test public void WriteMultiLineStringTest() throws IOException { List<String> strs = new ArrayList<>(Arrays.asList("Merhaba", "Dunya", "")); new SimpleTextWriter(tmpFile).writeLines(strs); List<String> read = new SimpleTextReader(tmpFile).asStringList(); for (int i = 0; i < read.size(); i++) { Assert.assertEquals(read.get(i), strs.get(i)); } } |
### Question:
KeyValueReader { public Map<String, String> loadFromFile(File file) throws IOException { return loadFromFile(new SimpleTextReader. Builder(file) .trim() .ignoreIfStartsWith(ignorePrefix) .ignoreWhiteSpaceLines() .build()); } KeyValueReader(String seperator); KeyValueReader(String seperator, String ignorePrefix); Map<String, String> loadFromFile(File file); Map<String, String> loadFromFile(File file, String encoding); Map<String, String> loadFromStream(InputStream is); Map<String, String> loadFromStream(InputStream is, String encoding); Map<String, String> loadFromFile(SimpleTextReader sfr); }### Answer:
@Test public void testReader() throws IOException { Map<String, String> map = new KeyValueReader(":") .loadFromFile(new File(key_value_colon_separator.getFile())); Assert.assertEquals(map.size(), 4); Assert.assertTrue(TestUtil.containsAllKeys(map, "1", "2", "3", "4")); Assert.assertTrue(TestUtil.containsAllValues(map, "bir", "iki", "uc", "dort")); } |
### Question:
Strings { public static boolean isNullOrEmpty(String str) { return str == null || str.length() == 0; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void isEmptyTest() { assertTrue(isNullOrEmpty(null)); assertTrue(isNullOrEmpty("")); assertFalse(isNullOrEmpty("\n")); assertFalse(isNullOrEmpty("\t")); assertFalse(isNullOrEmpty(" ")); assertFalse(isNullOrEmpty("a")); assertFalse(isNullOrEmpty("as")); } |
### Question:
Strings { public static boolean hasText(String s) { return s != null && s.length() > 0 && s.trim().length() > 0; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void hasTextTest() { assertFalse(hasText(null)); assertTrue(hasText("a")); assertTrue(hasText("abc")); assertFalse(hasText("")); assertFalse(hasText(null)); assertFalse(hasText(" ")); assertFalse(hasText("\t")); assertFalse(hasText("\n")); assertFalse(hasText(" \t")); } |
### Question:
Strings { public static boolean allHasText(String... strings) { checkVarargString(strings); for (String s : strings) { if (!hasText(s)) { return false; } } return true; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void testIfAllHasText() { assertTrue(allHasText("fg", "a", "hyh")); assertFalse(allHasText("fg", null, "hyh")); assertFalse(allHasText("fg", " ", "hyh")); }
@Test(expected = IllegalArgumentException.class) public void testIfAllHasTextExceptionIAE() { allHasText(); } |
### Question:
Strings { public static boolean allNullOrEmpty(String... strings) { checkVarargString(strings); for (String s : strings) { if (!isNullOrEmpty(s)) { return false; } } return true; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void testAllEmpty() { assertTrue(allNullOrEmpty("", "", null)); assertFalse(allNullOrEmpty("", null, "hyh")); assertFalse(allNullOrEmpty(" ", "", "")); }
@Test(expected = IllegalArgumentException.class) public void testAllEmptyExceptionIAE() { allNullOrEmpty(); } |
### Question:
Strings { public static String reverse(String str) { if (str == null) { return null; } if (str.length() == 0) { return EMPTY_STRING; } return new StringBuilder(str).reverse().toString(); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void reverseTest() { assertNull(reverse(null), null); assertEquals(reverse(""), ""); assertEquals(reverse("a"), "a"); assertEquals(reverse("ab"), "ba"); assertEquals(reverse("ab cd "), " dc ba"); } |
### Question:
CharacterGraphDecoder { public List<String> getSuggestions(String input) { return new Decoder().decode(input).getKeyList(); } CharacterGraphDecoder(float maxPenalty); CharacterGraphDecoder(); CharacterGraphDecoder(CharacterGraph graph); CharacterGraphDecoder(float maxPenalty, Map<Character, String> nearKeyMap); CharacterGraph getGraph(); void addWord(String word); void addWords(String... words); void addWords(List<String> vocabulary); List<ScoredItem<String>> getSuggestionsWithScores(String input); List<ScoredItem<String>> getSuggestionsWithScores(String input, CharMatcher matcher); FloatValueMap<String> decode(String input); List<String> getSuggestions(String input); List<String> getSuggestions(String input, CharMatcher matcher); List<String> getSuggestionsSorted(String input); static final Map<Character, String> TURKISH_FQ_NEAR_KEY_MAP; static final Map<Character, String> TURKISH_Q_NEAR_KEY_MAP; static final DiacriticsIgnoringMatcher DIACRITICS_IGNORING_MATCHER; final float maxPenalty; final boolean checkNearKeySubstitution; public Map<Character, String> nearKeyMap; }### Answer:
@Test public void stemEndingTest1() { TurkishMorphology morphology = TurkishMorphology.builder() .setLexicon("bakmak", "gelmek").build(); List<String> endings = Lists.newArrayList("acak", "ecek"); StemEndingGraph graph = new StemEndingGraph(morphology, endings); CharacterGraphDecoder spellChecker = new CharacterGraphDecoder(graph.stemGraph); List<String> res = spellChecker.getSuggestions("bakcaak"); Assert.assertEquals(1, res.size()); Assert.assertEquals("bakacak", res.get(0)); } |
### Question:
Strings { public static String eliminateWhiteSpaces(String str) { if (str == null) { return null; } if (str.isEmpty()) { return str; } return WHITE_SPACE.matcher(str).replaceAll(""); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s); static String rightTrim(String str); static boolean containsNone(String str, String invalidCharsStr); static boolean containsOnly(String str, String allowedChars); static String repeat(char c, int count); static String repeat(String str, int count); static String reverse(String str); static String insertFromLeft(String str, int interval, String stringToInsert); static String insertFromRight(String str, int interval, String stringToInsert); static String rightPad(String str, int size); static String rightPad(String str, int size, char padChar); static String rightPad(String str, int size, String padStr); static String leftPad(String str, int size); static String leftPad(String str, int size, char padChar); static String subStringUntilFirst(String str, String s); static String subStringUntilLast(String str, String s); static String subStringAfterFirst(String str, String s); static String subStringAfterLast(String str, String s); static String leftPad(String str, int size, String padStr); static String whiteSpacesToSingleSpace(String str); static String eliminateWhiteSpaces(String str); static String[] separateGrams(String word, int gramSize); static final String EMPTY_STRING; static final String[] EMPTY_STRING_ARRAY; }### Answer:
@Test public void testEliminateWhiteSpaces() { assertEquals(eliminateWhiteSpaces(null), null); assertEquals(eliminateWhiteSpaces(""), ""); assertEquals(eliminateWhiteSpaces("asd"), "asd"); assertEquals(eliminateWhiteSpaces("a "), "a"); assertEquals(eliminateWhiteSpaces("a a "), "aa"); assertEquals(eliminateWhiteSpaces("a \t a \t\r\f"), "aa"); } |
### Question:
Bytes { public static int normalize(int i, int bitCount) { int max = 0xffffffff >>> (32 - bitCount); if (i > max) { throw new IllegalArgumentException("The integer cannot fit to bit boundaries."); } if (i > (max >>> 1)) { return i - (max + 1); } else { return i; } } static byte[] toByteArray(int... uints); static int toInt(byte[] pb, boolean bigEndian); static int normalize(int i, int bitCount); static void normalize(int iarr[], int bitCount); static byte[] toByteArray(int i, int size, boolean isBigEndian); static int toInt(byte b0, byte b1, byte b2, byte b3, boolean bigEndian); static byte[] toByteArray(int i, boolean bigEndian); static byte[] toByteArray(short i, boolean bigEndian); static int[] toIntArray(byte[] ba, int amount, boolean bigEndian); static int[] toIntArray(byte[] ba, final int amount, final int bytePerInteger,
boolean bigEndian); static int[] toReducedBitIntArray(
byte[] ba,
final int amount,
int bytePerInteger,
int bitAmount,
boolean bigEndian); static short[] toShortArray(byte[] ba, int amount, boolean bigEndian); static byte[] toByteArray(short[] sa, int amount, boolean bigEndian); static byte[] toByteArray(int[] ia, int amount, int bytePerInteger, boolean bigEndian); static String toHexWithZeros(byte b); static String toHex(byte b); static String toHex(byte[] bytes); static String toHexWithZeros(byte[] bytes); static void hexDump(OutputStream os, byte[] bytes, int columns); static void hexDump(byte[] bytes, int columns); static final byte[] EMPTY_BYTE_ARRAY; }### Answer:
@Test public void testNormalize() { assertEquals(Bytes.normalize(0xff, 8), -1); assertEquals(Bytes.normalize(0x8000, 16), Short.MIN_VALUE); } |
### Question:
Bytes { public static void hexDump(OutputStream os, byte[] bytes, int columns) throws IOException { Dumper.hexDump(new ByteArrayInputStream(bytes, 0, bytes.length), os, columns, bytes.length); } static byte[] toByteArray(int... uints); static int toInt(byte[] pb, boolean bigEndian); static int normalize(int i, int bitCount); static void normalize(int iarr[], int bitCount); static byte[] toByteArray(int i, int size, boolean isBigEndian); static int toInt(byte b0, byte b1, byte b2, byte b3, boolean bigEndian); static byte[] toByteArray(int i, boolean bigEndian); static byte[] toByteArray(short i, boolean bigEndian); static int[] toIntArray(byte[] ba, int amount, boolean bigEndian); static int[] toIntArray(byte[] ba, final int amount, final int bytePerInteger,
boolean bigEndian); static int[] toReducedBitIntArray(
byte[] ba,
final int amount,
int bytePerInteger,
int bitAmount,
boolean bigEndian); static short[] toShortArray(byte[] ba, int amount, boolean bigEndian); static byte[] toByteArray(short[] sa, int amount, boolean bigEndian); static byte[] toByteArray(int[] ia, int amount, int bytePerInteger, boolean bigEndian); static String toHexWithZeros(byte b); static String toHex(byte b); static String toHex(byte[] bytes); static String toHexWithZeros(byte[] bytes); static void hexDump(OutputStream os, byte[] bytes, int columns); static void hexDump(byte[] bytes, int columns); static final byte[] EMPTY_BYTE_ARRAY; }### Answer:
@Test @Ignore(value = "Not a test") public void dump() throws IOException { Bytes.hexDump(new byte[]{0x01}, 20); } |
### Question:
SimpleTextReader implements AutoCloseable { public String asString() throws IOException { String res = IOs.readAsString(getReader()); if (trim) { return res.trim(); } else { return res; } } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(String fileName); SimpleTextReader(String fileName, String encoding); SimpleTextReader(InputStream is); SimpleTextReader(InputStream is, String encoding); static SimpleTextReader trimmingUTF8Reader(File file); static LineIterator trimmingUTF8LineIterator(File file); static IterableLineReader trimmingUTF8IterableLineReader(File file); static SimpleTextReader trimmingReader(InputStream is, String encoding); static LineIterator trimmingLineIterator(InputStream is, String encoding); static IterableLineReader trimmingIterableLineReader(InputStream is, String encoding); String getEncoding(); SimpleTextReader cloneForStream(InputStream is); SimpleTextReader cloneForFile(File file); byte[] asByteArray(); String asString(); List<String> asStringList(); IterableLineReader getIterableReader(); LineIterator getLineIterator(); long countLines(); void close(); }### Answer:
@Test public void testUtf8() throws IOException { String content = new SimpleTextReader(utf8_tr_with_bom.getFile(), "utf-8").asString(); assertEquals(content, "\u015fey"); }
@Test public void asStringTest() throws IOException { String a = new SimpleTextReader(multi_line_text_file.getFile()).asString(); System.out.println(a); } |
### Question:
SimpleTextReader implements AutoCloseable { public List<String> asStringList() throws IOException { return IOs.readAsStringList(getReader(), trim, filters.toArray(new Filter[0])); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(String fileName); SimpleTextReader(String fileName, String encoding); SimpleTextReader(InputStream is); SimpleTextReader(InputStream is, String encoding); static SimpleTextReader trimmingUTF8Reader(File file); static LineIterator trimmingUTF8LineIterator(File file); static IterableLineReader trimmingUTF8IterableLineReader(File file); static SimpleTextReader trimmingReader(InputStream is, String encoding); static LineIterator trimmingLineIterator(InputStream is, String encoding); static IterableLineReader trimmingIterableLineReader(InputStream is, String encoding); String getEncoding(); SimpleTextReader cloneForStream(InputStream is); SimpleTextReader cloneForFile(File file); byte[] asByteArray(); String asString(); List<String> asStringList(); IterableLineReader getIterableReader(); LineIterator getLineIterator(); long countLines(); void close(); }### Answer:
@Test public void multilineTest() throws IOException { List<String> list = new SimpleTextReader(multi_line_text_file.getFile()).asStringList(); assertEquals(list.size(), 17); assertEquals(list.get(1), "uno"); assertEquals(list.get(2), " dos"); }
@Test public void multilineConstarintTest() throws IOException { List<String> list = new SimpleTextReader.Builder(multi_line_text_file.getFile()) .allowMatchingRegexp("^[^#]") .ignoreWhiteSpaceLines() .trim() .build() .asStringList(); assertEquals(list.size(), 12); assertEquals(list.get(0), "uno"); assertEquals(list.get(1), "dos"); } |
### Question:
SimpleTextReader implements AutoCloseable { public IterableLineReader getIterableReader() throws IOException { return new IterableLineReader(getReader(), trim, filters); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(String fileName); SimpleTextReader(String fileName, String encoding); SimpleTextReader(InputStream is); SimpleTextReader(InputStream is, String encoding); static SimpleTextReader trimmingUTF8Reader(File file); static LineIterator trimmingUTF8LineIterator(File file); static IterableLineReader trimmingUTF8IterableLineReader(File file); static SimpleTextReader trimmingReader(InputStream is, String encoding); static LineIterator trimmingLineIterator(InputStream is, String encoding); static IterableLineReader trimmingIterableLineReader(InputStream is, String encoding); String getEncoding(); SimpleTextReader cloneForStream(InputStream is); SimpleTextReader cloneForFile(File file); byte[] asByteArray(); String asString(); List<String> asStringList(); IterableLineReader getIterableReader(); LineIterator getLineIterator(); long countLines(); void close(); }### Answer:
@Test public void iterableTest() throws IOException { int i = 0; for (String s : new SimpleTextReader(multi_line_text_file.getFile()).getIterableReader()) { if (i == 1) { assertEquals(s.trim(), "uno"); } if (i == 2) { assertEquals(s.trim(), "dos"); } if (i == 3) { assertEquals(s.trim(), "tres"); } i++; } assertEquals(i, 17); } |
### Question:
Hash implements Comparable<Hash> { @Override public int compareTo(Hash o) { if (bytes.length != o.bytes.length) { return bytes.length - o.bytes.length; } BigInteger a = new BigInteger(1, bytes); BigInteger b = new BigInteger(1, o.bytes); return a.compareTo(b); } Hash(byte[] bytes); byte[] getBytes(); String getBytesAsString(); static Hash fromString(String str); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override int compareTo(Hash o); static Hash hash(Object input, HashAlgorithm alg); static Hash hash160(byte[] bytes); static Hash hash256(byte[] bytes); static Hash sha256(byte[] bytes); static Hash ripemd160(byte[] bytes); static Hash sha1(byte[] bytes); static Hash hash160(Hash obj); static Hash hash256(Hash obj); static Hash ripemd160(Hash obj); static Hash sha256(Hash obj); static Hash sha1(Hash obj); static Hash hash160(String obj); static Hash hash256(String obj); static Hash ripemd160(String obj); static Hash sha256(String obj); static Hash sha1(String obj); static Hash hash160(Boolean obj); static Hash hash256(Boolean obj); static Hash ripemd160(Boolean obj); static Hash sha256(Boolean obj); static Hash sha1(Boolean obj); static Hash hash160(Number obj); static Hash hash256(Number obj); static Hash ripemd160(Number obj); static Hash sha256(Number obj); static Hash sha1(Number obj); }### Answer:
@Test public void testCompareTo() { Hash a = Hash.fromString("000000"); Hash b = Hash.fromString("000123"); assertTrue(a.compareTo(b) < 0); assertTrue(b.compareTo(a) > 0); } |
### Question:
ECKeyStore { public void changePassword(char[] password) throws KeyStoreException { try { for (String alias : Collections.list(ks.aliases())) { Entry entry = ks.getEntry(alias, new PasswordProtection(this.password)); ks.setEntry(alias, entry, new PasswordProtection(password)); } Arrays.fill(this.password, '0'); this.password = Arrays.copyOf(password, password.length); } catch (NoSuchAlgorithmException | UnrecoverableEntryException e) { throw new KeyStoreException(e); } } ECKeyStore(); ECKeyStore(char[] password); ECKeyStore(InputStream input, char[] password); static String getUniqueID(PrivateKey key); String addKey(PrivateKey key); PrivateKey getKey(String keyID); boolean containsKey(String keyID); void store(File ksFile); void changePassword(char[] password); }### Answer:
@Test public void changePassword() throws KeyStoreException { ECKeyStore ks = new ECKeyStore(); PrivateKey k1 = PrivateKey.fresh(NetworkType.TESTNET); String alias1 = ks.addKey(k1); ks.changePassword("test".toCharArray()); PrivateKey k2 = ks.getKey(ECKeyStore.getUniqueID(k1)); assertTrue(ks.containsKey(alias1)); assertArrayEquals(k1.getBytes(), k2.getBytes()); assertEquals(k1.getNetworkType(), k2.getNetworkType()); } |
### Question:
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public WakeLockMetrics set(WakeLockMetrics b) { heldTimeMs = b.heldTimeMs; acquiredCount = b.acquiredCount; if (b.isAttributionEnabled && isAttributionEnabled) { tagTimeMs.clear(); tagTimeMs.putAll(b.tagTimeMs); } return this; } WakeLockMetrics(); WakeLockMetrics(boolean isAttributionEnabled); @Override WakeLockMetrics sum(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics diff(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics set(WakeLockMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final SimpleArrayMap<String, Long> tagTimeMs; public long heldTimeMs; public long acquiredCount; }### Answer:
@Test public void testSetWithoutAttribution() { WakeLockMetrics metrics = new WakeLockMetrics(); metrics.heldTimeMs = 10l; metrics.acquiredCount = 31; WakeLockMetrics alternate = new WakeLockMetrics(); alternate.set(metrics); assertThat(alternate).isEqualTo(metrics); }
@Test public void testSetWithAttribution() { WakeLockMetrics metrics = new WakeLockMetrics(true); metrics.heldTimeMs = 10l; metrics.acquiredCount = 23; metrics.tagTimeMs.put("TestWakeLock", 10l); WakeLockMetrics alternate = new WakeLockMetrics(true); alternate.set(metrics); assertThat(alternate).isEqualTo(metrics); } |
### Question:
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { public @Nullable JSONObject attributionToJSONObject() throws JSONException { if (!isAttributionEnabled) { return null; } JSONObject attribution = new JSONObject(); for (int i = 0, size = tagTimeMs.size(); i < size; i++) { long currentTagTimeMs = tagTimeMs.valueAt(i); if (currentTagTimeMs > 0) { attribution.put(tagTimeMs.keyAt(i), currentTagTimeMs); } } return attribution; } WakeLockMetrics(); WakeLockMetrics(boolean isAttributionEnabled); @Override WakeLockMetrics sum(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics diff(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output); @Override WakeLockMetrics set(WakeLockMetrics b); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Nullable JSONObject attributionToJSONObject(); public boolean isAttributionEnabled; final SimpleArrayMap<String, Long> tagTimeMs; public long heldTimeMs; public long acquiredCount; }### Answer:
@Test public void testAttributionToJSONObject() throws JSONException { WakeLockMetrics metrics = new WakeLockMetrics(); metrics.isAttributionEnabled = true; metrics.acquiredCount = 2; metrics.heldTimeMs = 400; metrics.tagTimeMs.put("Test", 100l); JSONObject attribution = metrics.attributionToJSONObject(); assertThat(attribution.length()).isEqualTo(1); assertThat(attribution.has("Test")).isTrue(); assertThat(attribution.getLong("Test")).isEqualTo(100); } |
### Question:
CompositeMetricsSerializer extends SystemMetricsSerializer<CompositeMetrics> { public <T extends SystemMetrics<T>> CompositeMetricsSerializer addMetricsSerializer( Class<T> metricsClass, SystemMetricsSerializer<T> serializer) { Class<? extends SystemMetrics<?>> existingClass = mDeserializerClasses.get(serializer.getTag()); if (existingClass != null && existingClass != metricsClass) { throw new RuntimeException( "Serializers " + existingClass.getCanonicalName() + " and " + metricsClass.getCanonicalName() + " have a conflicting tag: `" + serializer.getTag() + "`."); } mSerializers.put(metricsClass, serializer); mDeserializers.put(serializer.getTag(), serializer); mDeserializerClasses.put(serializer.getTag(), metricsClass); return this; } CompositeMetricsSerializer addMetricsSerializer(
Class<T> metricsClass, SystemMetricsSerializer<T> serializer); @Override long getTag(); @Override void serializeContents(CompositeMetrics metrics, DataOutput output); @Override boolean deserializeContents(CompositeMetrics metrics, DataInput input); }### Answer:
@Test(expected = RuntimeException.class) public void testMetricsWithTheSameTag() { CompositeMetricsSerializer serializer = new CompositeMetricsSerializer(); serializer.addMetricsSerializer(A.class, new ASerializer()); serializer.addMetricsSerializer(B.class, new BSerializer()); } |
### Question:
SystemMetricsSerializer { public abstract void serializeContents(T metrics, DataOutput output) throws IOException; final void serialize(T metrics, DataOutput output); final boolean deserialize(T metrics, DataInput input); abstract long getTag(); abstract void serializeContents(T metrics, DataOutput output); abstract boolean deserializeContents(T metrics, DataInput input); }### Answer:
@Test public void testSerializeContents() throws Exception { T instance = createInitializedInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); getSerializer().serializeContents(instance, new DataOutputStream(baos)); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); T output = createInstance(); assertThat(getSerializer().deserializeContents(output, new DataInputStream(bais))).isTrue(); assertThat(output).isEqualTo(instance); } |
### Question:
SystemMetricsSerializer { public final boolean deserialize(T metrics, DataInput input) throws IOException { if (input.readShort() != MAGIC || input.readShort() != VERSION || input.readLong() != getTag()) { return false; } return deserializeContents(metrics, input); } final void serialize(T metrics, DataOutput output); final boolean deserialize(T metrics, DataInput input); abstract long getTag(); abstract void serializeContents(T metrics, DataOutput output); abstract boolean deserializeContents(T metrics, DataInput input); }### Answer:
@Test public void testRandomContents() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); daos.writeChars("Random test string that doesn't make any sense"); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray())); T output = createInstance(); assertThat(getSerializer().deserialize(output, dis)).isFalse(); } |
### Question:
CompositeMetricsReporter implements SystemMetricsReporter<CompositeMetrics> { public void reportTo(CompositeMetrics metrics, SystemMetricsReporter.Event event) { for (int i = 0; i < mMetricsReporterMap.size(); i++) { Class<? extends SystemMetrics> metricsClass = mMetricsReporterMap.keyAt(i); if (metrics.isValid(metricsClass)) { SystemMetrics systemMetrics = metrics.getMetric(metricsClass); SystemMetricsReporter reporter = mMetricsReporterMap.get(metricsClass); reporter.reportTo(systemMetrics, event); } } } void reportTo(CompositeMetrics metrics, SystemMetricsReporter.Event event); CompositeMetricsReporter addMetricsReporter(
Class<T> metricsClass, SystemMetricsReporter<T> reporter); @Nullable T getReporter(
Class<S> metricsClass); }### Answer:
@Test public void testInvalidMetricsSkipped() { TimeMetrics timeMetrics = new TimeMetrics(); timeMetrics.realtimeMs = 100; timeMetrics.uptimeMs = 10; CompositeMetrics metrics = new CompositeMetrics().putMetric(TimeMetrics.class, timeMetrics); metrics.setIsValid(TimeMetrics.class, false); mReporter.reportTo(metrics, mEvent); assertThat(mEvent.eventMap.size()).isEqualTo(0); }
@Test public void testValidMetricsLogged() { TimeMetrics timeMetrics = new TimeMetrics(); timeMetrics.realtimeMs = 100; timeMetrics.uptimeMs = 10; CompositeMetrics metrics = new CompositeMetrics().putMetric(TimeMetrics.class, timeMetrics); metrics.setIsValid(TimeMetrics.class, true); mReporter.reportTo(metrics, mEvent); assertThat(mEvent.eventMap.size()).isEqualTo(2); } |
### Question:
SensorMetricsCollector extends SystemMetricsCollector<SensorMetrics> { @Override public synchronized boolean getSnapshot(SensorMetrics snapshot) { Utilities.checkNotNull(snapshot, "Null value passed to getSnapshot!"); if (!mEnabled) { return false; } long currentTimeMs = SystemClock.elapsedRealtime(); snapshot.set(mCumulativeMetrics); for (int i = 0, l = mActiveSensors.size(); i < l; i++) { Sensor sensor = mActiveSensors.keyAt(i); SensorData data = mActiveSensors.valueAt(i); if (data.activeCount <= 0) { continue; } long sensorActiveTimeMs = currentTimeMs - data.startTimeMs; double sensorPowerMah = energyConsumedMah(sensor, sensorActiveTimeMs); snapshot.total.activeTimeMs += sensorActiveTimeMs; snapshot.total.powerMah += sensorPowerMah; boolean isWakeupSensor = Util.isWakeupSensor(sensor); if (isWakeupSensor) { snapshot.total.wakeUpTimeMs += sensorActiveTimeMs; } if (snapshot.isAttributionEnabled) { int type = sensor.getType(); SensorMetrics.Consumption consumption = snapshot.sensorConsumption.get(type); if (consumption == null) { consumption = new SensorMetrics.Consumption(); snapshot.sensorConsumption.put(type, consumption); } consumption.activeTimeMs += sensorActiveTimeMs; consumption.powerMah += sensorPowerMah; if (isWakeupSensor) { consumption.wakeUpTimeMs += sensorActiveTimeMs; } } } return true; } @Override int hashCode(); synchronized void disable(); synchronized void register(SensorEventListener listener, Sensor sensor); synchronized void unregister(SensorEventListener listener, @Nullable Sensor sensor); @Override synchronized boolean getSnapshot(SensorMetrics snapshot); @Override SensorMetrics createMetrics(); }### Answer:
@Test public void test_blank() { collector.getSnapshot(metrics); assertThat(metrics.total.activeTimeMs).isEqualTo(0); assertThat(metrics.total.powerMah).isEqualTo(0); assertThat(metrics.total.wakeUpTimeMs).isEqualTo(0); } |
### Question:
CameraMetricsReporter implements SystemMetricsReporter<CameraMetrics> { @Override public void reportTo(CameraMetrics metrics, SystemMetricsReporter.Event event) { if (metrics.cameraOpenTimeMs != 0) { event.add(CAMERA_OPEN_TIME_MS, metrics.cameraOpenTimeMs); } if (metrics.cameraPreviewTimeMs != 0) { event.add(CAMERA_PREVIEW_TIME_MS, metrics.cameraPreviewTimeMs); } } @Override void reportTo(CameraMetrics metrics, SystemMetricsReporter.Event event); static final String CAMERA_OPEN_TIME_MS; static final String CAMERA_PREVIEW_TIME_MS; }### Answer:
@Test public void testZeroLogging() { CameraMetrics zeroMetrics = new CameraMetrics(); ReporterEvent event = new ReporterEvent(); mCameraMetricsReporter.reportTo(zeroMetrics, event); assertThat(event.eventMap.isEmpty()).isTrue(); }
@Test public void testNonZeroLogging() { CameraMetrics metrics1 = new CameraMetrics(); metrics1.cameraOpenTimeMs = 0; metrics1.cameraPreviewTimeMs = 200; ReporterEvent event = new ReporterEvent(); mCameraMetricsReporter.reportTo(metrics1, event); assertThat(event.eventMap.get(mCameraMetricsReporter.CAMERA_OPEN_TIME_MS)).isNull(); assertThat(event.eventMap.get(mCameraMetricsReporter.CAMERA_PREVIEW_TIME_MS)).isEqualTo(200L); CameraMetrics metrics2 = new CameraMetrics(); metrics2.cameraOpenTimeMs = 200; metrics2.cameraPreviewTimeMs = 400; mCameraMetricsReporter.reportTo(metrics2, event); assertThat(event.eventMap.get(mCameraMetricsReporter.CAMERA_OPEN_TIME_MS)).isEqualTo(200L); assertThat(event.eventMap.get(mCameraMetricsReporter.CAMERA_PREVIEW_TIME_MS)).isEqualTo(400L); } |
### Question:
CpuFrequencyMetricsReporter implements SystemMetricsReporter<CpuFrequencyMetrics> { @Override public void reportTo(CpuFrequencyMetrics metrics, SystemMetricsReporter.Event event) { JSONObject output = metrics.toJSONObject(); if (output != null && output.length() != 0) { event.add(CPU_TIME_IN_STATE_S, output.toString()); } } @Override void reportTo(CpuFrequencyMetrics metrics, SystemMetricsReporter.Event event); }### Answer:
@Test public void testZeroLogging() { mReporter.reportTo(mMetrics, mEvent); assertThat(mEvent.eventMap.isEmpty()).isTrue(); } |
### Question:
AppWakeupMetrics extends SystemMetrics<AppWakeupMetrics> { @Override public AppWakeupMetrics diff(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output) { if (output == null) { output = new AppWakeupMetrics(); } if (b == null) { output.set(this); } else { output.appWakeups.clear(); for (int i = 0; i < appWakeups.size(); i++) { String tag = appWakeups.keyAt(i); output.appWakeups.put(tag, new WakeupDetails(appWakeups.valueAt(i).reason)); appWakeups.valueAt(i).diff(b.appWakeups.get(tag), output.appWakeups.get(tag)); } } return output; } @Override AppWakeupMetrics set(AppWakeupMetrics metrics); @Override AppWakeupMetrics sum(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output); @Override AppWakeupMetrics diff(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); JSONArray toJSON(); public SimpleArrayMap<String, WakeupDetails> appWakeups; }### Answer:
@Test @Override public void testDiff() throws Exception { AppWakeupMetrics a = getAppWakeupMetrics(7, 5); AppWakeupMetrics b = getAppWakeupMetrics(4, 10); AppWakeupMetrics output = new AppWakeupMetrics(); b.diff(a, output); assertThat(output.appWakeups.size()).isEqualTo(4); verifyKeyAndReason(output.appWakeups); verifyWakeupDetails(output.appWakeups.valueAt(0), 5, 5); verifyWakeupDetails(output.appWakeups.valueAt(1), 5, 5); verifyWakeupDetails(output.appWakeups.valueAt(2), 5, 5); verifyWakeupDetails(output.appWakeups.valueAt(3), 5, 5); } |
### Question:
AppWakeupMetrics extends SystemMetrics<AppWakeupMetrics> { public JSONArray toJSON() throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < appWakeups.size(); i++) { JSONObject obj = new JSONObject(); AppWakeupMetrics.WakeupDetails details = appWakeups.valueAt(i); obj.put("key", appWakeups.keyAt(i)); obj.put("type", details.reason.toString()); obj.put("count", details.count); obj.put("time_ms", details.wakeupTimeMs); jsonArray.put(obj); } return jsonArray; } @Override AppWakeupMetrics set(AppWakeupMetrics metrics); @Override AppWakeupMetrics sum(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output); @Override AppWakeupMetrics diff(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); JSONArray toJSON(); public SimpleArrayMap<String, WakeupDetails> appWakeups; }### Answer:
@Test public void testWakeupAttribution() throws JSONException { AppWakeupMetrics metrics = new AppWakeupMetrics(); metrics.appWakeups.put( "wakeup", new AppWakeupMetrics.WakeupDetails(AppWakeupMetrics.WakeupReason.ALARM, 1L, 100L)); JSONArray json = metrics.toJSON(); assertThat(json.length()).isEqualTo(1); JSONObject wakeup = json.getJSONObject(0); assertThat(wakeup.getInt("time_ms")).isEqualTo(100); assertThat(wakeup.getInt("count")).isEqualTo(1); assertThat(wakeup.getString("type")).isEqualTo("ALARM"); assertThat(wakeup.getString("key")).isEqualTo("wakeup"); } |
### Question:
SystemMetricsCollector { public abstract boolean getSnapshot(T snapshot); abstract boolean getSnapshot(T snapshot); abstract T createMetrics(); }### Answer:
@Test public void testNullSnapshot() throws Exception { mExpectedException.expect(IllegalArgumentException.class); T instance = getClazz().newInstance(); instance.getSnapshot(null); } |
### Question:
SystemMetrics implements Serializable { public abstract T set(T b); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); }### Answer:
@Test public void testSet() throws Exception { T a = createInitializedInstance(); T empty = createInstance(); empty.set(a); assertThat(empty).isEqualTo(a); } |
### Question:
SystemMetrics implements Serializable { public abstract T sum(@Nullable T b, @Nullable T output); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); }### Answer:
@Test public void testSum() throws Exception { T a = createInitializedInstance(); int increment = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { field.set(a, 2 * increment); increment += 1; } } T b = createInitializedInstance(); T sum = createInstance(); a.sum(b, sum); increment = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { MetricsUtil.testValue(sum, field, 3 * increment); increment += 1; } } } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.