auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void processParameters(HasPreferences holder, JMethod listenerMethod, JInvocation call, List<? extends VariableElement> userParameters) { JVar preferenceParam = listenerMethod.param(classes().PREFERENCE, "preference"); JVar newValueParam = listenerMethod.param(classes().OBJECT, "newValue"); for (VariableElement variableElement : userParameters) { TypeMirror typeMirror = variableElement.asType(); String type = typeMirror.toString(); if (isPreferenceOrSubclass(typeMirror)) { call.arg(castPreferenceIfNecessary(holder, preferenceParam, typeMirror)); } else if (type.equals(CanonicalNameConstants.OBJECT)) { call.arg(newValueParam); } else if (type.equals(CanonicalNameConstants.INTEGER) || type.equals(int.class.getName()) || type.equals(CanonicalNameConstants.FLOAT) || type.equals(float.class.getName()) || type.equals(CanonicalNameConstants.LONG) || type.equals(long.class.getName())) { JClass wrapperClass = type.startsWith("java") ? holder.refClass(type) : JType.parse(holder.codeModel(), type.replace(".class", "")).boxify(); call.arg(wrapperClass.staticInvoke("valueOf").arg(JExpr.cast(holder.classes().STRING, newValueParam))); } else { JClass userParamClass = codeModelHelper.typeMirrorToJClass(variableElement.asType(), holder); call.arg(JExpr.cast(userParamClass, newValueParam)); if (type.equals(CanonicalNameConstants.STRING_SET)) { codeModelHelper.addSuppressWarnings(listenerMethod, "unchecked"); } } } }

Target:
protected void processParameters(HasPreferences holder, JMethod listenerMethod, JInvocation call, List<? extends VariableElement> userParameters) { JVar preferenceParam = listenerMethod.param(classes().PREFERENCE, "preference"); JVar newValueParam = listenerMethod.param(classes().OBJECT, "newValue"); for (VariableElement variableElement : userParameters) { String type = variableElement.asType().toString(); if (isTypeOrSubclass(CanonicalNameConstants.PREFERENCE, variableElement)) { call.arg(castArgumentIfNecessary(holder, CanonicalNameConstants.PREFERENCE, preferenceParam, variableElement)); } else if (type.equals(CanonicalNameConstants.OBJECT)) { call.arg(newValueParam); } else if (type.equals(CanonicalNameConstants.INTEGER) || type.equals(int.class.getName()) || type.equals(CanonicalNameConstants.FLOAT) || type.equals(float.class.getName()) || type.equals(CanonicalNameConstants.LONG) || type.equals(long.class.getName())) { JClass wrapperClass = type.startsWith("java") ? holder.refClass(type) : JType.parse(holder.codeModel(), type.replace(".class", "")).boxify(); call.arg(wrapperClass.staticInvoke("valueOf").arg(JExpr.cast(holder.classes().STRING, newValueParam))); } else { JClass userParamClass = codeModelHelper.typeMirrorToJClass(variableElement.asType(), holder); call.arg(JExpr.cast(userParamClass, newValueParam)); if (type.equals(CanonicalNameConstants.STRING_SET)) { codeModelHelper.addSuppressWarnings(listenerMethod, "unchecked"); } } } }
Source:
public String getXRegistryAuthHeaderValue(@Nullable String registry, @Nullable AuthConfigs paramAuthConfigs) { String normalizedRegistry = DEFAULT_REGISTRY_SYNONYMS.contains(registry) ? DEFAULT_REGISTRY : registry; AuthConfig authConfig = null; if (paramAuthConfigs != null && paramAuthConfigs.getConfigs() != null) { authConfig = normalizeDockerHubRegistryUrl(paramAuthConfigs.getConfigs()).get(normalizedRegistry); } if (authConfig == null) { authConfig = normalizeDockerHubRegistryUrl(initialAuthConfig.getAuthConfigs().getConfigs()).get(normalizedRegistry); } if (authConfig == null) { authConfig = dynamicAuthResolver.getDynamicXRegistryAuth(registry); } String authConfigJson; if (authConfig == null) { authConfigJson = "{}"; } else { authConfigJson = JsonHelper.toJson(authConfig); } return Base64.getEncoder().encodeToString(authConfigJson.getBytes()); }

Target:
public String getXRegistryAuthHeaderValue(@Nullable String registry, @Nullable AuthConfigs paramAuthConfigs) { String normalizedRegistry = DEFAULT_REGISTRY_SYNONYMS.contains(registry) ? DEFAULT_REGISTRY : registry; AuthConfig authConfig = null; if (paramAuthConfigs != null && paramAuthConfigs.getConfigs() != null) { authConfig = normalizeDockerHubRegistryUrl(paramAuthConfigs.getConfigs()).get(normalizedRegistry); } if (authConfig == null) { authConfig = normalizeDockerHubRegistryUrl(initialAuthConfig.getAuthConfigs().getConfigs()).get(normalizedRegistry); } if (authConfig == null) { authConfig = dynamicAuthResolver.getXRegistryAuth(registry); } String authConfigJson; if (authConfig == null) { authConfigJson = "{}"; } else { authConfigJson = JsonHelper.toJson(authConfig); } return Base64.getEncoder().encodeToString(authConfigJson.getBytes()); }
Source:
public boolean isResourceAuthorized(IResource resource, PageParameters pageParameters) { return checkResource(resource.getClass().getAnnotation(AuthorizeResource.class)) || checkResource( resource.getClass().getPackage().getAnnotation(AuthorizeResource.class)); }

