auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testStoredRenditionsCleanup() { DocumentModel file1 = createBlobDoc("File"); DocumentModel file2 = createBlobDoc("File"); Rendition ren1 = renditionService.getRendition(file1, "dummyRendition", true); assertNotNull(ren1); DocumentModel renditionDoc1 = ren1.getHostDocument(); assertTrue(renditionDoc1.isVersion()); DocumentRef liveRenditionRef1 = new IdRef(renditionDoc1.getSourceId()); assertTrue(session.exists(liveRenditionRef1)); Rendition ren2 = renditionService.getRendition(file2, "dummyRendition", true); assertNotNull(ren2); DocumentModel renditionDoc2 = ren2.getHostDocument(); assertTrue(renditionDoc2.isVersion()); DocumentRef liveRenditionRef2 = new IdRef(renditionDoc2.getSourceId()); assertTrue(session.exists(liveRenditionRef2)); session.removeDocument(file1.getRef()); eventService.waitForAsyncCompletion(); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); renditionService.deleteStoredRenditions(session.getRepositoryName()); eventService.waitForAsyncCompletion(); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); assertFalse(session.exists(liveRenditionRef1)); assertFalse(session.exists(renditionDoc1.getRef())); assertTrue(session.exists(liveRenditionRef2)); assertTrue(session.exists(renditionDoc2.getRef())); }

Target:
public void testStoredRenditionsCleanup() { DocumentModel file1 = createBlobDoc("File"); DocumentModel file2 = createBlobDoc("File"); Rendition ren1 = renditionService.getRendition(file1, "dummyRendition", true); assertNotNull(ren1); DocumentModel renditionDoc1 = ren1.getHostDocument(); assertTrue(renditionDoc1.isVersion()); DocumentRef liveRenditionRef1 = new IdRef(renditionDoc1.getSourceId()); assertTrue(session.exists(liveRenditionRef1)); Rendition ren2 = renditionService.getRendition(file2, "dummyRendition", true); assertNotNull(ren2); DocumentModel renditionDoc2 = ren2.getHostDocument(); assertTrue(renditionDoc2.isVersion()); DocumentRef liveRenditionRef2 = new IdRef(renditionDoc2.getSourceId()); assertTrue(session.exists(liveRenditionRef2)); session.removeDocument(file1.getRef()); txFeature.nextTransaction(); renditionService.deleteStoredRenditions(session.getRepositoryName()); txFeature.nextTransaction(); assertFalse(session.exists(liveRenditionRef1)); assertFalse(session.exists(renditionDoc1.getRef())); assertTrue(session.exists(liveRenditionRef2)); assertTrue(session.exists(renditionDoc2.getRef())); }
Source:
protected void writeRecords(Map<I, EntityStorageRecord> records) { final RecordStorage<I> storage = getRecordStorage(); storage.write(records); }

Target:
protected void writeRecords(Map<I, EntityStorageRecord> records) { final RecordStorage<I> storage = recordStorage(); storage.write(records); }
Source:
public <T extends E> List<T> merge(final Optional<Id> id, Iterable<T> equivalents, Application application, Set<Annotation> activeAnnotations) { if (!application.getConfiguration().isPrecedenceEnabled()) { return ImmutableList.copyOf(equivalents); } Ordering<Sourced> publisherOrdering = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourced::getSource); Ordering<T> equivsOrdering = publisherOrdering.compound(ID_ORDERING); List<T> sortedEquivalents = equivsOrdering.sortedCopy(equivalents); if (sortedEquivalents.isEmpty()) { return ImmutableList.of(); } if (trivialMerge(sortedEquivalents)) { return ImmutableList.of( strategy.merge( sortedEquivalents, application, activeAnnotations ) ); } T chosen = sortedEquivalents.get(0); if (id.isPresent()) { Optional<T> requested = Iterables.tryFind(equivalents, idIs(id.get())); if (requested.isPresent() && chosen.getSource().equals(requested.get().getSource())) { sortedEquivalents.remove(requested.get()); sortedEquivalents.add(0, requested.get()); } } return ImmutableList.of(strategy.merge(sortedEquivalents, application, activeAnnotations)); }

Target:
public <T extends E> List<T> merge(final Optional<Id> id, Iterable<T> equivalents, Application application, Set<Annotation> activeAnnotations) { if (!application.getConfiguration().isPrecedenceEnabled()) { return ImmutableList.copyOf(equivalents); } Ordering<Sourced> publisherOrdering = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourced::getSource); Ordering<T> equivsOrdering = publisherOrdering.compound(ID_ORDERING); List<T> sortedEquivalents = equivsOrdering.sortedCopy(equivalents); if (sortedEquivalents.isEmpty()) { return ImmutableList.of(); } T chosen = sortedEquivalents.get(0); if (id.isPresent() && sortedEquivalents.size() > 1) { Optional<T> requested = Iterables.tryFind(equivalents, idIs(id.get())); if (requested.isPresent() && chosen.getSource().equals(requested.get().getSource())) { sortedEquivalents.remove(requested.get()); sortedEquivalents.add(0, requested.get()); } } return ImmutableList.of(strategy.merge(sortedEquivalents, application, activeAnnotations)); }
Source:
public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(dataLakeFileAsyncClient.create()) .then(dataLakeFileAsyncClient.upload(createRandomByteBufferFlux(options.getSize()), null, true)) .then(); }

Target:
public Mono<Void> globalSetupAsync() { return super.globalSetupAsync() .then(dataLakeFileAsyncClient.create()) .then(); }
Source:
public Object getTarget() { Jenkins.get().checkPermission(Jenkins.CONFIGURE); return this; }

