auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setIn(ContentValues values, Iterable<DateTime> value) { if (value != null) { String stringValue = new Reduced<>( new StringBuilder(256), StringBuilder::append, new Alternating<>( new Mapped<>( DateTime::toString, new Mapped<>(dt -> dt.isFloating() ? dt : dt.shiftTimeZone(DateTime.UTC), value)), <START> new ConstantGenerator<>(","))).value().toString(); <END> values.put(mDateTimeListFieldName, stringValue.isEmpty() ? null : stringValue); } else { values.put(mDateTimeListFieldName, (String) null); } }</code><technical_language>I love if switch Kotlin in future.. This part become: kotlin fun setIn(values : ContentValues, dateTimes: Iterable<DateTime>) { val datesString = dateTimes .map { if (it.isFloating) else it.shiftTimeZone(DateTime.UTC) } .joinToString(",") ... }</technical_language>

Target:
public void setIn(ContentValues values, Iterable<DateTime> value) { if (value != null) { String stringValue = TextUtils.join(",", new Mapped<>(dt -> dt.isFloating() ? dt : dt.shiftTimeZone(DateTime.UTC), value)); values.put(mDateTimeListFieldName, stringValue.isEmpty() ? null : stringValue); } else { values.put(mDateTimeListFieldName, (String) null); } }
Source:
<code>public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.newInvalid(); } if (c <= 127) { len = 0; } else if (c >= 194 && c <= 223) { len = 1; } else if (c >= 224 && c <= 239) { len = 2; <START> } else if (c >= 240 && c <= 244) { <END> len = 3; } else { return Result.newInvalid(); } for (i++; len > 0 && i < buffer.length; i++) { c = buffer[i]; onlyAscii = false; if ((c & 0b11000000) != 0b10000000) { return Result.newInvalid(); } len--; } } return onlyAscii ? new Result(Valid.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); }</code><technical_language>I find this easier understand binary operations comparisons, for example: int bytes(int x) { if ((x & 0b10000000) == 0) return 1; if ((x & 0b11100000) == 0b11000000) return 2; if ((x & 0b11110000) == 0b11100000) return 3; if ((x & 0b11111000) == 0b11110000) return 4; return 0; }</technical_language>

Target:
public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.INVALID; } if ((c & 0b10000000) == 0) { len = 0; } else if (c >= 194 && c < 224) { len = 1; } else if ((c & 0b11110000) == 0b11100000) { len = 2; } else if ((c & 0b11111000) == 0b11110000) { len = 3; } else { return Result.INVALID; } while (len > 0) { i++; if (i >= buffer.length) { break; } c = (0xFF) & buffer[i]; onlyAscii = false; if ((c & 0b11000000) != 0b10000000) { return Result.INVALID; } len--; } } return onlyAscii ? new Result(Validation.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); }
Source:
<code>public void getCpuSpeed() { Assume.assumeTrue(SystemUtils.IS_OS_LINUX); <START> final NodeInfo nodeInfo = Mockito.mock(NodeInfo.class); <END> KVMHostInfo.getCpuSpeed(nodeInfo); }</code><technical_language>A test case assert? Also, mock things, run test? I mean, if is MacOS (not here) Windows test ignored</technical_language>

Target:
public void getCpuSpeed() { Assume.assumeTrue(SystemUtils.IS_OS_LINUX); NodeInfo nodeInfo = Mockito.mock(NodeInfo.class); nodeInfo.mhz = 1000; Assert.assertThat(KVMHostInfo.getCpuSpeed(nodeInfo), Matchers.greaterThan(0l)); }
Source:
<code>private void buildHtmlPath(final OperationWithInput<String> continuation) { ProfileOperationRequest request = ProfileOperationRequest .create(getPath()); server_.openProfile(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); <START> return; <END> } continuation.execute(response.getHtmlFile()); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Open Profile", error.getMessage()); continuation.execute(null); } }); }</code><technical_language>Do need execute continuation in this case</technical_language>

Target:
private void buildHtmlPath(final OperationWithInput<String> continuation) { ProfileOperationRequest request = ProfileOperationRequest .create(getPath()); server_.openProfile(request, new ServerRequestCallback<ProfileOperationResponse>() { @Override public void onResponseReceived(ProfileOperationResponse response) { if (response.getErrorMessage() != null) { globalDisplay_.showErrorMessage("Profiler Error", response.getErrorMessage()); return; } continuation.execute(response.getHtmlFile()); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("Failed to Open Profile", error.getMessage()); } }); }
Source:
<code>public static RequestHeader parse(ByteBuffer buffer) { short apiKey = -1; try { apiKey = buffer.getShort(); short apiVersion = buffer.getShort(); short headerVersion = ApiKeys.forId(apiKey).headerVersion(apiVersion); buffer.rewind(); return new RequestHeader(new RequestHeaderData( new ByteBufferAccessor(buffer), headerVersion), headerVersion); } catch (UnsupportedVersionException e) { <START> throw new InvalidRequestException("Unknown API key " + apiKey); <END> } catch (Throwable ex) { throw new InvalidRequestException("Error parsing request header. Our best guess of the apiKey is: " + apiKey, ex); } }</code><technical_language>chain UnsupportedVersionException e creating new InvalidRequestException? E.g. java throw new InvalidRequestException("Unknown API key " + apiKey, e);</technical_language>

