auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String resolveCommonJsModuleFromRegistry(String requireName) { for (Map.Entry<String, ImmutableSet<String>> nodeModulesFolder : nodeModulesRegistry.entrySet()) { if (!this.path.startsWith(nodeModulesFolder.getKey())) { continue; } String fullModulePath = nodeModulesFolder.getKey() + "node_modules/" + requireName; String loadAddress = resolveCommonJsModuleFile(fullModulePath); if (loadAddress != null) { return loadAddress; } loadAddress = resolveCommonJsModuleDirectory(fullModulePath); if (loadAddress != null) { return loadAddress; } } return null; }

Target:
private String resolveCommonJsModuleFromRegistry(String requireName) { for (Map.Entry<String, ImmutableSet<String>> nodeModulesFolder : nodeModulesRegistry.entrySet()) { if (!this.path.startsWith(nodeModulesFolder.getKey())) { continue; } String fullModulePath = nodeModulesFolder.getKey() + "node_modules" + MODULE_SLASH + requireName; String loadAddress = resolveCommonJsModuleFile(fullModulePath); if (loadAddress != null) { return loadAddress; } loadAddress = resolveCommonJsModuleDirectory(fullModulePath); if (loadAddress != null) { return loadAddress; } } return null; }
Source:
static String writeJsonError(String error) throws IOException { StringWriter writer = new StringWriter(); JsonGenerator generator = JSON_FACTORY.createGenerator(writer); generator.useDefaultPrettyPrinter(); generator.writeStartObject(); generator.writeStringField("status", STATUS_DOWN); generator.writeObjectFieldStart("zipkin"); generator.writeStringField("status", STATUS_DOWN); generator.writeObjectFieldStart("details"); generator.writeStringField("error", error); generator.writeEndObject(); generator.writeEndObject(); generator.writeEndObject(); generator.flush(); return writer.toString(); }

Target:
static String writeJsonError(String error) throws IOException { StringWriter writer = new StringWriter(); try (JsonGenerator generator = JSON_FACTORY.createGenerator(writer)) { generator.useDefaultPrettyPrinter(); generator.writeStartObject(); generator.writeStringField("status", STATUS_DOWN); generator.writeObjectFieldStart("zipkin"); generator.writeStringField("status", STATUS_DOWN); generator.writeObjectFieldStart("details"); generator.writeStringField("error", error); generator.writeEndObject(); generator.writeEndObject(); generator.writeEndObject(); } return writer.toString(); }
Source:
private static void _chmod(File f, int mask) throws IOException { if (File.pathSeparatorChar==';') return; if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { Files.setPosixFilePermissions(Util.fileToPath(f).toAbsolutePath(), Util.modeToPermissions(mask)); } }

Target:
private static void _chmod(File f, int mask) throws IOException { if (File.pathSeparatorChar==';') return; if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { Files.setPosixFilePermissions(Util.fileToPath(f), Util.modeToPermissions(mask)); } }
Source:
private <T, U extends T> Supplier<T> createSupplier(SecurityContext securityContext, U event, EventMetadata metadata, ObserverExceptionHandler exceptionHandler, boolean handleExceptions, Runnable notifyAction) { return () -> { final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); final RequestContext requestContext = requestContextHolder.get(); final FastEvent<Object> requestInitializedEvent = requestInitializedEventHolder.get(); final FastEvent<Object> requestBeforeDestroyedEvent = requestBeforeDestroyedEventHolder.get(); final FastEvent<Object> requestDestroyedEvent = requestDestroyedEventHolder.get(); try { securityContext.associate(); requestInitializedEvent.fire(toString()); requestContext.activate(); notifyAction.run(); } finally { stack.pop(); requestBeforeDestroyedEvent.fire(toString()); requestContext.invalidate(); requestContext.deactivate(); requestDestroyedEvent.fire(toString()); securityContext.dissociate(); securityContext.close(); } if (handleExceptions) { handleExceptions(exceptionHandler); } return event; }; }

Target:
private <T, U extends T> Supplier<T> createSupplier(SecurityContext securityContext, U event, EventMetadata metadata, ObserverExceptionHandler exceptionHandler, boolean handleExceptions, Runnable notifyAction) { return () -> { final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); final RequestContext requestContext = requestContextHolder.get(); try { securityContext.associate(); requestContext.activate(); notifyAction.run(); } finally { stack.pop(); requestContext.invalidate(); requestContext.deactivate(); securityContext.dissociate(); securityContext.close(); } if (handleExceptions) { handleExceptions(exceptionHandler); } return event; }; }
Source:
public void setRequestCategories(Map<String, Long> requestCategories) { this.requestCategories = requestCategories; }

Target:
public synchronized void setRequestCategories(Map<String, Long> requestCategories) { this.requestCategories = requestCategories; }
Source:
private ConcurrentMap<String, WanReplicationPublisher> createPublishers(WanReplicationConfig wanConfig) { List<CustomWanPublisherConfig> customPublisherConfigs = wanConfig.getCustomPublisherConfigs(); int publisherCount = customPublisherConfigs.size(); if (publisherCount == 0) { return createConcurrentHashMap(1); } ConcurrentMap<String, WanReplicationPublisher> publishers = createConcurrentHashMap(publisherCount); Map<String, AbstractWanPublisherConfig> publisherConfigs = createHashMap(publisherCount); customPublisherConfigs.forEach( publisherConfig -> { String publisherId = getPublisherIdOrGroupName(publisherConfig); if (publishers.containsKey(publisherId)) { throw new InvalidConfigurationException( "Detected duplicate publisher ID '" + publisherId + "' for a single WAN replication config"); } WanReplicationPublisher publisher = createPublisher(publisherConfig); publishers.put(publisherId, publisher); publisherConfigs.put(publisherId, publisherConfig); }); for (Entry<String, WanReplicationPublisher> publisherEntry : publishers.entrySet()) { String publisherId = publisherEntry.getKey(); WanReplicationPublisher publisher = publisherEntry.getValue(); node.getSerializationService().getManagedContext().initialize(publisher); publisher.init(wanConfig, publisherConfigs.get(publisherId)); } return publishers; }