Target:
public Object getTarget() { Jenkins.get().checkPermission(Jenkins.ADMINISTER); return this; }
Source:
private String generateADGroupSearchFilter(String groupName) { final StringBuilder userObjectFilter = new StringBuilder(); userObjectFilter.append("(objectClass="); userObjectFilter.append(_ldapConfiguration.getUserObject()); userObjectFilter.append(")"); final StringBuilder memberOfFilter = new StringBuilder(); String groupCnName = _ldapConfiguration.getCommonNameAttribute() + "=" +groupName + "," + _ldapConfiguration.getBaseDn(); memberOfFilter.append("(memberOf:1.2.840.113556.1.4.1941:="); memberOfFilter.append(groupCnName); memberOfFilter.append(")"); final StringBuilder result = new StringBuilder(); result.append("(&"); result.append(userObjectFilter); result.append(memberOfFilter); result.append(")"); s_logger.debug("group search filter = " + result); return result.toString(); }

Target:
private String generateADGroupSearchFilter(String groupName) { final StringBuilder userObjectFilter = new StringBuilder(); userObjectFilter.append("(objectClass="); userObjectFilter.append(_ldapConfiguration.getUserObject()); userObjectFilter.append(")"); final StringBuilder memberOfFilter = new StringBuilder(); String groupCnName = _ldapConfiguration.getCommonNameAttribute() + "=" +groupName + "," + _ldapConfiguration.getBaseDn(); memberOfFilter.append("(" + MICROSOFT_AD_NESTED_MEMBERS_FILTER + ":="); memberOfFilter.append(groupCnName); memberOfFilter.append(")"); final StringBuilder result = new StringBuilder(); result.append("(&"); result.append(userObjectFilter); result.append(memberOfFilter); result.append(")"); s_logger.debug("group search filter = " + result); return result.toString(); }
Source:
WorkspaceEventsUnsubscriber(EventBus eventBus, AppContext appContext, SubscriptionManagerClient subscriptionManagerClient) { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, e -> { final Map<String, String> scope = singletonMap("workspaceId", appContext.getWorkspaceId()); subscriptionManagerClient.unSubscribe("ws-master", "workspace/statusChanged", scope); subscriptionManagerClient.unSubscribe("ws-master", "machine/statusChanged", scope); subscriptionManagerClient.unSubscribe("ws-master", "server/statusChanged", scope); subscriptionManagerClient.unSubscribe("ws-master-output", "machine/log", scope); subscriptionManagerClient.unSubscribe("ws-master-output", "installer/log", scope); }); }

Target:
WorkspaceEventsUnsubscriber(EventBus eventBus, AppContext appContext, SubscriptionManagerClient subscriptionManagerClient) { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, e -> { Map<String, String> scope = singletonMap("workspaceId", appContext.getWorkspaceId()); subscriptionManagerClient.unSubscribe("workspace/statuses", "workspace/statusChanged", scope); subscriptionManagerClient.unSubscribe("workspace/statuses", "machine/statusChanged", scope); subscriptionManagerClient.unSubscribe("workspace/statuses", "server/statusChanged", scope); subscriptionManagerClient.unSubscribe("workspace/output", "machine/log", scope); subscriptionManagerClient.unSubscribe("workspace/output", "installer/log", scope); }); }
Source:
private void onTextChangeOfPeopleSearchEditText() { etSearchPeople.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { peopleAdapter.changeCursor(getPeopleCursorGenerator().call()); } catch (Exception e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable s) { } }); }

Target:
private void onTextChangeOfPeopleSearchEditText() { etSearchPeople.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { peopleAdapter.changeCursor(getPeopleCursorGenerator().call()); } catch (Exception e) { ZLog.logException(e); } } @Override public void afterTextChanged(Editable s) { } }); }
Source:
private File checkIfItIsAlreadyExtracted(final String downloadedZipMd5hash) { File[] dirs = new File(mavenTargetDir).listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && downloadedZipMd5hash.equals(file.getName()); } }); if (dirs != null && dirs.length > 0) { return dirs[0]; } return null; }

Target:
private File checkIfItIsAlreadyExtracted(final String downloadedZipMd5hash) { File[] dirs = new File(mavenTargetDir).listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory() && downloadedZipMd5hash.equals(file.getName()); } }); if (dirs != null && dirs.length > 0) { return dirs[0]; } return null; }
Source:
public void testIsValid() { int hours = -18; while (true) { ZoneId zone = ZoneId.ofOffset( "UTC", ZoneOffset.ofHours( hours ) ); ChronoZonedDateTime future = ZonedDateTime.now( zone ).plusHours( 1 ); ChronoZonedDateTime past = ZonedDateTime.now( zone ).minusHours( 1 ); assertTrue( constraint.isValid( null, null ) ); assertTrue( constraint.isValid( past, null ) ); assertFalse( constraint.isValid( future, null ) ); hours++; if (hours > 18) { break; } } }

Target:
public void testIsValid() { assertTrue( constraint.isValid( null, null ), "null fails validation." ); for ( int i = -18; i <= 18; i++ ) { ZoneId zone = ZoneId.ofOffset( "UTC", ZoneOffset.ofHours( i ) ); ChronoZonedDateTime future = ZonedDateTime.now( zone ).plusHours( 1 ); ChronoZonedDateTime past = ZonedDateTime.now( zone ).minusHours( 1 ); assertTrue( constraint.isValid( past, null ), "Past ZonedDateTime '" + past + "' fails validation."); assertFalse( constraint.isValid( future, null ), "Future ZonedDateTime '" + future + "' validated as past."); } }
Source:
protected void doStart() { if (getDistributedObject() instanceof IMap) { ((IMap<?, ?>) getDistributedObject()).addEntryListener( new HazelcastEntryListener(this), new SqlPredicate(this.predicate), true); } else { throw new IllegalStateException( "Invalid 'cache' type is set. Only IMap cache object is acceptable for continuous query."); } }

