auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testFindAllByOrderByCacheVersionDescVepVersionDescVepVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { if (curAnnotationMetadata.getCacheVersion().equals(prevAnnotationMetadata.getCacheVersion())) { assertTrue(Integer.parseInt(curAnnotationMetadata.getCacheVersion()) <= Integer.parseInt(prevAnnotationMetadata.getCacheVersion())); } } }

Target:
public void testFindAllByOrderByCacheVersionDescVepVersionDescVepVersionOrder() throws Exception { List<AnnotationMetadata> annotationMetadataList = repository.findAllByOrderByCacheVersionDescVepVersionDesc(); AnnotationMetadata prevAnnotationMetadata = annotationMetadataList.get(0); for (AnnotationMetadata curAnnotationMetadata : annotationMetadataList.subList(1, annotationMetadataList.size())) { if (curAnnotationMetadata.getCacheVersion().equals(prevAnnotationMetadata.getCacheVersion())) { assertTrue(curAnnotationMetadata.getCacheVersion().compareTo(prevAnnotationMetadata.getCacheVersion()) <= 0); } } }
Source:
public HtpasswdUserService() { super(); this.htpasswdFile = GitBlit.getFileOrFolder(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE); }

Target:
public HtpasswdUserService() { super(); String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("windows") || os.startsWith("netware")) { SUPPORT_PLAINTEXT_PWD = true; } else { SUPPORT_PLAINTEXT_PWD = false; } }
Source:
public void testSegmentLoading1() throws Exception { zkCoordinator.start(); final DataSegment segment = makeSegment("test", "1", new Interval("P1d/2011-04-01")); zkCoordinator.removeSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); Assert.assertFalse(segmentsAnnouncedByMe.contains(segment)); zkCoordinator.addSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); Thread.sleep(1000); Assert.assertTrue(segmentsAnnouncedByMe.contains(segment)); Assert.assertFalse("segment files shouldn't be deleted", segmentLoader.getSegmentsInTrash().contains(segment)); zkCoordinator.stop(); }

Target:
public void testSegmentLoading1() throws Exception { zkCoordinator.start(); final DataSegment segment = makeSegment("test", "1", new Interval("P1d/2011-04-01")); zkCoordinator.removeSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); Assert.assertFalse(segmentsAnnouncedByMe.contains(segment)); zkCoordinator.addSegment(segment, new DataSegmentChangeCallback() { @Override public void execute() { } }); for (Runnable runnable : scheduledRunnable) { runnable.run(); } Assert.assertTrue(segmentsAnnouncedByMe.contains(segment)); Assert.assertFalse("segment files shouldn't be deleted", segmentLoader.getSegmentsInTrash().contains(segment)); zkCoordinator.stop(); }
Source:
private void synchronizeSelection() { if (isSingleSelectionOnly()) { setSelectedItem(selectionModel.asSingleSelectionModel().getSelectedObject()); } else { List<T> selectedItems = selectionModel.asMultiSelectionModel().getSelectedList(); setSelectedItems(selectedItems); if (selectedItems.size() == 1) { setSelectedItem(selectedItems.get(0)); } } }

Target:
private void synchronizeSelection() { if (isSingleSelectionOnly()) { setSelectedItem(selectionModel.asSingleSelectionModel().getSelectedObject()); } else { List<T> selectedItems = selectionModel.getSelectedObjects(); setSelectedItems(selectedItems); if (selectedItems.size() == 1) { setSelectedItem(selectedItems.get(0)); } } }
Source:
private void init() { if ( !config.isEnabled() ) { logger.info( "Cassandra client not enabled" ); return; } host = config.getCassandraHost(); port = config.getCassandraPort(); SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis( 120000 ); socketOptions.setReadTimeoutMillis( 120000 ); Cluster.Builder builder = Cluster.builder() .withoutJMXReporting() .addContactPoint( host ) .withPort( port ) .withSocketOptions( socketOptions ); username = config.getCassandraUser(); String password = config.getCassandraPass(); if ( isNotBlank( username ) && isNotBlank( password ) ) { logger.info( "Build with credentials, user: {}, pass: ****", username ); builder.withCredentials( username, password ); } cluster = builder.build(); }

Target:
private void init() { if ( !config.isEnabled() ) { logger.info( "Cassandra client not enabled" ); return; } host = config.getCassandraHost(); port = config.getCassandraPort(); SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis( 30000 ); socketOptions.setReadTimeoutMillis( 30000 ); Cluster.Builder builder = Cluster.builder() .withoutJMXReporting() .addContactPoint( host ) .withPort( port ) .withSocketOptions( socketOptions ); username = config.getCassandraUser(); String password = config.getCassandraPass(); if ( isNotBlank( username ) && isNotBlank( password ) ) { logger.info( "Build with credentials, user: {}, pass: ****", username ); builder.withCredentials( username, password ); } cluster = builder.build(); }
Source:
private PoolingListener<C> getDelegatePoolingListener() { if (unwrappedDelegate instanceof PoolingListener) { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { ((PoolingListener) unwrappedDelegate).onBorrow(connection); } @Override public void onReturn(C connection) { ((PoolingListener) unwrappedDelegate).onReturn(connection); } }; } else { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { throw new UnsupportedOperationException("The delegate connection provider does not support Pooling"); } @Override public void onReturn(C connection) { throw new UnsupportedOperationException("The delegate connection provider does not support Pooling"); } }; } }