Target:
private ConcurrentMap<String, WanReplicationPublisher> createPublishers(WanReplicationConfig wanConfig) { List<CustomWanPublisherConfig> customPublisherConfigs = wanConfig.getCustomPublisherConfigs(); int publisherCount = customPublisherConfigs.size(); if (publisherCount == 0) { return createConcurrentHashMap(1); } ConcurrentMap<String, WanReplicationPublisher> publishers = createConcurrentHashMap(publisherCount); Map<String, AbstractWanPublisherConfig> publisherConfigs = createHashMap(publisherCount); customPublisherConfigs.forEach( publisherConfig -> { String publisherId = getWanPublisherId(publisherConfig); if (publishers.containsKey(publisherId)) { throw new InvalidConfigurationException( "Detected duplicate publisher ID '" + publisherId + "' for a single WAN replication config"); } WanReplicationPublisher publisher = createPublisher(publisherConfig); publishers.put(publisherId, publisher); publisherConfigs.put(publisherId, publisherConfig); }); for (Entry<String, WanReplicationPublisher> publisherEntry : publishers.entrySet()) { String publisherId = publisherEntry.getKey(); WanReplicationPublisher publisher = publisherEntry.getValue(); node.getSerializationService().getManagedContext().initialize(publisher); publisher.init(wanConfig, publisherConfigs.get(publisherId)); } return publishers; }
Source:
public void selectMetadataTab() { selectTab(METADATA_TAB); }

Target:
public void selectMetadataTab() { clickTab(METADATA_TAB); }
Source:
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { classAnnotations.clear(); coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); }

Target:
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); }
Source:
public void setDateTime(String date, String time, TimeZone tz) { Date dateObject = DateUtils.toDate(date, time, tz); if (dateObject == null) { if (invalidDateStrategy == null) { throw new IllegalArgumentException("Date or time parameter is invalid."); } else { LOG.warn("Could not parse date/time. Attempting invalid date strategy: {}", invalidDateStrategy); switch (invalidDateStrategy.toUpperCase()) { case "USE_CURRENT": Date now = new Date(); date = new SimpleDateFormat("yyyy-MM-dd").format(now); dateObject = DateUtils.toDate(date, time, tz); if (dateObject == null) { LOG.warn("Couldn't parse time. Using current time instead."); dateObject = now; } break; default: throw new IllegalArgumentException("Date or time parameter is invalid."); } } } LOG.debug("Setting date to {}", date); setDateTime(dateObject); }

Target:
public void setDateTime(String date, String time, TimeZone tz) { Date dateObject = DateUtils.toDate(date, time, tz); setDateTime(dateObject); }
Source:
public static void saveNote(Note note) { if (note != null) { try { Note object = getNotesBucket().insertObject(note.getId(), Note.Schema.getJSON(note)); object.save(); } catch (BucketObjectNameInvalid e) { e.printStackTrace(); } } }

Target:
public static void saveNote(Note note) { if (note != null) { try { Note object = getNotesBucket().insertObject(note.getId(), Note.Schema.getJSON(note)); object.save(); } catch (BucketObjectNameInvalid e) { AppLog.e(AppLog.T.SIMPERIUM, e.getMessage()); } } }
Source:
public void deleteEncounter(String id) { org.openmrs.Encounter encounter = Context.getEncounterService().getEncounterByUuid(id); if (encounter == null) { Visit visit = Context.getVisitService().getVisitByUuid(id); if (visit == null) { IIdType idType = new IdDt(); idType.setValue(id); throw new ResourceNotFoundException(idType); } else { Context.getVisitService().voidVisit(visit, "DELETED by FHIR request"); } } else { Context.getEncounterService().voidEncounter(encounter, "DELETED by FHIR request"); } }

Target:
public void deleteEncounter(String id) { org.openmrs.Encounter encounter = Context.getEncounterService().getEncounterByUuid(id); if (encounter == null) { Visit visit = Context.getVisitService().getVisitByUuid(id); if (visit == null) { IIdType idType = new IdType(); idType.setValue(id); throw new ResourceNotFoundException(idType); } else { Context.getVisitService().voidVisit(visit, FHIRConstants.ENCOUNTER_DELETE_MESSAGE); } } else { Context.getEncounterService().voidEncounter(encounter, FHIRConstants.ENCOUNTER_DELETE_MESSAGE); } }
Source:
public Map<String, Object> getVariables() { return variables; }