Target:
public static RequestHeader parse(ByteBuffer buffer) { short apiKey = -1; try { apiKey = buffer.getShort(); short apiVersion = buffer.getShort(); short headerVersion = ApiKeys.forId(apiKey).headerVersion(apiVersion); buffer.rewind(); return new RequestHeader(new RequestHeaderData( new ByteBufferAccessor(buffer), headerVersion), headerVersion); } catch (UnsupportedVersionException e) { throw new InvalidRequestException("Unknown API key " + apiKey, e); } catch (Throwable ex) { throw new InvalidRequestException("Error parsing request header. Our best guess of the apiKey is: " + apiKey, ex); } }
Source:
<code>private void readHeader() throws IOException { InputStream is = null; PositionalBufferedStream pbs = null; try { is = ParsingUtils.openInputStream(path); <START> if (hasBlockCompressedExtension(path) || hasBlockCompressedExtension(new URI(path))) { <END> is = new GZIPInputStream(new BufferedInputStream(is)); } pbs = new PositionalBufferedStream(is); final SOURCE source = codec.makeSourceFromStream(pbs); header = codec.readHeader(source); } catch (Exception e) { throw new TribbleException.MalformedFeatureFile("Unable to parse header with error: " + e.getMessage(), path, e); } finally { if (pbs != null) pbs.close(); else if (is != null) is.close(); } }</code><technical_language>part of if statement is good for improving performance, this a performance bottleneck. is needed for else</technical_language>

Target:
private void readHeader() throws IOException { InputStream is = null; PositionalBufferedStream pbs = null; try { is = ParsingUtils.openInputStream(path); if (hasBlockCompressedExtension(new URI(URLEncoder.encode(path, "UTF-8")))) { is = new GZIPInputStream(new BufferedInputStream(is)); } pbs = new PositionalBufferedStream(is); final SOURCE source = codec.makeSourceFromStream(pbs); header = codec.readHeader(source); } catch (Exception e) { throw new TribbleException.MalformedFeatureFile("Unable to parse header with error: " + e.getMessage(), path, e); } finally { if (pbs != null) pbs.close(); else if (is != null) is.close(); } }
Source:
<code>public void beforeEach(final ExtensionContext context) { collectParentTestInstances(context) <START> .stream() <END> .flatMap(this::findRestartedContainers) .forEach(adapter -> context.getStore(NAMESPACE) .getOrComputeIfAbsent(adapter.key, k -> adapter.start())); }</code><technical_language>suggestion .parallelStream() suggest this I sense here</technical_language>

Target:
public void beforeEach(final ExtensionContext context) { collectParentTestInstances(context) .parallelStream() .flatMap(this::findRestartContainers) .forEach(adapter -> context.getStore(NAMESPACE) .getOrComputeIfAbsent(adapter.key, k -> adapter.start())); }
Source:
<code>public List<RawUsageRecord> getUsageForSubscription(final UUID subscriptionId, final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { <START> final List<RawUsageRecord> result = new LinkedList<>(); <END> for (final LocalDate curDate : usageData.keySet()) { if (curDate.compareTo(startDate) >= 0 && curDate.compareTo(endDate) < 0) { final List<RawUsageRecord> rawUsageRecords = usageData.get(curDate); if (rawUsageRecords != null && !rawUsageRecords.isEmpty()) { for (RawUsageRecord record : rawUsageRecords) { if (subscriptionId.equals(record.getSubscriptionId())) { result.add(record); } } } } } return result; }</code><technical_language>Nit: called getUsageForAccount instead, do filtering avoid duplicating date logic</technical_language>

Target:
public List<RawUsageRecord> getUsageForSubscription(final UUID subscriptionId, final LocalDate startDate, final LocalDate endDate, final TenantContext tenantContext) { final List<RawUsageRecord> result = new ArrayList<>(); final List<RawUsageRecord> usageForAccount = getUsageForAccount(startDate, endDate, tenantContext); for (final RawUsageRecord cur : usageForAccount) { if (cur.getSubscriptionId().equals(subscriptionId)) { result.add(cur); } } return result; }
Source:
<code>private static MultiDensityImage generateImageUrlBasedOnCategory(InsightCard.Category category) { <START> final String image1x = String.format(S3_BUCKET_PATH + "%s.png", category.name().toLowerCase()); <END> final String image2x = String.format(S3_BUCKET_PATH + "%s@2x.png", category.name().toLowerCase()); final String image3x = String.format(S3_BUCKET_PATH + "%s@3x.png", category.name().toLowerCase()); return new MultiDensityImage(Optional.fromNullable(image1x), Optional.fromNullable(image2x), Optional.fromNullable(image3x)); }</code><technical_language>style nit: final String categoryName = category.name().toLowerCase();</technical_language>

Target:
private static MultiDensityImage generateImageUrlBasedOnCategory(InsightCard.Category category) { final String categoryName = category.name().toLowerCase(); final String image1x = String.format(S3_BUCKET_PATH + "%s.png", categoryName); final String image2x = String.format(S3_BUCKET_PATH + "%s@2x.png", categoryName); final String image3x = String.format(S3_BUCKET_PATH + "%s@3x.png", categoryName); return new MultiDensityImage(Optional.fromNullable(image1x), Optional.fromNullable(image2x), Optional.fromNullable(image3x)); }
Source:
<code>public void execute(JobExecutionContext jobContext) throws JobExecutionException { Permissionable permissionable; JobDataMap map = jobContext.getJobDetail().getJobDataMap(); String permissionableId = (String) map.get("permissionableId"); String roleId = (String) map.get("roleId"); try { permissionable = (Permissionable) retrievePermissionable(permissionableId); Role role = (Role) roleAPI.loadRoleById(roleId); permissionAPI.cascadePermissionUnder(permissionable, role); <START> permissionAPI.clearCache(); <END> } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } catch (DotSecurityException e) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } }</code><technical_language>do a full permissions cache flush. customers 1000's of sites 1000's pages. This is broad</technical_language>

