auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Iterable<Integer> parseNumberList(String numberList) throws IllegalArgumentException { Assert.hasText(numberList, "must contain a list of values"); Set<Integer> numbers = new TreeSet<Integer>(); String[] numbersOrRanges = numberList.split(","); for (String numberOrRange : numbersOrRanges) { if (numberOrRange.contains("-")) { String[] split = numberOrRange.split("-"); Integer start = Integer.parseInt(split[0]); Integer end = Integer.parseInt(split[1]); if (start >= end) { throw new IllegalArgumentException(String.format("A range contains a start which is after the end: %d-%d", start, end)); } for (int i = start; i <= end; i++) { numbers.add(i); } } else { numbers.add(Integer.parseInt(numberOrRange)); } } return Collections.unmodifiableSet(numbers); }

Target:
public static Iterable<Integer> parseNumberList(String numberList) throws IllegalArgumentException { Assert.hasText(numberList, "must contain a list of values"); Assert.isTrue(PARTITION_LIST_VALIDATION_REGEX.matcher(numberList).matches(),"is not a list of numbers or ranges"); Set<Integer> numbers = new TreeSet<Integer>(); String[] numbersOrRanges = numberList.split(","); for (String numberOrRange : numbersOrRanges) { if (numberOrRange.contains("-")) { String[] split = numberOrRange.split("-"); Integer start = Integer.parseInt(split[0]); Integer end = Integer.parseInt(split[1]); if (start >= end) { throw new IllegalArgumentException(String.format("A range contains a start which is after the end: %d-%d", start, end)); } for (int i = start; i <= end; i++) { numbers.add(i); } } else { numbers.add(Integer.parseInt(numberOrRange)); } } return Collections.unmodifiableSet(numbers); }
Source:
public boolean loadGestures(String directory) { File dir = makeGesturesDirectory(directory); boolean loaded = true; for (File f : dir.listFiles()) { loaded = Utils.loadPythonFile(f.getAbsolutePath()); } return true; }