Target:
protected void doStart() { setHazelcastRegisteredEventListenerId(((IMap<?, ?>) this.distributedObject) .addEntryListener(new HazelcastEntryListener(), new SqlPredicate(this.predicate), this.includeValue)); }
Source:
private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { if (subGroups.isEmpty()) { return runningQueries.stream() .map(QueryExecution::getQueryInfo) .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.empty())) .collect(toImmutableList()); } return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); }

Target:
private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { synchronized (root) { if (subGroups.isEmpty()) { return runningQueries.stream() .map(QueryExecution::getQueryInfo) .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.empty())) .collect(toImmutableList()); } return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); } }
Source:
public void showView(String viewId, @ScriptParameter(defaultValue = "") String secondaryId) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); IViewPart view; if (secondaryId.isEmpty()) { view = activePage.showView(viewId); } else { view = activePage.showView(viewId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE); } if (view instanceof ScriptedTimeGraphView) { ((ScriptedTimeGraphView) view).refreshIfNeeded(); } } catch (final PartInitException e) { } } }); }

Target:
public void showView(String viewId, @ScriptParameter(defaultValue = "") String secondaryId) { Display.getDefault().asyncExec(() -> { try { final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage(); IViewPart view; if (secondaryId.isEmpty()) { view = activePage.showView(viewId); } else { view = activePage.showView(viewId, secondaryId, IWorkbenchPage.VIEW_ACTIVATE); } if (view instanceof ScriptedTimeGraphView) { ((ScriptedTimeGraphView) view).refreshIfNeeded(); } } catch (final PartInitException e) { } }); }
Source:
public String toSubscribeMessage() { prepareChannel(); final Map<Object, Object> dataMap = new LinkedHashMap<Object, Object>(); dataMap.put("channel", name); dataMap.put("auth", new String(authorizerData.getAuth())); if (authorizerData.getChannelData() != null) { dataMap.put("channel_data", authorizerData.channelData); } final Map<Object, Object> jsonObject = new LinkedHashMap<Object, Object>(); jsonObject.put("event", "pusher:subscribe"); jsonObject.put("authorizerData", dataMap); jsonObject.put("data", dataMap); return GSON.toJson(jsonObject); }

Target:
public String toSubscribeMessage() { String authKey = authenticate(); final Map<Object, Object> dataMap = new LinkedHashMap<Object, Object>(); dataMap.put("channel", name); dataMap.put("auth", authKey); final Map<Object, Object> jsonObject = new LinkedHashMap<Object, Object>(); jsonObject.put("event", "pusher:subscribe"); jsonObject.put("data", dataMap); return GSON.toJson(jsonObject); }
Source:
public void testFirstUpstreamBuildFirstProjectHasJustOneUpstreamJob() throws Exception { final Stapler stapler = Mockito.mock(Stapler.class); final HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); final StaplerRequest staplerRequest = new RequestImpl(stapler, servletRequest, Collections.EMPTY_LIST, null); { final WebApp webApp = Mockito.mock(WebApp.class); Mockito.when(webApp.getClassLoader()).thenReturn(this.getClass().getClassLoader()); Mockito.when(stapler.getWebApp()).thenReturn(webApp); } FreeStyleProject upstream = jenkins.createFreeStyleProject("upstream"); FreeStyleProject build = jenkins.createFreeStyleProject("build"); upstream.getPublishersList().add(new BuildTrigger("build", false)); jenkins.getInstance().rebuildDependencyGraph(); jenkins.buildAndAssertSuccess(upstream); jenkins.waitUntilNoActivity(); assertNotNull(upstream.getLastBuild()); assertNotNull(build.getLastBuild()); assertEquals(build.getLastBuild(), BuildUtil.getFirstUpstreamBuild(build.getLastBuild(), build)); Pipeline pipeline = Pipeline.extractPipeline("Pipeline", build); Component component = new Component("Component", "build", null, false, 3, pagingEnabledFalse, 1); List<Pipeline> pipelines = pipeline.createPipelineLatest(1, Jenkins.getInstance(), pagingEnabledFalse, component); assertEquals(1, pipelines.size()); assertEquals(1, pipelines.get(0).getTriggeredBy().size()); assertEquals(TriggerCause.TYPE_UPSTREAM, pipelines.get(0).getTriggeredBy().get(0).getType()); }

Target:
public void testFirstUpstreamBuildFirstProjectHasJustOneUpstreamJob() throws Exception { StaplerRequest request = Mockito.mock(StaplerRequest.class); FreeStyleProject upstream = jenkins.createFreeStyleProject("upstream"); FreeStyleProject build = jenkins.createFreeStyleProject("build"); upstream.getPublishersList().add(new BuildTrigger("build", false)); jenkins.getInstance().rebuildDependencyGraph(); jenkins.buildAndAssertSuccess(upstream); jenkins.waitUntilNoActivity(); assertNotNull(upstream.getLastBuild()); assertNotNull(build.getLastBuild()); assertEquals(build.getLastBuild(), BuildUtil.getFirstUpstreamBuild(build.getLastBuild(), build)); Pipeline pipeline = Pipeline.extractPipeline("Pipeline", build); Component component = new Component("Component", "build", null, false, 3, pagingEnabledFalse, 1); List<Pipeline> pipelines = pipeline.createPipelineLatest(1, Jenkins.getInstance(), pagingEnabledFalse, component); assertEquals(1, pipelines.size()); assertEquals(1, pipelines.get(0).getTriggeredBy().size()); assertEquals(TriggerCause.TYPE_UPSTREAM, pipelines.get(0).getTriggeredBy().get(0).getType()); }
Source:
public List<Action> getActions() { if(actions == null) { synchronized (this) { if(actions == null) { actions = new CopyOnWriteArrayList<Action>(); } } } else { for (Action action : actions) { if (action == null) { LOGGER.log(Level.WARNING, "Actionable#getActions: Found a null action: " + action.getClass().toString()); actions.remove(action); } } } return actions; }