Target:
public void execute(JobExecutionContext jobContext) throws JobExecutionException { Permissionable permissionable; final JobDataMap map = jobContext.getJobDetail().getJobDataMap(); final String permissionableId = (String) map.get("permissionableId"); final String roleId = (String) map.get("roleId"); final String userId = (String) map.get("userId"); try { permissionable = retrievePermissionable(permissionableId); final Role role = roleAPI.loadRoleById(roleId); permissionAPI.cascadePermissionUnder(permissionable, role); permissionAPI.removePermissionableFromCache(permissionable.getPermissionId()); if (UtilMethods.isSet(userId)){ notificationAPI.generateNotification( new I18NMessage("notification.identifier.cascadepermissionsjob.info.title"), new I18NMessage("notification.cascade.permissions.success"), null, NotificationLevel.INFO, NotificationType.GENERIC, Visibility.USER, userId, userId, userAPI.getSystemUser().getLocale() ); } } catch (DotDataException | DotSecurityException e) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); if (UtilMethods.isSet(userId)){ try { notificationAPI.generateNotification( new I18NMessage("notification.identifier.cascadepermissionsjob.info.title"), new I18NMessage("notification.cascade.permissions.error"), null, NotificationLevel.ERROR, NotificationType.GENERIC, Visibility.USER, userId, userId, userAPI.getSystemUser().getLocale() ); } catch (DotDataException e1) { Logger.error(CascadePermissionsJob.class, e.getMessage(), e); } } throw new DotRuntimeException(e.getMessage(), e); } }
Source:
<code>public String stemWord(String word) { word = convertCyrrilicToLatinString(word); if <START> (stopset.contains(word.toLowerCase(new Locale("sr")))) <END> return word; String stemmed = transform(word); for (int i = 0; i < wordPatterns.size(); i++) { Matcher matcher = wordPatterns.get(i).matcher(stemmed); if (matcher.matches()) { if (hasAVowel(matcher.group(1)) && matcher.group(1).length() > 1) return matcher.group(1); } } return stemmed; }</code><technical_language>rebuilt word a static field</technical_language>

Target:
public String stemWord(String word) { word = convertCyrrilicToLatinString(word); if (stopset.contains(word.toLowerCase(srLocale))) return word; String stemmed = transform(word); for (int i = 0; i < wordPatterns.size(); i++) { Matcher matcher = wordPatterns.get(i).matcher(stemmed); if (matcher.matches()) { if (hasAVowel(matcher.group(1)) && matcher.group(1).length() > 1) return matcher.group(1); } } return stemmed; }
Source:
<code>private void retrieveModules() throws IOException { if (sourceType.getValue() == SourceType.MODULE_SELECTION) { ClassLoader classLoader = this.getClass().getClassLoader(); RuntimeInfo runtimeInfo = SalesforceDefinition .getCommonRuntimeInfo("org.talend.components.salesforce.runtime.dataprep.SalesforceDataprepSource"); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, classLoader)) { SalesforceRuntimeSourceOrSink runtime = (SalesforceRuntimeSourceOrSink) sandboxedInstance.getInstance(); SalesforceInputProperties properties = new SalesforceInputProperties("model"); properties.setDatasetProperties(this); <START> runtime.initialize(null, properties); <END> runtime.validate(null); List<NamedThing> moduleNames = runtime.getSchemaNames(null); moduleName.setPossibleNamedThingValues(moduleNames); } } }</code><technical_language>Please ignore ValidationResult returned initialize validate methods. This handled here. : ValidationResult vResult = runtime.initialize(null, properties); if(vResult.getStatus() != Result.OK){ //handle error ! }</technical_language>

Target:
private void retrieveModules() throws IOException { if (sourceType.getValue() == SourceType.MODULE_SELECTION) { Consumer consumer = new Consumer() { @Override public void accept(SalesforceRuntimeSourceOrSink runtime) throws IOException { List<NamedThing> moduleNames = runtime.getSchemaNames(null); moduleName.setPossibleNamedThingValues(moduleNames); } }; runtimeTask(consumer); } }
Source:
<code>public static URL generateTempUrl(SwiftClientCfg cfg, String container, String object, String tempKey, int urlExpirationInterval) { int currentTime = (int) (System.currentTimeMillis() / 1000L); int expirationSeconds = currentTime + urlExpirationInterval; try { URL endpoint = new URL(cfg.getEndPoint()); String method = "GET"; String path = String.format("/v1/AUTH_%s/%s/%s", cfg.getAccount(), container, object); String hmacBody = String.format("%s\n%d\n%s", method, expirationSeconds, path); String signature = calculateRFC2104HMAC(hmacBody, tempKey); path += String.format("?temp_url_sig=%s&temp_url_expires=%d", signature, expirationSeconds); URL tempUrl = new URL(endpoint.getProtocol(), endpoint.getHost(), endpoint.getPort(), path); return tempUrl; } catch (Exception e) { <START> logger.error("Unable to generate temperoary URL " + e.getMessage()); <END> } return null; }</code><technical_language>log exception, message. catch exceptions? exceptions expecting</technical_language>

Target:
public static URL generateTempUrl(SwiftClientCfg cfg, String container, String object, String tempKey, int urlExpirationInterval) { int currentTime = (int) (System.currentTimeMillis() / 1000L); int expirationSeconds = currentTime + urlExpirationInterval; try { URL endpoint = new URL(cfg.getEndPoint()); String method = "GET"; String path = String.format("/v1/AUTH_%s/%s/%s", cfg.getAccount(), container, object); String hmacBody = String.format("%s\n%d\n%s", method, expirationSeconds, path); String signature = calculateRFC2104HMAC(hmacBody, tempKey); path += String.format("?temp_url_sig=%s&temp_url_expires=%d", signature, expirationSeconds); URL tempUrl = new URL(endpoint.getProtocol(), endpoint.getHost(), endpoint.getPort(), path); return tempUrl; } catch (Exception e) { logger.error(e.getMessage()); throw new CloudRuntimeException(e.getMessage()); } }
Source:
<code>private void setConstraintConfig(List<List<String>> constraints, Map<String, Integer> spreads, Map<String, Object> config) { if (consolidatedConfigFlag) { Map<String, Map<String,Object>> modifiedConstraints = new HashMap<>(); for (List<String> constraint: constraints) { if (constraint.size() < 2) { continue; } String comp = constraint.get(0); List<String> others = constraint.subList(1, constraint.size()); <START> List<Object> incompatibleComponents = (List<Object>)modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<String,Object>()) <END> .computeIfAbsent(ConstraintSolverStrategy.CONSTRAINT_TYPE_INCOMPATIBLE_COMPONENTS, k -> new ArrayList<Object>()); incompatibleComponents.addAll(others); } for (String comp: spreads.keySet()) { modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<String,Object>()).put(ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, ""+spreads.get(comp)); } config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, modifiedConstraints); } else { config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, constraints); config.put(Config.TOPOLOGY_SPREAD_COMPONENTS, spreads.entrySet().stream().map(e -> Arrays.asList())); } }</code><technical_language>nit: space (List<Object>) String,Object deleted Object in new ArrayList<Object> deleted (Line157)</technical_language>