Target:
private PoolingListener<C> getDelegatePoolingListener() { if (unwrappedDelegate instanceof PoolingListener) { return new PoolingListener<C>() { @Override public void onBorrow(C connection) { ((PoolingListener) unwrappedDelegate).onBorrow(connection); } @Override public void onReturn(C connection) { ((PoolingListener) unwrappedDelegate).onReturn(connection); } }; } else { return new PoolingListener<C>() {}; } }
Source:
public AbstractMap.SimpleEntry<String, JwtClaims> createNewSessionToken(String username, char[] password) { String sessionToken = new IAMRestClient().getSSOTicket(iamURL + IAMConfiguration.IAM_TICKET_REQUEST, username, password, ticketMarker, isJWTSession); JwtClaims claims = isJWTSession ? JWTUtils.parseJWT(sessionToken, tokenSignatureEnabled, tokenSignatureKey, tokenEncryptionEnabled, tokenEncryptionKey, iamURL, iamURL) : null; return new AbstractMap.SimpleEntry(sessionToken, claims); }

Target:
public AbstractMap.SimpleEntry<String, JwtClaims> createNewSessionToken(String username, char[] password) { String sessionToken = iamRestClient.getSSOTicket(iamURL + IAMConfiguration.IAM_TICKET_REQUEST, username, password, ticketMarker, isJWTSession); JwtClaims claims = isJWTSession ? JWTUtils.parseJWT(sessionToken, tokenSignatureEnabled, tokenSignatureKey, tokenEncryptionEnabled, tokenEncryptionKey, iamURL, iamURL) : null; return new AbstractMap.SimpleEntry(sessionToken, claims); }
Source:
protected void onNfcPostExecute() { handleResult(mInputParcel); vAnimator.setDisplayedChild(2); nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { while (true) { if (isNfcConnected()) { try { Thread.sleep(200); } catch (InterruptedException ignored) { } } else { return null; } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finish(); } }.execute(); }

Target:
protected final void onNfcPostExecute() { handleResult(mInputParcel); vAnimator.setDisplayedChild(2); nfcGuideView.setCurrentStatus(NfcGuideView.NfcGuideViewStatus.DONE); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { while (true) { if (isNfcConnected()) { try { Thread.sleep(200); } catch (InterruptedException ignored) { } } else { return null; } } } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finish(); } }.execute(); }
Source:
public final Type getType() { return null; }

Target:
public final Type getType() { TypeBuilder builder = new TypeBuilder(); return builder.build(this.getSignature()); }
Source:
public Optional<Argument> build(Type expectedType, Object value, ConfigRegistry config) { return FACTORIES.stream() .map(factory -> factory.build(expectedType, value, config)) .filter(Optional::isPresent) .findFirst() .map(Optional::get); }

Target:
public Optional<Argument> build(Type expectedType, Object value, ConfigRegistry config) { return FACTORIES.stream() .flatMap(factory -> JdbiStreams.toStream(factory.build(expectedType, value, config))) .findFirst(); }
Source:
public void testMbeanGetCoordinator() throws Exception { startGrid(0); startClientGrid(1); IgniteEx srv2 = startGrid(2); ZookeeperDiscoverySpiMBean mbean = getMxBean(srv2.context().igniteInstanceName(), "SPIs", ZookeeperDiscoverySpi.class, ZookeeperDiscoverySpiMBean.class); grid(0).close(); assertEquals(mbean.getCoordinatorNodeFormatted(), String.valueOf(srv2.localNode())); }

Target:
public void testMbeanGetCoordinator() throws Exception { startGrid(0); startClientGrid(1); IgniteEx srv2 = startGrid(2); ZookeeperDiscoverySpiMBean mbean = getMxBean(srv2.context().igniteInstanceName(), "SPIs", ZookeeperDiscoverySpi.class, ZookeeperDiscoverySpiMBean.class); stopGrid(0); assertEquals(mbean.getCoordinator(), srv2.localNode().id()); assertEquals(mbean.getCoordinatorNodeFormatted(), String.valueOf(srv2.localNode())); }
Source:
public ConstantExpression(final float value) { valueType = Type.FLOAT_TYPE; this.value = String.valueOf(value) + "f"; }

Target:
public ConstantExpression(final float value) { this(Type.FLOAT_TYPE, String.valueOf(value) + 'f'); }
Source:
Function<String, CharSource> invalidEscapeStringFunction(final InvalidEscapeStringPolicy policy) { return new Function<String, CharSource>() { final Pattern p = Pattern.compile("\\p{XDigit}+"); @Override public CharSource apply(@Nullable String input) { assert input != null; if (policy == InvalidEscapeStringPolicy.PASSTHROUGH) { return CharSource.wrap(input); } StringBuilder s = new StringBuilder(); char[] charArray = input.toCharArray(); for (int i=0 ; i < charArray.length ; i++) { char c = charArray[i]; if (c == '\\') { if (charArray.length > i + 1) { char next = charArray[i + 1]; switch (next) { case 'b': case 'f': case 'n': case 'r': case 't': case '"': case '\\': case '/': s.append(c); break; case 'u': if (charArray.length > i + 5) { char[] hexChars = {charArray[i + 2], charArray[i + 3], charArray[i + 4], charArray[i + 5]}; String hexString = new String(hexChars); if (p.matcher(hexString).matches()) { s.append(c); } } break; default: switch (policy) { case SKIP: i++; break; case UNESCAPE: break; } break; } } } else { s.append(c); } } return CharSource.wrap(s.toString()); } }; }