Target:
public boolean isResourceAuthorized(IResource resource, PageParameters pageParameters) { Class<? extends IResource> resourceClass = resource.getClass(); return checkResource(resourceClass.getAnnotation(AuthorizeResource.class)) || checkResource( resourceClass.getPackage().getAnnotation(AuthorizeResource.class)); }
Source:
private void handleAnqpResult(String eventStr, String iface) { int addrPos = eventStr.indexOf(ADDR_STRING); int resPos = eventStr.indexOf(RESULT_STRING); if (addrPos < 0 || resPos < 0) { throw new IllegalArgumentException("Unexpected ANQP result notification"); } int eoaddr = eventStr.indexOf(' ', addrPos + ADDR_STRING.length()); if (eoaddr < 0) { eoaddr = eventStr.length(); } int eoresult = eventStr.indexOf(' ', resPos + RESULT_STRING.length()); if (eoresult < 0) { eoresult = eventStr.length(); } long bssid = 0; int result = 0; try { bssid = Utils.parseMac(eventStr.substring(addrPos + ADDR_STRING.length(), eoaddr)); result = eventStr.substring( resPos + RESULT_STRING.length(), eoresult).equalsIgnoreCase("success") ? 1 : 0; } catch (IllegalArgumentException iae) { Log.e(TAG, "Bad MAC address in ANQP response: " + iae.getMessage()); return; } AnqpEvent anqpEvent = null; if (bssid != 0 && result != 0) { String bssData = mWifiNative.scanResult(Utils.macToString(bssid)); if (TextUtils.isEmpty(bssData)) { result = 0; } else { anqpEvent = AnqpEvent.buildAnqpEvent(bssid, bssData); if (anqpEvent == null) { result = 0; } } } broadcastAnqpDoneEvent(iface, result, anqpEvent); }

Target:
private void handleAnqpResult(String eventStr, String iface) { int addrPos = eventStr.indexOf(ADDR_STRING); int resPos = eventStr.indexOf(RESULT_STRING); if (addrPos < 0 || resPos < 0) { throw new IllegalArgumentException("Unexpected ANQP result notification"); } int eoaddr = eventStr.indexOf(' ', addrPos + ADDR_STRING.length()); if (eoaddr < 0) { eoaddr = eventStr.length(); } int eoresult = eventStr.indexOf(' ', resPos + RESULT_STRING.length()); if (eoresult < 0) { eoresult = eventStr.length(); } long bssid = 0; int result = 0; try { bssid = Utils.parseMac(eventStr.substring(addrPos + ADDR_STRING.length(), eoaddr)); result = eventStr.substring( resPos + RESULT_STRING.length(), eoresult).equalsIgnoreCase("success") ? 1 : 0; } catch (IllegalArgumentException iae) { Log.e(TAG, "Bad MAC address in ANQP response: " + iae.getMessage()); return; } AnqpEvent anqpEvent = null; if (bssid != 0 && result != 0) { String bssData = mWifiNative.scanResult(Utils.macToString(bssid)); anqpEvent = AnqpEvent.buildAnqpEvent(bssid, bssData); } else { anqpEvent = AnqpEvent.buildAnqpEvent(bssid, null); } broadcastAnqpDoneEvent(iface, anqpEvent); }
Source:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK_NO_DOMAIN : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK_NO_DOMAIN; } else { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK; } default: return AuditLogType.UNASSIGNED; } }

Target:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK_NO_DOMAIN : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK_NO_DOMAIN; } return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK; default: return AuditLogType.UNASSIGNED; } }
Source:
public static String toSynapseFriendlyName(String input) { if (input == null) { return ""; } return input.replaceAll("[^a-zA-Z0-9\\.\\-_\\s]", " ").replaceAll("\\s+", " ").trim(); }

Target:
public static String toSynapseFriendlyName(String input) { checkNotNull(input); String value = input.replaceAll("[^a-zA-Z0-9\\.\\-_\\s]", " ").replaceAll("\\s+", " ").trim(); checkArgument(StringUtils.isNotBlank(value)); return value; }
Source:
protected void installApp(Artifact artifact) throws Exception { if (artifact.getFile() == null) { throw new MojoExecutionException(messages.getString("error.install.app.missing")); } setAppsDirectory(); if (getAppsDirectory().equalsIgnoreCase("apps") && !isApplicationConfigured()) { addAppConfiguration(artifact.getArtifactId()); } File destDir = new File(serverDirectory, getAppsDirectory()); log.info(MessageFormat.format(messages.getString("info.install.app"), artifact.getFile().getCanonicalPath())); Copy copyFile = (Copy) ant.createTask("copy"); copyFile.setFile(artifact.getFile()); if (stripVersion) { String file = stripVersionFromName(artifact.getFile().getCanonicalPath(), artifact.getVersion()); file = file.substring(file.lastIndexOf(File.separator) + 1); copyFile.setTofile(new File(destDir, file)); } else { copyFile.setTodir(destDir); } copyFile.execute(); }

Target:
protected void installApp(Artifact artifact) throws Exception { if (artifact.getFile() == null) { throw new MojoExecutionException(messages.getString("error.install.app.missing")); } String appsDir = getAppsDirectory(); if (appsDir.equalsIgnoreCase("apps") && !isAppConfigInTargetServerXml()) { String fileName = getApplicationFilename(); if (fileName != null && fileName.endsWith(".war")) { addAppConfiguration(fileName.substring(0, fileName.length() - 4), "war"); } } else if (appsDir.equalsIgnoreCase("dropins") && isAppConfigInTargetServerXml()) throw new MojoExecutionException(messages.getString("error.install.app.dropins.directory")); File destDir = new File(serverDirectory, appsDir); log.info(MessageFormat.format(messages.getString("info.install.app"), artifact.getFile().getCanonicalPath())); Copy copyFile = (Copy) ant.createTask("copy"); copyFile.setFile(artifact.getFile()); if (stripVersion) { String file = stripVersionFromName(artifact.getFile().getCanonicalPath(), artifact.getVersion()); file = file.substring(file.lastIndexOf(File.separator) + 1); copyFile.setTofile(new File(destDir, file)); } else { copyFile.setTodir(destDir); } copyFile.execute(); }
Source:
public AbstractPartitionDataStoreWriter(Configuration configuration, Path basePath, CodecInfo codec, PartitionStrategy<T, K> partitionStrategy) { super(); this.configuration = configuration; this.basePath = basePath; this.codec = codec; this.partitionStrategy = partitionStrategy; }