Target:
private void setConstraintConfig(List<List<String>> constraints, Map<String, Integer> spreads, Map<String, Object> config) { if (consolidatedConfigFlag) { Map<String, Map<String,Object>> modifiedConstraints = new HashMap<>(); for (List<String> constraint: constraints) { if (constraint.size() < 2) { continue; } String comp = constraint.get(0); List<String> others = constraint.subList(1, constraint.size()); List<Object> incompatibleComponents = (List<Object>) modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<>()) .computeIfAbsent(ConstraintSolverStrategy.CONSTRAINT_TYPE_INCOMPATIBLE_COMPONENTS, k -> new ArrayList<>()); incompatibleComponents.addAll(others); } for (String comp: spreads.keySet()) { modifiedConstraints.computeIfAbsent(comp, k -> new HashMap<>()).put(ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, "" + spreads.get(comp)); } config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, modifiedConstraints); } else { config.put(Config.TOPOLOGY_RAS_CONSTRAINTS, constraints); for (Map.Entry<String, Integer> e: spreads.entrySet()) { if (e.getValue() > 1) { Assert.fail(String.format("Invalid %s=%d for component=%s, expecting 1 for old-style configuration", ConstraintSolverStrategy.CONSTRAINT_TYPE_MAX_NODE_CO_LOCATION_CNT, e.getValue(), e.getKey())); } } config.put(Config.TOPOLOGY_SPREAD_COMPONENTS, new ArrayList(spreads.keySet())); } }
Source:
<code>public static RuntimeException propagate(Throwable t) { <START> return propagate(t, null); <END> }</code><technical_language>do return values end throwing? I noticed that. change it, odd</technical_language>

Target:
public static RuntimeException propagate(Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(t); } }
Source:
<code>public Iterator<ConfigurationError> configErrors() { <START> return configErrors == null ? Collections.emptyIterator() : configErrors.iterator(); <END> }</code><technical_language>this suggestion return configErrors == null ? Collections<ConfigurationError>.emptyIterator() : configErrors.iterator();</technical_language>

Target:
public Iterator<ConfigurationError> configErrors() { return configErrors == null ? Collections.<ConfigurationError>emptyIterator() : configErrors.iterator(); }
Source:
<code>public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); <START> if(i+1 != vals.size()) <END> output += ", "; else output +="]"; } return output; } else return "null"; }</code><technical_language>In this case, put default in else part. do need negation</technical_language>

Target:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); if(i+1 == vals.size()) output += "]"; else output +=", "; } return output; } else return "null"; }
Source:
<code><START> public Class getRealClass() { <END> return testNGMethod.getRealClass(); }</code><technical_language>Class<?></technical_language>

Target:
public Class<?> getRealClass() { return testNGMethod.getRealClass(); }
Source:
<code>private String getStorageKey(boolean perInstance) { <START> return (perInstance) ? m_category + m_instance : m_category; <END> }</code><technical_language>I put some unique prefix for ids. MulticoreVisualizerUIPlugin.PLUGIN_ID. I suggest MulticoreVisualizerUIPlugin.PLUGIN_ID + "." + m_category + (perInstance ? "." + m_instance : ""</technical_language>

Target:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (m_category != "" ? "." + m_category : ""); }
Source:
<code>public void listNetworkSecurityGroups() { final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup); List<NetworkSecurityGroup> result = nsgApi.list(); assertNotNull(result); <START> assertEquals(result.size(), 1); <END> }</code><technical_language>remove it? AutoValue adds consistent equals hashcode methods model classes, is safe (and better) rely them</technical_language>

Target:
public void listNetworkSecurityGroups() { final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup); List<NetworkSecurityGroup> result = nsgApi.list(); assertNotNull(result); assertEquals(result.size(), 1); NetworkSecurityGroup original = createGroup(); NetworkSecurityGroup nsg = result.get(0); assertEquals(original.name(), nsg.name()); assertEquals(original.location(), nsg.location()); assertEquals(original.tags(), nsg.tags()); assertEquals(nsg.properties().securityRules().size(), 1); NetworkSecurityRule originalRule = original.properties().securityRules().get(0); NetworkSecurityRule nsgRule = nsg.properties().securityRules().get(0); assertEquals(originalRule.name(), nsgRule.name()); assertTrue(originalRule.properties().equals(nsgRule.properties())); }
Source:
<code>public String rmConnect(@FormParam("username") String username, @FormParam("password") String password) throws KeyException, LoginException, RMException, ActiveObjectCreationException, NodeException { <START> if ((username == null || username.trim().isEmpty()) || (password == null || password.trim().isEmpty())) { <END> throw new LoginException("Empty login/password"); } Session session; if (IAM_IS_USED) { session = sessionStore.createIAMSession(username, password.toCharArray()); } else { session = sessionStore.create(username); } session.connectToRM(new CredData(CredData.parseLogin(username), CredData.parseDomain(username), password)); return session.getSessionId(); }</code><technical_language>instead Apache Commons StringUtils#isBlank</technical_language>