Target:
Function<String, CharSource> invalidEscapeStringFunction(final InvalidEscapeStringPolicy policy) { return new Function<String, CharSource>() { final Pattern digitsPattern = Pattern.compile("\\p{XDigit}+"); @Override public CharSource apply(@Nullable String input) { Preconditions.checkNotNull(input); if (policy == InvalidEscapeStringPolicy.PASSTHROUGH) { return CharSource.wrap(input); } StringBuilder builder = new StringBuilder(); char[] charArray = input.toCharArray(); for (int characterIndex = 0; characterIndex < charArray.length; characterIndex++) { char c = charArray[characterIndex]; if (c == '\\') { if (charArray.length > characterIndex + 1) { char next = charArray[characterIndex + 1]; switch (next) { case 'b': case 'f': case 'n': case 'r': case 't': case '"': case '\\': case '/': builder.append(c); break; case 'u': if (charArray.length > characterIndex + 5) { char[] hexChars = {charArray[characterIndex + 2], charArray[characterIndex + 3], charArray[characterIndex + 4], charArray[characterIndex + 5]}; String hexString = new String(hexChars); if (digitsPattern.matcher(hexString).matches()) { builder.append(c); } else { if (policy == InvalidEscapeStringPolicy.SKIP) { characterIndex++; } } } break; default: switch (policy) { case SKIP: characterIndex++; break; case UNESCAPE: break; } break; } } } else { builder.append(c); } } return CharSource.wrap(builder.toString()); } }; }
Source:
private static JsonObject configureClusterManager() { JsonObject zkConfig = new JsonObject(); zkConfig.put("zookeeperHosts", "192.168.1.12"); zkConfig.put("rootPath", "io.vertx"); zkConfig.put("retry", new JsonObject() .put("initialSleepTime", 3000) .put("maxTimes", 3)); return zkConfig; }

Target:
private static JsonObject configureClusterManager() { JsonObject zkConfig = new JsonObject(); zkConfig.put("zookeeperHosts", "localhost"); zkConfig.put("rootPath", "io.vertx"); zkConfig.put("retry", new JsonObject() .put("initialSleepTime", 3000) .put("maxTimes", 3)); return zkConfig; }
Source:
private String getLeftNodeFieldName(RexNode left) { switch (left.getKind()) { case INPUT_REF: final RexInputRef left1 = (RexInputRef) left; return fieldNames.get(left1.getIndex()); case CAST: return getLeftNodeFieldName(((RexCall) left).operands.get(0)); case OTHER_FUNCTION: case ITEM: return left.accept(new GeodeRules.RexToGeodeTranslator(this.fieldNames)); default: return null; } }

Target:
private String getLeftNodeFieldName(RexNode left) { switch (left.getKind()) { case INPUT_REF: final RexInputRef left1 = (RexInputRef) left; return fieldNames.get(left1.getIndex()); case CAST: return getLeftNodeFieldName(((RexCall) left).operands.get(0)); case ITEM: case OTHER_FUNCTION: return left.accept(new GeodeRules.RexToGeodeTranslator(this.fieldNames)); default: return null; } }
Source:
public GlusterVolumeStatusReturnForXmlRpc(Guid clusterId, Map<String, Object> innerMap) { super(innerMap); mStatus = new StatusForXmlRpc((Map<String, Object>) innerMap.get(STATUS)); Map<String, Object> statusInfo = (Map<String, Object>) innerMap.get(VOLUME_STATUS); if (statusInfo != null) { String volumeName = (String) statusInfo.get(VOLUME_NAME); GlusterVolumeEntity volume = getGlusterVolumeDao().getByName(clusterId, volumeName); volumeAdvancedDetails.setVolumeId(volume.getId()); List<BrickDetails> brickDetails = prepareBrickDetails(volume, (Object[]) statusInfo.get(BRICKS)); volumeAdvancedDetails.setBrickDetails(brickDetails); if (statusInfo.containsKey(NFS_KEY) || statusInfo.containsKey(SHD_KEY)) { volumeAdvancedDetails.setServiceInfo(prepareServiceInfo(statusInfo)); } } }

Target:
public GlusterVolumeStatusReturnForXmlRpc(Guid clusterId, Map<String, Object> innerMap) { super(innerMap); mStatus = new StatusForXmlRpc((Map<String, Object>) innerMap.get(STATUS)); Map<String, Object> statusInfo = (Map<String, Object>) innerMap.get(VOLUME_STATUS); if (statusInfo != null) { String volumeName = (String) statusInfo.get(VOLUME_NAME); GlusterVolumeEntity volume = getGlusterVolumeDao().getByName(clusterId, volumeName); volumeAdvancedDetails.setVolumeId(volume.getId()); List<BrickDetails> brickDetails = prepareBrickDetails(volume, (Object[]) statusInfo.get(BRICKS)); volumeAdvancedDetails.setBrickDetails(brickDetails); volumeAdvancedDetails.setServiceInfo(prepareServiceInfo(statusInfo)); } }
Source:
private LocalDate decrement(LocalDate date, Interval interval) { switch (interval) { case DAILY: return LocalDate.now().minusDays(1); case MONTHLY: return LocalDate.now().minusMonths(1); case YEARLY: return LocalDate.now().minusYears(1); case FACT: return date.minusYears(999); default: return date.plusYears(999); } }

Target:
private LocalDate decrement(LocalDate date, Interval interval) { switch (interval) { case DAILY: return date.minusDays(1); case MONTHLY: return date.minusMonths(1); case YEARLY: return date.minusYears(1); default: return LocalDate.MIN; } }
Source:
public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { String fullClassName = className.replace("/", "."); if (isExcludedClass(loader, fullClassName)) { debug_transform.log("transform: ignoring excluded class %s%n", className); return null; } debug_transform.log("%ntransform: ENTER %s%n", className); JavaClass c; try { ClassParser parser = new ClassParser(new ByteArrayInputStream(classfileBuffer), className); c = parser.parse(); } catch (Exception e) { debug_transform.log("transform: EXIT parse of %s resulted in error %s%n", className, e); throw new RuntimeException("Unexpected parse exception", e); } try { ClassGen cg = new ClassGen(c); if (transformClass(cg)) { JavaClass javaClass = cg.getJavaClass(); if (ReplaceCallAgent.debug) { Path filepath = ReplaceCallAgent.debugPath.resolve(className + ".class"); javaClass.dump(filepath.toFile()); } debug_transform.log("transform: EXIT class %s transformed", className); return javaClass.getBytes(); } else { debug_transform.log("transform: EXIT class %s not transformed", className); return null; } } catch (Throwable e) { debug_transform.log( "transform: EXIT transform of %s resulted in exception %s%n", className, e); System.out.format( "Unexpected exception %s (%s) in class transform of %s%n", e, e.getCause(), className); e.printStackTrace(); return null; } }