Target:
public Map<String, Object> getVariables() { return new LinkedHashMap<>(variables); }
Source:
private ProcessResult processEMLFile(AbstractFile abstractFile) { String fileName; try { fileName = getTempPath() + File.separator + abstractFile.getName() + "-" + String.valueOf(abstractFile.getId()); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); return ProcessResult.ERROR; } File file = new File(fileName); long freeSpace = services.getFreeDiskSpace(); if ((freeSpace != IngestMonitor.DISK_FREE_SPACE_UNKNOWN) && (abstractFile.getSize() >= freeSpace)) { logger.log(Level.WARNING, String.format("Not enough disk space to write file '%s' (id=%d) to disk.", abstractFile.getName(), abstractFile.getId())); return ProcessResult.OK; } try { ContentUtils.writeToFile(abstractFile, file, context::fileIngestIsCancelled); } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed writing the vCard file '%s' (id=%d) to disk.", abstractFile.getName(), abstractFile.getId()), ex); return ProcessResult.OK; } try { EmailMessage message = EMLParser.parse(abstractFile, fileName); if(message == null) { return ProcessResult.OK; } List<AbstractFile> derivedFiles = new ArrayList<>(); BlackboardArtifact msgArtifact = addEmailArtifact(message, abstractFile); if ((msgArtifact != null) && (message.hasAttachment())) { derivedFiles.addAll(handleAttachments(message.getAttachments(), abstractFile, msgArtifact )); } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); } catch (IOException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } catch (MimeException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }

Target:
private ProcessResult processEMLFile(AbstractFile abstractFile) { try { EmailMessage message = EMLParser.parse(abstractFile); if (message == null) { return ProcessResult.OK; } List<AbstractFile> derivedFiles = new ArrayList<>(); BlackboardArtifact msgArtifact = addEmailArtifact(message, abstractFile); if ((msgArtifact != null) && (message.hasAttachment())) { derivedFiles.addAll(handleAttachments(message.getAttachments(), abstractFile, msgArtifact)); } if (derivedFiles.isEmpty() == false) { for (AbstractFile derived : derivedFiles) { services.fireModuleContentEvent(new ModuleContentEvent(derived)); } } context.addFilesToJob(derivedFiles); } catch (IOException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } catch (MimeException ex) { logger.log(Level.WARNING, String.format("Error reading eml file %s", abstractFile.getName()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }
Source:
protected Integer exitStatus(FilePath workspace, TaskListener listener) throws IOException, InterruptedException { FilePath status = getResultFile(workspace); return status.act(STATUS_CHECK_INSTANCE); }

Target:
protected @CheckForNull Integer exitStatus(FilePath workspace, TaskListener listener) throws IOException, InterruptedException { FilePath status = getResultFile(workspace); return status.act(STATUS_CHECK_INSTANCE); }
Source:
public void testTriplet() { Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Triplet<Object, Object, Object> pair = new Triplet<Object, Object, Object>(o1, o2, o3); Assert.assertEquals("Actual pair object x does not match expected, original object x.", pair.getX(), o1); Assert.assertEquals("Actual pair object y does not match expected, original object y.", pair.getY(), o2); Assert.assertEquals("Actual pair object z does not match expected, original object z.", pair.getZ(), o3); }

Target:
public void testTriplet() { Object o1 = new Object(); Object o2 = new Object(); Object o3 = new Object(); Triplet<Object, Object, Object> triplet = new Triplet<Object, Object, Object>(o1, o2, o3); Assert.assertEquals("Actual pair object x does not match expected, original object x.", triplet.getX(), o1); Assert.assertEquals("Actual pair object y does not match expected, original object y.", triplet.getY(), o2); Assert.assertEquals("Actual pair object z does not match expected, original object z.", triplet.getZ(), o3); }
Source:
protected void executeQueryCommand() { String password = null; try { final String token = sessionDataContainer.getSsoAccessToken(getParameters().getSessionId()); if (StringUtils.isEmpty(token)) { throw new RuntimeException("Unable to get sso access token for session."); } password = FiltersHelper.getPassword(token); } catch (Exception ex) { log.error("Unable to execute IsPasswordDelegationPossibleQuery with message {}", ex.getMessage()); log.debug("Exception", ex); } getQueryReturnValue().setReturnValue(password != null); getQueryReturnValue().setSucceeded(true); }

Target:
protected void executeQueryCommand() { String password = null; try { password = SsoUtils.getPassword(sessionDataContainer.getSsoAccessToken(getParameters().getSessionId())); } catch(Exception ex) { log.error("Unable to execute IsPasswordDelegationPossibleQuery with message {}", ex.getMessage()); log.debug("Exception", ex); } getQueryReturnValue().setReturnValue(password != null); getQueryReturnValue().setSucceeded(true); }
Source:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { if (cells.isEmpty()) { return ImmutableMap.of(); } Set<Cell> toLoad = Sets.newHashSet(); Map<Cell, byte[]> cacheHit = Maps.newHashMapWithExpectedSize(cells.size()); for (Cell cell : cells) { byte[] val = getCachedCellIfPresent(tableRef, cell); if (val != null) { if (val.length > 0) { cacheHit.put(cell, val); } } else { toLoad.add(cell); } } final Map<Cell, byte[]> loaded = super.get(tableRef, toLoad); cacheLoadedCells(tableRef, toLoad, loaded); cacheHit.putAll(loaded); return cacheHit; }

Target:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try { return getWithLoader( tableRef, cells, (tableReference, toRead) -> Futures.immediateFuture(super.get(tableReference, toRead))).get(); } catch (InterruptedException | ExecutionException e) { throw Throwables.rewrapAndThrowUncheckedException(e.getCause()); } }
Source:
private void prepareMockFileUrls() throws URISyntaxException { when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }

Target:
private final void prepareMockFileUrls() throws URISyntaxException { when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }
Source:
void free(long address) { if (trace) { Long prev = allocatedBlocks.remove(address); if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }

Target:
void free(long address) { Long prev = allocatedBlocks.remove(address); if (trace) { if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }
Source:
private Optional<RevCommit> refToCommit(RevWalk walk, Ref ref) throws IOException { RevObject maybehead = walk.parseAny(ref.getObjectId()); if (!(maybehead instanceof RevCommit)) { return Optional.empty(); } return Optional.of((RevCommit) maybehead); }

Target:
private Optional<RevCommit> refToCommit(RevWalk walk, Ref ref) throws IOException { try { return Optional.of(walk.parseCommit(ref.getObjectId())); } catch (IncorrectObjectTypeException e) { return Optional.empty(); } }
Source:
public void onTestFail(DataRecord testData, Description description, Failure failure) { if (mDestDir == null) { return; } final String fileName = String.format( "%s.%s-%d", description.getClassName(), description.getMethodName(), mTestIterations.get(description.getDisplayName())); final String pngFileName = String.format("%s.png", fileName); File img = takeScreenshot(pngFileName); if (img != null) { testData.addFileMetric(String.format("%s_%s", getTag(), img.getName()), img); } if (mIncludeUiXml) { File uixFile = collectUiXml(fileName); if (uixFile != null) { testData.addFileMetric( String.format("%s_%s", getTag(), uixFile.getName()), uixFile); } } }

Target:
public void onTestFail(DataRecord testData, Description description, Failure failure) { if (mDestDir == null) { return; } final String fileNameBase = String.format("%s.%s", description.getClassName(), description.getMethodName()); int iteration = mTestIterations.get(description.getDisplayName()); final String fileName = iteration == 1 ? fileNameBase : String.join("-", fileNameBase, String.valueOf(iteration)); final String pngFileName = String.format("%s.png", fileName); File img = takeScreenshot(pngFileName); if (img != null) { testData.addFileMetric(String.format("%s_%s", getTag(), img.getName()), img); } if (mIncludeUiXml) { File uixFile = collectUiXml(fileName); if (uixFile != null) { testData.addFileMetric( String.format("%s_%s", getTag(), uixFile.getName()), uixFile); } } }
Source:
public void TestSerDesr() throws IOException { LookupConfig lookupConfig = new LookupConfig(Files.createTempDir().getAbsolutePath()); Assert.assertEquals(lookupConfig, mapper.reader(LookupConfig.class).readValue(mapper.writeValueAsString(lookupConfig))); }

Target:
public void TestSerDesr() throws IOException { LookupConfig lookupConfig = new LookupConfig(temporaryFolder.newFile().getAbsolutePath()); Assert.assertEquals(lookupConfig, mapper.reader(LookupConfig.class).readValue(mapper.writeValueAsString(lookupConfig))); }
Source:
void createWithException() throws Exception { XWikiDocument document = mock(XWikiDocument.class); DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page"); when(this.xcontext.getWiki().getDocument(documentReference, this.xcontext)).thenThrow(new XWikiException()); this.modelBridge.create(documentReference); assertLog(Level.ERROR, "Failed to create document [{}].", documentReference); }

Target:
void createWithException() throws Exception { DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page"); when(this.xcontext.getWiki().getDocument(documentReference, this.xcontext)).thenThrow(new XWikiException()); this.modelBridge.create(documentReference); assertLog(Level.ERROR, "Failed to create document [{}].", documentReference); }
Source:
public static void main(String[] args) { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUrl"), properties.getProperty("databaseUrl")); flyway.setInitVersion("0"); flyway.setLocations("classpath:org.cru.godtools.migration", "classpath:db.migration"); flyway.migrate(); }

Target:
public static void main(String[] args) { Flyway flyway = new Flyway(); flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUsername"), properties.getProperty("databasePassword")); flyway.setInitVersion("0"); flyway.setLocations("classpath:org.cru.godtools.migration", "classpath:db.migration"); flyway.migrate(); }
Source:
Message<?> doPoll() { Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }

Target:
protected Message<?> doPoll() { Message<?> message = this.messageGroupStore.pollMessageFromGroup(this.groupId); this.messageStoreNotFull.signal(); return message; }
Source:
private static void writeMercs(SolGame game) { String fileName = getRsrcPath("mercenaries.json"); PrintWriter writer; ItemContainer mercIc = game.getHero().getTradeContainer().getMercs(); List<JsonObject> jsons = new ArrayList<JsonObject>(); JsonObject json; for (List<SolItem> group : mercIc) { for (SolItem item : group) { SolShip merc = ((MercItem) item).getSolShip(); String hullName = game.getHullConfigs().getName(merc.getHull().config); int money = (int) merc.getMoney(); ArrayList<SolItem> itemsList = new ArrayList<SolItem>(); for (List<SolItem> group1 : merc.getItemContainer()) { for (SolItem i : group1) { itemsList.add(0, i); } } String items = itemsToString(itemsList); json = new JsonObject(); json.addProperty("hull", hullName); json.addProperty("money", money); json.addProperty("items", items); jsons.add(json); } } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String toWrite = gson.toJson(jsons); try { writer = new PrintWriter(fileName, "UTF-8"); writer.write(toWrite); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { logger.error("Could not save mercenaries, " + e.getMessage()); } }

Target:
private static void writeMercs(SolGame game) { PrintWriter writer; ItemContainer mercenaries = game.getHero().getTradeContainer().getMercs(); List<JsonObject> jsons = new ArrayList<JsonObject>(); for (List<SolItem> group : mercenaries) { for (SolItem item : group) { SolShip merc = ((MercItem) item).getSolShip(); String hullName = game.getHullConfigs().getName(merc.getHull().config); int money = (int) merc.getMoney(); ArrayList<SolItem> itemsList = new ArrayList<SolItem>(); for (List<SolItem> group1 : merc.getItemContainer()) { for (SolItem i : group1) { itemsList.add(0, i); } } String items = itemsToString(itemsList); JsonObject json = new JsonObject(); json.addProperty("hull", hullName); json.addProperty("money", money); json.addProperty("items", items); jsons.add(json); } } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String toWrite = gson.toJson(jsons); try { writer = new PrintWriter(MERC_SAVE_FILE, "UTF-8"); writer.write(toWrite); writer.close(); } catch (FileNotFoundException | UnsupportedEncodingException e) { logger.error("Could not save mercenaries, " + e.getMessage()); } }
Source:
private String getTracerConfiguration(DeploymentPhaseContext deploymentPhaseContext) { DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); JBossWebMetaData jbossWebMetaData = getJBossWebMetaData(deploymentUnit); if (null == jbossWebMetaData || null == jbossWebMetaData.getContextParams()) { return null; } for (ParamValueMetaData param : jbossWebMetaData.getContextParams()) { if (TracerInitializer.SMALLRYE_OPENTRACING_TRACER_CONFIGURATION.equals(param.getParamName())) { return param.getParamValue(); } } final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); for (ServiceName serviceName : deploymentPhaseContext.getServiceRegistry().getServiceNames()) { if (serviceName.getCanonicalName().startsWith(TRACER_CAPABILITY_NAME) && support.hasCapability(DEFAULT_TRACER_CAPABILITY.getDynamicName(serviceName.getSimpleName()))) { return serviceName.getSimpleName(); } } return null; }

Target:
private String getTracerConfiguration(DeploymentPhaseContext deploymentPhaseContext) { DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit(); JBossWebMetaData jbossWebMetaData = getJBossWebMetaData(deploymentUnit); if (null == jbossWebMetaData || null == jbossWebMetaData.getContextParams()) { return null; } for (ParamValueMetaData param : jbossWebMetaData.getContextParams()) { if (SMALLRYE_OPENTRACING_TRACER_CONFIGURATION.equals(param.getParamName())) { String value = param.getParamValue(); if (value != null && !value.isEmpty()) { return TRACER_CAPABILITY.getDynamicName(param.getParamValue()); } } } final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT); if (support.hasCapability(DEFAULT_TRACER_CAPABILITY_NAME)) { return WildFlyTracerFactory.getDefaultTracerName(); } return null; }
Source:
public OffsetsForLeaderEpochRequest(Struct struct, short version) { super(ApiKeys.OFFSET_FOR_LEADER_EPOCH, version); replicaId = struct.get(REPLICA_ID); epochsByPartition = new HashMap<>(); for (Object topicAndEpochsObj : struct.get(TOPICS)) { Struct topicAndEpochs = (Struct) topicAndEpochsObj; String topic = topicAndEpochs.get(TOPIC_NAME); for (Object partitionAndEpochObj : topicAndEpochs.get(PARTITIONS)) { Struct partitionAndEpoch = (Struct) partitionAndEpochObj; int partitionId = partitionAndEpoch.get(PARTITION_ID); int leaderEpoch = partitionAndEpoch.get(LEADER_EPOCH); Optional<Integer> currentEpoch = RequestUtils.getLeaderEpoch(partitionAndEpoch, CURRENT_LEADER_EPOCH); TopicPartition tp = new TopicPartition(topic, partitionId); epochsByPartition.put(tp, new PartitionData(currentEpoch, leaderEpoch)); } } }

Target:
public OffsetsForLeaderEpochRequest(Struct struct, short version) { super(ApiKeys.OFFSET_FOR_LEADER_EPOCH, version); replicaId = struct.getOrElse(REPLICA_ID, CONSUMER_REPLICA_ID); epochsByPartition = new HashMap<>(); for (Object topicAndEpochsObj : struct.get(TOPICS)) { Struct topicAndEpochs = (Struct) topicAndEpochsObj; String topic = topicAndEpochs.get(TOPIC_NAME); for (Object partitionAndEpochObj : topicAndEpochs.get(PARTITIONS)) { Struct partitionAndEpoch = (Struct) partitionAndEpochObj; int partitionId = partitionAndEpoch.get(PARTITION_ID); int leaderEpoch = partitionAndEpoch.get(LEADER_EPOCH); Optional<Integer> currentEpoch = RequestUtils.getLeaderEpoch(partitionAndEpoch, CURRENT_LEADER_EPOCH); TopicPartition tp = new TopicPartition(topic, partitionId); epochsByPartition.put(tp, new PartitionData(currentEpoch, leaderEpoch)); } } }
Source:
@Override public Enumerable<Object[]> scan(DataContext root) { root.getRootSchema().add(name, this); final AtomicBoolean cancelFlag = DataContext.Variable.CANCEL_FLAG.get(root); return new AbstractEnumerable<Object[]>() { public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { private final List list = new ArrayList(rows); private int i = -1; @Override public Object[] current() { Object current = list.get(i); if (current == null) { return null; } return current.getClass().isArray() ? (Object[]) current : new Object[]{current}; } @Override public boolean moveNext() { if (cancelFlag != null && cancelFlag.get()) { return false; } return ++i < list.size(); } @Override public void reset() { i = -1; } @Override public void close() { } }; } }; }

Target:
@Override public Enumerable<Object[]> scan(DataContext root) { root.getRootSchema().add(name, this); final AtomicBoolean cancelFlag = DataContext.Variable.CANCEL_FLAG.get(root); return new AbstractEnumerable<Object[]>() { public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { private final List list = new ArrayList(rows); private int i = -1; @Override public Object[] current() { Object current = list.get(i); return current != null && current.getClass().isArray() ? (Object[]) current : new Object[]{current}; } @Override public boolean moveNext() { if (cancelFlag != null && cancelFlag.get()) { return false; } return ++i < list.size(); } @Override public void reset() { i = -1; } @Override public void close() { } }; } }; }
Source:
private void restoreTable( String tableName, TableBackup tableBackup, KijiMetaTable metaTable, Kiji kiji) throws IOException { Preconditions.checkNotNull(tableBackup); Preconditions.checkNotNull(tableBackup.getTableLayoutsBackup()); List<TableLayoutBackupEntry> layouts = tableBackup.getTableLayoutsBackup().getLayouts(); Preconditions.checkArgument(!layouts.isEmpty(), "Backup for table '%s' contains no layout.", tableName); LOG.info("Creating table '{}'.", tableName); long lowestTimestamp = KConstants.END_OF_TIME; TableLayoutBackupEntry initialEntry = null; for (TableLayoutBackupEntry entry : layouts) { if (entry.getTimestamp() < lowestTimestamp) { lowestTimestamp = entry.getTimestamp(); initialEntry = entry; } } final KijiTableLayout initialLayout = KijiTableLayout.newLayout(initialEntry.getLayout()); try { kiji.createTable(tableName, initialLayout.getDesc()); } catch (KijiAlreadyExistsException kaee) { LOG.info("Table already exists in HBase. Continuing with restore operation."); } LOG.info("Restoring layout history for table '%s' (%d layouts).", tableName, tableBackup.getTableLayoutsBackup().getLayouts().size()); metaTable.layoutsFromBackup(tableName, tableBackup.getTableLayoutsBackup()); metaTable.keyValuesFromBackup(tableName, tableBackup.getKeyValueBackup()); }

Target:
private void restoreTable( String tableName, TableBackup tableBackup, KijiMetaTable metaTable, Kiji kiji) throws IOException { Preconditions.checkNotNull(tableBackup); Preconditions.checkNotNull(tableBackup.getTableLayoutsBackup()); List<TableLayoutBackupEntry> layouts = tableBackup.getTableLayoutsBackup().getLayouts(); Preconditions.checkArgument(!layouts.isEmpty(), "Backup for table '%s' contains no layout.", tableName); LOG.info("Creating table '{}'.", tableName); long lowestTimestamp = KConstants.END_OF_TIME; TableLayoutBackupEntry initialEntry = null; for (TableLayoutBackupEntry entry : layouts) { if (entry.getTimestamp() < lowestTimestamp) { lowestTimestamp = entry.getTimestamp(); initialEntry = entry; } } try { kiji.createTable(initialEntry.getLayout()); } catch (KijiAlreadyExistsException kaee) { LOG.info("Table already exists in HBase. Continuing with restore operation."); } LOG.info("Restoring layout history for table '%s' (%d layouts).", tableName, tableBackup.getTableLayoutsBackup().getLayouts().size()); metaTable.layoutsFromBackup(tableName, tableBackup.getTableLayoutsBackup()); metaTable.keyValuesFromBackup(tableName, tableBackup.getKeyValueBackup()); }
Source:
public <U> PriorityQueue<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); throw new UnsupportedOperationException(); }

Target:
public <U> PriorityQueue<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { return flatMap(naturalComparator(), mapper); }
Source:
public boolean remove(T value) { NodePair window = find(value); if (window.second.getValue().compareTo(value) != 0) return false; while (true) { Node next = window.second.nextAndState.getReference(); if (!window.second.nextAndState.attemptMark(next, true)) continue; window.first.nextAndState.compareAndSet(window.second, next, false, false); return true; } }

Target:
public boolean remove(T value) { NodePair window = find(value); if (window.second == null || window.second.getValue().compareTo(value) != 0) return false; while (true) { Node next = window.second.nextAndState.getReference(); if (!window.second.nextAndState.attemptMark(next, true)) continue; window.first.nextAndState.compareAndSet(window.second, next, false, false); return true; } }
Source:
public long createEmbeddedObject(long columnKey, RealmFieldType parentPropertyType) { switch (parentPropertyType) { case OBJECT: parent.checkImmutable(); return nativeCreateEmbeddedObject(nativePtr, columnKey); case LIST: return getModelList(columnKey).createAndAddEmbeddedObject(); default: throw new IllegalArgumentException("Wrong parentPropertyType, expected OBJECT or LIST bur received " + parentPropertyType); } }

Target:
public long createEmbeddedObject(long columnKey, RealmFieldType parentPropertyType) { switch (parentPropertyType) { case OBJECT: parent.checkImmutable(); return nativeCreateEmbeddedObject(nativePtr, columnKey); case LIST: return getModelList(columnKey).createAndAddEmbeddedObject(); default: throw new IllegalArgumentException("Wrong parentPropertyType, expected OBJECT or LIST but received " + parentPropertyType); } }
Source:
protected void buildDocument(Context context, Item item) throws SQLException, IOException { String handle = item.getHandle(); if (handle == null) { handle = handleService.findHandle(context, item); } List<String> locations = getItemLocations(context, item); SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle, locations); log.debug("Building Item: " + handle); doc.addField("archived", item.isArchived()); doc.addField("withdrawn", item.isWithdrawn()); doc.addField("discoverable", item.isDiscoverable()); doc.addField("lastModified", item.getLastModified()); if (item.getSubmitter() != null) { doc.addField("submitter", item.getSubmitter().getID()); } List<DiscoveryConfiguration> discoveryConfigurations = SearchUtils.getAllDiscoveryConfigurations(item); addDiscoveryFields(doc, context, item, discoveryConfigurations); final String typeText = StringUtils.deleteWhitespace(item.getTypeText().toLowerCase()); String acvalue = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty( "discovery.facet.namedtype." + typeText, typeText + SolrServiceImpl.AUTHORITY_SEPARATOR + typeText); if (StringUtils.isNotBlank(acvalue)) { String fvalue = acvalue; addNamedResourceTypeIndex(doc, acvalue, fvalue); } try { writeDocument(doc, new FullTextContentStreams(context, item)); log.info("Wrote Item: " + handle + " to Index"); } catch (RuntimeException e) { log.error("Error while writing item to discovery index: " + handle + " message:" + e.getMessage(), e); } }

Target:
protected void buildDocument(Context context, Item item) throws SQLException, IOException { String handle = item.getHandle(); if (handle == null) { handle = handleService.findHandle(context, item); } List<String> locations = getItemLocations(context, item); SolrInputDocument doc = buildDocument(Constants.ITEM, item.getID(), handle, locations); log.debug("Building Item: " + handle); doc.addField("archived", item.isArchived()); doc.addField("withdrawn", item.isWithdrawn()); doc.addField("discoverable", item.isDiscoverable()); doc.addField("lastModified", item.getLastModified()); EPerson submitter = item.getSubmitter(); if (submitter != null) { addFacetIndex(doc, "submitter", submitter.getID().toString(), submitter.getFullName()); } List<DiscoveryConfiguration> discoveryConfigurations = SearchUtils.getAllDiscoveryConfigurations(item); addDiscoveryFields(doc, context, item, discoveryConfigurations); final String typeText = StringUtils.deleteWhitespace(item.getTypeText().toLowerCase()); String acvalue = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty( "discovery.facet.namedtype." + typeText, typeText + SolrServiceImpl.AUTHORITY_SEPARATOR + typeText); if (StringUtils.isNotBlank(acvalue)) { addNamedResourceTypeIndex(doc, acvalue); } try { writeDocument(doc, new FullTextContentStreams(context, item)); log.info("Wrote Item: " + item.getUniqueIndexID() + " to Index"); } catch (RuntimeException e) { log.error("Error while writing item to discovery index: " + item.getUniqueIndexID() + " message:" + e.getMessage(), e); } }
Source:
public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } if (template.equals("LABEL")) { return true; } if (template.equals("TYPE")) { return true; } if (template.equals("CLASS_TYPE")) { return true; } if (template.matches("^(A|>A|>AT|>AL|>AI|>>A|>>AT|>>AL|>>AI|AT|AL|AI|C|>C) .*")) { return true; } if (template.equals("CI")) { return true; } return false; }