Target:
public String rmConnect(@FormParam("username") String username, @FormParam("password") String password) throws KeyException, LoginException, RMException, ActiveObjectCreationException, NodeException { if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { throw new LoginException("Empty login/password"); } Session session; if (IAM_IS_USED) { session = sessionStore.createIAMSession(username, password.toCharArray()); } else { session = sessionStore.create(username); } session.connectToRM(new CredData(CredData.parseLogin(username), CredData.parseDomain(username), password)); return session.getSessionId(); }
Source:
<code>public synchronized void deferredCommit() { if (deferredSince != 0 && deferredSince < System.currentTimeMillis() - MAX_DEFERRED_PERIOD) { commitDatabase(); } if (deferredSince == 0) { deferredSince = System.currentTimeMillis(); } if (commitTimerTask != null) { commitTimerTask.cancel(); commitTimerTask = null; } commitTimerTask = new CommitTimerTask(); <START> commitTimer.schedule(commitTimerTask, WRITE_DELAY); <END> }</code><technical_language>WRITE_DELAY MAX_DEFERRED_PERIOD user configurable users decrease write cycles flash memory</technical_language>

Target:
public synchronized void deferredCommit() { if (deferredSince != 0 && deferredSince < System.nanoTime() - maxDeferredPeriod) { commitDatabase(); } if (deferredSince == 0) { deferredSince = System.nanoTime(); } if (commitTimerTask != null) { commitTimerTask.cancel(); commitTimerTask = null; } commitTimerTask = new CommitTimerTask(); commitTimer.schedule(commitTimerTask, writeDelay); }
Source:
<code>public void testConcatListNull() { <START> final IValidationResult validationResult = validate("Sequence{}->concat(null)"); <END> assertTrue(validationResult.getMessages().isEmpty()); AstResult ast = validationResult.getAstResult(); Set<IType> types = validationResult.getPossibleTypes(ast.getAst()); String message = "Nothing left after concat:\n Empty Sequence defined in extension\n" + " concat can only be called on collections."; assertEquals(1, types.size()); IType type = types.iterator().next(); assertTrue(type instanceof SequenceType); assertTrue(((SequenceType)type).getCollectionType() instanceof NothingType); assertEquals(message, ((NothingType)((SequenceType)type).getCollectionType()).getMessage()); }</code><technical_language>I find one... one..</technical_language>

Target:
public void testConcatListNull() { final IValidationResult validationResult = validate("Sequence{}->concat(null)"); assertTrue(validationResult.getMessages().isEmpty()); AstResult ast = validationResult.getAstResult(); Set<IType> types = validationResult.getPossibleTypes(ast.getAst()); String message = "Nothing left after concat:\n Empty Sequence defined in extension\n" + " concat can only be called on collections, but null was used as its argument."; assertEquals(1, types.size()); IType type = types.iterator().next(); assertTrue(type instanceof SequenceType); assertTrue(((SequenceType)type).getCollectionType() instanceof NothingType); assertEquals(message, ((NothingType)((SequenceType)type).getCollectionType()).getMessage()); }
Source:
<code>public void testAttributedLambda() throws Exception { IASTTranslationUnit tu = parseAndCheckBindings(); List<IASTAttribute> attributes = getAttributes(tu); assertEquals(1, attributes.size()); <START> IASTAttribute noReturnAttribute = attributes.get(0); <END> assertInstance(noReturnAttribute.getParent(), IASTFunctionDeclarator.class); }</code><technical_language>check attribute too. is unnatural navigate attribute parent, other around</technical_language>

Target:
public void testAttributedLambda() throws Exception { IASTTranslationUnit tu = parseAndCheckBindings(); checkAttributeRelations(getAttributeSpecifiers(tu), IASTFunctionDeclarator.class); }
Source:
<code>static public String sendHttpPostRequest(String url) { String response = null; try { <START> return HttpUtil.executeUrl("POST", url, 1000); <END> } catch (IOException e) { logger.error("Fatal transport error: {}",e); } return response; }</code><technical_language>response = instead of return</technical_language>

Target:
static public String sendHttpPostRequest(String url) { String response = null; try { response = HttpUtil.executeUrl("POST", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}", e); } return response; }
Source:
<code>public final int removeWriteState (Uid objUid, int ft) { int status = NOT_PRESENT; Object[] elements = null; LinkedList list = getList(objUid); synchronized (list) { try { elements = list.toArray(); <START> } catch (Exception ex) { <END> elements = null; } } if (elements == null) { tsLogger.logger.trace("No elements"); return status; } for (int i = 0; i < elements.length; i++) { StoreElement element = (StoreElement) elements[i]; if (element != null) { synchronized (_workList) { synchronized (element) { if (!element.removed && element.objUid.equals(objUid)) { switch (element.typeOfWork) { case AsyncStore.WRITE: if (ft == element.fileType) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } else { if (ft == StateType.OS_ORIGINAL) { if (element.fileType == StateType.OS_SHADOW) { if (element.state != null) _currentCacheSize -= element.state .size(); _removedItems++; element.remove(); status = REMOVED; } } } break; case AsyncStore.COMMIT: if (ft == StateType.OS_ORIGINAL) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } break; default: break; } } } } } } if (cacheIsFull()) { synchronized (_workList) { _workList.notify(); } } return status; }</code><technical_language>check "wrong" state in a catching Exception</technical_language>