Target:
public List<Action> getActions() { if(actions == null) { synchronized (this) { if (actions == null) { actions = new CopyOnWriteArrayList<Action>(); } else { Iterator<Action> actionIterator = actions.iterator(); Action action; while (actionIterator.hasNext()) { action = actionIterator.next(); if (!(action instanceof Action)) { LOGGER.log(Level.WARNING, "Not action found in " + this.getClass().getName()); actionIterator.remove(); } } } } } return actions; }
Source:
public void customize() { String command = String.format("mkdir -p %s", getRunDir()); newScript(LAUNCHING) .updateTaskAndFailOnNonZeroResultCode() .body.append(command).execute(); Map<String, String> scripts = entity.getConfig(MongoDBClient.SCRIPTS); for (String scriptName : scripts.keySet()) { copyResource(scripts.get(scriptName), getRunDir() + "/" + scriptName + ".js"); } }

Target:
public void customize() { String command = String.format("mkdir -p %s", getUserScriptDir()); newScript(CUSTOMIZING) .updateTaskAndFailOnNonZeroResultCode() .body.append(command).execute(); Map<String, String> scripts = entity.getConfig(MongoDBClient.JS_SCRIPTS); for (String scriptName : scripts.keySet()) { copyResource(scripts.get(scriptName), getUserScriptDir() + scriptName + ".js"); } }
Source:
private InsertType updateDropInteraction(int dropAction, @Nullable Transferable transferable) { DragDropInteraction interaction = (DragDropInteraction)myCurrentInteraction; assert interaction != null; if (transferable == null) { return null; } DnDTransferItem item = NlModel.getTransferItem(transferable, false ); if (item == null) { return null; } ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView == null) { return null; } NlModel model = screenView.getModel(); DragType dragType = dropAction == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; InsertType insertType = model.determineInsertType(dragType, item, false ); interaction.setType(dragType); interaction.setTransferItem(item); List<NlComponent> dragged = interaction.getDraggedComponents(); List<NlComponent> components; if (insertType.isMove()) { components = model.getSelectionModel().getSelection(); } else { components = model.createComponents(screenView, item, insertType); if (components == null) { return null; } } if (dragged.size() != components.size()) { throw new AssertionError("Problem with drop: dragged.size != components.size"); } for (int index = 0; index < dragged.size(); index++) { components.get(index).x = dragged.get(index).x; components.get(index).y = dragged.get(index).y; } dragged.clear(); dragged.addAll(components); return insertType; }

Target:
private InsertType updateDropInteraction(int dropAction, @Nullable Transferable transferable) { if (transferable == null) { return null; } DnDTransferItem item = NlModel.getTransferItem(transferable, false ); if (item == null) { return null; } ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView == null) { return null; } NlModel model = screenView.getModel(); DragType dragType = dropAction == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; InsertType insertType = model.determineInsertType(dragType, item, false ); DragDropInteraction interaction = (DragDropInteraction)myCurrentInteraction; assert interaction != null; interaction.setType(dragType); interaction.setTransferItem(item); List<NlComponent> dragged = interaction.getDraggedComponents(); List<NlComponent> components; if (insertType.isMove()) { components = model.getSelectionModel().getSelection(); } else { components = model.createComponents(screenView, item, insertType); if (components == null) { return null; } } if (dragged.size() != components.size()) { throw new AssertionError( String.format("Problem with drop: dragged.size(%1$d) != components.size(%1$d)", dragged.size(), components.size())); } for (int index = 0; index < dragged.size(); index++) { components.get(index).x = dragged.get(index).x; components.get(index).y = dragged.get(index).y; } dragged.clear(); dragged.addAll(components); return insertType; }
Source:
private void registerToLogReplicationLock() { try { IRetry.build(IntervalRetry.class, () -> { try { LockClient lock = new LockClient(nodeId, getCorfuRuntime()); LockListener logReplicationLockListener = new LogReplicationLockListener(this); lock.registerInterest(LOCK_GROUP, LOCK_NAME, logReplicationLockListener); } catch (Exception e) { log.error("Error while attempting to register interest on log replication lock {}:{}", LOCK_GROUP, LOCK_NAME, e); throw new RetryNeededException(); } return null; }).run(); } catch (InterruptedException e) { log.error("Unrecoverable exception when attempting to register interest on log replication lock.", e); throw new UnrecoverableCorfuError(e); } }

Target:
private void registerToLogReplicationLock() { try { IRetry.build(IntervalRetry.class, () -> { try { LockClient lock = new LockClient(logReplicationNodeId, getCorfuRuntime()); LockListener logReplicationLockListener = new LogReplicationLockListener(this); lock.registerInterest(LOCK_GROUP, LOCK_NAME, logReplicationLockListener); } catch (Exception e) { log.error("Error while attempting to register interest on log replication lock {}:{}", LOCK_GROUP, LOCK_NAME, e); throw new RetryNeededException(); } return null; }).run(); } catch (InterruptedException e) { log.error("Unrecoverable exception when attempting to register interest on log replication lock.", e); throw new UnrecoverableCorfuInterruptedError(e); } }
Source:
private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] os = new byte[bytes.length]; int j = 0; for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 2 >= bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); byte c1 = bytes[i + 1], c2 = bytes[i + 2]; int val; try { val = (RawParseUtils.parseHexInt4(c1) << 4) | RawParseUtils.parseHexInt4(c2); } catch (ArrayIndexOutOfBoundsException e) { throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); } os[j++] = (byte) val; i += 2; } else os[j++] = c; } return RawParseUtils.decode(os, 0, j); }

