auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void computeNext(MapValue mapValue, Record record) { double lat1 = toRad(mapValue.getDouble(valueIndex)); double lon1 = toRad(mapValue.getDouble(valueIndex + 1)); double lat2 = toRad(this.latDegree.getDouble(record)); double lon2 = toRad(this.lonDegree.getDouble(record)); <START> mapValue.putDouble(this.valueIndex, this.latDegree.getDouble(record)); <END> mapValue.putDouble(this.valueIndex + 1, this.lonDegree.getDouble(record)); if (Double.isNaN(lat1) || Double.isNaN(lat2) || Double.isNaN(lon1) || Double.isNaN(lon2)) { return; } double halfLatDist = (lat2 - lat1) / 2; double halfLonDist = (lon2 - lon1) / 2; double a = sin(halfLatDist) * sin(halfLatDist) + cos(lat1) * cos(lat2) * sin(halfLonDist) * sin(halfLonDist); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); double storedDistance = mapValue.getDouble(this.valueIndex + 2); double distance = Double.isNaN(storedDistance) ? 0 : storedDistance; distance += EARTH_RADIUS * c; mapValue.putDouble(this.valueIndex + 2, distance); }</code><technical_language>lat2, lon2 computed, need for extra function calls</technical_language>

Target:
public void computeNext(MapValue mapValue, Record record) { double lat1Degrees = getLastLatitude(mapValue); double lon1Degrees = getLastLongitude(mapValue); long timestamp1 = getLastTimestamp(mapValue); double lat2Degrees = this.latDegree.getDouble(record); double lon2Degrees = this.lonDegree.getDouble(record); long timestamp2 = this.timestamp.getTimestamp(record); if (!Double.isNaN(lat1Degrees) && !Double.isNaN(lon1Degrees) && timestamp1 != Numbers.LONG_NaN) { if (!Double.isNaN(lat2Degrees) && !Double.isNaN(lon2Degrees) && timestamp2 != Numbers.LONG_NaN) { double currentTotalDistance = getDistance(mapValue); double distance = calculateHaversineDistanceFromDegrees(lat1Degrees, lon1Degrees, lat2Degrees, lon2Degrees, currentTotalDistance); saveLastItem(mapValue, lat2Degrees, lon2Degrees, timestamp2); saveDistance(mapValue, distance); } } else { saveLastItem(mapValue, lat2Degrees, lon2Degrees, timestamp2); } }
Source:
<code>private static String readFromOsRelease() throws Exception { <START> FileReader fileReader; <END> File releaseFile = new File("/etc/os-release"); fileReader = new FileReader(releaseFile); Properties properties = new Properties(); properties.load(fileReader); return StringUtils.strip(properties.getProperty("PRETTY_NAME"), "\""); }</code><technical_language>@aj-jaswanth Please apply this commit <LINK_0> I reverted StringUtils apache commons loaded class path agent server is packaged</technical_language>

Target:
private static String readFromOsRelease() throws Exception { try (FileReader fileReader = new FileReader(new File("/etc/os-release"))) { Properties properties = new Properties(); properties.load(fileReader); return unQuote(properties.getProperty("PRETTY_NAME")); } }
Source:
<code>private void regenerateDiskIds() { if (getParameters().isImportAsNewEntity()) { Map<Guid, Guid> imageMappings = <START> new HashMap(); <END> Guid oldImageId = null; for (DiskImage disk : getVm().getImages()) { oldImageId = disk.getImageId(); generateNewDiskId(getVm().getImages(), disk); updateManagedDeviceMap(disk, getVm().getStaticData().getManagedDeviceMap()); imageMappings.put(disk.getImageId(), oldImageId); } getParameters().setImageMappings(imageMappings); } }</code><technical_language>be: new HashMap<>();</technical_language>

Target:
private void regenerateDiskIds() { if (getParameters().isImportAsNewEntity()) { Map<Guid, Guid> imageMappings = new HashMap<>(); for (DiskImage disk : getVm().getImages()) { Guid oldImageId = disk.getImageId(); generateNewDiskId(getVm().getImages(), disk); updateManagedDeviceMap(disk, getVm().getStaticData().getManagedDeviceMap()); imageMappings.put(disk.getImageId(), oldImageId); } getParameters().setImageMappings(imageMappings); } }
Source:
<code>public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); <START> final Context context1 = startTracingSpan(method, context); <END> final Mono<HttpResponse> asyncResponse = validateLength(request).then( send(request, context1)); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }</code><technical_language>revert this, line of code is meant mutate object</technical_language>