Target:
public void loadGestures(String directory) { String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = makeGesturesDirectory(directory); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (Utils.loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; gesturesList.add(f.getName()); } else { totalError += 1; } } else { log.warn("{} is not a file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); }
Source:
public String getCleanNodeName(boolean specialNodesAsRegex) { String name = this.getNodeName(); if (specialNodesAsRegex && this.isDataDriven()) { name = "(.+?)"; } else if (this.isLeaf()) { int colonIndex = name.indexOf(":"); if (colonIndex > 0) { name = name.substring(colonIndex + 1); } int bracketIndex = name.lastIndexOf("("); if (bracketIndex > 0) { name = name.substring(0, bracketIndex); } int questIndex = name.indexOf("?"); if (questIndex > 0) { name = name.substring(0, questIndex); } } return name; }

Target:
public String getCleanNodeName(boolean specialNodesAsRegex) { String name = this.getNodeName(); if (specialNodesAsRegex && this.isDataDriven()) { name = "(.+?)"; } else if (this.isLeaf()) { int colonIndex = name.indexOf(":"); if (colonIndex > 0) { name = name.substring(colonIndex + 1); } int bracketIndex = name.lastIndexOf("("); if (bracketIndex > 0) { name = name.substring(0, bracketIndex); } int queryIndex = name.indexOf("?"); if (queryIndex > 0) { name = name.substring(0, queryIndex); } } return name; }
Source:
public static String toString(Iterable<CypherAstBase> expressions) { return stream(expressions) .map(e -> e == null ? "null" : "") .map(Object::toString) .collect(Collectors.joining(", ")); }

Target:
public static String toString(Iterable<CypherAstBase> expressions) { return stream(expressions) .map(e -> e == null ? "null" : e) .map(Object::toString) .collect(Collectors.joining(", ")); }
Source:
public void removeFacilityContact(PerunSession sess, Facility facility, String name, Owner owner) throws InternalErrorException { try { ContactGroup contactGroup = getFacilityContactGroup(sess, facility, name); sess.getPerun().getAuditer().log(sess, "User/Owner (" + owner.getId() + ") removed from contact group " + contactGroup.toString() + "."); jdbc.update("delete from facility_contacts where facility_id=? and owner_id=? and name=?", facility.getId(), owner.getId(), name); log.info("Facility contact deleted. Facility: {}, ContactName: {}, Owner: " + owner, facility, name); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } catch (FacilityContactNotExistsException ex) { log.error("Facility contact for facility " + facility + " and user/owner " + owner + " was not found."); } }

Target:
public void removeFacilityContact(PerunSession sess, Facility facility, String name, Owner owner) throws InternalErrorException { try { jdbc.update("delete from facility_contacts where facility_id=? and owner_id=? and name=?", facility.getId(), owner.getId(), name); log.info("Facility contact deleted. Facility: {}, ContactName: {}, Owner: " + owner, facility, name); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); List<VM> vms = LinqUtils.filter(vmsFromDB, new Predicate<VM>() { @Override public boolean eval(VM v) { return v.getMigrationSupport().allowsMigration() && (!v.getMigrationSupport().limitsMigration() || v.getDedicatedVmForVdsList().size() >= 2); } }); return vms; }

Target:
private List<VM> getMigratableVmsRunningOnVds(final VmDao vmDao, final Guid hostId) { List<VM> vmsFromDB = vmDao.getAllRunningForVds(hostId); List<VM> vms = LinqUtils.filter(vmsFromDB, new Predicate<VM>() { @Override public boolean eval(VM v) { return v.getMigrationSupport().allowsMigration() && (v.getMigrationSupport().migrateAnywhere() || v.getDedicatedVmForVdsList().size() >= 2); } }); return vms; }
Source:
public LwjglCanvasRenderer(Context context) { try { this.textureMat = Assets.getMaterial("engine:UITexture").get(); } catch (java.util.NoSuchElementException noSuch) { throw new RuntimeException("Failing to find engine textures", noSuch); } this.billboard = Assets.getMesh("engine:UIBillboard").get(); this.fontMeshBuilder = new FontMeshBuilder(context.get(AssetManager.class).getAsset("engine:UIUnderline", Material.class).get()); this.renderingConfig = context.get(Config.class).getRendering(); this.uiScale = this.renderingConfig.getUiScale() / 100f; this.renderingConfig.subscribe(RenderingConfig.UI_SCALE, this); }

Target:
public LwjglCanvasRenderer(Context context) { this.textureMat = Assets.getMaterial("engine:UITexture").orElseThrow( () -> new RuntimeException("Failing to find engine textures")); this.billboard = Assets.getMesh("engine:UIBillboard").get(); this.fontMeshBuilder = new FontMeshBuilder(context.get(AssetManager.class).getAsset("engine:UIUnderline", Material.class).get()); this.renderingConfig = context.get(Config.class).getRendering(); this.uiScale = this.renderingConfig.getUiScale() / 100f; this.renderingConfig.subscribe(RenderingConfig.UI_SCALE, this); }
Source:
public VariantAnnotation getAnnotation(String variant) { boolean storeVariantJson = true; VariantAnnotation variantAnnotation = null; String annotationJSON = null; try { variantAnnotation = variantAnnotationRepository.findOne(variant); } catch (DataAccessResourceFailureException e) { LOG.warn("Failed to read from Mongo database - falling back on Ensembl server. Will not attempt to store variant in Mongo database."); storeVariantJson = false; } if (variantAnnotation == null) { try { annotationJSON = this.getRawAnnotation(variant); variantAnnotation = this.mapAnnotationJson(variant, annotationJSON); if (storeVariantJson) { try { variantAnnotationRepository.saveAnnotationJson(variant, annotationJSON); } catch (DataIntegrityViolationException e) { LOG.info(e.getLocalizedMessage()); } } } catch (HttpClientErrorException e) { variantAnnotation = new VariantAnnotation(variant, e.getResponseBodyAsString()); } catch (IOException e) { variantAnnotation = new VariantAnnotation(variant, annotationJSON); } } return variantAnnotation; }

Target:
public VariantAnnotation getAnnotation(String variant) { boolean saveAnnotationJson = true; VariantAnnotation variantAnnotation = null; String annotationJSON = null; try { variantAnnotation = variantAnnotationRepository.findOne(variant); } catch (DataAccessResourceFailureException e) { LOG.warn("Failed to read from Mongo database - falling back on Ensembl server. Will not attempt to store variant in Mongo database."); saveAnnotationJson = false; } if (variantAnnotation == null) { try { annotationJSON = this.getRawAnnotation(variant); variantAnnotation = this.mapAnnotationJson(variant, annotationJSON); if (saveAnnotationJson) { variantAnnotationRepository.saveAnnotationJson(variant, annotationJSON); } } catch (HttpClientErrorException e) { variantAnnotation = new VariantAnnotation(variant, e.getResponseBodyAsString()); } catch (IOException e) { variantAnnotation = new VariantAnnotation(variant, annotationJSON); } catch (DataIntegrityViolationException e) { LOG.info(e.getLocalizedMessage()); } } return variantAnnotation; }
Source:
protected Map<CaseInsensitiveString, StringBuilder> validate(SecretParams secretParams, Class<? extends Validatable> entityClass, String entityName, String entityNameOrErrorMessagePrefix) { HashMap<CaseInsensitiveString, StringBuilder> pipelinesWithErrors = new HashMap<>(); secretParams .groupBySecretConfigId() .forEach((secretConfigId, secretParam) -> { SecretConfig secretConfig = goConfigService.getSecretConfigById(secretConfigId); if (secretConfig == null) { addError(pipelinesWithErrors, new CaseInsensitiveString(entityName), format("%s '%s' is referring to none-existent secret config '%s'.", entityNameOrErrorMessagePrefix, entityName, secretConfigId)); } else if (!secretConfig.canRefer(entityClass, entityName)) { addError(pipelinesWithErrors, new CaseInsensitiveString(entityName), format("%s '%s' does not have permission to refer to secrets using secret config '%s'.", entityNameOrErrorMessagePrefix, entityName, secretConfigId)); } }); return pipelinesWithErrors; }

Target:
protected Map<CaseInsensitiveString, StringBuilder> validate(SecretParams secretParams, Class<? extends Validatable> entityClass, String entityName, String entityNameOrErrorMessagePrefix) { Map<CaseInsensitiveString, StringBuilder> pipelinesWithErrors = new HashMap<>(); secretParams .groupBySecretConfigId() .forEach((secretConfigId, secretParam) -> { SecretConfig secretConfig = goConfigService.getSecretConfigById(secretConfigId); if (secretConfig == null) { addError(pipelinesWithErrors, new CaseInsensitiveString(entityName), format("%s '%s' is referring to none-existent secret config '%s'.", entityNameOrErrorMessagePrefix, entityName, secretConfigId)); } else if (!secretConfig.canRefer(entityClass, entityName)) { addError(pipelinesWithErrors, new CaseInsensitiveString(entityName), format("%s '%s' does not have permission to refer to secrets using secret config '%s'.", entityNameOrErrorMessagePrefix, entityName, secretConfigId)); } }); return pipelinesWithErrors; }
Source:
private void cleanupExportWorkDirs(File baseDir, int maxAgeInMinutes) { long dirCount = 0; long delCount = 0; long leftCount = 0; Date cutOff = Util.addMinutesToDt(maxAgeInMinutes * -1); if (baseDir.listFiles() != null) { dirCount = baseDir.listFiles().length; for (File f : baseDir.listFiles()) { if (f.lastModified() < cutOff.getTime()) { try { FileUtils.deleteDirectory(f); delCount++; } catch (IOException io) { log.error("Unable to delete export directory that is old enough " + "to delete", io); } } else { leftCount++; } } } log.info("Begining directory count: " + dirCount); log.info("Directories deleted: " + delCount); log.info("Directories remaining: " + leftCount); }

Target:
private void cleanupExportWorkDirs(File baseDir, int maxAgeInMinutes) { long dirCount = 0; long delCount = 0; long leftCount = 0; Date cutOff = Util.addMinutesToDt(maxAgeInMinutes * -1); if (baseDir.listFiles() != null) { dirCount = baseDir.listFiles().length; for (File f : baseDir.listFiles()) { if (f.lastModified() < cutOff.getTime()) { try { FileUtils.deleteDirectory(f); delCount++; } catch (IOException io) { String errorMsg = String.format("Unable to delete export directory that is old " + "enough to delete: %s", f.getAbsolutePath()); log.error(errorMsg, io); } } else { leftCount++; } } } log.info("Begining directory count: {}", dirCount); log.info("Directories deleted: {}", delCount); log.info("Directories remaining: {}", leftCount); }
Source:
public SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry) { return new EventHubSystemProducer(systemName, new EventHubConfig(config, systemName), registry); }

Target:
public SystemProducer getProducer(String systemName, Config config, MetricsRegistry registry) { EventHubConfig eventHubConfig = new EventHubConfig(config); return new EventHubSystemProducer(eventHubConfig, systemName, new EventHubClientManagerFactory(), getInterceptorsMap(eventHubConfig, systemName), registry); }
Source:
public void testBulkWrites(){ for(int i=0 ; i<10; i++) testCache.put("test"+i, "test"+i); Map<String, String> entries = new HashMap<String, String>(10); Set<String> keys = new HashSet<String>(10); for(int i=10 ; i<20; i++) { entries.put("test"+i, "test"+i); keys.add("test"+i); } testCache.putAll(entries); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(loaderWriter.getData().size(), is(20)); testCache.removeAll(keys); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(loaderWriter.getData().size(), is(10)); }

Target:
public void testBulkWrites() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(20); loaderWriter.setLatch(countDownLatch); for(int i=0 ; i<10; i++) testCache.put("test"+i, "test"+i); Map<String, String> entries = new HashMap<String, String>(10); Set<String> keys = new HashSet<String>(10); for(int i=10 ; i<20; i++) { entries.put("test"+i, "test"+i); keys.add("test"+i); } testCache.putAll(entries); countDownLatch.await(5, TimeUnit.SECONDS); assertThat(loaderWriter.getData().size(), is(20)); CountDownLatch countDownLatch1 = new CountDownLatch(10); loaderWriter.setLatch(countDownLatch1); testCache.removeAll(keys); countDownLatch1.await(5, TimeUnit.SECONDS); assertThat(loaderWriter.getData().size(), is(10)); }
Source:
public void handleLogAddressSpaceRequest(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { log.trace("handleLogAddressSpaceRequest[{}]: received a log " + "address space request {}", req.getHeader().getRequestId(), TextFormat.shortDebugString(req)); batchWriter.<StreamsAddressResponse>addTask(BatchWriterOperation.Type.LOG_ADDRESS_SPACE_QUERY, req) .thenAccept(resp -> { r.sendResponse(getResponseMsg(req.getHeader(), getLogAddressSpaceResponseMsg( resp.getLogTail(), resp.getEpoch(), resp.getAddressMap())), ctx); }).exceptionally(ex -> { handleException(ex, ctx, req, r); return null; }); }

Target:
public void handleLogAddressSpaceRequest(RequestMsg req, ChannelHandlerContext ctx, IServerRouter r) { if (log.isTraceEnabled()) { log.trace("handleLogAddressSpaceRequest[{}]: received a log " + "address space request {}", req.getHeader().getRequestId(), TextFormat.shortDebugString(req)); } batchWriter.<StreamsAddressResponse>addTask(BatchWriterOperation.Type.LOG_ADDRESS_SPACE_QUERY, req) .thenAccept(resp -> { r.sendResponse(getResponseMsg(req.getHeader(), getLogAddressSpaceResponseMsg( resp.getLogTail(), resp.getEpoch(), resp.getAddressMap())), ctx); }).exceptionally(ex -> { handleException(ex, ctx, req, r); return null; }); }
Source:
public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { NativeImageLoader loader = new NativeImageLoader(224, 224, 3); INDArray image = loader.asMatrix(stream); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = model.output(false, image); String modelOutput = TrainedModels.VGG16.decodePredictions(output[0]); modelOutput = modelOutput.replace("Predictions for batch :\n", ""); modelOutput = modelOutput.replace("%", ""); String objs[] = modelOutput.split("\n"); List<RecognisedObject> objects = new ArrayList<>(); for (String obj : objs) { String data[]; data = obj.split(","); double confidence = Double.parseDouble(data[0]); objects.add(new RecognisedObject(data[1].trim(), "eng", data[1].trim(), confidence)); } return objects; }

Target:
public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { INDArray image = imageLoader.asMatrix(stream); preProcessor.transform(image); INDArray[] output = model.output(false, image); return predict(output[0]); }
Source:
public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); try { Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } }

Target:
public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); return Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); }
Source:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 300: return; case 400: break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } command.setException(exception); }

Target:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 300: if (command.getCurrentRequest().getFirstHeaderOrNull(ZoneToEndpointNegotiateVersion.VERSION_NEGOTIATION_HEADER) != null) { return; } break; case 400: break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } command.setException(exception); }
Source:
public Queue replies() { return new AnonymousQueue(new AnonymousQueue.Base64UrlNamingStrategy()); }

Target:
public Queue replies() { return new AnonymousQueue(); }
Source:
private void addTags( List<Tag> tags ) { this.reportModel.addTags( tags ); this.scenarioModel.addTags( tags ); }

Target:
private void addTags( List<Tag> tags ) { if( tags.isEmpty() ) { return; } if( reportModel != null ) { this.reportModel.addTags( tags ); } if( scenarioModel != null ) { this.scenarioModel.addTags( tags ); } }
Source:
public void InteractiveMaps_031_PalantirSetPlayerPositionOutOfMap() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); selectedMap.openMap(wikiURL, 3); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(9300, 15000, 3, true); poi.verifyWrongPlayerPos(handle.success, handle.responseCode, handle.message); poi.verifyPoiNotAppearOnMap(); }

Target:
public void InteractiveMaps_031_PalantirSetPlayerPositionOutOfMap() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(9300, 15000, 3, true); poi.verifyWrongPlayerPos(handle); poi.verifyPoiNotAppearOnMap(); }
Source:
public void run() { ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); if (!(sysLoader instanceof URLClassLoader)) { return; } File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, file.toURI().toURL()); } catch (ReflectiveOperationException | MalformedURLException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }

Target:
public void run() { if (nonUrlClassLoader) { return; } ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); if (!(sysLoader instanceof URLClassLoader)) { nonUrlClassLoader = true; GlowServer.logger.severe("This JVM isn't fully supported. Please use Oracle or" + " OpenJDK 8, not 9. (System class loader must be a URLClassLoader.)"); return; } File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, file.toURI().toURL()); } catch (ReflectiveOperationException | MalformedURLException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }
Source:
private MultiMap<Class<?>, AnalyticalTask<?>> determineTasks() { MultiMap<Class<?>, AnalyticalTask<?>> result = MultiMap.create(); context.getParts((Class<AnalyticalTask<?>>) getAnalyticalTaskType()).forEach(task -> { if (isMatchingEntityType(task)) { result.put(task.getType(), task); } }); return result; }

Target:
private MultiMap<Class<?>, AnalyticalTask<?>> determineTasks() { MultiMap<Class<?>, AnalyticalTask<?>> result = MultiMap.create(); context.getParts((Class<AnalyticalTask<?>>) getAnalyticalTaskType()) .stream() .filter(this::isMatchingEntityType) .forEach(task -> result.put(task.getType(), task)); return result; }
Source:
public void expectedInitialParameters() throws Exception { TimeZone.setDefault(tzPlus0800); con = TestUtil.openDB(); Map<String,String> params = ((PGConnection)con).getParameterStatuses(); Assert.assertEquals("UTF8", params.get("client_encoding")); Assert.assertNotNull(params.get("DateStyle")); Assert.assertTrue(params.get("DateStyle").startsWith("ISO")); Assert.assertEquals("GMT-08:00", params.get("TimeZone")); Assert.assertNotNull(params.get("integer_datetimes")); Assert.assertNotNull(params.get("is_superuser")); Assert.assertNotNull(params.get("server_encoding")); Assert.assertNotNull(params.get("server_version")); Assert.assertNotNull(params.get("session_authorization")); Assert.assertNotNull(params.get("standard_conforming_strings")); if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) { Assert.assertNotNull(params.get("IntervalStyle")); } else { Assert.assertNull(params.get("IntervalStyle")); } if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) { Assert.assertEquals("Driver Tests", params.get("application_name")); } else { Assert.assertNull(params.get("application_name")); } Assert.assertNull(params.get("nonexistent")); Assert.assertNull(params.get("enable_hashjoin")); TestUtil.closeDB(con); }