Target:
public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } if (template.equals("LABEL")) { return true; } if (template.equals("TYPE")) { return true; } if (template.equals("CLASS_TYPE")) { return true; } if (template.matches("^(>?C|>{0,2}A[L,T,I]?) .*")) { return true; } if (template.equals("CI")) { return true; } return false; }
Source:
public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { com.google.longrunning.Operation operation = snapshotTable(snapshotName, tableName); try { waitForOperation(operation.getName()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Create snapshot operation was interrupted", e); } }

Target:
public void snapshot(String snapshotName, TableName tableName) throws IOException, SnapshotCreationException, IllegalArgumentException { waitForOperation(snapshotTable(snapshotName, tableName)); }
Source:
public int getWifiEnabledState() { enforceAccessPermission(); mLog.trace("getWifiEnabledStated uid=%").c(Binder.getCallingUid()).flush(); return mWifiStateMachine.syncGetWifiState(); }

Target:
public int getWifiEnabledState() { enforceAccessPermission(); mLog.trace("getWifiEnabledState uid=%").c(Binder.getCallingUid()).flush(); return mWifiStateMachine.syncGetWifiState(); }
Source:
private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException { byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8); byte[] mockBytes; try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length)) { GZIPOutputStream zipStream = new GZIPOutputStream((byteStream)); zipStream.write(dataToCompress); zipStream.close(); mockBytes = byteStream.toByteArray(); } final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse(); mockResponse.setContent(mockBytes); mockResponse.setContentEncoding(contentEncoding); mockResponse.setContentType("text/plain"); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return mockResponse; } }; } }; HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent(); assertFalse(output.isClosed()); assertEquals("abcd", response.parseAsString()); assertTrue(output.isClosed()); }