Target:
public AbstractPartitionDataStoreWriter(Configuration configuration, Path basePath, CodecInfo codec, PartitionStrategy<T, K> partitionStrategy) { super(); this.configuration = configuration; this.basePath = basePath; this.codec = codec; this.partitionStrategy = partitionStrategy; Assert.notNull(partitionStrategy, "Partition strategy must be set"); }
Source:
public ResponseEntity<String> getApplicantsByGroupID(@PathVariable String groupID) { try { resultBYGroupID = applicantService.getApplicantsInAGroup(groupID); } catch (GroupNotFoundException e) { String badRequest = jsonUtil.toJson("group not found"); return new ResponseEntity<>(badRequest, HttpStatus.BAD_REQUEST); } String response = jsonUtil.toJson(resultBYGroupID); return new ResponseEntity<>(response, HttpStatus.OK); }

Target:
public ResponseEntity<List<Applicant>> getApplicantsByGroupID(@PathVariable String groupID) { List<Applicant> resultBYGroupID = applicantService.getApplicantsByGroupID(groupID); if(resultBYGroupID.isEmpty() || resultBYGroupID == null){ return new ResponseEntity<>(resultBYGroupID, HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(resultBYGroupID, HttpStatus.OK); }
Source:
public Throwable handleError(RetrofitError cause) { Response response = cause.getResponse(); Collection<String> contentTypes = ImmutableSet.of(); for (Header header : response.getHeaders()) { if (header.getName().equals("Content-Type")) { contentTypes = ImmutableSet.of(header.getValue()); break; } } InputStream body; try { body = response.getBody().in(); } catch (IOException e) { return new RuntimeException("Cannot get input stream from response: " + e.getMessage(), e); } return SerializableErrorErrorDecoder.INSTANCE.decode(contentTypes, response.getStatus(), response.getReason(), body); }

Target:
public Throwable handleError(RetrofitError cause) { Response response = cause.getResponse(); Collection<String> contentTypes = ImmutableSet.of(); for (Header header : response.getHeaders()) { if (header.getName().equals("Content-Type")) { contentTypes = ImmutableSet.of(header.getValue()); break; } } InputStream body; try { body = response.getBody().in(); } catch (IOException e) { return new RuntimeException("Cannot get input stream from response: " + e.getMessage(), e); } return SerializableErrorToExceptionConverter.getException(contentTypes, response.getStatus(), response.getReason(), body); }
Source:
public void should_print_number_of_analyzed_classes() throws Exception { execute("report", "-classfiles", getClassPath()); assertOk(); assertContains("[INFO] Writing report with 14 classes.", out); }

Target:
public void should_print_number_of_analyzed_classes() throws Exception { execute("report", "--classfiles", getClassPath()); assertOk(); assertContains("[INFO] Analyzing 14 classes.", out); }
Source:
public int hashCode() { int result = id.hashCode(); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + model.hashCode(); result = 31 * result + fields.hashCode(); result = 31 * result + layoutTemplate.hashCode(); return result; }

Target:
public int hashCode() { int result = id.hashCode(); result = ~~result; result = 31 * result + (name != null ? name.hashCode() : 0); result = ~~result; result = 31 * result + model.hashCode(); result = ~~result; result = 31 * result + fields.hashCode(); result = ~~result; result = 31 * result + layoutTemplate.hashCode(); result = ~~result; return result; }
Source:
public synchronized void registerServer(BlobServer server) { log.info("Registering new blob server of class \"" + server.getClass().getName() + "\"."); servers.add(server); }

Target:
public void registerServer(BlobServer server) { log.info("Registering blob server of class \"" + server.getClass().getName() + "\"."); serverReference.set(server); }
Source:
public void testValidatePrimaryKeyColumns() { Schema pinotSchema; pinotSchema = new Schema.SchemaBuilder() .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "time"), new TimeGranularitySpec(DataType.INT, TimeUnit.DAYS, "time")).addSingleValueDimension("col", DataType.INT) .setPrimaryKeyColumns(Lists.newArrayList("test")).build(); checkValidationFails(pinotSchema); pinotSchema = new Schema.SchemaBuilder() .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "time"), new TimeGranularitySpec(DataType.INT, TimeUnit.DAYS, "time")).addSingleValueDimension("col", DataType.INT) .setPrimaryKeyColumns(Lists.newArrayList("time")).build(); checkValidationFails(pinotSchema); pinotSchema = new Schema.SchemaBuilder() .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "time"), new TimeGranularitySpec(DataType.INT, TimeUnit.DAYS, "time")).addSingleValueDimension("col", DataType.INT) .setPrimaryKeyColumns(Lists.newArrayList("col")).build(); checkValidationFails(pinotSchema); }