Target:
public void expectedInitialParameters() throws Exception { TimeZone.setDefault(tzPlus0800); con = TestUtil.openDB(); Map<String,String> params = ((PGConnection)con).getParameterStatuses(); Assert.assertEquals("UTF8", params.get("client_encoding")); Assert.assertNotNull(params.get("DateStyle")); Assert.assertThat(params.get("DateStyle"), StringStartsWith.startsWith("ISO")); Assert.assertEquals("GMT-08:00", params.get("TimeZone")); Assert.assertNotNull(params.get("integer_datetimes")); Assert.assertNotNull(params.get("is_superuser")); Assert.assertNotNull(params.get("server_encoding")); Assert.assertNotNull(params.get("server_version")); Assert.assertNotNull(params.get("session_authorization")); Assert.assertNotNull(params.get("standard_conforming_strings")); if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) { Assert.assertNotNull(params.get("IntervalStyle")); } else { Assert.assertNull(params.get("IntervalStyle")); } if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) { Assert.assertEquals("Driver Tests", params.get("application_name")); } else { Assert.assertNull(params.get("application_name")); } Assert.assertNull(params.get("nonexistent")); Assert.assertNull(params.get("enable_hashjoin")); TestUtil.closeDB(con); }
Source:
public void testObjectMovedWithinPack() throws IncorrectObjectTypeException, IOException { final Repository eden = createBareRepository(); final RevObject o1 = writeBlob(eden, "o1"); final File[] out1 = pack(eden, o1); assertEquals(o1.name(), parse(o1).name()); whackCache(); final RevObject o2 = writeBlob(eden, "o2"); try (final PackWriter pw = new PackWriter(eden)) { pw.addObject(o2); pw.addObject(o1); write(out1, pw); } assertEquals(o1.name(), parse(o1).name()); assertEquals(o2.name(), parse(o2).name()); }

Target:
public void testObjectMovedWithinPack() throws IncorrectObjectTypeException, IOException { final Repository eden = createBareRepository(); final RevObject o1 = writeBlob(eden, "o1"); final File[] out1 = pack(eden, o1); assertEquals(o1.name(), parse(o1).name()); whackCache(); final RevObject o2 = writeBlob(eden, "o2"); try (PackWriter pw = new PackWriter(eden)) { pw.addObject(o2); pw.addObject(o1); write(out1, pw); } assertEquals(o1.name(), parse(o1).name()); assertEquals(o2.name(), parse(o2).name()); }
Source:
public Map<TaskId, Long> getTaskOffsetSums() { final Map<TaskId, Long> taskOffsetSums = new HashMap<>(); final File[] stateDirs = stateDirectory.listTaskDirectories(); if (stateDirs != null) { for (final File dir : stateDirs) { try { final TaskId id = TaskId.parse(dir.getName()); final Task task = tasks.get(id); if (task != null) { if (task.isActive() && task.state() == RUNNING) { taskOffsetSums.put(id, Task.LATEST_OFFSET); } else { taskOffsetSums.put(id, computeOffsetSum(task.changelogOffsets())); } } else { try { final File checkpointFile = new File(dir, StateManagerUtil.CHECKPOINT_FILE_NAME); if (stateDirectory.lock(id) && checkpointFile.exists()) { taskOffsetSums.put(id, computeOffsetSum(new OffsetCheckpoint(checkpointFile).read())); lockedUnassignedTaskDirectories.add(id); } } catch (final IOException e) { } } } catch (final TaskIdFormatException e) { } } } return taskOffsetSums; }

Target:
public Map<TaskId, Long> getTaskOffsetSums() { final Map<TaskId, Long> taskOffsetSums = new HashMap<>(); for (final TaskId id : lockedTaskDirectories) { final Task task = tasks.get(id); if (task != null) { if (task.isActive() && task.state() == RUNNING) { taskOffsetSums.put(id, Task.LATEST_OFFSET); } else { taskOffsetSums.put(id, sumOfChangelogOffsets(id, task.changelogOffsets())); } } else { final File checkpointFile = stateDirectory.checkpointFileFor(id); try { if (checkpointFile.exists()) { taskOffsetSums.put(id, sumOfChangelogOffsets(id, new OffsetCheckpoint(checkpointFile).read())); } } catch (final IOException e) { log.warn(String.format("Exception caught while trying to read checkpoint for task %s:", id), e); } } } return taskOffsetSums; }
Source:
private void saveCommonStorageProperties(StorageModel model) { storageDomain.setStorageName(model.getName().getEntity()); saveDefaultedStorageProperties(model, storageDomain); }