Target:
private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] os = new byte[bytes.length]; int j = 0; for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 2 >= bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); os[j++] = parseHexByte(bytes[i + 1], bytes[i + 2]);; i += 2; } else os[j++] = c; } return RawParseUtils.decode(os, 0, j); }
Source:
public void acceptsInstanceMethodReferences() throws Exception { final Environment.Mock mock = new Environment.Mock(); final File license = this.rule .savePackageInfo(new File(mock.basedir(), DIRECTORY)) .withLines(new String[] {"Hello."}) .withEol("\n") .file(); final String content = Joiner.on("\n").join( " ", "package foo;", " ", "public final class Main {", " ", " private void start() {", " Collections.singletonList(\"1\")", " .forEach(this::doSomething);", " }", " ", " private void doSomething(final String value) {", " System.out.println(value);", " }", "}", "" ); final StringWriter writer = new StringWriter(); org.apache.log4j.Logger.getRootLogger().addAppender( new WriterAppender(new SimpleLayout(), writer) ); final Environment env = mock.withParam( CheckstyleValidatorTest.LICENSE_PROP, this.toURL(license) ).withFile("src/main/java/foo/Main.java", content); new CheckstyleValidator().validate(env); MatcherAssert.assertThat( writer.toString(), Matchers.containsString("No Checkstyle violations found") ); }

Target:
public void acceptsInstanceMethodReferences() throws Exception { final Environment.Mock mock = new Environment.Mock(); final File license = this.rule.savePackageInfo( new File(mock.basedir(), CheckstyleValidatorTest.DIRECTORY) ).withLines(new String[] {"Hello."}) .withEol("\n") .file(); final String content = Joiner.on("\n").join( " ", "package foo;", " ", "public final class Main {", " ", " private void start() {", " Collections.singletonList(\"1\")", " .forEach(this::doSomething);", " }", " ", " private void doSomething(final String value) {", " System.out.println(value);", " }", "}", "" ); final StringWriter writer = new StringWriter(); org.apache.log4j.Logger.getRootLogger().addAppender( new WriterAppender(new SimpleLayout(), writer) ); final Environment env = mock.withParam( CheckstyleValidatorTest.LICENSE_PROP, this.toURL(license) ).withFile("src/main/java/foo/Main.java", content); new CheckstyleValidator().validate(env); MatcherAssert.assertThat( writer.toString(), Matchers.containsString("No Checkstyle violations found") ); }
Source:
private Operation<Void> actionComplete(final List<ResourceBasedNode<?>> nodes) { final ProjectDescriptor project = appContext.getCurrentProject().getRootProject(); return new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { if (actionCompletedCallBack != null) { actionCompletedCallBack.onSuccess(null); } Map<String, List<String>> atributes = project.getAttributes(); if (!(atributes.containsKey("vcs.provider.name") && atributes.get("vcs.provider.name").contains("git"))) { return; } final Unmarshallable<Status> unmarshall = dtoUnmarshallerFactory.newUnmarshaller(Status.class); gitService.status(project, new AsyncRequestCallback<Status>(unmarshall) { @Override protected void onSuccess(final Status result) { if (!result.getMissing().isEmpty()) { askAddToIndex(project, nodes, result.getMissing()); } } @Override protected void onFailure(Throwable exception) { notificationManager.showError(exception.getMessage()); } }); } }; }