Target:
public void testValidatePrimaryKeyColumns() { Schema pinotSchema; pinotSchema = new Schema.SchemaBuilder() .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "incoming"), new TimeGranularitySpec(DataType.INT, TimeUnit.DAYS, "outgoing")).addSingleValueDimension("col", DataType.INT) .setPrimaryKeyColumns(Lists.newArrayList("test")).build(); checkValidationFails(pinotSchema); pinotSchema = new Schema.SchemaBuilder() .addTime(new TimeGranularitySpec(DataType.LONG, TimeUnit.MILLISECONDS, "incoming"), new TimeGranularitySpec(DataType.INT, TimeUnit.DAYS, "outgoing")).addSingleValueDimension("col", DataType.INT) .setPrimaryKeyColumns(Lists.newArrayList("col")).build(); SchemaUtils.validate(pinotSchema); }
Source:
public void testTagKeyById_404() throws Exception { server.enqueue(response404()); api.getTagApi().tagKeyById("tagKeyId"); assertSent(GET, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/tag/tagKey/tagKeyId"); }

Target:
public void testTagKeyById_404() throws Exception { server.enqueue(response404()); final TagKey tagKey = api.getTagApi().tagKeyById("tagKeyId"); assertSent(GET, "/caas/" + VERSION + "/6ac1e746-b1ea-4da5-a24e-caf1a978789d/tag/tagKey/tagKeyId"); assertNull(tagKey); }
Source:
void handleExpiredResource(SamzaResourceRequest request, SamzaResource resource, String preferredHost, ResourceRequestState resourceRequestState, ContainerAllocator allocator) { LOG.info("Allocated resource has been expired for Processor ID: request: re-requesting resource again", resource, request.getProcessorId(), request); resourceRequestState.releaseUnstartableContainer(resource, preferredHost); resourceRequestState.cancelResourceRequest(request); SamzaResourceRequest resourceRequest = allocator.getResourceRequest(request.getProcessorId(), request.getPreferredHost()); if (hasActiveContainerPlacementAction(request.getProcessorId())) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(request.getProcessorId()).get(); metadata.recordResourceRequest(resourceRequest); } allocator.issueResourceRequest(request); }

Target:
void handleExpiredResource(SamzaResourceRequest request, SamzaResource resource, String preferredHost, ResourceRequestState resourceRequestState, ContainerAllocator allocator) { LOG.info("Allocated resource has expired for Processor ID: request: {}. Re-requesting resource again", resource, request.getProcessorId(), request); resourceRequestState.releaseUnstartableContainer(resource, preferredHost); resourceRequestState.cancelResourceRequest(request); SamzaResourceRequest newResourceRequest = allocator.getResourceRequest(request.getProcessorId(), request.getPreferredHost()); if (hasActiveContainerPlacementAction(newResourceRequest.getProcessorId())) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(request.getProcessorId()).get(); metadata.recordResourceRequest(newResourceRequest); } allocator.issueResourceRequest(newResourceRequest); }
Source:
public PhoneNumber parsePhoneNumber(String numberText) { if (!StringUtils.isEmpty(numberText)) { if (numberText.startsWith("00")) { numberText = numberText.replaceFirst("00", "+"); } try { final PhoneNumber phoneNumber = PHONE_UTIL.parse(numberText, null); if (PHONE_UTIL.isValidNumber(phoneNumber)) { return phoneNumber; } } catch (NumberParseException e) { System.out.println("O n�mero n�o � v�lido:" + e); return null; } } return null; }

Target:
public PhoneNumber parsePhoneNumber(String numberText) { if (!StringUtils.isEmpty(numberText)) { if (numberText.startsWith("00")) { numberText = numberText.replaceFirst("00", "+"); } try { final PhoneNumber phoneNumber = PHONE_UTIL.parse(numberText, null); if (PHONE_UTIL.isValidNumber(phoneNumber)) { return phoneNumber; } } catch (NumberParseException e) { return null; } } return null; }
Source:
private String buildOracleExportCommand() { String dbConnectionString = config.dbUsername + "/" + config.dbPassword + "@" + config.oracleSID; String colSeparator = getColSeparator(config.format); StringBuilder scriptContent = new StringBuilder(); scriptContent.append("set colsep " + "\"" + colSeparator + "\"" + "\n"); scriptContent.append("set linesize 10000" + "\n"); scriptContent.append("set newpage none" + "\n"); scriptContent.append("set wrap off" + "\n"); scriptContent.append("set pagesize 0" + "\n"); scriptContent.append("set heading off" + "\n"); scriptContent.append("spool on" + "\n"); scriptContent.append(validateQuery(config.queryToExecute) + "\n"); scriptContent.append("spool off" + "\n"); scriptContent.append("exit"); String tmpSqlScriptFile = config.tmpSQLScriptDirectory + "/tmpHydrator.sql"; String setPath = "export ORACLE_HOME=" + config.oracleHome + "; export ORACLE_SID=" + config.oracleSID + ";"; String tmpScriptCreationCommand = "echo '" + scriptContent.toString() + "' > " + tmpSqlScriptFile + ";"; String sqlPlusSpoolExecutionCommand = config.oracleHome + "/bin" + "/sqlplus -s " + dbConnectionString + " @" + tmpSqlScriptFile + " | sed 's/\\s*" + colSeparator + "\\s*/" + colSeparator + "/g';"; String tmpSpoolScriptRemovalCommand = "rm " + tmpSqlScriptFile + ""; return setPath + tmpScriptCreationCommand + sqlPlusSpoolExecutionCommand + tmpSpoolScriptRemovalCommand; }