Target:
private void saveCommonStorageProperties(StorageModel model) { saveDefaultedStorageProperties(model, storageDomain); }
Source:
public void massClearNetworkFromNics(List<Guid> nicIds) { getCallsHandler().executeStoredProcAsBatch("Clear_network_from_nics", nicIds, new MapSqlParameterMapper<Guid>() { @Override public MapSqlParameterSource map(Guid id) { CustomMapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("id", id); return paramSource; } }); }

Target:
public void massClearNetworkFromNics(List<Guid> nicIds) { getCallsHandler().executeStoredProcAsBatch("Clear_network_from_nics", nicIds, getIdParameterMapper()); }
Source:
public void associateAsyncPrettyPrinterWithId( String requestId, AsyncPrettyPrinter asyncPrettyPrinter) { if (mRequestIdMap.containsKey(requestId)) { throw new IllegalArgumentException("cannot associate different " + "pretty printers with the same request id: "+requestId); } mRequestIdMap.put(requestId, asyncPrettyPrinter); }

Target:
public void associateAsyncPrettyPrinterWithId( String requestId, AsyncPrettyPrinter asyncPrettyPrinter) { if (mRequestIdMap.put(requestId, asyncPrettyPrinter) != null) { throw new IllegalArgumentException("cannot associate different " + "pretty printers with the same request id: "+requestId); } }
Source:
private int calculateLegendHeight() { return simplePlot.getOffsetHeight() - 28; }

Target:
private int calculateLegendHeight() { return simplePlot.getOffsetHeight() - X_AXIS_LABEL_HEIGHT - 2 * TOTAL_BORDERS_WIDTH; }
Source:
public static String getMimeTypeFromUrl(String url) { if (url != null) { String extension = FilenameUtils.getExtension(url); if (extension != null) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } } return null; }

Target:
public static String getMimeTypeFromUrl(String url) { if (url == null) { return null; } String extension = FilenameUtils.getExtension(url); if (extension == null) { return null; } return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
Source:
public void conditional_expression_in_lambda() { Result result = Result.createFor("ConditionalExpressionInLambda"); JavaSymbol foo = result.symbol("foo"); assertThat(foo.usages()).hasSize(1); }

Target:
public void conditional_expression_in_lambda() { Result result = Result.createFor("ConditionalExpressionInLambda"); JavaSymbol foo = result.symbol("foo"); assertThat(foo.usages()).hasSize(1); IdentifierTree map = result.referenceTree(8, 8); MethodJavaType mapJavaType = (MethodJavaType) map.symbolType(); assertThat(mapJavaType.resultType.isTagged(JavaType.DEFERRED)).isTrue(); JavaType lambdaType = (JavaType) ((MethodInvocationTree) map.parent().parent()).arguments().get(0).symbolType(); assertThat(lambdaType.isParameterized()).isTrue(); assertThat(lambdaType.is("java.util.function.Function")).isTrue(); JavaType returnType = ((ParametrizedTypeJavaType) lambdaType).typeSubstitution.substitutedTypes().get(1); assertThat(returnType.isSubtypeOf("java.lang.Comparable")).isTrue(); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); IdentifierTree flatMap = result.referenceTree(13, 8); MethodJavaType flatMapJavaType = (MethodJavaType) flatMap.symbolType(); assertThat(flatMapJavaType.resultType.isTagged(JavaType.DEFERRED)).isTrue(); lambdaType = (JavaType) ((MethodInvocationTree) flatMap.parent().parent()).arguments().get(0).symbolType(); assertThat(lambdaType.isParameterized()).isTrue(); assertThat(lambdaType.is("java.util.function.Function")).isTrue(); returnType = ((ParametrizedTypeJavaType) lambdaType).typeSubstitution.substitutedTypes().get(1); assertThat(returnType.isParameterized()).isTrue(); assertThat(returnType.is("java.util.stream.Stream")).isTrue(); JavaType substitution = ((ParametrizedTypeJavaType) returnType).typeSubstitution.substitutedTypes().get(0); assertThat(substitution.is("java.lang.Integer")).isTrue(); }
Source:
protected ChannelHandler findHttpResponseDecoderToReplace(ChannelPipeline pipeline) throws IllegalStateException { if (httpResponseDecoderName != null) { final ChannelHandler decoder = pipeline.get(httpResponseDecoderName); if (decoder == null) { throw new IllegalStateException("No http response decoder found with name \"" + httpResponseDecoderName + "\""); } else if (!(decoder instanceof HttpResponseDecoder || decoder instanceof HttpClientCodec)) { throw new IllegalStateException("Expected decoder with name \"" + httpResponseDecoderName + "\" to be a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName() + " but found " + decoder.getClass().getCanonicalName()); } return decoder; } ChannelHandler decoder = pipeline.get(HttpResponseDecoder.class); if (decoder == null) { decoder = pipeline.get(HttpClientCodec.class); if (decoder == null) { throw new IllegalStateException("ChannelPipeline does not contain " + "a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName()); } } return decoder; }