Target:
public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { String fullClassName = className.replace("/", "."); if (isExcludedClass(loader, fullClassName)) { debug_transform.log("transform: ignoring excluded class %s%n", className); return null; } debug_transform.log("%ntransform: ENTER %s%n", className); JavaClass c; try { ClassParser parser = new ClassParser(new ByteArrayInputStream(classfileBuffer), className); c = parser.parse(); } catch (Exception e) { debug_transform.log("transform: EXIT parse of %s resulted in error %s%n", className, e); return null; } try { ClassGen cg = new ClassGen(c); if (transformClass(cg)) { JavaClass javaClass = cg.getJavaClass(); if (ReplaceCallAgent.debug) { Path filepath = ReplaceCallAgent.debugPath.resolve(className + ".class"); javaClass.dump(filepath.toFile()); } debug_transform.log("transform: EXIT class %s transformed", className); return javaClass.getBytes(); } else { debug_transform.log("transform: EXIT class %s not transformed", className); return null; } } catch (IllegalClassFormatException e) { debug_transform.log( "transform: EXIT transform of %s resulted in exception %s%n", className, e); System.out.format( "Unexpected exception %s (%s) in class transform of %s%n", e, e.getCause(), className); throw e; } catch (Throwable e) { debug_transform.log( "transform: EXIT transform of %s resulted in exception %s%n", className, e); System.out.format( "Unexpected exception %s (%s) in class transform of %s%n", e, e.getCause(), className); e.printStackTrace(); return null; } }
Source:
public void loadCredentials(){ mCredentials = new Credentials("<LINK_0>","", ""); }

Target:
public void loadCredentials(){ mCredentials = new Credentials(BuildConfig.DEFAULT_SERVER, BuildConfig.DEFAULT_USER, BuildConfig.DEFAULT_PASSWORD); }
Source:
public void exceptionsAreSuppressedAndReportedWhenClosing() { SafeShutdownRunner runner = new SafeShutdownRunner(Duration.ofSeconds(1)); assertThatCode(() -> runner.shutdownSafely(throwingRunnable)).doesNotThrowAnyException(); assertThatThrownBy(runner::close) .isInstanceOf(RuntimeException.class) .hasSuppressedException(EXCEPTION); }

Target:
public void exceptionsAreSuppressedAndReportedWhenClosing() { SafeShutdownRunner runner = new SafeShutdownRunner(Duration.ofSeconds(1)); assertThatCode(() -> runner.shutdownSafely(throwingRunnable)).doesNotThrowAnyException(); assertThatThrownBy(runner::close) .isInstanceOf(SafeRuntimeException.class) .hasSuppressedException(EXCEPTION); }
Source:
private void populateAndVerifyTimeWindowCase(final KieBase kieBase) { final KieSessionConfiguration sessionConfiguration = KieSessionUtil.getKieSessionConfigurationWithClock(ClockTypeOption.get("pseudo"), null); this.initKieSession(kieBase, sessionConfiguration); final SessionPseudoClock clock = this.kieSession.getSessionClock(); final MessageEvent pingEvent = new MessageEvent(MessageEvent.Type.sent, new Message("Ping")); this.kieSession.insert(pingEvent); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping2Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping2Event); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping3Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping3Event); clock.advanceTime(1, TimeUnit.SECONDS); this.kieSession.fireAllRules(); Assertions.assertThat(this.events).as("The rule should have fired for 2 events").contains(ping2Event, ping3Event); this.events.clear(); final MessageEvent pongEvent = new MessageEvent(MessageEvent.Type.sent, new Message("Pong")); this.kieSession.insert(pongEvent); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping4Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping4Event); clock.advanceTime(1, TimeUnit.SECONDS); this.kieSession.fireAllRules(); Assertions.assertThat(this.events).as("The rule should have fired for ping event only").contains(ping4Event); }

Target:
private void populateAndVerifyTimeWindowCase(final KieBase kieBase) { final KieSessionConfiguration sessionConfiguration = KieSessionUtil.getKieSessionConfigurationWithClock(ClockTypeOption.get("pseudo"), null); this.initKieSession(kieBase, sessionConfiguration); final SessionPseudoClock clock = this.kieSession.getSessionClock(); final MessageEvent pingEvent = new MessageEvent(MessageEvent.Type.sent, new Message("Ping")); this.kieSession.insert(pingEvent); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping2Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping2Event); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping3Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping3Event); clock.advanceTime(1, TimeUnit.SECONDS); this.kieSession.fireAllRules(); Assertions.assertThat(this.events).as("The rule should have fired for 2 events").containsExactlyInAnyOrder(ping2Event, ping3Event); this.events.clear(); final MessageEvent pongEvent = new MessageEvent(MessageEvent.Type.sent, new Message("Pong")); this.kieSession.insert(pongEvent); clock.advanceTime(1, TimeUnit.SECONDS); final MessageEvent ping4Event = new MessageEvent(MessageEvent.Type.received, new Message("Ping")); this.kieSession.insert(ping4Event); clock.advanceTime(1, TimeUnit.SECONDS); this.kieSession.fireAllRules(); Assertions.assertThat(this.events).as("The rule should have fired for ping event only").contains(ping4Event); }
Source:
public void platformMotionUpAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.PLATFORM, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 3)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1), new Point(2, 2)), new Point(0, -1)); assertTrue(cell.getType() == Cell.EMPTY); }