Target:
private String buildOracleExportCommand() { String dbConnectionString = config.dbUsername + "/" + config.dbPassword + "@" + config.oracleSID; String colSeparator = getColSeparator(config.format); StringBuilder scriptContent = new StringBuilder(); scriptContent.append("set colsep " + "\"" + colSeparator + "\"" + "\n"); scriptContent.append("set linesize 32767" + "\n"); scriptContent.append("set newpage none" + "\n"); scriptContent.append("set wrap off" + "\n"); scriptContent.append("set trimspool on" + "\n"); scriptContent.append("set trimout on" + "\n"); scriptContent.append("set pagesize 0" + "\n"); scriptContent.append("set heading off" + "\n"); scriptContent.append("spool on" + "\n"); scriptContent.append(config.queryToExecute + "\n"); scriptContent.append("spool off" + "\n"); scriptContent.append("exit"); String setPath = "export ORACLE_HOME=" + config.oracleHome + "; export ORACLE_SID=" + config.oracleSID + ";"; String tmpScriptCreationCommand = "echo '" + scriptContent.toString() + "' > " + config.tmpSQLScriptFile + ";"; String sqlPlusSpoolExecutionCommand; if (Strings.isNullOrEmpty(config.commandToRun)) { sqlPlusSpoolExecutionCommand = config.oracleHome + "/bin" + "/sqlplus -s " + dbConnectionString + " @" + config.tmpSQLScriptFile; } else { sqlPlusSpoolExecutionCommand = config.commandToRun; } sqlPlusSpoolExecutionCommand += " | sed 's/\\s*" + colSeparator + "\\s*/" + colSeparator + "/g';"; String tmpSpoolScriptRemovalCommand = "rm " + config.tmpSQLScriptFile + ""; return setPath + tmpScriptCreationCommand + sqlPlusSpoolExecutionCommand + tmpSpoolScriptRemovalCommand; }
Source:
public void testSharedPreferencesClearedOnLoggingFailed() { CrashReporter.storeUnhandledException(exception); assertTrue(!sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }

Target:
public void testSharedPreferencesClearedOnLoggingFailed() { CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
public static List<String> sanitizeListForCsv(List<String> strList) { List<String> sanitizedStrList = new ArrayList<>(); strList.forEach(string -> sanitizedStrList.add(sanitizeForCsv(string))); return sanitizedStrList; }

Target:
public static List<String> sanitizeListForCsv(List<String> strList) { return strList.stream().map(string -> sanitizeForCsv(string)) .collect(Collectors.toList()); }
Source:
public Locale getLocale() { return Locale.forLanguageTag(this.locale); }

Target:
public Locale getLocale() { return LanguageUtil.LOCALE_CACHE.getUnchecked(this.locale); }
Source:
public boolean canFlipToNextPage() { if (selectedDataObservable.getValue() == null || selectedDataObservable.getValue() instanceof Document) { return false; } return super.canFlipToNextPage(); }

Target:
public boolean canFlipToNextPage() { final Object data = selectedDataObservable.getValue(); if (data == null || data instanceof Document) { return false; } return super.canFlipToNextPage(); }
Source:
protected Guid lookupStorageDomainIdByName(String name) { List<storage_domains> storageDomains = getBackendCollection(storage_domains.class, VdcQueryType.GetAllStorageDomains, new VdcQueryParametersBase()); for (storage_domains storageDomain : storageDomains) { if (storageDomain.getstorage_name().equals(name)) { return storageDomain.getId(); } } return null; }

Target:
protected Guid lookupStorageDomainIdByName(String name) { if (!isFiltered()) { return getEntity(storage_domains.class, SearchType.StorageDomain, "Storage: name=" + name).getId(); } else { List<storage_domains> storageDomains = getBackendCollection(storage_domains.class, VdcQueryType.GetAllStorageDomains, new VdcQueryParametersBase()); for (storage_domains storageDomain : storageDomains) { if (storageDomain.getstorage_name().equals(name)) { return storageDomain.getId(); } } return null; } }
Source:
StringBuilder buildValidationResultSummary(List<ValidationResult> validationResults) { StringBuilder validationResultSummary = new StringBuilder(); validationResultSummary .append("Import validation results for ") .append(project.getName()) .append("\n\n"); if (validationResults.isEmpty()) { validationResultSummary.append("Invalid - ").append(NO_PACKAGE_IMPORTS_FOUND).append("\n"); } else { for (ValidationResult result : validationResults) { validationResultSummary.append(result).append("\n"); } } return validationResultSummary; }

Target:
StringBuilder buildValidationResultSummary(List<ValidationResult> validationResults) { StringBuilder validationResultSummary = new StringBuilder(); validationResultSummary .append("Import validation results for ") .append(project.getName()) .append("\n\n"); if (validationResults.isEmpty()) { validationResultSummary.append("Invalid - ").append(NO_PACKAGE_IMPORTS_FOUND).append("\n"); return validationResultSummary; } for (ValidationResult result : validationResults) { validationResultSummary.append(result).append("\n"); } return validationResultSummary; }
Source:
private static void checkUpdatesDelivery(boolean isConcurrent, BoundedContextAction... dispatchActions) { checkNotNull(dispatchActions); final Stand stand = mock(Stand.class); final Executor executor = isConcurrent ? Executors.newFixedThreadPool(Given.THREADS_COUNT_IN_POOL_EXECUTOR) : MoreExecutors.directExecutor(); final BoundedContext boundedContext = spy(Given.boundedContext(stand, executor)); for (BoundedContextAction dispatchAction : dispatchActions) { dispatchAction.perform(boundedContext); } verify(boundedContext, times(dispatchActions.length)).getStandFunnel(); if (isConcurrent) { try { ((ExecutorService) executor).awaitTermination(Given.SEVERAL, TimeUnit.SECONDS); } catch (InterruptedException ignore) { } } verify(stand, times(dispatchActions.length)).update(ArgumentMatchers.any(), any(Any.class)); }

Target:
private static void checkUpdatesDelivery(boolean isConcurrent, BoundedContextAction... dispatchActions) { checkNotNull(dispatchActions); final Stand stand = mock(Stand.class); final Executor executor = isConcurrent ? Executors.newFixedThreadPool(Given.THREADS_COUNT_IN_POOL_EXECUTOR) : MoreExecutors.directExecutor(); final BoundedContext boundedContext = spy(Given.boundedContext(stand, executor)); for (BoundedContextAction dispatchAction : dispatchActions) { dispatchAction.perform(boundedContext); } verify(boundedContext, times(dispatchActions.length)).getStandFunnel(); if (isConcurrent) { try { ((ExecutorService) executor).awaitTermination(Given.SEVERAL, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } } verify(stand, times(dispatchActions.length)).update(ArgumentMatchers.any(), any(Any.class)); }
Source:
void splitSegment(String processorName, int segmentId) { EventProcessor eventProcessor = getEventProcessor(processorName); if (!(eventProcessor instanceof TrackingEventProcessor)) { logger.info("Split segment requested for processor which is not a Tracking Event Processor"); return; } ((TrackingEventProcessor) eventProcessor).splitSegment(segmentId).whenComplete( (result, throwable) -> { if (throwable != null) { logger.error("Failed to split segment for processor [{}]", segmentId, processorName, throwable); return; } if (result) { logger.info("Successfully split segment of processor [{}]", segmentId, processorName); } else { logger.warn("Was not able to split segment for processor [{}]", segmentId, processorName); } } ); }

Target:
boolean splitSegment(String processorName, int segmentId) { EventProcessor eventProcessor = getEventProcessor(processorName); if (!(eventProcessor instanceof TrackingEventProcessor)) { logger.info("Split segment requested for processor which is not a Tracking Event Processor"); return false; } return ((TrackingEventProcessor) eventProcessor) .splitSegment(segmentId) .thenApply(result -> { if (result) { logger.info("Successfully split segment of processor [{}]", segmentId, processorName); } else { logger.warn("Was not able to split segment for processor [{}]", segmentId, processorName); } return result; }).join(); }
Source:
public static void addCheckStyleMessagesToBundle(ClassLoader checkStylePluginClassLoader) throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException, IOException { final Map<String, String> nameToModuleName = getModuleMapFromPackageObjectFactory(checkStylePluginClassLoader); addMessagesToCheckStyleBundleForLoadedChecks(nameToModuleName, checkStylePluginClassLoader); }

Target:
public static void addCheckStyleMessagesToBundle(ClassLoader checkStylePluginClassLoader) throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException, IOException { Map<String, String> nameToModuleName = getModuleMapFromPackageObjectFactory(checkStylePluginClassLoader); addMessagesToCheckStyleBundleForLoadedChecks(nameToModuleName, checkStylePluginClassLoader); }
Source:
public void updateJob(int type, Job job) { switch(type) { case JobConstants.JOB_ADDED: list_.addJob(job); if (job.show) bringToFront(); events_.fireEvent(new JobSelectionEvent(job.id, true, false)); break; case JobConstants.JOB_REMOVED: if (job.id == current_) { hideJobOutput(job.id, true); } list_.removeJob(job); break; case JobConstants.JOB_UPDATED: list_.updateJob(job); if (job.id == current_) { if (job.completed > 0 && progress_ != null) { progress_.setComplete(); } else { if (progress_ == null) { progress_ = new JobProgress(); toolbar_.addLeftWidget(progress_); } progress_.showProgress(new LocalJobProgress(job)); } } break; default: Debug.logWarning("Unrecognized job update type " + type); } }

Target:
public void updateJob(int type, Job job) { switch(type) { case JobConstants.JOB_ADDED: list_.addJob(job); if (job.show) { bringToFront(); events_.fireEvent(new JobSelectionEvent(job.id, true, false)); } break; case JobConstants.JOB_REMOVED: if (job.id == current_) { hideJobOutput(job.id, true); } list_.removeJob(job); break; case JobConstants.JOB_UPDATED: list_.updateJob(job); if (job.id == current_) { if (job.completed > 0 && progress_ != null) { progress_.setComplete(); } else { if (progress_ == null) { progress_ = new JobProgress(); toolbar_.addLeftWidget(progress_); } progress_.showProgress(new LocalJobProgress(job)); } } break; default: Debug.logWarning("Unrecognized job update type " + type); } }
Source:
private void storeBuffer(Database db, long offset, TypeMarshalBuffer buf, int maxInlineSize) throws CoreException { int len= buf.getPosition(); if (len > 0) { if (len <= maxInlineSize) { db.putBytes(offset, buf.getBuffer(), len); } else { db.putByte(offset, (byte) TypeMarshalBuffer.INDIRECT_TYPE); long chainOffset = offset + 1; buf.putInt(len); int lenSize = buf.getPosition() - len; int bufferPos = 0; while (bufferPos < len) { int chunkLength = bufferPos == 0 ? len + lenSize : len - bufferPos; boolean chainingRequired = false; if (chunkLength > Database.MAX_MALLOC_SIZE) { chunkLength = Database.MAX_MALLOC_SIZE; chainingRequired = true; } long ptr = db.malloc(chunkLength); db.putRecPtr(chainOffset, ptr); if (bufferPos == 0) { db.putBytes(ptr, buf.getBuffer(), len, lenSize); ptr += lenSize; chunkLength -= lenSize; } if (chainingRequired) { chainOffset = ptr; ptr += Database.PTR_SIZE; chunkLength -= Database.PTR_SIZE; } db.putBytes(ptr, buf.getBuffer(), bufferPos, chunkLength); bufferPos += chunkLength; } buf.setPosition(len); } } }

Target:
private void storeBuffer(Database db, long offset, TypeMarshalBuffer buf, int maxInlineSize) throws CoreException { int len= buf.getPosition(); if (len > 0) { if (len <= maxInlineSize) { db.putBytes(offset, buf.getBuffer(), len); } else { db.putByte(offset, TypeMarshalBuffer.INDIRECT_TYPE); long chainOffset = offset + 1; buf.putInt(len); int lenSize = buf.getPosition() - len; int bufferPos = 0; while (bufferPos < len) { int chunkLength = bufferPos == 0 ? len + lenSize : len - bufferPos; boolean chainingRequired = false; if (chunkLength > Database.MAX_MALLOC_SIZE) { chunkLength = Database.MAX_MALLOC_SIZE; chainingRequired = true; } long ptr = db.malloc(chunkLength); db.putRecPtr(chainOffset, ptr); if (bufferPos == 0) { db.putBytes(ptr, buf.getBuffer(), len, lenSize); ptr += lenSize; chunkLength -= lenSize; } if (chainingRequired) { chainOffset = ptr; ptr += Database.PTR_SIZE; chunkLength -= Database.PTR_SIZE; } db.putBytes(ptr, buf.getBuffer(), bufferPos, chunkLength); bufferPos += chunkLength; } buf.setPosition(len); } } }
Source:
public DetailViewPane(TimeLineController controller) { super(controller); Platform.runLater(() -> { VBox vBox = new VBox(getSpecificLabelPane(), getContextLabelPane()); vBox.setFillWidth(false); HBox hBox = new HBox(getSpacer(), vBox); hBox.setFillHeight(false); setBottom(hBox); DoubleBinding spacerSize = getYAxis().widthProperty().add(getYAxis().tickLengthProperty()).add(getAxisMargin()); getSpacer().minWidthProperty().bind(spacerSize); getSpacer().prefWidthProperty().bind(spacerSize); getSpacer().maxWidthProperty().bind(spacerSize); }); this.selectedEvents = new MappedList<>(getSelectedNodes(), EventNodeBase<?>::getEvent); setChart(new DetailsChart(controller, detailsChartDateAxis, pinnedDateAxis, verticalAxis, getSelectedNodes())); setSettingsNodes(new DetailViewSettingsPane(getChart().getLayoutSettings()).getChildrenUnmodifiable()); detailsChartDateAxis.getTickMarks().addListener((Observable observable) -> layoutDateLabels()); detailsChartDateAxis.getTickSpacing().addListener(observable -> layoutDateLabels()); verticalAxis.setAutoRanging(false); getSelectedNodes().addListener((Observable observable) -> { getChart().setHighlightPredicate(getSelectedNodes()::contains); getController().selectEventIDs(getSelectedNodes().stream() .flatMap(detailNode -> detailNode.getEventIDs().stream()) .collect(Collectors.toList())); }); }

Target:
public DetailViewPane(TimeLineController controller) { super(controller); this.selectedEvents = new MappedList<>(getSelectedNodes(), EventNodeBase<?>::getEvent); setChart(new DetailsChart(controller, detailsChartDateAxis, pinnedDateAxis, verticalAxis, getSelectedNodes())); setSettingsNodes(new DetailViewSettingsPane(getChart().getLayoutSettings()).getChildrenUnmodifiable()); detailsChartDateAxis.getTickMarks().addListener((Observable observable) -> layoutDateLabels()); detailsChartDateAxis.getTickSpacing().addListener(observable -> layoutDateLabels()); verticalAxis.setAutoRanging(false); getSelectedNodes().addListener((Observable observable) -> { getChart().setHighlightPredicate(getSelectedNodes()::contains); getController().selectEventIDs(getSelectedNodes().stream() .flatMap(detailNode -> detailNode.getEventIDs().stream()) .collect(Collectors.toList())); }); }
Source:
public HierarchyElementView(Context context, HierarchyElement it) { super(context); RelativeLayout layout = (RelativeLayout) inflate(context, R.layout.hierarchy_element_view, null); layout.setBackgroundColor(it.getColor()); mPrimaryTextView = ((TextView)layout.findViewById(R.id.hev_primary_text)); mPrimaryTextView.setText(it.getPrimaryText()); mSecondaryTextView = ((TextView)layout.findViewById(R.id.hev_secondary_text)); mSecondaryTextView.setText(it.getSecondaryText()); mIcon = ((ImageView)layout.findViewById(R.id.hev_icon)); mIcon.setImageDrawable(it.getIcon()); addView(layout); if (BuildConfig.DEBUG) { Log.i("HEVTYPE", "Type of HEV (" + hashCode() + ") is " + it.getType()); Log.i("HEVTYPE", "Icon of HEV (" + hashCode() + ") is " + (it.getIcon() == null ? "null" : it.getIcon().toString())); } }

Target:
public HierarchyElementView(Context context, HierarchyElement it) { super(context); RelativeLayout layout = (RelativeLayout) inflate(context, R.layout.hierarchy_element_view, null); layout.setBackgroundColor(it.getColor()); mPrimaryTextView = ((TextView)layout.findViewById(R.id.hev_primary_text)); mPrimaryTextView.setText(it.getPrimaryText()); mSecondaryTextView = ((TextView)layout.findViewById(R.id.hev_secondary_text)); mSecondaryTextView.setText(it.getSecondaryText()); mIcon = ((ImageView)layout.findViewById(R.id.hev_icon)); mIcon.setImageDrawable(it.getIcon()); addView(layout); if (BuildConfig.DEBUG) { Log.i(TAG, "Type of HEV (" + hashCode() + ") is " + it.getType()); Log.i(TAG, "Icon of HEV (" + hashCode() + ") is " + (it.getIcon() == null ? "null" : it.getIcon().toString())); } }
Source:
public void setDigestAlgorithm(String digestAlgorithm) throws NoSuchAlgorithmException { throw new IllegalStateException("Not implemented"); }

Target:
public void setDigestAlgorithm(String digestAlgorithm) { throw new IllegalStateException("Not implemented"); }
Source:
public String toString(String format) { StringBuilder sb = new StringBuilder(); sb.append(super.toString(format)); sb.append(String.format(format, "hubConfig", hubConfig)); sb.append(toString(format, "jettyMaxThreads", jettyMaxThreads)); sb.append(toString(format, "capabilityMatcher", capabilityMatcher.getClass().getCanonicalName())); sb.append(toString(format, "newSessionWaitTimeout", newSessionWaitTimeout)); sb.append(toString(format, "prioritizer", prioritizer != null? prioritizer.getClass().getCanonicalName(): null)); sb.append(toString(format, "throwOnCapabilityNotPresent", throwOnCapabilityNotPresent)); return sb.toString(); }

Target:
public String toString(String format) { StringBuilder sb = new StringBuilder(); sb.append(super.toString(format)); sb.append(toString(format, "hubConfig", hubConfig)); sb.append(toString(format, "jettyMaxThreads", jettyMaxThreads)); sb.append(toString(format, "capabilityMatcher", capabilityMatcher.getClass().getCanonicalName())); sb.append(toString(format, "newSessionWaitTimeout", newSessionWaitTimeout)); sb.append(toString(format, "prioritizer", prioritizer != null? prioritizer.getClass().getCanonicalName(): null)); sb.append(toString(format, "throwOnCapabilityNotPresent", throwOnCapabilityNotPresent)); return sb.toString(); }
Source:
public ApprovedWhitelist() throws IOException { try { reconfigure(); } catch (IOException e) { LOG.log(Level.SEVERE, "Malformed signature entry in scriptApproval.xml: '" + e.getMessage() + "'"); throw e; } }

Target:
public ApprovedWhitelist() { try { reconfigure(); } catch (IOException e) { LOG.log(Level.SEVERE, "Malformed signature entry in scriptApproval.xml: '" + e.getMessage() + "'"); } }
Source:
public void testCreateOrReplaceWithoutDeleteExisting() { server.expect().get().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200 , service).once(); server.expect().get().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/services").andReturn(200, service).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/configmaps").andReturn(200, configMap).once(); KubernetesClient client = server.getClient(); KubernetesList list = new KubernetesListBuilder().withItems(service, configMap).build(); client.resourceList(list).inNamespace("ns1").createOrReplace(); }

Target:
public void testCreateOrReplaceWithoutDeleteExisting() throws Exception { server.expect().get().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200 , service).times(2); server.expect().get().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).times(2); server.expect().put().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200, updatedService).once(); server.expect().put().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, updatedConfigMap).once(); KubernetesClient client = server.getClient(); KubernetesList list = new KubernetesListBuilder().withItems(updatedService, updatedConfigMap).build(); client.resourceList(list).inNamespace("ns1").createOrReplace(); assertEquals(6, server.getMockServer().getRequestCount()); RecordedRequest request = server.getLastRequest(); assertEquals("/api/v1/namespaces/ns1/configmaps/my-configmap", request.getPath()); assertEquals("PUT", request.getMethod()); }
Source:
public void onBindViewHolder(HistoryScanHolder holder, int position) { holder.txtTitle.setText(list.get(position).getTitle()); holder.txtBarcode.setText(list.get(position).getBarcode()); holder.txtBrands.setText(list.get(position).getBrands()); holder.imgProduct.setImageBitmap(list.get(position).getUrl()); Date date = list.get(position).getTime(); long time = date.getTime(); String timeStamp = String.valueOf(DateUtils.getRelativeTimeSpanString(time,System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS,DateUtils.FORMAT_ABBREV_RELATIVE)); holder.txtDate.setText(timeStamp); }