Target:
protected ChannelHandler findHttpResponseDecoderToReplace(ChannelPipeline pipeline) throws IllegalStateException { if (httpResponseDecoderName != null) { final ChannelHandler decoder = pipeline.get(httpResponseDecoderName); if (decoder == null) { throw new IllegalStateException("No http response decoder found with name \"" + httpResponseDecoderName + "\""); } if (!(decoder instanceof HttpResponseDecoder || decoder instanceof HttpClientCodec)) { throw new IllegalStateException("Expected decoder with name \"" + httpResponseDecoderName + "\" to be a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName() + " but found " + decoder.getClass().getCanonicalName()); } return decoder; } ChannelHandler decoder = pipeline.get(HttpResponseDecoder.class); if (decoder == null) { decoder = pipeline.get(HttpClientCodec.class); if (decoder == null) { throw new IllegalStateException("ChannelPipeline does not contain " + "an " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName()); } } return decoder; }
Source:
Map<String, String> getSeverityReasonAttributes() { return severityReasonAttributes; }

Target:
Map<String, String> getSeverityReasonAttributes() { return Collections.unmodifiableMap(severityReasonAttributes); }
Source:
private boolean validPayload(final SessionWrapper session, final Payload payload) { final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); if ( null != verifier ) { return verifier.verified(payload, session); } return true; }

Target:
private boolean validPayload(final SessionWrapper session, final Payload payload) { final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); return (null != verifier) ? verifier.verified(payload, session) : true; }
Source:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; return em.createNativeQuery(qstr, Object[].class).getResultList(); }

Target:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; return em.createNativeQuery(qstr).getResultList(); }
Source:
private static List<VmDevice> getPluggedInterfaces(List<VmDevice> devices) { ArrayList<VmDevice> result = new ArrayList<VmDevice>(); for (VmDevice device : devices) { if (isBridge(device) && device.getIsPlugged()) { result.add(device); } } return result; }

Target:
private static List<VmDevice> getPluggedInterfaces(List<VmDevice> devices) { List<VmDevice> result = new ArrayList<VmDevice>(); for (VmDevice device : devices) { if (isBridge(device) && device.getIsPlugged()) { result.add(device); } } return result; }
Source:
private String writeToCSV(SortedMap<Long, List<CircuitStatistics>> circuitStatistics) throws IOException { StringBuilder sb = new StringBuilder(); CSVWriter writer = new CSVWriter(new StringBuilderWriter(sb), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); try { for (Long timestamp : circuitStatistics.keySet()) for (CircuitStatistics currentStatistic : circuitStatistics.get(timestamp)) { String[] csvStatistic = new String[7]; csvStatistic[0] = String.valueOf(timestamp); csvStatistic[1] = String.valueOf(currentStatistic.getSlaFlowId()); csvStatistic[2] = String.valueOf(currentStatistic.getThroughput()); csvStatistic[3] = String.valueOf(currentStatistic.getPacketLoss()); csvStatistic[4] = String.valueOf(currentStatistic.getDelay()); csvStatistic[5] = String.valueOf(currentStatistic.getJitter()); csvStatistic[6] = String.valueOf(currentStatistic.getFlowData()); writer.writeNext(csvStatistic); } return sb.toString(); } finally { writer.close(); } }

Target:
private String writeToCSV(SortedMap<Long, List<CircuitStatistics>> circuitStatistics) throws IOException { StringBuilder sb = new StringBuilder(); CSVWriter writer = new CSVWriter(new StringBuilderWriter(sb), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); try { for (Long timestamp : circuitStatistics.keySet()) for (CircuitStatistics currentStatistic : circuitStatistics.get(timestamp)) { String[] csvStatistic = new String[7]; csvStatistic[0] = String.valueOf(timestamp); csvStatistic[1] = currentStatistic.getSlaFlowId(); csvStatistic[2] = currentStatistic.getThroughput(); csvStatistic[3] = currentStatistic.getPacketLoss(); csvStatistic[4] = currentStatistic.getDelay(); csvStatistic[5] = currentStatistic.getJitter(); csvStatistic[6] = currentStatistic.getFlowData(); writer.writeNext(csvStatistic); } return sb.toString(); } finally { writer.close(); } }
Source:
public Serializable next() { if (!this.hasNext()) { throw new NoSuchElementException(); } AttributeDescriptor attributeDescriptor = this.attributeDescriptorList.get(index); Attribute attribute = metacard.getAttribute(attributeDescriptor.getName()); index++; if (attribute != null) { if (attributeDescriptor.isMultiValued()) { StringBuilder valuesBuilder = new StringBuilder(); List<Serializable> values = attribute.getValues(); for (int i = 0; i < values.size(); i++) { if (i > 0) { valuesBuilder.append(MULTIVALUE_DELIMITER); } valuesBuilder.append(values.get(i)); } return valuesBuilder.toString(); } else { return attribute.getValue(); } } return ""; }

Target:
public Serializable next() { if (!this.hasNext()) { throw new NoSuchElementException(); } AttributeDescriptor attributeDescriptor = this.attributeDescriptorList.get(index); Attribute attribute = metacard.getAttribute(attributeDescriptor.getName()); index++; if (attribute != null) { if (attributeDescriptor.isMultiValued()) { return StringUtils.join(attribute.getValues(), MULTIVALUE_DELIMITER); } else { return attribute.getValue(); } } return ""; }
Source:
public void testAddRemoveAdd_fromSameWorkSource() { WorkSource ws1 = null; WorkSource ws2 = new WorkSource(50, "foo"); ws1 = ws2; ws1.add(ws2); assertTrue(ws1.remove(ws2)); ws1.add(ws2); assertEquals(0, ws1.size()); }