Target:
public void platformMotionUpAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.PLATFORM, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 3)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1), new Point(2, 2)), new Point(0, -1)); assertEquals(cell, Cell.EMPTY); }
Source:
void updateButton() { getButtonWidget().setVisible(command.getIsAvailable() && command.getIsVisible()); getButtonWidget().setEnabled(command.getIsExecutionAllowed()); String title = ""; StringBuilder sb = new StringBuilder(""); if (!command.getExecuteProhibitionReasons().isEmpty()) { for (String reason : command.getExecuteProhibitionReasons()) { sb.append(reason).append(","); } title = sb.toString(); if (!title.equals("")) { title = title.substring(0, title.length() -1); } } else { title = !getButtonWidget().getText().equals("") ? getButtonWidget().getText() : command.getTitle(); } getButtonWidget().setTitle(title); if (command.getTitle() == null) { getButtonWidget().setText(""); } else if (getButtonWidget().getText().equals("")) { getButtonWidget().setText(command.getTitle()); } }

Target:
void updateButton() { getButtonWidget().setVisible(command.getIsAvailable() && command.getIsVisible()); getButtonWidget().setEnabled(command.getIsExecutionAllowed()); String title = ""; StringBuilder sb = new StringBuilder(); if (!command.getExecuteProhibitionReasons().isEmpty()) { for (String reason : command.getExecuteProhibitionReasons()) { sb.append(reason).append(","); } title = sb.toString(); if (title.length() != 0) { title = title.substring(0, title.length() -1); } } else { title = !getButtonWidget().getText().equals("") ? getButtonWidget().getText() : command.getTitle(); } getButtonWidget().setTitle(title); if (command.getTitle() == null) { getButtonWidget().setText(""); } else if (getButtonWidget().getText().equals("")) { getButtonWidget().setText(command.getTitle()); } }
Source:
private static boolean matches(String expectedLine, String actualLine) { if (expectedLine.equals(actualLine)) { return true; } try { Pattern pattern = Pattern.compile(expectedLine); Matcher matcher = pattern.matcher(actualLine); return matcher.matches(); } catch (PatternSyntaxException ignore) { return false; } }

Target:
static boolean matches(String expectedLine, String actualLine) { if (expectedLine.equals(actualLine)) { return true; } try { return actualLine.matches(expectedLine); } catch (PatternSyntaxException ignore) { return false; } }
Source:
public void run() { boolean done = Repeater.create(String.format("Request %s status check", builder.request.toString())) .every(Duration.ONE_SECOND) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final String json = HttpTool.httpGet(builder.httpClient, URI.create(builder.request.getHref()), builder.headers).getContentAsString(); final String status = JsonPath.read(json, "$.Requests.request_status"); if (!VALID_STATES.contains(status)) { throw new RuntimeException( "Request fails with state " + status + ". Check here for details " + builder.request.getHref()); } return StringUtils.equals(status, "COMPLETED"); } }) .limitTimeTo(builder.timeout) .rethrowExceptionImmediately() .run(); if (!done) { throw new RuntimeException(builder.errorMessage); } ; }

Target:
public void run() { boolean done = Repeater.create(String.format("Request %s status check", builder.request.toString())) .every(Duration.ONE_SECOND) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final String json = HttpTool.httpGet(builder.httpClient, URI.create(builder.request.getHref()), builder.headers).getContentAsString(); final String status = JsonPath.read(json, "$.Requests.request_status"); if (!VALID_STATES.contains(status)) { throw new RuntimeException( "Request fails with state " + status + ". Check here for details " + builder.request.getHref()); } return StringUtils.equals(status, "COMPLETED"); } }) .limitTimeTo(builder.timeout) .rethrowExceptionImmediately() .run(); if (!done) { throw new RuntimeException(builder.errorMessage); } }
Source:
public Boolean get(Object key) { if (key == null) { throw new IllegalArgumentException("Query key is null"); } if (jexl.containsKey(key) && jexl.get(key) != null) { return jexl.get(key); } final JexlVCMatchExp exp = (JexlVCMatchExp) key; final boolean matches = evaluateExpression(exp); jexl.put(exp, matches); return matches; }

Target:
public Boolean get(Object key) { if (key == null) { throw new IllegalArgumentException("Query key is null"); } final Boolean value = jexl.get(key); if (jexl.containsKey(key) && value != null) { return value; } final JexlVCMatchExp exp = (JexlVCMatchExp) key; final boolean matches = evaluateExpression(exp); jexl.put(exp, matches); return matches; }
Source:
public boolean hasACL( NodeCache cache ) { return getMixinTypes(cache).contains(ModeShapeLexicon.ACCESS_CONTROLLABLE); }

Target:
public boolean hasACL( NodeCache cache ) { if (hasACL == null) { hasACL = getChildReferences(cache).getChild(ModeShapeLexicon.ACCESS_LIST_NODE_NAME) != null; } return hasACL; }
Source:
private void initSessionFromCache() { session = OutcomesUtils.getCachedSession(); if (session.isIndirect()) indirectNotificationIds = getLastNotificationsReceivedIds(); else if (session.isDirect()) directNotificationId = OutcomesUtils.getCacheNotificationOpenId(); }

Target:
private void initSessionFromCache() { session = OutcomesUtils.getCachedSession(); if (session.isIndirect()) indirectNotificationIds = getLastNotificationsReceivedIds(); else if (session.isDirect()) directNotificationId = OutcomesUtils.getCachedNotificationOpenId(); }
Source:
public void addStreamFile(File streamFile) throws CTFReaderException { File indexFile = new File(streamFile.getParentFile(), "index" + File.separator + streamFile.getName() + ".IDX"); Set<StreamInputPacketIndexEntry> sipies = new HashSet<>(); if (indexFile.exists()) { CTFIndexFile ctfIndex = new CTFIndexFile(indexFile); sipies.addAll(ctfIndex.getStreamInputPacketIndexEntries()); } openStreamInput(streamFile, sipies); }

