auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
T build(ServiceLocator serviceLocator) { Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, new ServiceConfiguration<?>[]{}); this.statisticsExecutor = Executors.newScheduledThreadPool( Integer.getInteger("org.ehcache.StandaloneCacheBuilder.statisticsExecutor.poolSize", 1) , new ThreadFactory() { private AtomicInteger cnt = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "Statistics Thread-" + cnt.incrementAndGet()); t.setDaemon(true); return t; } }); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoader, cacheWriter, statisticsExecutor); return (T) ehcache; }

Target:
T build(ServiceLocator serviceLocator) { Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); ExecutorFactoryService executorService = serviceLocator.findService(ExecutorFactoryService.class); if (executorService != null && executorService.getStatisticsExecutor() != null) { statisticsExecutor = executorService.getStatisticsExecutor(); } else { statisticsExecutor = StatisticsThreadPoolUtil.getDefaultStatisticsExecutorService(); } final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry, new ServiceConfiguration<?>[]{}); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoader, cacheWriter, statisticsExecutor); return (T) ehcache; }
Source:
public String getAmqpUrl() { return String.format("amqp://" + getContainerIpAddress() + ":" + getMappedPort(DEFAULT_AMQP_PORT)); }

Target:
public String getAmqpUrl() { return "amqp://" + getContainerIpAddress() + ":" + getAmqpPort(); }
Source:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); Object result = method.invoke(this.previousContext, args); long delta = System.currentTimeMillis() - start; String methodName = method.getName(); int argsLength = args != null ? args.length : 0; if (methodName != null && !methodName.equalsIgnoreCase("close")) { logDetails(start, delta, ((DirContext) this.previousContext).getEnvironment(), methodName, argsLength, stringify(args)); } return result; }

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); Object result = method.invoke(this.previousContext, args); long delta = System.currentTimeMillis() - start; String methodName = method.getName(); int argsLength = 0; if (args != null) { argsLength = args.length; } if (!StringUtils.equalsIgnoreCase("close", methodName)) { CorrelationLogDTO correlationLogDTO = new CorrelationLogDTO(); correlationLogDTO.setStartTime(start); correlationLogDTO.setDelta(delta); correlationLogDTO.setEnvironment(((DirContext) this.previousContext).getEnvironment()); correlationLogDTO.setMethodName(methodName); correlationLogDTO.setArgsLength(argsLength); correlationLogDTO.setArgs(stringify(args)); logDetails(correlationLogDTO); } return result; }
Source:
protected void generateStaticRelationSlots(Role role, PrintWriter out) { newline(out); Role otherRole = role.getOtherRole(); boolean isDirectRelation = role.isDirect(); String genericType = "<" + getTypeFullName((isDirectRelation ? otherRole : role).getType()) + "," + getTypeFullName((isDirectRelation ? role : otherRole).getType()) + ">"; String relationSlotName = role.getRelation().getName(); String directRelationType = getDirectRelationType(); String methodName = "getRelation" + role.getRelation().getName(); if (isDirectRelation) { print(out, "private final static class "); print(out, relationSlotName); newBlock(out); print(out, "public static final "); print(out, directRelationType); print(out, genericType); print(out, " relation"); print(out, " = "); print(out, "new "); print(out, directRelationType); print(out, genericType); print(out, "("); print(out, getRoleHandlerName(role, false)); print(out, ", \""); print(out, role.getRelation().getName()); print(out, "\""); generateDefaultRelationListeners(role, out); print(out, ");"); closeBlock(out); } if (isDirectRelation || !role.getType().equals(otherRole.getType())) { printMethod(out, "public static", getDirectRelationInterfaceType() + genericType, methodName); startMethodBody(out); print(out, "return "); if (isDirectRelation) { print(out, relationSlotName + ".relation"); } else { print(out, role.getType().getFullName() + "." + methodName + "()"); } print(out, ";"); endMethodBody(out); } }

Target:
protected void generateStaticRelationSlots(Role role, PrintWriter out) { newline(out); Role otherRole = role.getOtherRole(); boolean isDirectRelation = role.isDirect(); String genericType = "<" + getTypeFullName((isDirectRelation ? otherRole : role).getType()) + "," + getTypeFullName((isDirectRelation ? role : otherRole).getType()) + ">"; String relationSlotName = role.getRelation().getName(); String directRelationType = getDirectRelationType(); String methodName = "getRelation" + role.getRelation().getName(); if (isDirectRelation) { print(out, "private final static class "); print(out, relationSlotName); newBlock(out); print(out, "private static final "); print(out, directRelationType); print(out, genericType); print(out, " relation"); print(out, " = "); print(out, "new "); print(out, directRelationType); print(out, genericType); print(out, "("); print(out, getRoleHandlerName(role, false)); print(out, ", \""); print(out, role.getRelation().getName()); print(out, "\""); generateDefaultRelationListeners(role, out); print(out, ");"); closeBlock(out); } if (isDirectRelation || !role.getType().equals(otherRole.getType())) { printMethod(out, "public static", getDirectRelationInterfaceType() + genericType, methodName); startMethodBody(out); print(out, "return "); if (isDirectRelation) { print(out, relationSlotName + ".relation"); } else { print(out, role.getType().getFullName() + "." + methodName + "()"); } print(out, ";"); endMethodBody(out); } }
Source:
String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }

Target:
protected String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }
Source:
public void executeJavaScriptTest() throws Exception { String javascript = "alert('Alert!')"; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains("Alert!")); iface.acceptDialog(); assertFalse(iface.isDialogVisible()); javascript = "alert(arguments[0])"; String arg = "one"; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript, arg); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains(arg)); iface.acceptDialog(); assertFalse(iface.isDialogVisible()); javascript = "alert(arguments[0] + ' and ' + arguments[1])"; String[] args = { "two", "three" }; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript, args); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains(args[0])); assertTrue(iface.wd.switchTo().alert().getText().contains(args[1])); iface.acceptDialog(); assertFalse(iface.isDialogVisible()); }

Target:
public void executeJavaScriptTest() throws Exception { String javascript = "alert('Alert!')"; iface.executeJavascript(javascript); assertTrue(iface.wd.switchTo().alert().getText().contains("Alert!")); iface.acceptDialog(); javascript = "alert(arguments[0])"; String arg = "one"; iface.executeJavascript(javascript, arg); assertTrue(iface.wd.switchTo().alert().getText().contains(arg)); iface.acceptDialog(); javascript = "alert(arguments[0] + ' and ' + arguments[1])"; String[] args = { "two", "three" }; iface.executeJavascript(javascript, args); assertTrue(iface.wd.switchTo().alert().getText().contains(args[0])); assertTrue(iface.wd.switchTo().alert().getText().contains(args[1])); iface.acceptDialog(); }
Source:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = null; Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = (String) attribute.getValue(); Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }
Source:
public void deleteBlob(String key) throws AuthorizationException, KeyNotFoundException, TException { try { String topoName = ConfigUtils.getIdFromBlobKey(key); if (topoName != null) { if (isTopologyActiveOrActivating(stormClusterState, topoName)) { String message = "Attempting to delete blob " + key + " from under active topology " + topoName; LOG.warn(message); throw new TException(message); } } blobStore.deleteBlob(key, getSubject()); LOG.info("Deleted blob for key {}", key); } catch (Exception e) { LOG.warn("delete blob exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }

Target:
public void deleteBlob(String key) throws AuthorizationException, KeyNotFoundException, IllegalStateException, TException { try { String topoName = ConfigUtils.getIdFromBlobKey(key); if (topoName != null) { if (isTopologyActiveOrActivating(stormClusterState, topoName)) { String message = "Attempting to delete blob " + key + " from under active topology " + topoName; LOG.warn(message); throw new WrappedIllegalStateException(message); } } blobStore.deleteBlob(key, getSubject()); LOG.info("Deleted blob for key {}", key); } catch (Exception e) { LOG.warn("delete blob exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
private Runnable cleaner( AtomicLong nextId, AtomicReference<Throwable> error, AtomicInteger cleanedPointers ) { return () -> { try ( PageCursor cursor = pagedFile.io( 0, PagedFile.PF_SHARED_READ_LOCK ); PageCursor writeCursor = pagedFile.io( 0, PagedFile.PF_SHARED_WRITE_LOCK ) ) { while ( nextId.get() < highTreeNodeId ) { int batchCount = 0; for ( ; batchCount < 1_000; batchCount++ ) { long id = nextId.getAndIncrement(); if ( id >= highTreeNodeId ) { break; } PageCursorUtil.goTo( cursor, "clean", id ); if ( hasCrashedGSPP( treeNode, cursor ) ) { writeCursor.next( cursor.getCurrentPageId() ); cleanTreeNode( treeNode, writeCursor, cleanedPointers ); } } if ( error.get() != null ) { break; } } } catch ( Throwable e ) { error.compareAndSet( null, e ); } }; }

Target:
private Runnable cleaner( AtomicLong nextId, AtomicReference<Throwable> error, AtomicInteger cleanedPointers ) { return () -> { try ( PageCursor cursor = pagedFile.io( 0, PagedFile.PF_SHARED_READ_LOCK ); PageCursor writeCursor = pagedFile.io( 0, PagedFile.PF_SHARED_WRITE_LOCK ) ) { long localNextId; while ( ( localNextId = nextId.getAndAdd( batchSize )) < highTreeNodeId ) { for ( int i = 0; i < batchSize && localNextId < highTreeNodeId; i++, localNextId++ ) { PageCursorUtil.goTo( cursor, "clean", localNextId ); if ( hasCrashedGSPP( treeNode, cursor ) ) { writeCursor.next( cursor.getCurrentPageId() ); cleanTreeNode( treeNode, writeCursor, cleanedPointers ); } } if ( error.get() != null ) { break; } } } catch ( Throwable e ) { error.compareAndSet( null, e ); } }; }
Source:
public boolean detect() { try { return jdbcTemplate.queryForInt("select count(*) from information_schema.tables where table_schema = 'pg_catalog' and table_name = 'stl_s3client'") > 0; } catch (SQLException e) { e.printStackTrace(); return false; } }

Target:
public boolean detect() { try { return jdbcTemplate.queryForInt("select count(*) from information_schema.tables where table_schema = 'pg_catalog' and table_name = 'stl_s3client'") > 0; } catch (SQLException e) { LOG.error("Unable to check whether this is a Redshift database", e); return false; } }
Source:
public Future<?> submit(Runnable r) { if (useMainThread) { r.run(); return new FutureTask<Void>(() -> {}, null); } else { return threadPool.submit(r); } }

Target:
public Future<?> submit(Runnable r) { if (useCallerThread) { r.run(); return new FutureTask<Void>(() -> {}, null); } else { return threadPool.submit(r); } }
Source:
private ResponseEntity<Object> exportXML(XMLExportRequest exportRequest) { Map<String, Object> result = new HashMap<>(); result.put("action", "export xml"); try { service.exportXml(GroupsThreadStore.getUsername(), GroupsThreadStore.getGroups(), new XMLExportRequest( exportRequest.getPids(), exportRequest.getExportChildren(), exportRequest.getEmail())); } catch (Exception e) { result.put("error", e.getMessage()); if (e instanceof AccessRestrictionException) { result.put("error", "User must have a username to export xml"); return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { log.error("Failed to begin export of xml due to ", e); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }

Target:
private ResponseEntity<Object> exportXML(XMLExportRequest exportRequest) { Map<String, Object> result = new HashMap<>(); result.put("action", "export xml"); AgentPrincipals agent = AgentPrincipals.createFromThread(); try { service.exportXml(agent.getUsername(), agent.getGroups(), new XMLExportRequest( exportRequest.getPids(), exportRequest.getExportChildren(), exportRequest.getEmail())); } catch (Exception e) { result.put("error", e.getMessage()); if (e instanceof AccessRestrictionException) { result.put("error", "User must have a username to export xml"); return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { log.error("Failed to begin export of xml due to ", e); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }
Source:
public @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent) { ViewHolder viewHolder; View rowView = convertView; if (rowView == null) { LayoutInflater layoutInflater = context.getLayoutInflater(); rowView = layoutInflater.inflate(layout, null, true); viewHolder = new ViewHolder(); viewHolder.title = (TextView) rowView.findViewById(R.id.title); viewHolder.description = (TextView) rowView.findViewById(R.id.description); viewHolder.icon = (ImageView) rowView.findViewById(R.id.icon); viewHolder.compoundButton = (CompoundButton) rowView.findViewById(R.id.compound_button); rowView.setTag(viewHolder); } else { viewHolder = (ViewHolder) rowView.getTag(); } ProfileDataObject mode = modes.get(position); Drawable iconDrawable; if (getMyApp(context) != null) { if (mode.isSelected()) { iconDrawable = getMyApp(context).getUIUtilities().getIcon(mode.getIconRes(), mode.getIconColor(!getMyApp(context).getSettings().isLightContent()) ); } else { iconDrawable = getMyApp(context).getUIUtilities() .getIcon(mode.getIconRes(), R.color.profile_icon_color_inactive); } } else { iconDrawable = context.getDrawable(mode.getIconRes()); } viewHolder.title.setText(mode.getName()); viewHolder.description.setText(mode.getDescription()); viewHolder.icon.setImageDrawable(iconDrawable); viewHolder.compoundButton.setChecked(mode.isSelected()); return rowView; }

Target:
public @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent) { ViewHolder viewHolder; View rowView = convertView; if (rowView == null) { LayoutInflater layoutInflater = context.getLayoutInflater(); rowView = layoutInflater.inflate(layout, null, true); viewHolder = new ViewHolder(); viewHolder.title = (TextView) rowView.findViewById(R.id.title); viewHolder.description = (TextView) rowView.findViewById(R.id.description); viewHolder.icon = (ImageView) rowView.findViewById(R.id.icon); viewHolder.compoundButton = (CompoundButton) rowView.findViewById(R.id.compound_button); rowView.setTag(viewHolder); } else { viewHolder = (ViewHolder) rowView.getTag(); } ProfileDataObject mode = modes.get(position); Drawable iconDrawable; if (mode.isSelected()) { iconDrawable = app.getUIUtilities().getIcon(mode.getIconRes(), mode.getIconColor(!app.getSettings().isLightContent())); } else { iconDrawable = app.getUIUtilities().getIcon(mode.getIconRes(), R.color.profile_icon_color_inactive); } viewHolder.title.setText(mode.getName()); viewHolder.description.setText(mode.getDescription()); viewHolder.icon.setImageDrawable(iconDrawable); viewHolder.compoundButton.setChecked(mode.isSelected()); return rowView; }
Source:
private void findTargetLineBreakpoint( final IBreakpointsTargetDMContext bpTargetDMC, final List<MIBreakpoint> candidates, final String fileName, final Integer lineNumber, final String function, final String address, final Boolean isHardware, final Boolean isTemporary, final DataRequestMonitor<MIBreakpoint> drm) { Sequence s = new Sequence(getExecutor(), new RequestMonitor(getExecutor(), drm) { @Override @ConfinedToDsfExecutor( "fExecutor" ) protected void handleCompleted() { drm.setStatus(getStatus()); drm.done(); } }) { @Override public Step[] getSteps() { Step[] steps = new Step[candidates.size()]; for (int i = 0; i < steps.length; ++i) { steps[i] = new FindTargetBreakpointStep(candidates.get(i)) { @Override public void execute(final RequestMonitor rm) { if (drm.getData() != null) { rm.done(); return; } getSource( bpTargetDMC, getFileName(fMIBpt), new DataRequestMonitor<String>(getExecutor(), rm) { @Override @ConfinedToDsfExecutor( "fExecutor" ) protected void handleSuccess() { if (compareBreakpointAttributes( fMIBpt, getData(), fileName, lineNumber, function, address, isHardware, isTemporary)) { drm.setData(fMIBpt); } rm.done(); } }); } }; } return steps; } }; getExecutor().execute(s); }

Target:
private void findTargetLineBreakpoint( final IBreakpointsTargetDMContext bpTargetDMC, final List<MIBreakpoint> candidates, final String fileName, final Integer lineNumber, final String function, final String address, final Boolean isHardware, final Boolean isTemporary, final DataRequestMonitor<MIBreakpoint> drm) { class FindBreakpointRM extends ImmediateDataRequestMonitor<MIBreakpoint> { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { final List<MIBreakpoint> bpts = new ArrayList<MIBreakpoint>(candidates); if (bpts.isEmpty()) { drm.done(); return; } final MIBreakpoint bpt = bpts.remove(0); final String debuggerPath = getFileName(bpt); getSource( bpTargetDMC, debuggerPath, new DataRequestMonitor<String>(getExecutor(), drm) { @Override @ConfinedToDsfExecutor( "fExecutor" ) protected void handleCompleted() { if (!isSuccess()) { GdbPlugin.log(getStatus()); } if (compareBreakpointAttributes( bpt, isSuccess() ? getData() : debuggerPath, fileName, lineNumber, function, address, isHardware, isTemporary)) { drm.setData(bpt); drm.done(); } else { new FindBreakpointRM().done(); } } }); } }; new FindBreakpointRM().done(); }
Source:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = WifiManager.WIFI_FEATURE_INFRA; for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }

Target:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = 0; for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }
Source:
String normal_ping(String ip){ String result = ""; try { if(InetAddress.getByAddress(ip.getBytes()).isReachable(G.logPingTimeout() * 1000)){ result = String.format(context.getString(R.string.reachable_timeout), finish_time()); } } catch (IOException e) { Log.e(TAG, "Exception(04): " + e.getMessage()); result = String.format("Currently IP(%s) is not Reachable, timeout: %d ms", ip, finish_time()); } return result; }

Target:
String normal_ping(String ip){ String result = ""; try { if(InetAddress.getByAddress(ip.getBytes()).isReachable(G.logPingTimeout() * 1000)){ result = String.format(context.getString(R.string.reachable_timeout), finish_time()); } } catch (Exception e) { Log.e(TAG, "Exception(04): " + e.getMessage()); result = String.format("Currently IP(%s) is not Reachable, timeout: %d ms", ip, finish_time()); } return result; }
Source:
protected int getMaximumTotalSize() { return DiagramUIPlugin.getPlugin().getPreferenceStore().getInt(SiriusDiagramUiPreferencesKeys.PREF_MAXIMUM_EXPORT_BUFFER_SIZE.name()); }

Target:
protected int getMaximumTotalSize() { SiriusDiagramUiPreferencesKeys pref = SiriusDiagramUiPreferencesKeys.PREF_MAXIMUM_EXPORT_BUFFER_SIZE; if ("win32".equals(SWT.getPlatform())) { pref = SiriusDiagramUiPreferencesKeys.PREF_MAXIMUM_EXPORT_BUFFER_SIZE_WINDOWS; } return DiagramUIPlugin.getPlugin().getPreferenceStore().getInt(pref.name()); }
Source:
public PwaRegistry(PWA pwa, ServletContext servletContext) throws IOException { if (System.getProperty(HEADLESS_PROPERTY) == null) { System.setProperty(HEADLESS_PROPERTY, Boolean.TRUE.toString()); } pwaConfiguration = new PwaConfiguration(pwa, servletContext); if (pwaConfiguration.isEnabled()) { URL logo = getUrl(servletContext, pwaConfiguration.relIconPath()); URL offlinePage = getUrl(servletContext, pwaConfiguration.relOfflinePath()); BufferedImage baseImage = getBaseImage(logo); if (baseImage == null) { LoggerFactory.getLogger(PwaRegistry.class).error( "Image is not found or can't be loaded: " + logo); } else { int bgColor = baseImage.getRGB(0, 0); icons = initializeIcons(baseImage, bgColor); } offlineHtml = initializeOfflinePage(pwaConfiguration, offlinePage); offlineHash = offlineHtml.hashCode(); manifestJson = initializeManifest().toJson(); serviceWorkerJs = initializeServiceWorker(servletContext); } }

Target:
public PwaRegistry(PWA pwa, ServletContext servletContext) throws IOException { if (System.getProperty(HEADLESS_PROPERTY) == null) { System.setProperty(HEADLESS_PROPERTY, Boolean.TRUE.toString()); } pwaConfiguration = new PwaConfiguration(pwa, servletContext); if (pwaConfiguration.isEnabled()) { URL logo = getResourceUrl(servletContext, pwaConfiguration.relIconPath()); URL offlinePage = getResourceUrl(servletContext, pwaConfiguration.relOfflinePath()); BufferedImage baseImage = getBaseImage(logo); if (baseImage == null) { LoggerFactory.getLogger(PwaRegistry.class).error( "Image is not found or can't be loaded: " + logo); } else { int bgColor = baseImage.getRGB(0, 0); icons = initializeIcons(baseImage, bgColor); } offlineHtml = initializeOfflinePage(pwaConfiguration, offlinePage); offlineHash = offlineHtml.hashCode(); manifestJson = initializeManifest().toJson(); serviceWorkerJs = initializeServiceWorker(servletContext); } }
Source:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is master.", latch == null ? null : latch.getLeader().getId()); stopBeingMaster(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingMaster(); return; } } DynamicConfigs dynamicConfigs = configManager.watch(DynamicConfigs.CONFIG_KEY,DynamicConfigs.class).get(); DruidMasterRuntimeParams params = DruidMasterRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withDynamicConfigs(dynamicConfigs) .withEmitter(emitter) .build(); for (DruidMasterHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }

Target:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is master.", latch == null ? null : latch.getLeader().getId()); stopBeingMaster(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingMaster(); return; } } DruidMasterRuntimeParams params = DruidMasterRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withMasterSegmentSettings(segmentSettingsAtomicReference.get()) .withEmitter(emitter) .build(); for (DruidMasterHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }
Source:
public static int fromHours(int hours) { int refreshRate = hours * 3600; RefreshRate.validateRefreshRate(refreshRate); return refreshRate; }

Target:
public static int fromHours(int hours) { int refreshRate = hours * RefreshRate.SECONDS_PER_HOUR; RefreshRate.validateRefreshRate(refreshRate); return refreshRate; }
Source:
public List<User> getUsers(PerunSession sess, Map<String, String> attributesWithSearchingValues) throws InternalErrorException, AttributeNotExistsException, PrivilegeException, WrongAttributeAssignmentException { if (!AuthzResolver.authorizedInternal(sess, "getUsers_Map<String, String>_policy", Collections.emptyList())) throw new PrivilegeException(sess, "getUsers"); return searcherBl.getUsers(sess, attributesWithSearchingValues); }

Target:
public List<User> getUsers(PerunSession sess, Map<String, String> attributesWithSearchingValues) throws InternalErrorException, AttributeNotExistsException, PrivilegeException, WrongAttributeAssignmentException { if (!AuthzResolver.authorizedInternal(sess, "getUsers_Map<String_String>_policy")) throw new PrivilegeException(sess, "getUsers"); return searcherBl.getUsers(sess, attributesWithSearchingValues); }
Source:
public boolean verifyPasswordStructure(String password) { if (StringUtils.isBlank(password)) { return false; } if (StringUtils.length(password) < 6) { return false; } return true; }

Target:
public boolean verifyPasswordStructure(String password) { if (StringUtils.length(password) < 6) { return false; } return true; }
Source:
private void logFullWorkflowRefresh(final Workflow workflow) { if (workflow.getMode() == WorkflowMode.FULL) { LOG.info(String.format("%s: Refreshing %s workflow named %s", dashboardPrefix, workflow.getDescriptorType(), workflow.getWorkflowPath())); } }

Target:
private void logFullWorkflowRefresh(final Workflow workflow) { if (workflow.getMode() == WorkflowMode.FULL) { LOG.info(String.format("%s: Refreshing %s workflow named %s", dashboardPrefix, workflow.getDescriptorType(), workflow.getEntryPath())); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_story); ButterKnife.inject(this); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); story = getIntent().getParcelableExtra(Constants.News.STORY); Picasso.with(this).load(story.getCoverImage().getRepresentations().get(0).getUrl()) .placeholder(R.drawable.grey_rect).into(storyImageView); String template = readInHtmlTemplate(); if (story.getTitle() != null) { template = template.replace("__TITLE__", story.getTitle()); } else { template = template.replace("__TITLE__", ""); } if (story.getAuthor() != null) { template = template.replace("__AUTHOR__", story.getAuthor()); } else { template = template.replace("__AUTHOR__", ""); } if (story.getPublishedAt() != null) { template = template.replace("__DATE__", NewsUtils.formatNewsPublishedTime(story.getPublishedAt())); } else { template = template.replace("__DATE__", ""); } if (story.getDek() != null) { template = template.replace("__DEK__", story.getDek()); } else { template = template.replace("__DEK__", ""); } if (story.getBodyHtml() != null) { template = template.replace("__BODY__", story.getBodyHtml()); } else { template = template.replace("__BODY__", ""); } template = template.replace("__WIDTH__", String.valueOf(displayMetrics.widthPixels)); storyWebView.loadData(template, "text/html;charset=utf-8", "UTF-8"); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_story); ButterKnife.inject(this); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); story = getIntent().getParcelableExtra(Constants.News.STORY); Picasso.with(this).load(story.getOriginalCoverImageUrl()) .placeholder(R.drawable.grey_rect).into(storyImageView); storyWebView.getSettings().setJavaScriptEnabled(true); String template = readInHtmlTemplate(); if (story.getTitle() != null) { template = template.replace("__TITLE__", story.getTitle()); } else { template = template.replace("__TITLE__", ""); } if (story.getAuthor() != null) { template = template.replace("__AUTHOR__", story.getAuthor()); } else { template = template.replace("__AUTHOR__", ""); } if (story.getPublishedAt() != null) { template = template.replace("__DATE__", NewsUtils.formatNewsPublishedTime(story.getPublishedAt())); } else { template = template.replace("__DATE__", ""); } if (story.getDek() != null) { template = template.replace("__DEK__", story.getDek()); } else { template = template.replace("__DEK__", ""); } if (story.getBodyHtml() != null) { template = template.replace("__BODY__", story.getBodyHtml()); } else { template = template.replace("__BODY__", ""); } template = template.replace("__WIDTH__", String.valueOf(displayMetrics.widthPixels)); storyWebView.loadData(template, "text/html;charset=utf-8", "UTF-8"); }
Source:
private final void checkMaps(final boolean strict, final GridDhtCacheAdapter<String, Integer>... caches) throws Exception { if (caches.length < 2) return; assert GridTestUtils.waitForCondition(() -> { info("Checking partition maps."); for (int i = 0; i < caches.length; i++) info("Partition map for node " + i + ": " + caches[i].topology().partitionMap(false).toFullString()); GridDhtPartitionFullMap orig = caches[0].topology().partitionMap(true); for (int i = 1; i < caches.length; i++) { GridDhtPartitionFullMap cmp = caches[i].topology().partitionMap(true); if(!orig.keySet().equals(cmp.keySet())) { info("Cache[0] key set is not equal to cache[1] key set, rerun"); return false; } for (Map.Entry<UUID, GridDhtPartitionMap> entry : orig.entrySet()) { UUID nodeId = entry.getKey(); GridDhtPartitionMap nodeMap = entry.getValue(); GridDhtPartitionMap cmpMap = cmp.get(nodeId); if (cmpMap == null || !nodeMap.keySet().equals(cmpMap.keySet())) { info("Cache key set is not equal to nodeMap key set, rerun"); return false; } for (Map.Entry<Integer, GridDhtPartitionState> nodeEntry : nodeMap.entrySet()) { GridDhtPartitionState state = cmpMap.get(nodeEntry.getKey()); boolean isOk = state != null && state != GridDhtPartitionState.EVICTED && (!strict || state == GridDhtPartitionState.OWNING) && state == nodeEntry.getValue(); if (!isOk) { info("Entry state is invalid, rerun"); return false; } } } } return true; }, 25000); }

Target:
private final void checkMaps(final boolean strict, final GridDhtCacheAdapter<String, Integer>... caches) throws Exception { if (caches.length < 2) return; assert GridTestUtils.waitForCondition(() -> { info("Checking partition maps."); for (int i = 0; i < caches.length; i++) info("Partition map for node " + i + ": " + caches[i].topology().partitionMap(false).toFullString()); GridDhtPartitionFullMap orig = caches[0].topology().partitionMap(true); for (int i = 1; i < caches.length; i++) { GridDhtPartitionFullMap cmp = caches[i].topology().partitionMap(true); if(!orig.keySet().equals(cmp.keySet())) { info("Cache[0] key set is not equal to cache[1] key set, rerun"); return false; } for (Map.Entry<UUID, GridDhtPartitionMap> entry : orig.entrySet()) { UUID nodeId = entry.getKey(); GridDhtPartitionMap nodeMap = entry.getValue(); GridDhtPartitionMap cmpMap = cmp.get(nodeId); if (cmpMap == null || !nodeMap.keySet().equals(cmpMap.keySet())) { info("Cache key set is not equal to nodeMap key set, rerun"); return false; } for (Map.Entry<Integer, GridDhtPartitionState> nodeEntry : nodeMap.entrySet()) { GridDhtPartitionState state = cmpMap.get(nodeEntry.getKey()); boolean isOk = state != null && state != GridDhtPartitionState.EVICTED && (!strict || state == GridDhtPartitionState.OWNING) && state == nodeEntry.getValue(); if (!isOk) { info("Partition state is invalid, rerun"); return false; } } } } return true; }, 25000); }
Source:
public void realmResults_readableAcrossThreads() { final long TEST_SIZE = 10; Realm realm = looperThread.getRealm(); realm.beginTransaction(); for (int i = 0; i < TEST_SIZE; i++) { realm.createObject(AllTypes.class).setColumnLong(1); } realm.commitTransaction(); subscription = realm.where(AllTypes.class).sort(AllTypes.FIELD_LONG).findAllAsync().asFlowable() .subscribeOn(Schedulers.io()) .filter(RealmResults::isLoaded) .map(results -> { RealmLog.error(Thread.currentThread().getName()); return new Pair<>(results.size(), results); }) .observeOn(Schedulers.computation()) .subscribe( pair -> { RealmLog.error(Thread.currentThread().getName()); assertEquals(TEST_SIZE, pair.first.intValue()); assertEquals(TEST_SIZE, pair.second.size()); looperThread.testComplete(); } ); }

Target:
public void realmResults_readableAcrossThreads() { final long TEST_SIZE = 10; Realm realm = looperThread.getRealm(); realm.beginTransaction(); for (int i = 0; i < TEST_SIZE; i++) { realm.createObject(AllTypes.class).setColumnLong(1); } realm.commitTransaction(); AtomicLong startingThread = new AtomicLong(Thread.currentThread().getId()); AtomicLong subscriberThread = new AtomicLong(); subscription = realm.where(AllTypes.class).sort(AllTypes.FIELD_LONG).findAllAsync().asFlowable() .doOnSubscribe((r) -> { subscriberThread.set(Thread.currentThread().getId()); }) .subscribeOn(Schedulers.io()) .filter(results -> { assertNotEquals(startingThread.get(), subscriberThread.get()); return results.isLoaded(); }) .map(results -> new Pair<>(results.size(), new Pair<>(results, results.first()))) .observeOn(Schedulers.computation()) .subscribe( pair -> { assertNotEquals(startingThread.get(), Thread.currentThread().getId()); assertNotEquals(subscriberThread.get(), Thread.currentThread().getId()); assertEquals(TEST_SIZE, pair.first.intValue()); assertEquals(TEST_SIZE, pair.second.first.size()); assertEquals(pair.second.second.getColumnLong(), pair.second.first.first().getColumnLong()); disposeSuccessfulTest(realm); } ); }
Source:
public void loadRepository(boolean refresh) { Consumer subscriber = repository -> { mRepository = (Repository) repository; updateTitle(); invalidateTabs(); if (mInitialPage >= PAGE_REPO_OVERVIEW && mInitialPage <= PAGE_ACTIVITY) { getPager().setCurrentItem(mInitialPage); mInitialPage = -1; } setContentShown(true); supportInvalidateOptionsMenu(); }; RepositoryService.loadRepository(this, mRepoOwner, mRepoName, refresh) .subscribe(subscriber, e -> {}); }

Target:
private void loadRepository(boolean refresh) { Consumer<Repository> subscriber = repository -> { mRepository = repository; updateTitle(); invalidateTabs(); if (mInitialPage >= PAGE_REPO_OVERVIEW && mInitialPage <= PAGE_ACTIVITY) { getPager().setCurrentItem(mInitialPage); mInitialPage = -1; } setContentShown(true); supportInvalidateOptionsMenu(); }; RepositoryService.loadRepository(this, mRepoOwner, mRepoName, refresh) .subscribe(subscriber, error -> {}); }
Source:
protected boolean canLoad(Object key) { return !cacheConfiguration.clustering().cacheMode().isDistributed() || cdl.localNodeIsOwner(key); }

Target:
protected boolean canLoad(Object key) { return !cacheConfiguration.clustering().cacheMode().isDistributed() || dm.getReadConsistentHash().isKeyLocalToNode(cdl.getAddress(), key); }
Source:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode metadataObjectNode; try { metadataObjectNode = mapper.readValue((String) entry.getDocument(), ObjectNode.class); } catch (IOException e) { return result; } Map<String, Object> metadata = DocumentToMetadataProcessor.asMap(metadataObjectNode); if(entry == null || entry.getMetadata() == null) return result; String index = (String) metadata.get("index"); String type = (String) metadata.get("type"); String id = (String) metadata.get("id"); if( index == null ) { index = this.config.getIndexes().get(0); } if( type == null ) { type = this.config.getTypes().get(0); } if( id == null ) { id = entry.getId(); } GetRequestBuilder getRequestBuilder = elasticsearchClientManager.getClient().prepareGet(index, type, id); getRequestBuilder.setFields("*", "_timestamp"); getRequestBuilder.setFetchSource(true); GetResponse getResponse = getRequestBuilder.get(); if( getResponse == null || getResponse.isExists() == false || getResponse.isSourceEmpty() == true ) return result; entry.setDocument(getResponse.getSource()); if( getResponse.getField("_timestamp") != null) { DateTime timestamp = new DateTime(((Long) getResponse.getField("_timestamp").getValue()).longValue()); entry.setTimestamp(timestamp); } result.add(entry); return result; }

Target:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newArrayList(); ObjectNode metadataObjectNode; try { metadataObjectNode = mapper.readValue((String) entry.getDocument(), ObjectNode.class); } catch (IOException e) { return result; } Map<String, Object> metadata = ElasticsearchMetadataUtil.asMap(metadataObjectNode); if(entry == null || entry.getMetadata() == null) return result; String index = ElasticsearchMetadataUtil.getIndex(metadata, config); String type = ElasticsearchMetadataUtil.getType(metadata, config); String id = ElasticsearchMetadataUtil.getId(metadata); GetRequestBuilder getRequestBuilder = elasticsearchClientManager.getClient().prepareGet(index, type, id); getRequestBuilder.setFields("*", "_timestamp"); getRequestBuilder.setFetchSource(true); GetResponse getResponse = getRequestBuilder.get(); if( getResponse == null || getResponse.isExists() == false || getResponse.isSourceEmpty() == true ) return result; entry.setDocument(getResponse.getSource()); if( getResponse.getField("_timestamp") != null) { DateTime timestamp = new DateTime(((Long) getResponse.getField("_timestamp").getValue()).longValue()); entry.setTimestamp(timestamp); } result.add(entry); return result; }
Source:
public boolean test() throws Exception { @NonNull TmfTimeRange curWindowRange = TmfTraceManager.getInstance().getTraceContext(fTrace).getWindowRange(); if (!curWindowRange.equals(fWindowRange)) { fFailureMessage = "Current window range " + curWindowRange + " is not expected " + fWindowRange; return false; } if (fView.isDirty()) { fFailureMessage = "Time graph is dirty"; return false; } return true; }

Target:
public boolean test() throws Exception { ITmfTrace trace = fView.getTrace(); if (!fTrace.equals(trace)) { String traceName = trace != null ? trace.getName() : "none"; fFailureMessage = "Expected view to display trace:" + fTrace.getName() + " but was displaying trace: " + traceName; } @NonNull TmfTimeRange curWindowRange = TmfTraceManager.getInstance().getTraceContext(fTrace).getWindowRange(); if (!curWindowRange.equals(fWindowRange)) { fFailureMessage = "Current window range " + curWindowRange + " is not expected " + fWindowRange; return false; } if (fView.isDirty()) { fFailureMessage = "Time graph is dirty"; return false; } return true; }
Source:
public ResponseEntity createSampleListFolder(@PathVariable final String crop, @RequestParam final String folderName, @RequestParam final Integer parentId, @RequestParam final String programUUID) { Map<String, Object> map; try { map = this.sampleListService.createSampleListFolder(folderName, parentId, programUUID); } catch (final MiddlewareException e) { final ErrorResponse response = new ErrorResponse(); response.addError("Something went wrong, please try again"); return new ResponseEntity<>(response, HttpStatus.CONFLICT); } return new ResponseEntity<>(map, HttpStatus.OK); }

Target:
public ResponseEntity createSampleListFolder(@PathVariable final String crop, @RequestParam final String folderName, @RequestParam final Integer parentId, @RequestParam final String programUUID) { final Map<String, Object> map; try { map = this.sampleListService.createSampleListFolder(folderName, parentId, programUUID); } catch (final MiddlewareException e) { final ErrorResponse response = new ErrorResponse(); response.addError("Something went wrong, please try again"); return new ResponseEntity<>(response, HttpStatus.CONFLICT); } return new ResponseEntity<>(map, HttpStatus.OK); }
Source:
public boolean isTopLevelClass() { return !classInfo.name().isInner(); }

Target:
public boolean isTopLevelClass() { return classInfo.nestingType().equals(ClassInfo.NestingType.TOP_LEVEL); }
Source:
public void handleSlotClick(EntityPlayer player, ItemStack filter, boolean shiftClick, boolean rightClick) { if (!shiftClick && !player.inventory.getItemStack().isEmpty() && cachedItemMap.getTotalItemCount() != getMaxStorage()) { tryAddItem(player, player.inventory.getItemStack()); } else if (!filter.isEmpty()) { tryGetItem(player, filter, shiftClick, rightClick); } }

Target:
public void handleSlotClick(EntityPlayer player, ItemStack filter, boolean shiftClick, boolean rightClick) { if (!shiftClick && !player.inventory.getItemStack().isEmpty()) { tryAddItem(player, player.inventory.getItemStack()); } else if (!filter.isEmpty()) { tryGetItem(player, filter, shiftClick, rightClick); } }
Source:
private String convertBoolean(final String value) { String result = value; if (result.equals("true")) { result = "Yes"; } if (result.equals("false")) { result = "No"; } return result; }

Target:
private String convertBoolean(final String value) { String result = value; if (result.equals("true")) { result = "Yes"; } else if (result.equals("false")) { result = "No"; } return result; }
Source:
public Void call() throws Exception { LOG.debug("Starting region operation on " + region); region.startRegionOperation(); try { LOG.debug("Flush region " + region.toString() + " started..."); region.flushcache(families, false, FlushLifeCycleTracker.DUMMY); } finally { LOG.debug("Closing region operation on " + region); region.closeRegionOperation(); } return null; }

Target:
public Void call() throws Exception { LOG.debug("Starting region operation on " + region); region.startRegionOperation(); try { LOG.debug("Flush region " + region.toString() + " started..."); if (families == null) { region.flush(true); } else { region.flushcache(families, false, FlushLifeCycleTracker.DUMMY); } } finally { LOG.debug("Closing region operation on " + region); region.closeRegionOperation(); } return null; }
Source:
private List<Method> getAllDeclaredHandlerMethods(Class<?> clazz) { final List<Method> handlerMethods = new ArrayList<>(); while (clazz != null && !Collection.class.isAssignableFrom(clazz) && !clazz.isArray()) { for (final Method handlerMethod : clazz.getDeclaredMethods()) { if (handlerMethod.isAnnotationPresent(EventListener.class)) { if (handlerMethod.getReturnType().equals(Void.TYPE) && handlerMethod.getParameterTypes().length == 1 && ApplicationEvent.class.isAssignableFrom(handlerMethod.getParameterTypes()[0])) { handlerMethods.add(handlerMethod); } else { LOG.warn( "@EventListener {}.{} skipped. Methods must be public, void, and accept exactly" + " one argument extending com.netflix.governator.event.ApplicationEvent.", clazz.getName(), handlerMethod.getName()); } } } clazz = clazz.getSuperclass(); } return handlerMethods; }

Target:
private List<Method> getAllDeclaredHandlerMethods(Class<?> clazz) { final List<Method> handlerMethods = new ArrayList<>(); while (clazz != null && !Collection.class.isAssignableFrom(clazz) && !clazz.isArray()) { for (final Method handlerMethod : clazz.getDeclaredMethods()) { if (handlerMethod.isAnnotationPresent(EventListener.class)) { if (handlerMethod.getReturnType().equals(Void.TYPE) && handlerMethod.getParameterTypes().length == 1 && ApplicationEvent.class.isAssignableFrom(handlerMethod.getParameterTypes()[0])) { handlerMethods.add(handlerMethod); } else { throw new IllegalArgumentException("@EventListener " + clazz.getName() + "." + handlerMethod.getName() + "skipped. Methods must be public, void, and accept exactly" + " one argument extending com.netflix.governator.event.ApplicationEvent."); } } } clazz = clazz.getSuperclass(); } return handlerMethods; }