Target:
public void testAddRemoveAdd_fromSameWorkSource() { WorkSource ws = new WorkSource(50, "foo"); ws.add(ws); assertEquals(1, ws.size()); assertTrue(ws.remove(ws)); assertEquals(0, ws.size()); ws.add(ws); assertEquals(0, ws.size()); }
Source:
private void removeEmptyGroupAfterTimeout(MessageGroup messageGroup, long timeout) { Object groupId = messageGroup.getGroupId(); UUID groupUuid = UUIDConverter.getUUID(groupId); ScheduledFuture<?> scheduledFuture = getTaskScheduler() .schedule(() -> { Lock lock = this.lockRegistry.obtain(groupUuid.toString()); try { lock.lockInterruptibly(); try { this.messageStore.removeMessageGroup(groupId); } finally { lock.unlock(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); this.logger.debug("Thread was interrupted while trying to obtain lock"); } }, new Date(System.currentTimeMillis() + timeout)); if (this.logger.isDebugEnabled()) { this.logger.debug("Schedule empty MessageGroup [ " + groupId + "] for removal."); } this.expireGroupScheduledFutures.put(groupUuid, scheduledFuture); }

Target:
private void removeEmptyGroupAfterTimeout(MessageGroup messageGroup, long timeout) { Object groupId = messageGroup.getGroupId(); UUID groupUuid = UUIDConverter.getUUID(groupId); ScheduledFuture<?> scheduledFuture = getTaskScheduler() .schedule(() -> { Lock lock = this.lockRegistry.obtain(groupUuid.toString()); try { lock.lockInterruptibly(); try { this.expireGroupScheduledFutures.remove(groupUuid); MessageGroup groupNow = this.messageStore.getMessageGroup(groupUuid); boolean removeGroup = groupNow.size() == 0 && groupNow.getLastModified() <= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups); if (removeGroup) { if (this.logger.isDebugEnabled()) { this.logger.debug("Removing empty group: " + groupUuid); } this.messageStore.removeMessageGroup(groupId); } } finally { lock.unlock(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (this.logger.isDebugEnabled()) { this.logger.debug("Thread was interrupted while trying to obtain lock." + "Rescheduling empty MessageGroup [ " + groupId + "] for removal."); } removeEmptyGroupAfterTimeout(messageGroup, timeout); } }, new Date(System.currentTimeMillis() + timeout)); if (this.logger.isDebugEnabled()) { this.logger.debug("Schedule empty MessageGroup [ " + groupId + "] for removal."); } this.expireGroupScheduledFutures.put(groupUuid, scheduledFuture); }
Source:
public String toString() { return "profile (" + authz + ")"; }

Target:
public String toString() { return profile + " (" + authz + ")"; }
Source:
public void third_party_symbols() { Map<String, Symbol> emojiSymbols = TypeShed.typeShedSymbols("emoji").stream().collect(Collectors.toMap(Symbol::name, Function.identity())); Symbol emojizeSymbol = emojiSymbols.get("emojize"); assertThat(emojizeSymbol.kind()).isEqualTo(Kind.FUNCTION); assertThat(((FunctionSymbolImpl) emojizeSymbol).declaredReturnType().canOnlyBe("str")).isTrue(); assertThat(TypeShed.standardLibrarySymbol("emoji", "emoji.emojize")).isSameAs(emojizeSymbol); }

Target:
public void third_party_symbols() { Map<String, Symbol> emojiSymbols = TypeShed.typeShedSymbolsForModule("emoji").stream().collect(Collectors.toMap(Symbol::name, Function.identity())); Symbol emojizeSymbol = emojiSymbols.get("emojize"); assertThat(emojizeSymbol.kind()).isEqualTo(Kind.FUNCTION); assertThat(((FunctionSymbolImpl) emojizeSymbol).declaredReturnType().canOnlyBe("str")).isTrue(); assertThat(TypeShed.standardLibrarySymbol("emoji", "emoji.emojize")).isSameAs(emojizeSymbol); }
Source:
private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, String emptyValue, int maxCharsPerColumn, boolean ignoreTrailingAndLeadingWhitespace) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); Preconditions.condition(maxCharsPerColumn > 0, () -> "maxCharsPerColumn must be a positive number: " + maxCharsPerColumn); settings.setMaxCharsPerColumn(maxCharsPerColumn); return settings; }

Target:
private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, String emptyValue, int maxCharsPerColumn, boolean ignoreTrailingAndLeadingWhitespace) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); settings.setIgnoreLeadingWhitespaces(ignoreTrailingAndLeadingWhitespace); settings.setIgnoreTrailingWhitespaces(ignoreTrailingAndLeadingWhitespace); Preconditions.condition(maxCharsPerColumn > 0, () -> "maxCharsPerColumn must be a positive number: " + maxCharsPerColumn); settings.setMaxCharsPerColumn(maxCharsPerColumn); return settings; }