Target:
public void onBindViewHolder(HistoryScanHolder holder, int position) { holder.txtTitle.setText(list.get(position).getTitle()); holder.txtBarcode.setText(list.get(position).getBarcode()); holder.txtBrands.setText(list.get(position).getBrands()); holder.imgProduct.setImageBitmap(list.get(position).getUrl()); Date date = list.get(position).getTime(); calcTime(date, holder); }
Source:
public void toXmlTest() throws IOException, XmlPullParserException, SmackParsingException { String xml = "<tune xmlns='<LINK_0>'>" + "<artist>Yes</artist>" + "<length>686</length>" + "<rating>8</rating>" + "<source>Yessongs</source>" + "<title>Heart of the Sunrise</title>" + "<track>3</track>" + "<uri><LINK_1></uri>" + "</tune>"; URI uri = null; try { uri = new URI("<LINK_1>"); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI"); } UserTuneElement.Builder builder = UserTuneElement.getBuilder(); UserTuneElement userTuneElement = builder.setArtist("Yes") .setLength(686) .setRating(8) .setSource("Yessongs") .setTitle("Heart of the Sunrise") .setTrack(3) .setUri(uri) .build(); assertXmlSimilar(xml, userTuneElement.toXML().toString()); XmlPullParser parser = TestUtils.getParser(xml); UserTuneElement parsed = UserTuneProvider.INSTANCE.parse(parser); assertEquals(xml, parsed.toXML().toString()); }

Target:
public void toXmlTest() throws IOException, XmlPullParserException, SmackParsingException, URISyntaxException { URI uri = new URI("<LINK_1>"); UserTuneElement.Builder builder = UserTuneElement.getBuilder(); UserTuneElement userTuneElement = builder.setArtist("Yes") .setLength(686) .setRating(8) .setSource("Yessongs") .setTitle("Heart of the Sunrise") .setTrack("3") .setUri(uri) .build(); assertXmlSimilar(xml, userTuneElement.toXML().toString()); }
Source:
private PartitionId getPartitionForPut() throws CoordinatorException { if (clusterMap.getWritablePartitionIdsCount() < 1) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } long index = getRandomLong(random, clusterMap.getWritablePartitionIdsCount()); return clusterMap.getWritablePartitionIdAt(index); }

Target:
private PartitionId getPartitionForPut() throws CoordinatorException { if (clusterMap.getWritablePartitionIdsCount() < 1) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } long index = getRandomLong(randomForPartitionSelection, clusterMap.getWritablePartitionIdsCount()); return clusterMap.getWritablePartitionIdAt(index); }
Source:
private void applyEdits(ServiceFeatureTable featureTable) { ListenableFuture<List<FeatureEditResult>> editResults = featureTable.applyEditsAsync(); editResults.addDoneListener(() -> { try { if (editResults.get().iterator().hasNext()) { FeatureEditResult edit = editResults.get().iterator().next(); if (!edit.hasCompletedWithErrors()) { logToUser(false, getString(R.string.success_feature_deleted)); } else { throw edit.getError(); } } } catch (InterruptedException | ExecutionException e) { logToUser(true, getString(R.string.error_applying_edits, e.getCause().getMessage())); } }); }