Target:
private void do_testGetContent_gzipEncoding_finishReading(String contentEncoding) throws IOException { byte[] dataToCompress = "abcd".getBytes(StandardCharsets.UTF_8); byte[] mockBytes; try ( ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length); GZIPOutputStream zipStream = new GZIPOutputStream((byteStream)) ) { zipStream.write(dataToCompress); zipStream.close(); mockBytes = byteStream.toByteArray(); } final MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse(); mockResponse.setContent(mockBytes); mockResponse.setContentEncoding(contentEncoding); mockResponse.setContentType("text/plain"); HttpTransport transport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException { return new MockLowLevelHttpRequest() { @Override public LowLevelHttpResponse execute() throws IOException { return mockResponse; } }; } }; HttpRequest request = transport.createRequestFactory().buildHeadRequest(HttpTesting.SIMPLE_GENERIC_URL); HttpResponse response = request.execute(); try (TestableByteArrayInputStream output = (TestableByteArrayInputStream) mockResponse.getContent()) { assertFalse(output.isClosed()); assertEquals("abcd", response.parseAsString()); assertTrue(output.isClosed()); } }
Source:
private void safeCloseStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }

Target:
private static void safeCloseStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }
Source:
public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); int count; while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { buffer.writerIndex(buffer.writerIndex() + count); if (buffer.writableBytes() <= 0) { buffer.ensureWritable(count); } } return buffer.writerIndex() - initial; }