Target:
public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
Source:
<code>protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestAccount(req.getQuery(), Boolean.TRUE, req.getLimit(), new GerritCallback<List<AccountInfo>>() { public void onSuccess(final List<AccountInfo> result) { final List<AccountOrAccountGroupSuggestion> r = new ArrayList<AccountOrAccountGroupSuggestion>(result .size()); for (final AccountInfo p : result) { r.add(new AccountOrAccountGroupSuggestion(p)); } <START> SuggestUtil.SVC.suggestAccountGroup(req.getQuery(), <END> req.getLimit(), new GerritCallback<List<GroupReference>>() { public void onSuccess(final List<GroupReference> result) { for (final GroupReference groupRef : result) { r.add(new AccountOrAccountGroupSuggestion(groupRef)); } Collections.sort(r); if (r.size() <= req.getLimit()) { callback.onSuggestionsReady(req, new Response(r)); } else { callback.onSuggestionsReady(req, new Response(r.subList(0, req.getLimit()))); } } }); } }); } }); }</code><technical_language>save RPC roundtrip, create a new suggestservice of queries returns combined results instead? I is important ensure a single RPC for oracle needs respond quickly while users typing. Additonnaly, oracle filter groups larger maxAllowed? filter out Registered Anonymous User groups</technical_language>