Target:
public void addStreamFile(File streamFile) throws CTFReaderException { File indexFile = new File(streamFile.getParentFile(), INDEX_FILE_FILTER + File.separator + streamFile.getName() + INDEX_EXTENSION); Set<StreamInputPacketIndexEntry> sipies = new HashSet<>(); if (indexFile.exists()) { CTFIndexFile ctfIndex = new CTFIndexFile(indexFile); sipies.addAll(ctfIndex.getStreamInputPacketIndexEntries()); } openStreamInput(streamFile, sipies); }
Source:
private synchronized void createMissingTokens( String[] names, int[] ids ) { PrimitiveIntSet unresolvedIndexes = Primitive.intSet(); resolveIds( names, ids, i -> !unresolvedIndexes.add( i ) ); if ( !unresolvedIndexes.isEmpty() ) { createUnresolvedTokens( unresolvedIndexes, names, ids ); unresolvedIndexes.visitKeys( i -> { tokenCache.put( tokenFactory.newToken( names[i], ids[i] ) ); return false; } ); } }

Target:
private synchronized void createMissingTokens( String[] names, int[] ids ) { MutableIntSet unresolvedIndexes = new IntHashSet(); resolveIds( names, ids, i -> !unresolvedIndexes.add( i ) ); if ( !unresolvedIndexes.isEmpty() ) { ObjectIntHashMap<String> createdTokens = createUnresolvedTokens( unresolvedIndexes, names, ids ); createdTokens.forEachKeyValue( ( name, index ) -> tokenCache.put( tokenFactory.newToken( name, ids[index] ) ) ); } }
Source:
public int addExperiment(String expID) throws SQLException, IOException { if (expID == null || expID.isEmpty()) { throw new IOException("Invalid experiment ID."); } Experiment e = getExperiment(expID); if (e != null) { throw new IOException(expID + " already exists"); } fpg.generateExperimentFolders(expID); String query = "INSERT INTO Experiment " + "(ExpID) VALUES (?)"; int rs = 0; try (PreparedStatement stmt= conn.prepareStatement(query);) { stmt.setString(1, expID); rs = stmt.executeUpdate(); stmt.close(); } catch (SQLException ex) { conn.rollback(); throw ex; } return rs; }

Target:
public int addExperiment(String expID) throws SQLException, IOException { if (expID == null || expID.isEmpty()) { throw new IOException("Invalid experiment ID."); } Experiment e = getExperiment(expID); if (e != null) { throw new IOException(expID + " already exists"); } fpg.generateExperimentFolders(expID); String query = "INSERT INTO Experiment " + "(ExpID) VALUES (?)"; int rs = 0; try (PreparedStatement stmt= conn.prepareStatement(query);) { stmt.setString(1, expID); rs = stmt.executeUpdate(); } catch (SQLException ex) { conn.rollback(); throw ex; } return rs; }
Source:
public long getBucketKeyFor(Object event) { if (getter == null) { Class<?> fqcn = event.getClass(); Getter<Object, Object> getterTime = PojoUtils.createGetter(fqcn, keyExpression, Object.class); getter = getterTime; } return Math.abs(((Object)getter.get(event)).hashCode()) % noOfBuckets; }

Target:
public long getBucketKeyFor(Object event) { return Math.abs(((Object)getter.get(event)).hashCode()) % noOfBuckets; }
Source:
protected void starting(Description description) { if(!isRecorderDisabled()) { startRecording(description); } }

Target:
protected void starting(Description description) { if (isRecorderEnabled()) { startRecording(description); } }
Source:
public boolean indexShareable() { TypedProperties properties = properties(); boolean hasRamDirectoryProvider = false; boolean hasOtherDirectoryProvider = false; for (Object objKey : properties.keySet()) { String key = (String) objKey; if (key.endsWith(DIRECTORY_PROVIDER_KEY)) { if (properties.get(key).equals(RAM_DIRECTORY_PROVIDER)) { hasRamDirectoryProvider = true; } else { hasOtherDirectoryProvider = true; } } } boolean ramOnly = hasRamDirectoryProvider && !hasOtherDirectoryProvider; return !ramOnly; }

Target:
public boolean indexShareable() { TypedProperties properties = properties(); boolean hasRamDirectoryProvider = false; for (Object objKey : properties.keySet()) { String key = (String) objKey; if (key.endsWith(DIRECTORY_PROVIDER_KEY)) { if (properties.get(key).equals(RAM_DIRECTORY_PROVIDER)) { hasRamDirectoryProvider = true; } else { return true; } } } return !hasRamDirectoryProvider; }
Source:
private CompletableFuture<RestResponse> createCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = request.contents(); String cacheName = request.variables().get("cacheName"); byte[] bytes = contents.rawContent(); if (bytes == null || bytes.length == 0) { return CompletableFuture.supplyAsync(() -> { restCacheManager.getInstance().administration().createCache(cacheName, (String) null); responseBuilder.status(OK); return responseBuilder.build(); }, executor); } ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); MediaType sourceType = request.contentType() == null ? APPLICATION_JSON : request.contentType(); if (sourceType.match(APPLICATION_JSON)) { JSON_READER.readJson(cfgBuilder, StandardConversions.convertTextToObject(bytes, sourceType)); } else if (sourceType.match(MediaType.APPLICATION_XML)) { ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(bytes, UTF_8)); cfgBuilder = builderHolder.getCurrentConfigurationBuilder(); } else { responseBuilder.status(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE); return CompletableFuture.completedFuture(responseBuilder.build()); } ConfigurationBuilder finalCfgBuilder = cfgBuilder; return CompletableFuture.supplyAsync(() -> { restCacheManager.getInstance().administration().createCache(cacheName, finalCfgBuilder.build()); responseBuilder.status(OK); return responseBuilder.build(); }); }