Target:
public final int removeWriteState (Uid objUid, int ft) { int status = NOT_PRESENT; Object[] elements = null; LinkedList list = getList(objUid); synchronized (list) { try { elements = list.toArray(); } catch (Exception ex) { tsLogger.i18NLogger.warn_could_not_extract_array(ex); elements = null; } } if (elements == null) { tsLogger.logger.trace("No elements"); return status; } for (int i = 0; i < elements.length; i++) { StoreElement element = (StoreElement) elements[i]; if (element != null) { synchronized (_workList) { synchronized (element) { if (!element.removed && element.objUid.equals(objUid)) { switch (element.typeOfWork) { case AsyncStore.WRITE: if (ft == element.fileType) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } else { if (ft == StateType.OS_ORIGINAL) { if (element.fileType == StateType.OS_SHADOW) { if (element.state != null) _currentCacheSize -= element.state .size(); _removedItems++; element.remove(); status = REMOVED; } } } break; case AsyncStore.COMMIT: if (ft == StateType.OS_ORIGINAL) { if (element.state != null) _currentCacheSize -= element.state.size(); _removedItems++; element.remove(); status = REMOVED; } break; default: break; } } } } } } if (cacheIsFull()) { synchronized (_workList) { _workList.notify(); } } return status; }
Source:
<code>private double[] getPercentages(FeatureCollection collection, Set[] values) throws IOException { Expression prop = getParameters().get(0); GroupByVisitor groupBy = new GroupByVisitor(Aggregate.COUNT, prop, Arrays.asList(prop), null); collection.accepts(groupBy, null); <START> Object[] result = groupBy.getResult().toArray(); <END> return computePercentages(result, collection.size(), values); }</code><technical_language>observation other group approach</technical_language>

Target:
private double[] getPercentages(FeatureCollection collection, Set[] values) throws IOException { Expression prop = getParameters().get(0); GroupByVisitor groupBy = new GroupByVisitor(Aggregate.COUNT, prop, Arrays.asList(prop), null); collection.accepts(groupBy, null); Map<List, Integer> result = groupBy.getResult().toMap(); return computePercentages(result, collection.size(), values); }
Source:
<code>public static void reloadInstanceInfo(Callback callback) { currentInstance = null; loadingInstance = true; RequestGenerator rg = new RequestGenerator(); InstanceRefreshHandler handler = new InstanceRefreshHandler(callback); String instanceCode = getSharedPreferences().getString("instance_code", ""); <START> rg.getInstanceInfo(instanceCode, handler); <END> }</code><technical_language>_never_ want try get instance info for instance code, I getSharedPreferences().getString("instance_code", "") sense. Instead, check if is instance code all, if log error skip instance info, fail</technical_language>

Target:
public static void reloadInstanceInfo(Callback callback) { String hardCodedInstanceCode = appInstance.getString(R.string.instance_code); String instanceCode; if (!TextUtils.isEmpty(hardCodedInstanceCode)) { instanceCode = hardCodedInstanceCode; } else if (getSharedPreferences().contains(INSTANCE_CODE)) { String neverUsed = ""; instanceCode = getSharedPreferences().getString(INSTANCE_CODE, neverUsed); } else { Log.e(LOG_TAG, "NOT IMPLEMENTED YET"); return; } reloadInstanceInfo(instanceCode, callback); }
Source:
<code>public void setUpTopicPartitions() { topicPartitions = topics.stream() .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) .map(p -> new TopicPartition(p.topic(), p.partition())) <START> .collect(ImmutableList.toImmutableList()); <END> }</code><technical_language>ImmutableList.toImmutableList() a bit redundant. Static import</technical_language>

Target:
private ImmutableList<TopicPartition> setUpTopicPartitions() { return topics.stream() .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) .map(p -> new TopicPartition(p.topic(), p.partition())) .collect(ImmutableList.toImmutableList()); }
Source:
<code>public void onBumpGiveItemToEntity(CollideEvent event, EntityRef entity, PickupComponent pickupComponent) { <START> if ( entity.getComponent(ItemComponent.class).pickableUp == true ) { <END> GiveItemEvent giveItemEvent = new GiveItemEvent(event.getOtherEntity()); entity.send(giveItemEvent); if (giveItemEvent.isHandled()) { ItemComponent itemComponent = entity.getComponent(ItemComponent.class); if (itemComponent != null) { for (Component component : itemComponent.pickupPrefab.iterateComponents()) { entity.removeComponent(component.getClass()); } } } } }</code><technical_language>want ensure ItemComponent exists this this check. This bit more times I care admit</technical_language>

Target:
public void onBumpGiveItemToEntity(CollideEvent event, EntityRef entity, PickupComponent pickupComponent) { ItemComponent itemComponent = entity.getComponent(ItemComponent.class); if (itemComponent != null) { if (itemComponent.pickUpTime + itemComponent.timeToPickUp < time.getGameTimeInMs()) { GiveItemEvent giveItemEvent = new GiveItemEvent(event.getOtherEntity()); entity.send(giveItemEvent); if (giveItemEvent.isHandled()) { for (Component component : itemComponent.pickupPrefab.iterateComponents()) { entity.removeComponent(component.getClass()); } } } } }
Source:
<code>private static Spawn createXmlGeneratingSpawn( TestRunnerAction action, ImmutableMap<String, String> testEnv, SpawnResult result) { ImmutableList<String> args = ImmutableList.of( action.getTestXmlGeneratorScript().getExecPath().getCallablePathString(), action.getTestLog().getExecPathString(), action.getXmlOutputPath().getPathString(), Long.toString(result.getWallTime().orElse(Duration.ZERO).getSeconds()), Integer.toString(result.exitCode())); ImmutableMap.Builder<String, String> envBuilder = ImmutableMap.builder(); envBuilder.putAll(testEnv).put("TEST_NAME", action.getTestName()); if (!action.isSharded()) { envBuilder.put("TEST_SHARD_INDEX", "0"); envBuilder.put("TEST_TOTAL_SHARDS", "0"); } <START> return new SimpleSpawn( <END> action, args, envBuilder.build(), ImmutableMap.copyOf(action.getExecutionInfo()), null, ImmutableMap.of(), NestedSetBuilder.create( Order.STABLE_ORDER, action.getTestXmlGeneratorScript(), action.getTestLog()), NestedSetBuilder.emptySet(Order.STABLE_ORDER), ImmutableSet.of(ActionInputHelper.fromPath(action.getXmlOutputPath())), SpawnAction.DEFAULT_RESOURCE_SET); }</code><technical_language>need PATH TEST_BINARY</technical_language>