Target:
private Operation<Void> actionComplete(final List<ResourceBasedNode<?>> nodes) { final ProjectConfigDto project = appContext.getCurrentProject().getRootProject(); return new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { if (actionCompletedCallBack != null) { actionCompletedCallBack.onSuccess(null); } Map<String, List<String>> atributes = project.getAttributes(); if (!(atributes.containsKey("vcs.provider.name") && atributes.get("vcs.provider.name").contains("git")) || nodes.get(0) instanceof ProjectNode) { return; } final Unmarshallable<Status> unmarshall = dtoUnmarshallerFactory.newUnmarshaller(Status.class); gitService.status(project, new AsyncRequestCallback<Status>(unmarshall) { @Override protected void onSuccess(final Status result) { if (!result.getMissing().isEmpty()) { askAddToIndex(project, nodes, result.getMissing()); } } @Override protected void onFailure(Throwable exception) { notificationManager.showError(exception.getMessage()); } }); } }; }
Source:
public GetbtcPlaceOrder placeGetbtcOrder(BigDecimal amount, String currency, BigDecimal price,String type) throws IOException { Map params = new HashMap(); params.put("api_key", this.apiKey); params.put("nonce", System. currentTimeMillis()); try { params.put("signature", RestSignUtil.getHmacSHA256(params, this.secretKey)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return exxAuthenticated.placeLimitOrder(params); }

Target:
public GetbtcPlaceOrder placeGetbtcOrder( BigDecimal amount, String currency, BigDecimal price, String type) throws IOException { Map params = new HashMap(); params.put("api_key", this.apiKey); params.put("nonce", System.currentTimeMillis()); try { params.put("signature", RestSignUtil.getHmacSHA256(params, this.secretKey)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } return exxAuthenticated.placeLimitOrder(params); }
Source:
protected Repository getRepository() throws ResourceException { if (this.repository == null) { this.repository = deployRepository(repositoryURL); } return this.repository; }

Target:
protected synchronized Repository getRepository() throws ResourceException { if (this.repository == null) { this.repository = deployRepository(repositoryURL); } return this.repository; }
Source:
public String printRelationsNew(ParsedSentence parse) { FeatureNode root = parse.getLeft(); RuleSet relexRuleSet = _relex2LogicRuleLoader.getFreshRuleSet(); LogicProcessor ruleProcessor = new LogicProcessor(relexRuleSet); String schemeOutput = ruleProcessor.applyRulesToParse(root); String parseNode = "(ParseNode \"" + parse.getIDString() + "\")"; String interpretationNode = "(InterpretationNode \"" + parse.getIDString() + "_interpretation_$X" + "\")"; schemeOutput = schemeOutput.replaceAll("sentence_index", parseNode); schemeOutput = schemeOutput.replaceAll("interpretation_index", interpretationNode); schemeOutput = schemeOutput.concat("(r2l-marker-processing)\n"); return schemeOutput; }

Target:
public String printRelationsNew(ParsedSentence parse) { FeatureNode root = parse.getLeft(); RuleSet relexRuleSet = _relex2LogicRuleLoader.getFreshRuleSet(); LogicProcessor ruleProcessor = new LogicProcessor(relexRuleSet); String schemeOutput = ruleProcessor.applyRulesToParse(root); String parseNode = "(ParseNode \"" + parse.getIDString() + "\")"; String interpretationNode = "(InterpretationNode \"" + parse.getIDString() + "_interpretation_$X" + "\")"; schemeOutput = schemeOutput.replaceAll("sentence_index", parseNode); schemeOutput = schemeOutput.replaceAll("interpretation_index", Matcher.quoteReplacement(interpretationNode)); schemeOutput = schemeOutput.concat("(r2l-marker-processing)\n"); return schemeOutput; }
Source:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warn("Could not perform live snapshot due to error, VM will still be configured to the new created snapshot", e); addCustomValue("SnapshotName", getSnapshotName()); addCustomValue("VmName", getVmName()); updateCallStackFromThrowable(e); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }

Target:
private void handleVdsLiveSnapshotFailure(VdcBLLException e) { log.warn("Could not perform live snapshot due to error, VM will still be configured to the new created" + " snapshot: {}", e.getMessage()); log.debug("Exception", e); addCustomValue("SnapshotName", getSnapshotName()); addCustomValue("VmName", getVmName()); updateCallStackFromThrowable(e); AuditLogDirector.log(this, AuditLogType.USER_CREATE_LIVE_SNAPSHOT_FINISHED_FAILURE); }
Source:
private String generateAcronym(String phrase) { String newPhrase = phrase.replace("_", ""); return Arrays.stream(newPhrase.split("(?!')\\W")) .filter(word -> !word.isEmpty()) .map(word -> word.substring(0, 1)) .collect(Collectors.joining()) .toUpperCase(); }

Target:
private String generateAcronym(String phrase) { String phraseWithoutUnderscores = phrase.replace("_", ""); return Arrays.stream(phraseWithoutUnderscores.split("(?!')\\W")) .filter(word -> !word.isEmpty()) .map(word -> word.substring(0, 1)) .collect(Collectors.joining()) .toUpperCase(); }
Source:
public static void toJSON(OutputWriter jsonWriter, Stage stage) { jsonWriter.add("name", stage.getName()); jsonWriter.add("counter", stage.getCounter()); jsonWriter.add("approval_type", stage.getApprovalType()); jsonWriter.add("approved_by", stage.getApprovedBy()); jsonWriter.add("created_time", stage.getCreatedTime().getTime()); jsonWriter.add("last_transitioned_time", stage.getLastTransitionedTime().getTime()); if (stage.getResult() != null) { jsonWriter.add("result", stage.getResult().toString()); if (stage.getResult() == StageResult.Cancelled) { jsonWriter.add("cancelled_by", stage.getCancelledBy() == null? "GoCD" : stage.getCancelledBy()); } } if (stage.getRerunOfCounter() == null) { jsonWriter.add("rerun_of_counter", (String) null); } else { jsonWriter.add("rerun_of_counter", stage.getRerunOfCounter()); } jsonWriter.add("fetch_materials", stage.shouldFetchMaterials()); jsonWriter.add("clean_working_directory", stage.shouldCleanWorkingDir()); jsonWriter.add("artifacts_deleted", stage.isArtifactsDeleted()); if (stage.getIdentifier() != null) { jsonWriter.add("pipeline_name", stage.getIdentifier().getPipelineName()); jsonWriter.add("pipeline_counter", stage.getIdentifier().getPipelineCounter()); } jsonWriter.addChildList("jobs", jobsWriter -> stage.getJobInstances().forEach( jobInstance -> jobsWriter.addChild( jobInstanceWriter -> JobInstanceRepresenter.toJSON(jobInstanceWriter, jobInstance)))); }

Target:
public static void toJSON(OutputWriter jsonWriter, Stage stage) { jsonWriter.add("name", stage.getName()); jsonWriter.add("counter", stage.getCounter()); jsonWriter.add("approval_type", stage.getApprovalType()); jsonWriter.add("approved_by", stage.getApprovedBy()); jsonWriter.add("scheduled_at", stage.getCreatedTime().getTime()); jsonWriter.add("last_transitioned_time", stage.getLastTransitionedTime().getTime()); if (stage.getResult() != null) { jsonWriter.add("result", stage.getResult().toString()); if (stage.getResult() == StageResult.Cancelled) { jsonWriter.add("cancelled_by", stage.getCancelledBy() == null? "GoCD" : stage.getCancelledBy()); } } if (stage.getRerunOfCounter() == null) { jsonWriter.add("rerun_of_counter", (String) null); } else { jsonWriter.add("rerun_of_counter", stage.getRerunOfCounter()); } jsonWriter.add("fetch_materials", stage.shouldFetchMaterials()); jsonWriter.add("clean_working_directory", stage.shouldCleanWorkingDir()); jsonWriter.add("artifacts_deleted", stage.isArtifactsDeleted()); if (stage.getIdentifier() != null) { jsonWriter.add("pipeline_name", stage.getIdentifier().getPipelineName()); jsonWriter.add("pipeline_counter", stage.getIdentifier().getPipelineCounter()); } jsonWriter.addChildList("jobs", jobsWriter -> stage.getJobInstances().forEach( jobInstance -> jobsWriter.addChild( jobInstanceWriter -> JobInstanceRepresenter.toJSON(jobInstanceWriter, jobInstance)))); }
Source:
public ExpressionTree VARIABLE_WITHOUT_OBJECTS() { return b.<ExpressionTree>nonterminal(PHPLexicalGrammar.VARIABLE_WITHOUT_OBJECTS) .is(f.variableWithoutObjects( b.zeroOrMore(b.token(PHPLexicalGrammar.VARIABLE_VARIABLE_DOLLAR)), COMPOUND_VARIABLE(), b.zeroOrMore(b.firstOf( DIMENSIONAL_OFFSET(), f.alternativeArrayAccess(b.token(LCURLYBRACE), b.optional(EXPRESSION()), b.token(RCURLYBRACE)) )))); }

Target:
public ExpressionTree VARIABLE_WITHOUT_OBJECTS() { return b.<ExpressionTree>nonterminal(PHPLexicalGrammar.VARIABLE_WITHOUT_OBJECTS) .is(f.variableWithoutObjects( b.zeroOrMore(b.token(PHPLexicalGrammar.VARIABLE_VARIABLE_DOLLAR)), COMPOUND_VARIABLE(), b.zeroOrMore(b.firstOf( DIMENSIONAL_OFFSET(), ALTERNATIVE_DIMENSIONAL_OFFSET() )))); }
Source:
public void loadCollectionSheet(int groupId, CollectionSheetRequestPayload payload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchCollectionSheet(groupId, payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CollectionSheetResponse>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(CollectionSheetResponse sheet) { getMvpView().showProgressbar(false); getMvpView().showCollection(sheet); } })); }