Target:
public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); int count; while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { buffer.writerIndex(buffer.writerIndex() + count); buffer.ensureWritable(count); } return buffer.writerIndex() - initial; }
Source:
public InputStream getInputStream(boolean buffered) { if (inputStream != null) { return inputStream; } InputStream inputStream = requestContext.getInputStream(); return inputStream; }

Target:
public InputStream getInputStream(boolean buffered) { return requestContext.getInputStream(); }
Source:
void setColumns(List<String> columns) { for (ListIterator<String> iterator = columns.listIterator(); iterator .hasNext();) { String string = iterator.next(); iterator.set(StringUtils.defaultIfEmpty(string, StringConstants.UNICODE_NULL)); } m_columns = columns; }

Target:
void setColumns(List<String> columns) { m_columns = columns; }
Source:
public void onEventMainThread(DiscussionCommentPostedEvent event) { if (null != event.getParent() && event.getParent().getIdentifier().equalsIgnoreCase(discussionResponse.getIdentifier())) { discussionCommentsAdapter.insertCommentAtEnd(event.getComment()); } }

Target:
public void onEventMainThread(DiscussionCommentPostedEvent event) { if (null != event.getParent() && event.getParent().getIdentifier().equals(discussionResponse.getIdentifier())) { discussionCommentsAdapter.insertCommentAtEnd(event.getComment()); } }
Source:
private WinRm getService() { if (winrm != null) { return winrm; } else { if (context != null) { cleanupContext = false; } else { context = WinRmClientContext.newInstance(); cleanupContext = true; } Bus prevBus = BusFactory.getAndSetThreadDefaultBus(context.getBus()); try { return createService(); } finally { if (BusFactory.getThreadDefaultBus(false) != prevBus) { BusFactory.setThreadDefaultBus(prevBus); } } } }