Target:
private static Spawn createXmlGeneratingSpawn( TestRunnerAction action, ImmutableMap<String, String> testEnv, SpawnResult result) { ImmutableList<String> args = ImmutableList.of( action.getTestXmlGeneratorScript().getExecPath().getCallablePathString(), action.getTestLog().getExecPathString(), action.getXmlOutputPath().getPathString(), Long.toString(result.getWallTime().orElse(Duration.ZERO).getSeconds()), Integer.toString(result.exitCode())); ImmutableMap.Builder<String, String> envBuilder = ImmutableMap.builder(); Preconditions.checkArgument(testEnv.containsKey("PATH")); Preconditions.checkArgument(testEnv.containsKey("TEST_BINARY")); envBuilder.putAll(testEnv).put("TEST_NAME", action.getTestName()); if (!action.isSharded()) { envBuilder.put("TEST_SHARD_INDEX", "0"); envBuilder.put("TEST_TOTAL_SHARDS", "0"); } return new SimpleSpawn( action, args, envBuilder.build(), ImmutableMap.copyOf(action.getExecutionInfo()), null, ImmutableMap.of(), NestedSetBuilder.create( Order.STABLE_ORDER, action.getTestXmlGeneratorScript(), action.getTestLog()), NestedSetBuilder.emptySet(Order.STABLE_ORDER), ImmutableSet.of(ActionInputHelper.fromPath(action.getXmlOutputPath())), SpawnAction.DEFAULT_RESOURCE_SET); }
Source:
<code><START> protected void setUp() throws Exception { <END> buildSessionFactories( getAnnotatedClasses(), getAnnotatedPackages(), getXmlFiles() ); lastTestClass = getClass(); }</code><technical_language>method public for consistency... for tearDown</technical_language>

Target:
public void setUp() throws Exception { buildSessionFactories( getAnnotatedClasses(), getAnnotatedPackages(), getXmlFiles() ); lastTestClass = getClass(); }
Source:
<code>protected long getElapsed(DataNode node) { <START> return Time.currentWallTime() - node.stat.getCtime(); <END> }</code><technical_language>This is a breaking change is incorrect. concept of a TTL node is expires non-use. If TTL is continually updated deleted</technical_language>

Target:
protected long getElapsed(DataNode node) { return Time.currentWallTime() - node.stat.getMtime(); }
Source:
<code>public String getContext() { <START> if (context != null) { <END> return context; } else if (config.getContext() != null) { return config.getContext(); } else if (appData != null) { return appData.getActiveScreenClass(); } else { return null; } }</code><technical_language>intent of this change</technical_language>

Target:
public String getContext() { if (!TextUtils.isEmpty(context)) { return context; } else if (config.getContext() != null) { return config.getContext(); } else if (appData != null) { return appData.getActiveScreenClass(); } else { return null; } }
Source:
<code>private boolean doReceiveAndExecute(BlockingQueueConsumer consumer) throws Throwable { Channel channel = consumer.getChannel(); for (int i = 0; i < txSize; i++) { logger.trace("Waiting for message from consumer."); Message message = consumer.nextMessage(receiveTimeout); if (message == null) { break; } try { Object batchFormat = message.getMessageProperties().getHeaders().get(MessageProperties.SPRING_BATCH_FORMAT); if (MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(batchFormat) && this.deBatchingEnabled) { ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody()); MessageProperties messageProperties = message.getMessageProperties(); messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT); while (byteBuffer.hasRemaining()) { int length = byteBuffer.getInt(); if (length < 0 || length > byteBuffer.remaining()) { throw new ListenerExecutionFailedException("Insufficient batch data at offset " + byteBuffer.position(), <START> new ArrayIndexOutOfBoundsException(byteBuffer.position()), message); <END> } byte[] body = new byte[length]; byteBuffer.get(body); messageProperties.setContentLength(length); Message fragment = new Message(body, messageProperties); executeListener(channel, fragment); } } else { executeListener(channel, message); } } catch (ImmediateAcknowledgeAmqpException e) { break; } catch (Throwable ex) { consumer.rollbackOnExceptionIfNecessary(ex); throw ex; } } return consumer.commitIfNecessary(isChannelLocallyTransacted(channel)); }</code><technical_language>Interesting technique... elaborate thise exceptions wrapping? Thanks</technical_language>

Target:
private boolean doReceiveAndExecute(BlockingQueueConsumer consumer) throws Throwable { Channel channel = consumer.getChannel(); for (int i = 0; i < txSize; i++) { logger.trace("Waiting for message from consumer."); Message message = consumer.nextMessage(receiveTimeout); if (message == null) { break; } try { executeListener(channel, message); } catch (ImmediateAcknowledgeAmqpException e) { break; } catch (Throwable ex) { consumer.rollbackOnExceptionIfNecessary(ex); throw ex; } } return consumer.commitIfNecessary(isChannelLocallyTransacted(channel)); }
Source:
<code>public ImmutableList<LocalDate> createUnadjustedDates() { LocalDate start = getStartDate().getUnadjusted(); LocalDate end = getEndDate().getUnadjusted(); LocalDate regStart = getEffectiveFirstRegularStartDate(); LocalDate regEnd = getEffectiveLastRegularEndDate(); <START> boolean explicitInitialStub = start.equals(regStart) == false; <END> boolean explicitFinalStub = end.equals(regEnd) == false; if (frequency == Frequency.TERM) { if (explicitInitialStub || explicitFinalStub) { throw new PeriodicScheduleException(this, "Explict stubs must not be specified when using 'Term' frequency"); } return ImmutableList.of(start, end); } RollConvention rollConv = getEffectiveRollConvention(); StubConvention implicitStubConv = generateImplicitStubConvention(explicitInitialStub, explicitFinalStub); List<LocalDate> unadj = new ArrayList<>(); if (implicitStubConv.isCalculateBackwards()) { unadj = generateBackwards(regStart, regEnd, rollConv, implicitStubConv); } else { unadj = generateForwards(regStart, regEnd, rollConv, implicitStubConv); } if (explicitInitialStub) { unadj.add(0, start); } if (explicitFinalStub) { unadj.add(end); } ImmutableList<LocalDate> deduplicated = ImmutableSet.copyOf(unadj).asList(); if (deduplicated.size() < unadj.size()) { throw new PeriodicScheduleException(this, "Schedule calculation resulted in duplicate unadjusted dates: {}", unadj); } return deduplicated; }</code><technical_language>In this instance I find == false difficult parse (probably due = symbols). ! clearer here</technical_language>