Target:
private void applyEdits(ServiceFeatureTable featureTable) { ListenableFuture<List<FeatureEditResult>> featureEditsFuture = featureTable.applyEditsAsync(); featureEditsFuture.addDoneListener(() -> { try { if (featureEditsFuture.get().iterator().hasNext()) { FeatureEditResult edit = featureEditsFuture.get().iterator().next(); if (!edit.hasCompletedWithErrors()) { logToUser(false, getString(R.string.success_feature_deleted)); } else { throw edit.getError(); } } } catch (InterruptedException | ExecutionException e) { logToUser(true, getString(R.string.error_applying_edits, e.getCause().getMessage())); } }); }
Source:
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; int x1,y1,x2,y2; int cx,cy; x1 = (windowWidth - boardSize)/2; y1 = 20; x2 = x1 + boardSize; y2 = y1 + boardSize; cx = (x1 + x2)/2; cy = (y1 + y2)/2; cellSize = (x2 - x1) / numCells; g2.setPaint(new Color(255, 255, 255)); g2.fillRect(x1, y1, x2-x1, y2-y1); for (int i = -(numCells-1)/2; i <= (numCells-1)/2; i++) for (int j = -(numCells-1)/2; j <= (numCells-1)/2; j++) DrawCell(g2, cx + i*cellSize, cy + j*cellSize, xCenterCell + i, yCenterCell + j); }

Target:
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; int x1,y1,x2,y2; int cx,cy; x1 = (windowWidth - boardSize)/2; y1 = topPadding; x2 = x1 + boardSize; y2 = y1 + boardSize; cx = (x1 + x2)/2; cy = (y1 + y2)/2; cellSize = (x2 - x1) / numCells; g2.setPaint(new Color(255, 255, 255)); g2.fillRect(x1, y1, x2-x1, y2-y1); for (int i = -(numCells-1)/2; i <= (numCells-1)/2; i++) for (int j = -(numCells-1)/2; j <= (numCells-1)/2; j++) DrawCell(g2, cx + i*cellSize, cy + j*cellSize, xCenterCell + i, yCenterCell + j); }