Target:
private synchronized WinRm getService() { if (winrm != null) { return winrm; } else { if (context != null) { cleanupContext = false; } else { context = WinRmClientContext.newInstance(); cleanupContext = true; } Bus prevBus = BusFactory.getAndSetThreadDefaultBus(context.getBus()); try { return createService(); } finally { if (BusFactory.getThreadDefaultBus(false) != prevBus) { BusFactory.setThreadDefaultBus(prevBus); } } } }
Source:
public String deployJob( @CliOption(key = { "", "name" }, help = "the name of the job to deploy", mandatory = true, optionContext = "existing-job undeployed disable-string-converter") String name, @CliOption(key = { PROPERTIES_OPTION }, help = "the properties for this deployment", mandatory = false) String properties, @CliOption(key = { PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)", mandatory = false) File propertiesFile ) throws IOException { int which = Assertions.atMostOneOf(PROPERTIES_OPTION, properties, PROPERTIES_FILE_OPTION, propertiesFile); Map<String, String> propertiesToUse; switch (which) { case 0: propertiesToUse = DeploymentPropertiesFormat.parseDeploymentProperties(properties); break; case 1: Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(propertiesFile)) { props.load(fis); } propertiesToUse = DeploymentPropertiesFormat.convert(props); break; default: throw new AssertionError(); } jobOperations().deploy(name, propertiesToUse); return String.format("Deployed stream '%s'", name); }

Target:
public String deployJob( @CliOption(key = { "", "name" }, help = "the name of the job to deploy", mandatory = true, optionContext = "existing-job undeployed disable-string-converter") String name, @CliOption(key = { PROPERTIES_OPTION }, help = "the properties for this deployment", mandatory = false) String properties, @CliOption(key = { PROPERTIES_FILE_OPTION }, help = "the properties for this deployment (as a File)", mandatory = false) File propertiesFile ) throws IOException { int which = Assertions.atMostOneOf(PROPERTIES_OPTION, properties, PROPERTIES_FILE_OPTION, propertiesFile); Map<String, String> propertiesToUse; switch (which) { case 0: propertiesToUse = DeploymentPropertiesFormat.parseDeploymentProperties(properties); break; case 1: Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(propertiesFile)) { props.load(fis); } propertiesToUse = DeploymentPropertiesFormat.convert(props); break; default: throw new AssertionError(); } jobOperations().deploy(name, propertiesToUse); return String.format("Deployed job '%s'", name); }