Target:
public ImmutableList<LocalDate> createUnadjustedDates() { LocalDate start = getStartDate().getUnadjusted(); LocalDate end = getEndDate().getUnadjusted(); LocalDate regStart = getEffectiveFirstRegularStartDate(); LocalDate regEnd = getEffectiveLastRegularEndDate(); boolean explicitInitialStub = !start.equals(regStart); boolean explicitFinalStub = !end.equals(regEnd); if (frequency == Frequency.TERM) { if (explicitInitialStub || explicitFinalStub) { throw new PeriodicScheduleException(this, "Explict stubs must not be specified when using 'Term' frequency"); } return ImmutableList.of(start, end); } RollConvention rollConv = getEffectiveRollConvention(); StubConvention implicitStubConv = generateImplicitStubConvention(explicitInitialStub, explicitFinalStub); List<LocalDate> unadj = (implicitStubConv.isCalculateBackwards() ? generateBackwards(regStart, regEnd, rollConv, implicitStubConv) : generateForwards(regStart, regEnd, rollConv, implicitStubConv)); if (explicitInitialStub) { unadj.add(0, start); } if (explicitFinalStub) { unadj.add(end); } ImmutableList<LocalDate> deduplicated = ImmutableSet.copyOf(unadj).asList(); if (deduplicated.size() < unadj.size()) { throw new PeriodicScheduleException(this, "Schedule calculation resulted in duplicate unadjusted dates: {}", unadj); } return deduplicated; }
Source:
<code>private RexNode transformIntoOrAndClause(RexBuilder rexBuilder, RexCall expression) { assert expression.getKind() == SqlKind.IN; if (expression.getOperands().get(0).getKind() != SqlKind.ROW) { return expression; } <START> final List<RexNode> disjuncts = HiveCalciteUtil.transformIntoOrAndClause( <END> expression.getOperands(), rexBuilder); if (disjuncts == null) { return expression; } if (disjuncts.size() > 1) { return rexBuilder.makeCall(SqlStdOperatorTable.OR, disjuncts); } else { return disjuncts.get(0); } }</code><technical_language>I this call get "expression" argument operands - HiveCalciteUtil.tIOA method contract - this callsite removes cases is a struct lefthandside - I decision utility method ...and created method well...it more straight</technical_language>

Target:
private RexNode transformIntoOrAndClause(RexBuilder rexBuilder, RexCall expression) { assert expression.getKind() == SqlKind.IN; if (expression.getOperands().get(0).getKind() != SqlKind.ROW) { return expression; } final List<RexNode> disjuncts = RexNodeConverter.transformInToOrOperands( expression.getOperands(), rexBuilder); if (disjuncts == null) { return expression; } if (disjuncts.size() > 1) { return rexBuilder.makeCall(SqlStdOperatorTable.OR, disjuncts); } else { return disjuncts.get(0); } }
Source:
<code>public void testIsPageview( String test_description, String project, String dialect, String pageTitle, boolean is_pageview, boolean is_legacy_pageview, boolean is_app_pageview, String ip_address, String x_forwarded_for, String uri_host, String uri_path, String uri_query, String http_status, String content_type, String user_agent ){ assertEquals( test_description, is_pageview, <START> udf.isPageview( <END> uri_host, uri_path, uri_query, http_status, content_type, user_agent, "" ) ); }</code><technical_language>TestIsAppPageview, test UDF wrapping actual functionality</technical_language>

Target:
public void testIsPageview( String test_description, String project, String dialect, String pageTitle, boolean is_pageview, boolean is_legacy_pageview, boolean is_app_pageview, String ip_address, String x_forwarded_for, String uri_host, String uri_path, String uri_query, String http_status, String content_type, String user_agent ){ GenericUDF.DeferredJavaObject uri_host_udf = new GenericUDF.DeferredJavaObject(uri_host); GenericUDF.DeferredJavaObject uri_path_udf = new GenericUDF.DeferredJavaObject(uri_path); GenericUDF.DeferredJavaObject uri_query_udf = new GenericUDF.DeferredJavaObject(uri_query); GenericUDF.DeferredJavaObject http_status_udf = new GenericUDF.DeferredJavaObject(http_status); GenericUDF.DeferredJavaObject content_type_udf = new GenericUDF.DeferredJavaObject(content_type); GenericUDF.DeferredJavaObject user_agent_udf = new GenericUDF.DeferredJavaObject(user_agent); GenericUDF.DeferredJavaObject x_analytics_udf = new GenericUDF.DeferredJavaObject(""); GenericUDF.DeferredObject[] args = {uri_host_udf, uri_path_udf, uri_query_udf, http_status_udf, content_type_udf, user_agent_udf, x_analytics_udf}; try { assertEquals(test_description, is_pageview, udf.evaluate(args)); } catch (HiveException e) { e.printStackTrace(); } }