Target:
private CompletableFuture<RestResponse> createCache(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = request.contents(); String cacheName = request.variables().get("cacheName"); byte[] bytes = contents.rawContent(); if (bytes == null || bytes.length == 0) { return CompletableFuture.supplyAsync(() -> { restCacheManager.getInstance().administration().createCache(cacheName, (String) null); responseBuilder.status(OK); return responseBuilder.build(); }, executor); } ConfigurationBuilder cfgBuilder = new ConfigurationBuilder(); MediaType sourceType = request.contentType() == null ? APPLICATION_JSON : request.contentType(); if (sourceType.match(APPLICATION_JSON)) { JSON_READER.readJson(cfgBuilder, StandardConversions.convertTextToObject(bytes, sourceType)); } else if (sourceType.match(MediaType.APPLICATION_XML)) { ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(bytes, UTF_8)); cfgBuilder = builderHolder.getCurrentConfigurationBuilder(); } else { responseBuilder.status(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE); return CompletableFuture.completedFuture(responseBuilder.build()); } ConfigurationBuilder finalCfgBuilder = cfgBuilder; return CompletableFuture.supplyAsync(() -> { restCacheManager.getInstance().administration().createCache(cacheName, finalCfgBuilder.build()); responseBuilder.status(OK); return responseBuilder.build(); }, executor); }
Source:
private PollingResult compare(Launcher launcher, TaskListener listener, MercurialTagAction baseline, PrintStream output, Node node, FilePath repository) throws IOException, InterruptedException { HgExe hg = new HgExe(this, launcher, node, listener, new EnvVars()); String remote = hg.tip(repository, getBranch()); String rev = hg.tipNumber(repository, getBranch()); if (remote == null) { throw new IOException("failed to find ID of branch head"); } if (remote.equals(baseline.id)) { return new PollingResult(baseline, new MercurialTagAction(remote, rev, subdir), Change.NONE); } if (rev == null) { throw new IOException("failed to find revision of branch head"); } Set<String> changedFileNames = parseStatus(hg.popen(repository, listener, false, new ArgumentListBuilder("status", "--rev", baseline.id, "--rev", remote))); MercurialTagAction cur = new MercurialTagAction(remote, rev, subdir); return new PollingResult(baseline,cur,computeDegreeOfChanges(changedFileNames,output)); }

Target:
private PollingResult compare(Launcher launcher, TaskListener listener, MercurialTagAction baseline, PrintStream output, Node node, FilePath repository) throws IOException, InterruptedException { HgExe hg = new HgExe(this, launcher, node, listener, new EnvVars()); String remote = hg.tip(repository, getBranch()); String rev = hg.tipNumber(repository, getBranch()); if (remote == null) { throw new IOException("failed to find ID of branch head"); } if (rev == null) { throw new IOException("failed to find revision of branch head"); } if (remote.equals(baseline.id)) { return new PollingResult(baseline, new MercurialTagAction(remote, rev, subdir), Change.NONE); } Set<String> changedFileNames = parseStatus(hg.popen(repository, listener, false, new ArgumentListBuilder("status", "--rev", baseline.id, "--rev", remote))); MercurialTagAction cur = new MercurialTagAction(remote, rev, subdir); return new PollingResult(baseline,cur,computeDegreeOfChanges(changedFileNames,output)); }
Source:
public static <T> ArrayList<T> Intersection(ArrayList<ArrayList<T>> lists) { ArrayList<T> result = new ArrayList<T>(); if (lists != null) { for (ArrayList<T> list : lists) { result.retainAll(list); } } return result; }

Target:
public static <T> ArrayList<T> Intersection(ArrayList<ArrayList<T>> lists) { ArrayList<T> result = new ArrayList<T>(); if (lists != null) { result.addAll(lists.get(0)); for (ArrayList<T> list : lists) { result.retainAll(list); } } return result; }
Source:
public Transfer generateGroupFileContent( Group group, List<ArtifactStore> members, String path, EventMetadata eventMetadata ) throws IndyWorkflowException { String realPath = path; boolean canProcess; if ( canProcess( realPath ) ) { canProcess = true; } else { realPath = pathCalculator.calculateStoragePath( group.getKey(), path ); canProcess = canProcess( realPath ); } if ( !canProcess ) { return null; } final Transfer target = fileManager.getTransfer( group, realPath ); logger.debug( "Working on metadata file: (already exists? {})", target, target != null && target.exists() ); if ( !target.exists() ) { String toMergePath = realPath; if ( !realPath.endsWith( PackageMetadataMerger.METADATA_NAME ) ) { toMergePath = normalize( normalize( parentPath( toMergePath ) ), PackageMetadataMerger.METADATA_NAME ); } final List<Transfer> sources = fileManager.retrieveAllRaw( members, toMergePath, new EventMetadata() ); final byte[] merged = merger.merge( sources, group, toMergePath ); if ( merged != null ) { OutputStream fos = null; try { fos = target.openOutputStream( TransferOperation.GENERATE, true, eventMetadata ); fos.write( merged ); } catch ( final IOException e ) { throw new IndyWorkflowException( "Failed to write merged metadata to: {}.\nError: {}", e, target, e.getMessage() ); } finally { closeQuietly( fos ); } helper.writeMergeInfo( merged, sources, group, toMergePath ); } } if ( target.exists() ) { return target; } return null; }