Target:
public void loadCollectionSheet(int groupId, CollectionSheetRequestPayload payload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(collectionDataManager.fetchCollectionSheet(groupId, payload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<CollectionSheetResponse>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(CollectionSheetResponse collectionSheetResponse) { getMvpView().showProgressbar(false); getMvpView().showCollection(collectionSheetResponse); } })); }
Source:
public DataRetentionKey(String tenantId, MetricType type) { metricId = new MetricId(tenantId, type, "$" + type.getText()); }

Target:
public DataRetentionKey(String tenantId, MetricType type) { metricId = new MetricId(tenantId, type, makeSafe(type.getText())); }
Source:
public CronTasksConfigurationDto getTasksConfigurationDto() { final Lock readLock = cronTasksConfigurationLock.readLock(); readLock.lock(); try { return ThrowingFunction.unchecked((CronTasksConfigurationDto x) -> SerializationUtils.clone(x)).apply(configuration); } finally { readLock.unlock(); } }

Target:
public CronTasksConfigurationDto getTasksConfigurationDto() { final Lock readLock = cronTasksConfigurationLock.readLock(); readLock.lock(); try { return SerializationUtils.clone(configuration); } finally { readLock.unlock(); } }
Source:
public static String getFilenameFromUploadUrl(@NonNull String url) { String[] splitArray = url.split("/"); String thumbnailName = splitArray[splitArray.length - 1]; if (splitArray.length > 2) { String originalFilename = splitArray[splitArray.length - 2]; if (originalFilename.matches("^[\\w,\\s-]+\\.[A-Za-z]{3}$")) { return originalFilename; } } return thumbnailName; }

Target:
public static String getFilenameFromUploadUrl(@NonNull String url) { String[] splitArray = url.split("/"); String thumbnailName = splitArray[splitArray.length - 1]; if (url.contains("/thumb/") && splitArray.length > 2) { return splitArray[splitArray.length - 2]; } return thumbnailName; }
Source:
public ExtendedQueryResult<T> firstResult(int first) { lastPaginatedQuery = null; if (!context.getRepositoryMethod().isQuery()) { firstResult = first; } else { context.addJpaQueryPostProcessor(new FirstResultPostProcessor(first)); } return this; }

Target:
public ExtendedQueryResult<T> firstResult(int first) { lastPaginatedQuery = null; if (context.getRepositoryMethod().isQuery()) { context.addJpaQueryPostProcessor(new FirstResultPostProcessor(first)); } else { firstResult = first; } return this; }
Source:
private List<CheckpointedResultSubpartition> calculateMapping(ResultSubpartitionInfo info) { final RescaledChannelsMapping rescaledChannelsMapping = channelMapping.getChannelMapping(info.getPartitionIdx()); final List<CheckpointedResultSubpartition> subpartitions = Arrays.stream(rescaledChannelsMapping.getNewChannelIndexes(info.getSubPartitionIdx())) .mapToObj(newIndexes -> getSubpartition(info.getPartitionIdx(), newIndexes)) .collect(Collectors.toList()); LOG.info("output#calculateMapping for using {}: {}", info, rescaledChannelsMapping, subpartitions.stream().map(CheckpointedResultSubpartition::getSubpartitionInfo).collect(Collectors.toList())); return subpartitions; }