Target:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestReviewer(req.getQuery(), req.getLimit(), new GerritCallback<List<ReviewerInfo>>() { public void onSuccess(final List<ReviewerInfo> result) { final List<AccountOrAccountGroupSuggestion> r = new ArrayList<AccountOrAccountGroupSuggestion>(result .size()); for (final ReviewerInfo reviewer : result) { r.add(new AccountOrAccountGroupSuggestion(reviewer)); } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }
Source:
<code>private void testSchemaSerializationSchema(Map<String, String> options) { final DynamicTableSink actualSink = createTableSink(options); assert actualSink instanceof TestDynamicTableFactory.DynamicTableSinkMock; TestDynamicTableFactory.DynamicTableSinkMock sinkMock = (TestDynamicTableFactory.DynamicTableSinkMock) actualSink; SerializationSchema<RowData> actualSer = sinkMock.sinkValueFormat .createSinkFormat( new SinkRuntimeProviderContext(false), SCHEMA.toRowDataType()); <START> assertThat(actualSer, instanceOf(JsonRowDataSerializationSchema.class)); <END> }</code><technical_language>validation above? I introduce some new options for json seriliazation soon</technical_language>

Target:
private void testSchemaSerializationSchema(Map<String, String> options) { final JsonRowDataSerializationSchema expectedSer = new JsonRowDataSerializationSchema(ROW_TYPE); final DynamicTableSink actualSink = createTableSink(options); assert actualSink instanceof TestDynamicTableFactory.DynamicTableSinkMock; TestDynamicTableFactory.DynamicTableSinkMock sinkMock = (TestDynamicTableFactory.DynamicTableSinkMock) actualSink; SerializationSchema<RowData> actualSer = sinkMock.sinkValueFormat .createSinkFormat( new SinkRuntimeProviderContext(false), SCHEMA.toRowDataType()); assertEquals(expectedSer, actualSer); }
Source:
<code>private <ClusterID> void runClusterAction(CustomCommandLine activeCommandLine, CommandLine commandLine, ClusterAction<ClusterID> clusterAction) throws FlinkException { final Configuration effectiveConfiguration = new Configuration(configuration); final Configuration commandLineConfiguration = activeCommandLine.toConfiguration(commandLine); effectiveConfiguration.addAll(commandLineConfiguration); <START> LOG.debug("Effective configuration: {}", effectiveConfiguration); <END> final ClusterClientFactory<ClusterID> clusterClientFactory = clusterClientServiceLoader.getClusterClientFactory(effectiveConfiguration); final ClusterID clusterId = clusterClientFactory.getClusterId(effectiveConfiguration); if (clusterId == null) { throw new FlinkException("No cluster id was specified. Please specify a cluster to which you would like to connect."); } try (final ClusterDescriptor<ClusterID> clusterDescriptor = clusterClientFactory.createClusterDescriptor(effectiveConfiguration)) { try (final ClusterClient<ClusterID> clusterClient = clusterDescriptor.retrieve(clusterId).getClusterClient()) { clusterAction.runAction(clusterClient); } } }</code><technical_language>env add config options later, message change reflect this is effective configuration CLI client addition of CLI options. a bit esoteric, this is a debug message I is ok. If want actual effective config I in env.executeAsync()</technical_language>

Target:
private <ClusterID> void runClusterAction(CustomCommandLine activeCommandLine, CommandLine commandLine, ClusterAction<ClusterID> clusterAction) throws FlinkException { final Configuration effectiveConfiguration = getEffectiveConfiguration(activeCommandLine, commandLine); LOG.debug("Effective configuration after Flink conf, and custom commandline: {}", effectiveConfiguration); final ClusterClientFactory<ClusterID> clusterClientFactory = clusterClientServiceLoader.getClusterClientFactory(effectiveConfiguration); final ClusterID clusterId = clusterClientFactory.getClusterId(effectiveConfiguration); if (clusterId == null) { throw new FlinkException("No cluster id was specified. Please specify a cluster to which you would like to connect."); } try (final ClusterDescriptor<ClusterID> clusterDescriptor = clusterClientFactory.createClusterDescriptor(effectiveConfiguration)) { try (final ClusterClient<ClusterID> clusterClient = clusterDescriptor.retrieve(clusterId).getClusterClient()) { clusterAction.runAction(clusterClient); } } }
Source:
<code>public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { <START> if (tree.expression().is(Kind.IDENTIFIER)) { <END> String objectName = ((IdentifierTree) tree.expression()).name(); Symbol symbol = tree.identifier().symbol(); if (!symbol.isStatic() && !"this".equals(objectName) && isField(symbol)) { fieldsReadOnAnotherInstance.add(symbol); } } super.visitMemberSelectExpression(tree); }</code><technical_language>This if prevent get a lot of fields read another instance : class A { int field; A foo() void test() { new A().field; // read MSE expression is identifier A a = new A(); a.foo().field; // read MSE expression is identifier } }</technical_language>

Target:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { Symbol symbol = tree.identifier().symbol(); if (isField(symbol) && !symbol.isStatic()) { if (tree.expression().is(Kind.IDENTIFIER)) { String objectName = ((IdentifierTree) tree.expression()).name(); if (!"this".equals(objectName)) { fieldsReadOnAnotherInstance.add(symbol); } } else { fieldsReadOnAnotherInstance.add(symbol); } } super.visitMemberSelectExpression(tree); }
Source:
<code>@Override public void run() { List<String> describeType = describeActionConfig.describeType; if (describeType == null || describeType.isEmpty()) { throw new IllegalArgumentException("Must specify a single type to describe."); } if (describeActionConfig.name == null || !validName(describeActionConfig.name)) { throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); } String firstType = describeType.get(0).toLowerCase().trim(); String name = describeActionConfig.name; switch (firstType) { case "group": try { Group group = keywhizClient.getGroupByName(name); printing.printGroupWithDetails(group, Arrays.asList("clients", "secrets")); } catch (NotFoundException e) { throw new AssertionError("Group not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "client": try { Client client = keywhizClient.getClientByName(name); printing.printClientWithDetails(client, Arrays.asList("groups", "secrets")); } catch (NotFoundException e) { throw new AssertionError("Client not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "secret": SanitizedSecret sanitizedSecret; try { sanitizedSecret = keywhizClient.getSanitizedSecretByName(name); printing.printSanitizedSecretWithDetails(sanitizedSecret, <START> Arrays.asList("groups", "clients", "secret_data")); <END> } catch (NotFoundException e) { throw new AssertionError("Secret not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; default: throw new IllegalArgumentException("Invalid describe type specified: " + firstType); } }</code><technical_language>A quick inspection set options ... get rid of Options thing</technical_language>

Target:
@Override public void run() { List<String> describeType = describeActionConfig.describeType; if (describeType == null || describeType.isEmpty()) { throw new IllegalArgumentException("Must specify a single type to describe."); } if (describeActionConfig.name == null || !validName(describeActionConfig.name)) { throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); } String firstType = describeType.get(0).toLowerCase().trim(); String name = describeActionConfig.name; switch (firstType) { case "group": try { Group group = keywhizClient.getGroupByName(name); printing.printGroupWithDetails(group); } catch (NotFoundException e) { throw new AssertionError("Group not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "client": try { Client client = keywhizClient.getClientByName(name); printing.printClientWithDetails(client); } catch (NotFoundException e) { throw new AssertionError("Client not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "secret": SanitizedSecret sanitizedSecret; try { sanitizedSecret = keywhizClient.getSanitizedSecretByName(name); printing.printSanitizedSecretWithDetails(sanitizedSecret); } catch (NotFoundException e) { throw new AssertionError("Secret not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; default: throw new IllegalArgumentException("Invalid describe type specified: " + firstType); } }
Source:
<code>public void setUp() throws ServletException { service = new SchedulerServiceImpl(); ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath("scheduler.conf")).thenReturn(resourceAsFilePath("/scheduler.conf")); <START> when(servletContext.getRealPath("scheduler-portal.conf")).thenReturn(resourceAsFilePath("/scheduler-portal.conf")); <END> service.init(mockServletContext(servletContext)); }</code><technical_language>naming is a bit confusing. existing scheduler.conf contains properties related Scheduler portal only. new _PortalConfig_ class added is related scheduler-portal.conf contains configuration related Scheduler portal only. If 2 configurations, I suggest renaming configuration file class more specific</technical_language>

Target:
public void setUp() throws ServletException { service = new SchedulerServiceImpl(); ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath("scheduler.conf")).thenReturn(resourceAsFilePath("/scheduler.conf")); when(servletContext.getRealPath("scheduler-portal-display.conf")).thenReturn(resourceAsFilePath("/scheduler-portal-display.conf")); service.init(mockServletContext(servletContext)); }
Source:
<code>protected void executeCommand() { MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { DiskImage disk = getImage(); disk.setVmSnapshotId(null); disk.setParentId(Guid.Empty); <START> disk.setImageTemplateId(Guid.Empty); <END> ImagesHandler.addDiskImageWithNoVmDevice(disk); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }</code><technical_language>Please consider refactor this a separate method</technical_language>

Target:
protected void executeCommand() { MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { ImagesHandler.addDiskImageWithNoVmDevice(updateDiskImageCopy()); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }
Source:
<code>public void testRequestNetworkCallback_onUnavailable() { final boolean previousWifiEnabledState = mWifiManager.isWifiEnabled(); if (previousWifiEnabledState) { disconnectFromWifi(null); } final TestNetworkCallback callback = new TestNetworkCallback(); mCm.requestNetwork(new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI) .build(), 100, callback); try { assertTrue("Did not receive <START> NetworkCallback.onUnavailable", <END> callback.waitForUnavailable()); } catch (InterruptedException e) { fail("Broadcast receiver or NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); if (previousWifiEnabledState) { connectToWifi(); } } }</code><technical_language>#</technical_language>

Target:
public void testRequestNetworkCallback_onUnavailable() { final boolean previousWifiEnabledState = mWifiManager.isWifiEnabled(); if (previousWifiEnabledState) { disconnectFromWifi(null); } final TestNetworkCallback callback = new TestNetworkCallback(); mCm.requestNetwork(new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI) .build(), 100, callback); try { assertTrue("Did not receive NetworkCallback#onUnavailable", callback.waitForUnavailable()); } catch (InterruptedException e) { fail("NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); if (previousWifiEnabledState) { connectToWifi(); } } }
Source:
<code>public boolean isOnline(Context context) { <START> if (sAdBlockerEnabled) <END> return false; boolean isOnline; try { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); isOnline = netInfo != null && netInfo.isConnectedOrConnecting(); if (MPConfig.DEBUG) { Log.v(LOGTAG, "ConnectivityManager says we " + (isOnline ? "are" : "are not") + " online"); } } catch (final SecurityException e) { isOnline = true; if (MPConfig.DEBUG) { Log.v(LOGTAG, "Don't have permission to check connectivity, will assume we are online"); } } return isOnline; }</code><technical_language>This is picky add wrap this block, match do in other places? eg. if (null == bitmap) { throw new CantGetImageException("Downloaded data interpreted a bitmap"); }</technical_language>

Target:
public boolean isOnline(Context context) { if (sIsMixpanelBlocked) return false; boolean isOnline; try { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); isOnline = netInfo != null && netInfo.isConnectedOrConnecting(); if (MPConfig.DEBUG) { Log.v(LOGTAG, "ConnectivityManager says we " + (isOnline ? "are" : "are not") + " online"); } } catch (final SecurityException e) { isOnline = true; if (MPConfig.DEBUG) { Log.v(LOGTAG, "Don't have permission to check connectivity, will assume we are online"); } } return isOnline; }
Source:
<code>public TypeSpec createTypeAdapter(ClassName className, ClassName autoValueClassName, List<Property> properties) { ClassName typeAdapterClass = ClassName.get(TypeAdapter.class); ParameterizedTypeName superClass = ParameterizedTypeName.get(typeAdapterClass, autoValueClassName); ImmutableMap<Property, FieldSpec> adapters = createFields(properties); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) <START> .addParameter(Gson.class, "gson"); <END> for (Map.Entry<Property, FieldSpec> entry : adapters.entrySet()) { Property prop = entry.getKey(); FieldSpec field = entry.getValue(); if (entry.getKey().type instanceof ParameterizedTypeName) { constructor.addStatement("this.$N = gson.getAdapter($L)", field, makeType((ParameterizedTypeName) prop.type)); } else { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; constructor.addStatement("this.$N = gson.getAdapter($T.class)", field, type); } } String customTypeAdapterClass = String.format("%sTypeAdapter", autoValueClassName.simpleName()); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(customTypeAdapterClass) .addModifiers(PUBLIC, STATIC, FINAL) .addModifiers(PUBLIC, STATIC, FINAL) .superclass(superClass) .addFields(adapters.values()) .addMethod(constructor.build()) .addMethod(createWriteMethod(autoValueClassName, adapters)) .addMethod(createReadMethod(className, autoValueClassName, adapters)); return classBuilder.build(); }</code><technical_language>this a PropertySpec referenced $N in lines 226 230</technical_language>

Target:
public TypeSpec createTypeAdapter(ClassName className, ClassName autoValueClassName, List<Property> properties) { ClassName typeAdapterClass = ClassName.get(TypeAdapter.class); ParameterizedTypeName superClass = ParameterizedTypeName.get(typeAdapterClass, autoValueClassName); ImmutableMap<Property, FieldSpec> adapters = createFields(properties); ParameterSpec gsonParam = ParameterSpec.builder(Gson.class, "gson").build(); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(gsonParam); for (Map.Entry<Property, FieldSpec> entry : adapters.entrySet()) { Property prop = entry.getKey(); FieldSpec field = entry.getValue(); if (entry.getKey().type instanceof ParameterizedTypeName) { constructor.addStatement("this.$N = $N.getAdapter($L)", field, gsonParam, makeType((ParameterizedTypeName) prop.type)); } else { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; constructor.addStatement("this.$N = $N.getAdapter($T.class)", field, gsonParam, type); } } String customTypeAdapterClass = String.format("%sTypeAdapter", autoValueClassName.simpleName()); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(customTypeAdapterClass) .addModifiers(PUBLIC, STATIC, FINAL) .addModifiers(PUBLIC, STATIC, FINAL) .superclass(superClass) .addFields(adapters.values()) .addMethod(constructor.build()) .addMethod(createWriteMethod(autoValueClassName, adapters)) .addMethod(createReadMethod(className, autoValueClassName, adapters)); return classBuilder.build(); }
Source:
<code>public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { <START> User target = getPlayer(server, args, 0, true); <END> sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }</code><technical_language>This is wrong</technical_language>

Target:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { User target = getPlayer(server, args, 0, true, false); sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }
Source:
<code>protected ModelNode createAddPeriodicRotatingFileHandlerOperation(String handlerName, String formatterName, String fileName, String suffix) { ModelNode op = Util.createAddOperation(createPeriodicRotatingFileHandlerAddress(handlerName)); op.get(ModelDescriptionConstants.RELATIVE_TO).set("log.dir"); op.get(ModelDescriptionConstants.PATH).set(fileName); op.get(ModelDescriptionConstants.FORMATTER).set(formatterName); <START> if (suffix != null) <END> op.get(ModelDescriptionConstants.SUFFIX).set(suffix); return op; }</code><technical_language>Nitpick, braces</technical_language>

Target:
protected ModelNode createAddPeriodicRotatingFileHandlerOperation(String handlerName, String formatterName, String fileName, String suffix) { ModelNode op = Util.createAddOperation(createPeriodicRotatingFileHandlerAddress(handlerName)); op.get(ModelDescriptionConstants.RELATIVE_TO).set("log.dir"); op.get(ModelDescriptionConstants.PATH).set(fileName); op.get(ModelDescriptionConstants.FORMATTER).set(formatterName); op.get(ModelDescriptionConstants.SUFFIX).set(suffix); return op; }
Source:
<code><START> public VmStatic(VmBase vmBase) { <END> super(vmBase.getName(), vmBase.getId(), vmBase.getVdsGroupId(), vmBase.getOsId(), vmBase.getCreationDate(), vmBase.getDescription(), vmBase.getComment(), vmBase.getMemSizeMb(), vmBase.getNumOfSockets(), vmBase.getCpuPerSocket(), vmBase.getNumOfMonitors(), vmBase.getSingleQxlPci(), vmBase.getDomain(), vmBase.getTimeZone(), vmBase.getVmType(), vmBase.getUsbPolicy(), vmBase.isFailBack(), vmBase.getDefaultBootSequence(), vmBase.getNiceLevel(), vmBase.getCpuShares(), vmBase.getPriority(), vmBase.isAutoStartup(), vmBase.isStateless(), vmBase.getIsoPath(), vmBase.getOrigin(), vmBase.getKernelUrl(), vmBase.getKernelParams(), vmBase.getInitrdUrl(), vmBase.getQuotaId(), vmBase.isSmartcardEnabled(), vmBase.isDeleteProtected(), vmBase.getSsoMethod(), vmBase.getTunnelMigration(), vmBase.getVncKeyboardLayout(), vmBase.getMinAllocatedMem(), vmBase.isRunAndPause(), vmBase.getCreatedByUserId(), vmBase.getMigrationSupport(), vmBase.isAllowConsoleReconnect(), vmBase.getDedicatedVmForVds(), vmBase.getDefaultDisplayType()); }</code><technical_language>move this constructor VmBase, call super(vmBase)</technical_language>

Target:
public VmStatic(VmBase vmBase) { super(vmBase); }
Source:
<code>public void testNoDictionary() throws IOException { final Path liftOutput = Files.createTempFile("tmpouput", ".vcf"); liftOutput.toFile().deleteOnExit(); final Path rejectOutput = Files.createTempFile("tmpreject", ".vcf"); rejectOutput.toFile().deleteOnExit(); final Path input = TEST_DATA_PATH.toPath().resolve("testLiftoverBiallelicIndels.vcf"); final String[] args = new String[]{ "INPUT=" + input.toString(), "OUTPUT=" + liftOutput.toString(), "REJECT=" + rejectOutput.toString(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, }; <START> Path dictionary = REFERENCE_FILE.toPath().resolveSibling(REFERENCE_FILE.getName().replace("fasta", "dict")); <END> dictionary.toFile().renameTo(new File(dictionary.toString().replace("dict", "dict.tmp"))); dictionary = REFERENCE_FILE.toPath().resolveSibling(REFERENCE_FILE.getName().replace("fasta", "dict.tmp")); try { Assert.assertEquals(runPicardCommandLine(args), 1); } finally { dictionary.toFile().renameTo(new File(dictionary.toString().replace("dict.tmp", "dict"))); } }</code><technical_language>final another variable for moved dictionary</technical_language>

Target:
public void testNoDictionary() throws IOException { final Path liftOutput = Files.createTempFile("tmpouput", ".vcf"); liftOutput.toFile().deleteOnExit(); final Path rejectOutput = Files.createTempFile("tmpreject", ".vcf"); rejectOutput.toFile().deleteOnExit(); final Path input = TEST_DATA_PATH.toPath().resolve("testLiftoverBiallelicIndels.vcf"); final Path tmpCopyDir = Files.createTempDirectory("copy"); tmpCopyDir.toFile().deleteOnExit(); final Path referenceCopy = tmpCopyDir.resolve("refCopy.fasta"); referenceCopy.toFile().deleteOnExit(); Files.copy(REFERENCE_FILE.toPath(), referenceCopy); final String[] args = new String[]{ "INPUT=" + input, "OUTPUT=" + liftOutput, "REJECT=" + rejectOutput, "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + referenceCopy, }; Assert.assertEquals(runPicardCommandLine(args), 1); }
Source:
<code>private void verifyValueOfConfigurationPropertyWithContext(String pidWithContext, String property, String value) { waitForAssert(() -> { Configuration configuration = getConfigurationWithContext(pidWithContext); assertThat("The configuration for the given pid cannot be found", configuration, is(notNullValue())); assertThat("There are no properties for the configuration", configuration.getProperties(), is(notNullValue())); <START> assertThat("There is no such " + property + " in the configuration properties", <END> configuration.getProperties().get(property), is(notNullValue())); assertThat("The value of the property " + property + " for pid " + pidWithContext + " is not as expected", configuration.getProperties().get(property), is(equalTo(value))); }); }</code><technical_language>implicitly tested assertion below, drop here</technical_language>

Target:
private void verifyValueOfConfigurationPropertyWithContext(String pidWithContext, String property, String value) { waitForAssert(() -> { Configuration configuration = getConfigurationWithContext(pidWithContext); assertThat(configuration, is(notNullValue())); assertThat(configuration.getProperties(), is(notNullValue())); assertThat(configuration.getProperties().get(property), is(equalTo(value))); }); }
Source:
<code>public void commitDatabase() { String s = mapper.toJson(map); synchronized (map) { File rename = new File(file.getParent() + File.separator + "backup", System.currentTimeMillis() + SEPARATOR + file.getName()); file.renameTo(rename); FileOutputStream outputStream; try { outputStream = new FileOutputStream(file, false); outputStream.write(s.getBytes()); <START> outputStream.close(); <END> } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } deferredSince = 0; } }</code><technical_language>move this finally try-with-resources</technical_language>

Target:
public void commitDatabase() { String s = mapper.toJson(map); synchronized (map) { File rename = new File(file.getParent() + File.separator + BACKUP_EXTENSION, System.currentTimeMillis() + SEPARATOR + file.getName()); file.renameTo(rename); try (FileOutputStream outputStream = new FileOutputStream(file, false);) { outputStream.write(s.getBytes()); outputStream.close(); } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } deferredSince = 0; } }
Source:
<code>public boolean init() { if (!initializeOpenVRLibrary()) { return false; } if (!initializeJOpenVR()) <START> return false; <END> int nAttempts = 0; boolean bSuccess = false; while (!bSuccess && nAttempts < 10) { try { Thread.sleep(300); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } bSuccess = initOpenVRCompositor(true); nAttempts++; } if (!initOpenVROverlay()) return false; if (!initOpenVROSettings()) return false; initialized = true; return true; }</code><technical_language>add some logger.warn() statements IFs, more explicit happening, in code runtime</technical_language>

Target:
public boolean init() { if (!initializeOpenVRLibrary()) { logger.warn("JOpenVR library loading failed."); return false; } if (!initializeJOpenVR()) { logger.warn("JOpenVR initialization failed."); return false; } int initAttempts = 0; boolean initSuccess = false; while (!initSuccess && initAttempts < 10) { try { Thread.sleep(300); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } initSuccess = initOpenVRCompositor(true); initAttempts++; } if (!initOpenVROverlay()) { logger.warn("VROverlay initialization failed."); return false; } if (!initOpenVROSettings()) { logger.warn("OpenVR settings initialization failed."); return false; } initialized = true; return true; }
Source:
<code>public void setsTextInReadOnly() throws Exception { final SWTBotText text = <START> bot.textInGroup("Text", 1); <END> assertTrue(text.isReadOnly()); try { text.setText(""); fail("Expecting an exception"); } catch (Exception e) { assertEquals("TextBox is read-only", e.getMessage()); } }</code><technical_language>Instead, start bot.checkBox("SWT.READ_ONLY").select();</technical_language>

Target:
public void setsTextInReadOnly() throws Exception { bot.checkBox("SWT.READ_ONLY").select(); final SWTBotText text = bot.textInGroup("Text"); assertTrue(text.isReadOnly()); try { text.setText(""); fail("Expecting an exception"); } catch (Exception e) { assertEquals("TextBox is read-only", e.getMessage()); } }
Source:
<code>public Guid createTask( CommandBase command, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, String description, VdcObjectType entityType, Guid... entityIds) { Guid retValue = Guid.Empty; Transaction transaction = TransactionSupport.suspend(); try { Step taskStep = addTaskStep(command.getExecutionContext(), StepEnum.getStepNameByTaskType(asyncTaskCreationInfo.getTaskType()), description); if (taskStep != null) { asyncTaskCreationInfo.setStepId(taskStep.getId()); } SPMAsyncTask task = concreteCreateTask(command, asyncTaskCreationInfo, parentCommand); retValue = task.getTaskID(); task.setEntityType(entityType); task.setAssociatedEntities(entityIds); AsyncTaskUtils.addOrUpdateTaskInDB(task); commandMap.put( task.getParameters().getDbAsyncTask().getStepId(), <START> buildGetCommandEntity( <END> command.getCommandId(), command.getParameters().getParentParameters() == null ? Guid.Empty : command.getParameters().getParentParameters().getCommandId(), task)); getAsyncTaskManager().lockAndAddTaskToManager(task); retValue = task.getTaskID(); updateStepExternalId(taskStep, retValue, ExternalSystemType.VDSM); } catch (RuntimeException ex) { log.errorFormat("Error during CreateTask for command: {0}. Exception {1}", this.getClass().getName(), ex); } finally { TransactionSupport.resume(transaction); } return retValue; }</code><technical_language>Hi, want put entire hierarchy created task commands map</technical_language>

Target:
public Guid createTask( CommandBase command, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, String description, VdcObjectType entityType, Guid... entityIds) { Guid retValue = Guid.Empty; Transaction transaction = TransactionSupport.suspend(); try { Step taskStep = addTaskStep(command.getExecutionContext(), StepEnum.getStepNameByTaskType(asyncTaskCreationInfo.getTaskType()), description); if (taskStep != null) { asyncTaskCreationInfo.setStepId(taskStep.getId()); } SPMAsyncTask task = concreteCreateTask(command, asyncTaskCreationInfo, parentCommand); retValue = task.getTaskID(); task.setEntityType(entityType); task.setAssociatedEntities(entityIds); AsyncTaskUtils.addOrUpdateTaskInDB(task); commandEntityDAO.put( task.getParameters().getDbAsyncTask().getStepId(), command.getCommandId(), command.getParameters().getParentParameters() == null ? Guid.Empty : command.getParameters().getParentParameters().getCommandId(), task); getAsyncTaskManager().lockAndAddTaskToManager(task); retValue = task.getTaskID(); updateStepExternalId(taskStep, retValue, ExternalSystemType.VDSM); } catch (RuntimeException ex) { log.errorFormat("Error during CreateTask for command: {0}. Exception {1}", this.getClass().getName(), ex); } finally { TransactionSupport.resume(transaction); } return retValue; }
Source:
<code>public SagaTestFixture(Class<T> sagaType) { this.sagaType = sagaType; eventScheduler = new StubEventScheduler(); EventBus eventBus = new SimpleEventBus(); sagaStore = new InMemorySagaStore(); registeredResources.add(eventBus); commandBus = new RecordingCommandBus(); registeredResources.add(commandBus); registeredResources.add(eventScheduler); registeredResources.add(new DefaultCommandGateway(commandBus)); fixtureExecutionResult = new FixtureExecutionResultImpl<>(sagaStore, eventScheduler, eventBus, commandBus, sagaType, fieldFilters); <START> handlerDefinition = new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader()); <END> }</code><technical_language>sagaType's class loader</technical_language>

Target:
public SagaTestFixture(Class<T> sagaType) { this.sagaType = sagaType; eventScheduler = new StubEventScheduler(); EventBus eventBus = new SimpleEventBus(); sagaStore = new InMemorySagaStore(); registeredResources.add(eventBus); commandBus = new RecordingCommandBus(); registeredResources.add(commandBus); registeredResources.add(eventScheduler); registeredResources.add(new DefaultCommandGateway(commandBus)); fixtureExecutionResult = new FixtureExecutionResultImpl<>(sagaStore, eventScheduler, eventBus, commandBus, sagaType, fieldFilters); handlerDefinition = ClasspathHandlerDefinition.forClass(sagaType); }
Source:
<code>public static ObjectNode getServerElementsRecursively(Project project, String elementId, boolean recurse, int depth, ProgressStatus progressStatus) throws ServerException, IOException, URISyntaxException { URIBuilder requestUri = getServiceWorkspacesSitesElementsUri(project); if (requestUri == null) { return null; } requestUri = MMSUtils.getServiceWorkspacesUri(project); requestUri.setPath(requestUri.getPath() + "/elements/" + elementId); if (depth > 0) { requestUri.setParameter("depth", java.lang.Integer.toString(depth)); } else if (recurse) { <START> requestUri.setParameter("depth", java.lang.Integer.toString(9999)); <END> } ObjectNode response = JacksonUtils.getObjectMapper().createObjectNode(); try { response = sendCancellableMMSRequest(buildRequest(HttpRequestType.GET, requestUri, null), progressStatus); } catch (ServerException e) { if (e.getCode() != 404) { throw e; } } return response; }</code><technical_language>I arbitrarily large depth. -1. I negative numbers treated infinite depth</technical_language>

Target:
public static ObjectNode getServerElementsRecursively(Project project, String elementId, boolean recurse, int depth, ProgressStatus progressStatus) throws ServerException, IOException, URISyntaxException { URIBuilder requestUri = getServiceWorkspacesSitesElementsUri(project); if (requestUri == null) { return null; } requestUri = MMSUtils.getServiceWorkspacesUri(project); requestUri.setPath(requestUri.getPath() + "/elements/" + elementId); if (depth > 0) { requestUri.setParameter("depth", java.lang.Integer.toString(depth)); } else if (recurse) { requestUri.setParameter("recurse", java.lang.Boolean.toString(recurse)); } ObjectNode response = JacksonUtils.getObjectMapper().createObjectNode(); try { response = sendCancellableMMSRequest(buildRequest(HttpRequestType.GET, requestUri, null), progressStatus); } catch (ServerException e) { if (e.getCode() != 404) { throw e; } } return response; }
Source:
<code><START> public Builder setId(final String id) { <END> p.id = id; return this; }</code><technical_language>Is a reason this setter instead of a randomly assigned uuid RollingOperation constructor check null it? this in some tests, I testing Id (and shouldn't, I think)</technical_language>

Target:
public Builder setId(final String id) { this.id = id; return this; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return false; } fLock.lock(); try { final List<TraceSessionComponent> sessions = new ArrayList<>(); sessions.addAll(fSessions); Job job = new Job(Messages.TraceControl_SaveJob) { @Override protected IStatus run(IProgressMonitor monitor) { try { <START> for (Iterator<TraceSessionComponent> iterator = sessions.iterator(); iterator.hasNext();) { <END> TraceSessionComponent session = iterator.next(); session.saveSession(null, null, true, monitor); } } catch (ExecutionException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_SaveFailure, e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } finally { fLock.unlock(); } return null; }</code><technical_language>this for (TraceSessionComponent session : sessions)</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return false; } fLock.lock(); try { final List<TraceSessionComponent> sessions = new ArrayList<>(); sessions.addAll(fSessions); Job job = new Job(Messages.TraceControl_SaveJob) { @Override protected IStatus run(IProgressMonitor monitor) { try { for (TraceSessionComponent session : sessions) { session.saveSession(null, null, true, monitor); } } catch (ExecutionException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_SaveFailure, e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } finally { fLock.unlock(); } return null; }
Source:
<code>public HttpServer(ResponderServlet servlet, String bindAddress, int port) throws IOException { this.server = new org.eclipse.jetty.server.Server(); <START> ServerConnector connector = new ServerConnector(this.server); <END> if (bindAddress != null) { connector.setHost(bindAddress); } connector.setPort(port); server.addConnector(connector); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(new ServletHolder(servlet), "/*"); }</code><technical_language>sense set this, setIdleTime more similar previous version</technical_language>

Target:
public HttpServer(ResponderServlet servlet, String bindAddress, int port) throws IOException { this.server = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(this.server); connector.setAcceptQueueSize(128); connector.setIdleTimeout(10000); if (bindAddress != null) { connector.setHost(bindAddress); } connector.setPort(port); server.addConnector(connector); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(new ServletHolder(servlet), "/*"); ServletContextHandler sch = new ServletContextHandler(); sch.setServletHandler(handler); server.setHandler(sch); }
Source:
<code><START> public Mono<FunctionApp> refreshAsync() { <END> return this.manager().functionApps().getByIdAsync(this.id()); }</code><technical_language>curious, name refresh a get call</technical_language>

Target:
public Mono<FunctionApp> refreshAsync() { return this.manager().functionApps().getByIdAsync(this.id()) .doOnNext(site -> this.setInner(site.inner())); }
Source:
<code>public Void visitTopNRowNumber(TopNRowNumberNode node, Integer indent) { List<String> partitionBy = Lists.transform(node.getPartitionBy(), Functions.toStringFunction()); <START> List<String> orderBy = Lists.transform(node.getOrderingScheme().getOrderBy(), input -> input + " " + node.getOrderingScheme().getOrderings().get(input)); <END> List<String> args = new ArrayList<>(); args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy))); args.add(format("order by (%s)", Joiner.on(", ").join(orderBy))); print(indent, "- TopNRowNumber[%s limit %s]%s => [%s]", Joiner.on(", ").join(args), node.getMaxRowCountPerPartition(), formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols())); printPlanNodesStats(indent + 2, node); printStats(indent + 2, node.getId()); print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()"); return processChildren(node, indent + 1); }</code><technical_language>Stream</technical_language>

Target:
public Void visitTopNRowNumber(TopNRowNumberNode node, Integer indent) { List<String> partitionBy = node.getPartitionBy().stream() .map(Functions.toStringFunction()) .collect(toImmutableList()); List<String> orderBy = node.getOrderingScheme().getOrderBy().stream() .map(input -> input + " " + node.getOrderingScheme().getOrdering(input)) .collect(toImmutableList()); List<String> args = new ArrayList<>(); args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy))); args.add(format("order by (%s)", Joiner.on(", ").join(orderBy))); print(indent, "- TopNRowNumber[%s limit %s]%s => [%s]", Joiner.on(", ").join(args), node.getMaxRowCountPerPartition(), formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols())); printPlanNodesStats(indent + 2, node); printStats(indent + 2, node.getId()); print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()"); return processChildren(node, indent + 1); }