Target:
public Transfer generateGroupFileContent( Group group, List<ArtifactStore> members, String path, EventMetadata eventMetadata ) throws IndyWorkflowException { String realPath = path; boolean canProcess; if ( canProcess( realPath ) ) { canProcess = true; } else { realPath = pathGenerator.getPath( new ConcreteResource( LocationUtils.toLocation( group ), path ) ); canProcess = canProcess( realPath ); } if ( !canProcess ) { return null; } final Transfer target = fileManager.getTransfer( group, realPath ); logger.debug( "Working on metadata file: (already exists? {})", target, exists( target ) ); if ( !exists( target ) ) { String toMergePath = realPath; if ( !realPath.endsWith( PackageMetadataMerger.METADATA_NAME ) ) { toMergePath = normalize( normalize( parentPath( toMergePath ) ), PackageMetadataMerger.METADATA_NAME ); } final List<Transfer> sources = fileManager.retrieveAllRaw( members, toMergePath, new EventMetadata() ); final byte[] merged = merger.merge( sources, group, toMergePath ); if ( merged != null ) { try (OutputStream fos = target.openOutputStream( TransferOperation.GENERATE, true, eventMetadata )) { fos.write( merged ); } catch ( final IOException e ) { throw new IndyWorkflowException( "Failed to write merged metadata to: {}.\nError: {}", e, target, e.getMessage() ); } helper.writeMergeInfo( helper.generateMergeInfo( sources ), group, toMergePath ); } } if ( target.exists() ) { return target; } return null; }
Source:
public int getTotalParameterCount() { int total = 0; for (CurveParameterSize entry : data) { total += entry.getParameterCount(); } return total; }

Target:
public int getTotalParameterCount() { return data.stream() .mapToInt(CurveParameterSize::getParameterCount) .sum(); }
Source:
private Collection<? extends Permissionable> findFolderAssetContainers(final User user, final String hostId, final String orderByParam) { try { final Host host = this.hostAPI.find(hostId, user, false); final List<Folder> subFolders = this.findContainersAssetsByHost(host, user); final List<Container> containers = this.getFolderContainers(host, user, subFolders); if (UtilMethods.isSet(orderByParam)) { switch (orderByParam) { case "title asc": containers.sort(Comparator.comparing(Container::getTitle)); break; case "title desc": containers.sort(Comparator.comparing(Container::getTitle).reversed()); break; case "modDate asc": containers.sort(Comparator.comparing(Container::getModDate)); break; case "modDate desc": containers.sort(Comparator.comparing(Container::getModDate).reversed()); break; } } return containers; } catch (Exception e) { Logger.error(this, e.getMessage(), e); return Collections.emptyList(); } }

Target:
private Collection<? extends Permissionable> findFolderAssetContainers(final User user, final String hostId, final String orderByParam) { try { final Host host = this.hostAPI.find(hostId, user, false); final List<Folder> subFolders = this.findContainersAssetsByHost(host, user); final List<Container> containers = this.getFolderContainers(host, user, subFolders); if (UtilMethods.isSet(orderByParam)) { switch (orderByParam.toLowerCase()) { case "title asc": containers.sort(Comparator.comparing(Container::getTitle)); break; case "title desc": containers.sort(Comparator.comparing(Container::getTitle).reversed()); break; case "moddate asc": containers.sort(Comparator.comparing(Container::getModDate)); break; case "moddate desc": containers.sort(Comparator.comparing(Container::getModDate).reversed()); break; } } return containers; } catch (Exception e) { Logger.error(this, e.getMessage(), e); return Collections.emptyList(); } }
Source:
public static File getValidTestBundleFile(TemporaryFolder temporaryFolder) throws IOException { ZipEntrySource[] addedEntries = new ZipEntrySource[] { new FileSource(TestFiles.getTestLoadFile().getName(), TestFiles.getTestLoadFile()), new FileSource(TestFiles.getTestDeploymentDescriptorFile().getName(), TestFiles.getTestDeploymentDescriptorFile()), new FileSource("models/" + TestFiles.getModelsFolderFile().listFiles()[0].getName(), TestFiles.getModelsFolderFile().listFiles()[0]), new FileSource("models/" + TestFiles.getModelsFolderFile().listFiles()[1].getName(), TestFiles.getModelsFolderFile().listFiles()[1]),}; File zipFile = temporaryFolder.newFile(new BigInteger(130, new SecureRandom()).toString(32) + ".zip"); ZipUtil.pack(addedEntries, zipFile); return zipFile; }

Target:
public static File getValidTestBundleFile(TemporaryFolder temporaryFolder) throws IOException { ZipEntrySource[] addedEntries = new ZipEntrySource[] { new FileSource(TestFiles.getTestLoadFile().getName(), TestFiles.getTestLoadFile()), new FileSource(TestFiles.getTestDeploymentDescriptorFile().getName(), TestFiles.getTestDeploymentDescriptorFile())}; File zipFile = temporaryFolder.newFile(new BigInteger(130, new SecureRandom()).toString(32) + ".zip"); ZipUtil.pack(addedEntries, zipFile); addModelsToZipFile(zipFile); return zipFile; }
Source:
private void handleClick(final GQuery w) { final String indexOfSelected = w.css("order"); final List<Element> elements = Lists.newArrayList(w.get(0), activeItem.get(0)); activeItem.bind(TRANSITION_END, new Function() { @Override public void f() { $(this).unbind(TRANSITION_END); activeItem.removeClass(sliderResources.style().activeProduct()); w.addClass(sliderResources.style().activeProduct()); setOrder(w, String.valueOf(3)); setOrder(activeItem, indexOfSelected); $(elements).css("transform", "scale(1)"); activeItem = w; } }); $(elements).css("transform", "scale(0.1)"); }

Target:
private void handleClick(final GQuery w) { final String indexOfSelected = w.css("order"); final List<Element> elements = Lists.newArrayList(w.get(0), activeItem.get(0)); activeItem.bind(TRANSITION_END, new Function() { @Override public void f() { $(this).unbind(TRANSITION_END); activeItem.removeClass(sliderResources.style().activeProduct()); w.addClass(sliderResources.style().activeProduct()); setOrder(w, String.valueOf(3)); setOrder(activeItem, indexOfSelected); $(children).css("transform", "scale(1)"); activeItem = w; } }); $(elements).css("transform", "scale(0.1)"); }