Target:
private List<CheckpointedResultSubpartition> calculateMapping(ResultSubpartitionInfo info) { final RescaledChannelsMapping rescaledChannelsMapping = channelMapping.getChannelMapping(info.getPartitionIdx()); final List<CheckpointedResultSubpartition> subpartitions = Arrays.stream(rescaledChannelsMapping.getNewChannelIndexes(info.getSubPartitionIdx())) .mapToObj(newIndexes -> getSubpartition(info.getPartitionIdx(), newIndexes)) .collect(Collectors.toList()); if (subpartitions.isEmpty()) { throw new IllegalStateException("Recovered a buffer from old " + info + " that has no mapping in " + rescaledChannelsMapping); } return subpartitions; }
Source:
public Document getInnerDocument() { IRubyObject innerDocument = getRubyProperty("inner_document"); if (innerDocument.isNil()) return null; return (Document) NodeConverter.createASTNode(innerDocument); }

Target:
public Document getInnerDocument() { IRubyObject innerDocument = getRubyProperty("inner_document"); if (innerDocument.isNil()) { return null; } return (Document) NodeConverter.createASTNode(innerDocument); }
Source:
public static TribbleFeatureSource getFeatureSource(ResourceLocator locator, Genome genome, boolean useCache) throws IOException, TribbleIndexNotFoundException { AbstractFeatureReader.setComponentMethods(IGVComponentMethods.getInstance()); FeatureCodec codec = CodecFactory.getCodec(locator, genome); boolean indexExists = false; String idxPath = locator.getIndexPath(); if (idxPath != null) { if (FileUtils.isRemote(idxPath)) { idxPath = HttpUtils.mapURL(idxPath); } indexExists = true; } else { String maybeIdxPath = ResourceLocator.indexFile(locator); if (maybeIdxPath == null) { indexExists = false; } else { if (FileUtils.isRemote(maybeIdxPath)) { maybeIdxPath = HttpUtils.mapURL(maybeIdxPath); } if(FileUtils.resourceExists(maybeIdxPath)) { indexExists = true; idxPath = maybeIdxPath; } } } final int hundredMB = 100000000; final int oneGB = 1000000000; long size = FileUtils.getLength(locator.getPath()); final boolean indexRequired = size > oneGB; if (!Globals.isHeadless() && locator.isLocal() && !locator.getPath().endsWith(".gz") && !indexExists) { if (size > hundredMB) { createIndex(locator, indexRequired); } } String path = locator.getPath(); if (FileUtils.isRemote(path)) { path = HttpUtils.mapURL(path); } AbstractFeatureReader basicReader = AbstractFeatureReader.getFeatureReader(path, idxPath, codec, indexRequired || indexExists); if (indexExists) { return new IndexedFeatureSource(basicReader, codec, locator, genome, true); } else { return new NonIndexedFeatureSource(basicReader, codec, locator, genome, indexRequired || indexExists); } }

Target:
public static TribbleFeatureSource getFeatureSource(ResourceLocator locator, Genome genome, boolean useCache) throws IOException, TribbleIndexNotFoundException { AbstractFeatureReader.setComponentMethods(IGVComponentMethods.getInstance()); FeatureCodec codec = CodecFactory.getCodec(locator, genome); boolean indexExists = false; String idxPath = locator.getIndexPath(); if (idxPath != null) { if (FileUtils.isRemote(idxPath)) { idxPath = HttpUtils.mapURL(idxPath); } indexExists = true; } else { String maybeIdxPath = ResourceLocator.indexFile(locator); if (maybeIdxPath == null) { indexExists = false; } else { if (FileUtils.isRemote(maybeIdxPath)) { maybeIdxPath = HttpUtils.mapURL(maybeIdxPath); } if(FileUtils.resourceExists(maybeIdxPath)) { indexExists = true; idxPath = maybeIdxPath; } } } final int hundredMB = 100000000; final int oneGB = 1000000000; long size = FileUtils.getLength(locator.getPath()); final boolean indexRequired = size > oneGB; if (!Globals.isHeadless() && locator.isLocal() && !locator.getPath().endsWith(".gz") && !indexExists) { if (size > hundredMB) { createIndex(locator, indexRequired); } } String path = locator.getPath(); if (FileUtils.isRemote(path)) { path = HttpUtils.mapURL(path); } AbstractFeatureReader basicReader = AbstractFeatureReader.getFeatureReader(path, idxPath, codec, indexRequired || indexExists); if (indexExists) { return new IndexedFeatureSource(basicReader, codec, locator, genome, useCache, true); } else { return new NonIndexedFeatureSource(basicReader, codec, locator, genome, indexRequired || indexExists); } }
Source:
public Message next() { Timer.Context readingTimerContext = readingTimer.time(); try { MessageAndMetadata<byte[], byte[]> message = iterator.next(); MessageWithMetadata unwrappedContent = contentWrapper.unwrapContent(message.message()); return new Message( unwrappedContent.getMessageMetadata().getId(), message.offset(), message.partition(), message.topic(), unwrappedContent.getContent(), unwrappedContent.getMessageMetadata().getTimestamp(), clock.getTime()); } catch (ConsumerTimeoutException consumerTimeoutException) { throw new MessageReceivingTimeoutException("No messages received", consumerTimeoutException); } catch (Exception e) { throw new InternalProcessingException("Message received failed", e); } finally { readingTimerContext.close(); } }

Target:
public Message next() { try (Timer.Context readingTimerContext = readingTimer.time()) { MessageAndMetadata<byte[], byte[]> message = iterator.next(); UnwrappedMessageContent unwrappedContent = contentWrapper.unwrapContent(message.message()); return new Message( unwrappedContent.getMessageMetadata().getId(), message.offset(), message.partition(), message.topic(), unwrappedContent.getContent(), unwrappedContent.getMessageMetadata().getTimestamp(), clock.getTime()); } catch (ConsumerTimeoutException consumerTimeoutException) { throw new MessageReceivingTimeoutException("No messages received", consumerTimeoutException); } catch (Exception e) { throw new InternalProcessingException("Message received failed", e); } }