auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void invokeOnSelection() { try { INVOKE_COUNT.incrementAndGet(this); if (!urgent) { invocationService.checkInvocationAllowed(); } if (isBindToSingleConnection()) { boolean invoked = invocationService.invokeOnConnection(this, (ClientConnection) connection); if (!invoked) { notifyException(new IOException("Could not invoke on connection " + connection)); } return; } boolean invoked; if (isSmartRoutingEnabled) { if (partitionId != -1) { invoked = invocationService.invokeOnPartitionOwner(this, partitionId); } else if (uuid != null) { invoked = invocationService.invokeOnTarget(this, uuid); } else { invoked = invocationService.invokeOnRandomTarget(this); } if (allowRetryOnRandom && !invoked) { invoked = invocationService.invokeOnRandomTarget(this); } } else { invoked = invocationService.invokeOnRandomTarget(this); } if (!invoked) { notifyException(new IOException("No connection found to invoke")); } } catch (Throwable e) { notifyException(e); } }

Target:
private void invokeOnSelection() { try { INVOKE_COUNT.incrementAndGet(this); if (!urgent) { invocationService.checkInvocationAllowed(); } if (isBindToSingleConnection()) { boolean invoked = invocationService.invokeOnConnection(this, (ClientConnection) connection); if (!invoked) { notifyException(new IOException("Could not invoke on connection " + connection)); } return; } boolean invoked; if (isSmartRoutingEnabled) { if (partitionId != -1) { invoked = invocationService.invokeOnPartitionOwner(this, partitionId); } else if (uuid != null) { invoked = invocationService.invokeOnTarget(this, uuid); } else { invoked = invocationService.invoke(this); } if (allowRetryOnRandom && !invoked) { invoked = invocationService.invoke(this); } } else { invoked = invocationService.invoke(this); } if (!invoked) { notifyException(new IOException("No connection found to invoke")); } } catch (Throwable e) { notifyException(e); } }
Source:
public void setNode(Node givenNode) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (tvc != null) { tvc.cancelLoadingThumbnails(); } try { if (givenNode != null) { if (givenNode instanceof TableFilterNode){ tfn = (TableFilterNode) givenNode; } tvc = new ThumbnailViewChildren(givenNode,thumbSize); final Node root = new AbstractNode(tvc); pageUpdater.setRoot(root); root.addNodeListener(pageUpdater); em.setRootContext(root); } else { tfn = null; tvc = null; Node emptyNode = new AbstractNode(Children.LEAF); em.setRootContext(emptyNode); iconView.setBackground(Color.BLACK); } } finally { this.setCursor(null); } }

Target:
public void setNode(Node givenNode) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (tvc != null) { tvc.cancelLoadingThumbnails(); } try { if (givenNode != null) { tfn = (TableFilterNode) givenNode; tvc = new ThumbnailViewChildren(givenNode,thumbSize); final Node root = new AbstractNode(tvc); pageUpdater.setRoot(root); root.addNodeListener(pageUpdater); em.setRootContext(root); } else { tfn = null; tvc = null; Node emptyNode = new AbstractNode(Children.LEAF); em.setRootContext(emptyNode); iconView.setBackground(Color.BLACK); } } finally { this.setCursor(null); } }
Source:
public Key (String tenantId, String schemaName, String tableName) { this.tenantId = tenantId; this.schemaName = schemaName; this.tableName = tableName; }

Target:
public Key (String tenantId, String schemaName, String tableName) throws IllegalArgumentException { if (tableName == null) { throw new IllegalArgumentException(); } serializedValue = (tenantId != null ? tenantId + "," : ",") + (schemaName != null ? schemaName + "," : ",") + tableName; }
Source:
private void collectVmPrestartFailureReasons(Map<String, Integer> failureReasons, List<String> messages) { String reason = String.join(", ", messages); Integer count = failureReasons.get(reason); failureReasons.put(reason, count == null ? 1 : count + 1); }

Target:
private void collectVmPrestartFailureReasons(Map<String, Integer> failureReasons, List<String> messages) { if (log.isInfoEnabled()) { String reason = messages.stream() .filter(ErrorMessageUtils::isMessage) .collect(Collectors.joining(", ")); Integer count = failureReasons.get(reason); failureReasons.put(reason, count == null ? 1 : count + 1); } }
Source:
default String toJSON() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { LoggerFactory.getLogger(JSONable.class).log(Level.WARNING, "failed to convert object of class {0} to JSON: {1}", new Object[]{this.getClass().toString(), this}); return ""; } }

Target:
default String toJSON() { ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { LoggerFactory.getLogger(JSONable.class).log(Level.WARNING, String.format("failed to convert object of class %s to JSON: %s", this.getClass().toString(), this), e); return EMPTY; } }
Source:
private void showErrorsAndCleanupState(FactModelTuple factModelTuple) { StringBuilder builder = new StringBuilder(); boolean showError = false; if (factModelTuple.getTopLevelCollectionError().size() > 0) { showError = true; builder.append("Top level collections are not supported:<br/>"); factModelTuple.getTopLevelCollectionError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); builder.append("<br/>"); } if (factModelTuple.getMultipleNestedCollectionError().size() > 0) { showError = true; builder.append("Multiple collections nested are not supported:<br/>"); factModelTuple.getMultipleNestedCollectionError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); builder.append("<br/>"); } if (factModelTuple.getMultipleNestedObjectError().size() > 0) { showError = true; builder.append("Multiple nested objects inside a collection are not supported:<br/>"); factModelTuple.getMultipleNestedObjectError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); } if (showError) { factModelTuple.getTopLevelCollectionError().clear(); factModelTuple.getMultipleNestedCollectionError().clear(); factModelTuple.getMultipleNestedObjectError().clear(); eventBus.fireEvent(new UnsupportedDMNEvent(builder.toString())); } }

Target:
private void showErrorsAndCleanupState(FactModelTuple factModelTuple) { StringBuilder builder = new StringBuilder(); boolean showError = false; if (factModelTuple.getTopLevelCollectionError().size() > 0) { showError = true; builder.append("Top-level collections are not supported! Violated by:<br/>"); factModelTuple.getTopLevelCollectionError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); builder.append("<br/>"); } if (factModelTuple.getMultipleNestedCollectionError().size() > 0) { showError = true; builder.append("Nested collections are not supported! Violated by:<br/>"); factModelTuple.getMultipleNestedCollectionError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); builder.append("<br/>"); } if (factModelTuple.getMultipleNestedObjectError().size() > 0) { showError = true; builder.append("Complex nested objects inside a collection are not supported! Violated by:<br/>"); factModelTuple.getMultipleNestedObjectError().forEach(error -> builder.append("<b>"+ error + "</b><br/>")); } if (showError) { factModelTuple.getTopLevelCollectionError().clear(); factModelTuple.getMultipleNestedCollectionError().clear(); factModelTuple.getMultipleNestedObjectError().clear(); eventBus.fireEvent(new UnsupportedDMNEvent(builder.toString())); } }
Source:
private CassandraNodeHealthCheckDetails performHealthCheck(@NotNull final CassandraNodeHealthCheckTask healthCheckTask) { CassandraNodeHealthCheckDetails.Builder builder = CassandraNodeHealthCheckDetails.newBuilder(); try (JmxConnect jmx = new JmxConnect(getHostAddress(), (int) healthCheckTask.getJmxPort() & 0xffff)) { CassandraNodeInfo info = buildInfo(jmx); builder.setHealthy(true) .setInfo(info); LOGGER.info("Healthcheck succeeded: operationMode:{} joined:{} gossip:{} native:{} rpc:{} uptime:{}s endpoint:{}, dc:{}, rack:{}, hostId:{}, version:{}", info.getOperationMode(), info.getJoined(), info.getGossipRunning(), info.getNativeTransportRunning(), info.getRpcServerRunning(), info.getUptimeSeconds(), info.getEndpoint(), info.getDataCenter(), info.getRack(), info.getHostId(), info.getVersion()); } catch (Exception e) { LOGGER.warn("Healthcheck failed.", e); builder.setMsg(e.toString()); } return builder.build(); }

Target:
private CassandraNodeHealthCheckDetails performHealthCheck(@NotNull final CassandraNodeHealthCheckTask healthCheckTask) { CassandraNodeHealthCheckDetails.Builder builder = CassandraNodeHealthCheckDetails.newBuilder(); try (JmxConnect jmx = new JmxConnect(getHostAddress(), (int) healthCheckTask.getJmxPort() & 0xffff)) { CassandraNodeInfo info = buildInfo(jmx); builder.setHealthy(true); LOGGER.info("Healthcheck succeeded: operationMode:{} joined:{} gossip:{} native:{} rpc:{} uptime:{}s endpoint:{}, dc:{}, rack:{}, hostId:{}, version:{}", info.getOperationMode(), info.getJoined(), info.getGossipRunning(), info.getNativeTransportRunning(), info.getRpcServerRunning(), info.getUptimeMillis() / 1000, info.getEndpoint(), info.getDataCenter(), info.getRack(), info.getHostId(), info.getVersion()); } catch (Exception e) { LOGGER.warn("Healthcheck failed.", e); builder.setHealthy(true) .setMsg(e.toString()); } return builder.build(); }
Source:
NestedClassSelector(List<String> enclosingClassNames, String nestedClassName) { this.enclosingClassSelectors = enclosingClassNames.stream().map(ClassSelector::new).collect( Collectors.toList()); this.nestedClassSelector = new ClassSelector(nestedClassName); }

Target:
NestedClassSelector(List<String> enclosingClassNames, String nestedClassName) { this.enclosingClassSelectors = enclosingClassNames.stream().map(ClassSelector::new).collect(toList()); this.nestedClassSelector = new ClassSelector(nestedClassName); }
Source:
public RequestSendFailedException(final Throwable cause) { super(throwableToException(cause)); }

Target:
public RequestSendFailedException(final Throwable cause) { super(); initCause(cause); }
Source:
void checkInConnection(String connectionId) { availableConnections.add(connectionId); availableCount++; }

Target:
void checkInConnection(String connectionId) { availableConnections.add(connectionId); }
Source:
public String toString() { readLock.lock(); try { return "FileListCacheValue{fileNames=" + getFileNames() + "}"; } finally { readLock.unlock(); } }

Target:
public String toString() { return "FileListCacheValue{fileNames=" + getFileNames() + "}"; }
Source:
public Market getM() { return currentMarket; }

Target:
private Market getM() { return currentMarket; }
Source:
private boolean canReuseWorkspace(FilePath repo, boolean jobShouldUseSharing, AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { if (!new FilePath(repo, ".hg/hgrc").exists()) { return false; } boolean jobUsesSharing = new FilePath(repo, ".hg/sharedpath").exists(); if (jobShouldUseSharing != jobUsesSharing) { return false; } EnvVars env = build.getEnvironment(listener); HgExe hg = new HgExe(this,launcher,build,listener); String upstream = hg.config(repo, "paths.default"); if (upstream == null) { return false; } if (HgExe.pathEquals(getSource( env ), upstream)) { return true; } listener.error( "Workspace reports paths.default as " + upstream + "\nwhich looks different than " + getSource( env ) + "\nso falling back to fresh clone rather than incremental update"); return false; }

Target:
private boolean canReuseWorkspace(FilePath repo, boolean jobShouldUseSharing, AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { if (!new FilePath(repo, ".hg/hgrc").exists()) { return false; } boolean jobUsesSharing = new FilePath(repo, ".hg/sharedpath").exists(); if (jobShouldUseSharing != jobUsesSharing) { return false; } EnvVars env = build.getEnvironment(listener); HgExe hg = new HgExe(this,launcher,build,listener); String upstream = hg.config(repo, "paths.default"); if (upstream == null) { return false; } String source = getSource( env ); if (HgExe.pathEquals(source, upstream)) { return true; } listener.error( "Workspace reports paths.default as " + upstream + "\nwhich looks different than " + source + "\nso falling back to fresh clone rather than incremental update"); return false; }
Source:
public void onNotification(Request coapRequest, Response coapResponse) { LOG.trace("notification received for request {}: {}", coapRequest, coapResponse); if (listeners.isEmpty()) return; String regid = coapRequest.getUserContext().get(CTX_REGID); Observation observation = registrationStore.getObservation(regid, coapResponse.getToken()); if (observation == null) { LOG.error("Unexpected error: Unable to find observation with token for registration {}", observation, coapResponse.getToken()); return; } Registration registration = registrationStore.getRegistration(observation.getRegistrationId()); if (registration == null) { LOG.error("Unexpected error: There is no registration with id for this observation {}", observation.getRegistrationId(), observation); return; } clientStatusTracker.setClientOnline(registration); try { LwM2mModel model = modelProvider.getObjectModel(registration); ObserveResponse response = createObserveResponse(observation, model, coapResponse); for (ObservationListener listener : listeners) { listener.onResponse(observation, registration, response); } } catch (InvalidResponseException e) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Invalid notification for observation [%s]", observation), e); } for (ObservationListener listener : listeners) { listener.onError(observation, registration, e); } } catch (RuntimeException e) { if (LOG.isErrorEnabled()) { LOG.error(String.format("Unable to handle notification for observation [%s]", observation), e); } for (ObservationListener listener : listeners) { listener.onError(observation, registration, e); } } }

Target:
public void onNotification(Request coapRequest, Response coapResponse) { LOG.trace("notification received for request {}: {}", coapRequest, coapResponse); if (listeners.isEmpty()) return; String regid = coapRequest.getUserContext().get(CTX_REGID); Observation observation = registrationStore.getObservation(regid, coapResponse.getToken()); if (observation == null) { LOG.error("Unexpected error: Unable to find observation with token for registration {}", observation, coapResponse.getToken()); return; } Registration registration = registrationStore.getRegistration(observation.getRegistrationId()); if (registration == null) { LOG.error("Unexpected error: There is no registration with id for this observation {}", observation.getRegistrationId(), observation); return; } try { LwM2mModel model = modelProvider.getObjectModel(registration); ObserveResponse response = createObserveResponse(observation, model, coapResponse); for (ObservationListener listener : listeners) { listener.onResponse(observation, registration, response); } } catch (InvalidResponseException e) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Invalid notification for observation [%s]", observation), e); } for (ObservationListener listener : listeners) { listener.onError(observation, registration, e); } } catch (RuntimeException e) { if (LOG.isErrorEnabled()) { LOG.error(String.format("Unable to handle notification for observation [%s]", observation), e); } for (ObservationListener listener : listeners) { listener.onError(observation, registration, e); } } }
Source:
public AbstractSideTabWithDetailsView( SearchableTableModelProvider<T, M> modelProvider, ApplicationResources applicationResources, final ClientStorage clientStorage) { this.modelProvider = modelProvider; this.table = createActionTable(); this.table.showRefreshButton(); this.clientStorage = clientStorage; applicationResources.sideTabWithDetailsViewStyle().ensureInjected(); subTabPanelContainer.setStyleName(applicationResources.sideTabWithDetailsViewStyle().detailsContentPanel()); splitPanel = new ExtendedViewSplitLayoutPanel(applicationResources.extendedViewSplitterSnap()) { @Override public void onResize() { super.onResize(); if (subTabPanelVisible) { clientStorage.setLocalItem(SubTabHelper.SUB_TAB_HEIGHT_KEY, String.valueOf(subTabPanelContainer.getOffsetHeight())); } } }; initWidget(splitPanel); initSplitPanel(); }

Target:
public AbstractSideTabWithDetailsView( SearchableTableModelProvider<T, M> modelProvider, ApplicationResources applicationResources, final ClientStorage clientStorage) { this.modelProvider = modelProvider; this.table = createActionTable(); this.table.showRefreshButton(); this.clientStorage = clientStorage; applicationResources.sideTabWithDetailsViewStyle().ensureInjected(); subTabPanelContainer.setStyleName(applicationResources.sideTabWithDetailsViewStyle().detailsContentPanel()); splitPanel = new ExtendedViewSplitLayoutPanel(applicationResources.extendedViewSplitterSnap()) { @Override public void onResize() { super.onResize(); if (subTabPanelVisible) { SubTabHelper.storeSubTabHeight(clientStorage, subTabPanelContainer); } } }; initWidget(splitPanel); initSplitPanel(); }
Source:
protected void showDismissDialog() { new AlertDialog.Builder(getContext()) .setMessage(R.string.username_changer_dismiss_message) .setPositiveButton(R.string.username_changer_dismiss_button_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialogController.dismiss(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); }

Target:
protected void showDismissDialog() { mIsShowingDismissDialog = true; new AlertDialog.Builder(getContext()) .setMessage(R.string.username_changer_dismiss_message) .setPositiveButton(R.string.username_changer_dismiss_button_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialogController.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mIsShowingDismissDialog = false; } }) .show(); }
Source:
public boolean applySchemaPatch(QuerySchemaPatch patch) { synchronized (schemaMux) { boolean res = schema.applyPatch(patch); Optional<SchemaAbstractOperation> op = patch.getPatchOperations().stream() .filter(o -> o instanceof SchemaAddQueryEntityOperation).findFirst(); if (res && op.isPresent()) cacheCfg = GridCacheUtils.patchCacheConfiguration(cacheCfg, (SchemaAddQueryEntityOperation)op.get()); return res; } }

Target:
public boolean applySchemaPatch(QuerySchemaPatch patch) { synchronized (schemaMux) { boolean res = schema.applyPatch(patch); if (res) { for (SchemaAbstractOperation op: patch.getPatchOperations()) { if (op instanceof SchemaAddQueryEntityOperation) cacheCfg = GridCacheUtils.patchCacheConfiguration(cacheCfg, (SchemaAddQueryEntityOperation)op); } } return res; } }
Source:
public static String formatVCFDouble(final double d) { final int numSignificant = 5; final double lowerLimit = Math.pow(10, -numSignificant); if (d == 0.0) { return "0.0"; } else if (d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY || Double.isNaN(d)) { return String.format("%f", d); } else if (d >= 0.1) { final DecimalFormat df = new DecimalFormat("0.0" + String.join("", Collections.nCopies(numSignificant-1, "#"))); return df.format(round(d, numSignificant)); } else { int denominator = 1; int denominatorCount = 0; while (d * denominator < 1.0) { denominator *= 10; denominatorCount++; } final double roundedValue = round(d * denominator, numSignificant); final double finalValue = roundedValue / denominator; if (roundedValue == (double)(int)roundedValue && finalValue >= lowerLimit) { return String.format("%." + denominatorCount + "f", finalValue); } else { return String.format("%." + numSignificant + "e", finalValue); } } }

Target:
public static String formatVCFDouble(final double d) { final int numSignificant = 4; final double lowerLimit = Math.pow(10, -numSignificant); if (d == 0.0) { return "0.0"; } else if (d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY || Double.isNaN(d)) { return String.format("%f", d); } else if (d >= 0.1) { final DecimalFormat df = new DecimalFormat("0.0" + String.join("", Collections.nCopies(numSignificant - 1, "#"))); return df.format(round(d, numSignificant)); } else { final int denominatorCount = -(int) Math.floor(Math.log10(d)); final double denominator = Math.pow(10, -denominatorCount); final double roundedValue = round(d / denominator, numSignificant); final double finalValue = roundedValue * denominator; final String string1 = String.format("%." + (numSignificant+denominatorCount) + "f", finalValue); final String string2 = String.format("%." + numSignificant + "e", finalValue); return string1.length() <= string2.length() ? string1 : string2; } }
Source:
public static byte[] encodeBase64URLSafe(byte[] binaryData) { if(binaryData == null){ return null; } return com.google.common.io.BaseEncoding.base64Url().omitPadding().encode(binaryData).getBytes(); }

Target:
public static byte[] encodeBase64URLSafe(byte[] binaryData) { if (binaryData == null) { return null; } return BaseEncoding.base64Url().omitPadding().encode(binaryData).getBytes(); }
Source:
public void executeUpgrade() throws DotDataException, DotRuntimeException { Logger.debug(this, "Upgrading Front-end and Back-End roles definition."); try { DbConnectionFactory.getConnection().setAutoCommit(true); } catch (SQLException e) { throw new DotDataException(e.getMessage(), e); } final DotConnect dotConnect = new DotConnect(); dotConnect.setSQL(FRONTEND_ROLE_SANITY_CHECK); final int count = dotConnect.getInt("c"); if(count > 0){ throw new DotDataException( String.format("The front-end Role defined as `LoggedIn Site User` has %d layouts associated. This must be corrected manually before this upgrade task can run.", count) ); } if (DbConnectionFactory.isPostgres()) { dotConnect.setSQL(POSTGRES_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(POSTGRES_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isOracle()) { dotConnect.setSQL(ORACLE_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(ORACLE_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isMsSql()) { dotConnect.setSQL(MSSQL_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(MSSQL_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isMySql()) { dotConnect.setSQL(MYSQL_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(MYSQL_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } }

Target:
public void executeUpgrade() throws DotDataException, DotRuntimeException { Logger.debug(this, "Upgrading Front-end and Back-End roles definition."); try { DbConnectionFactory.getConnection().setAutoCommit(true); } catch (SQLException e) { throw new DotDataException(e.getMessage(), e); } final DotConnect dotConnect = new DotConnect(); dotConnect.setSQL(FRONTEND_ROLE_SANITY_CHECK); final int count = dotConnect.getInt("c"); if(count > 0){ throw new DotDataException( String.format("The front-end Role defined as `LoggedIn Site User` has %d layouts associated. This must be corrected manually before this upgrade task can run.", count) ); } if (DbConnectionFactory.isPostgres()) { dotConnect.setSQL(POSTGRES_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(POSTGRES_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isOracle()) { dotConnect.setSQL(ORACLE_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(ORACLE_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isMsSql()) { dotConnect.setSQL(MSSQL_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(MSSQL_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } if (DbConnectionFactory.isMySql()) { dotConnect.setSQL(MYSQL_RENAME_ROLE_KEY_FRONT_END_USER); dotConnect.loadResult(); dotConnect.setSQL(MYSQL_RENAME_ROLE_KEY_BACK_END_USER); dotConnect.loadResult(); } final List<Map> users = loadUsersWithLayoutButNotBackendRole(dotConnect); addBackendRole(users, dotConnect); }
Source:
public WakeupResponse wakeup(@ApiParam("Internal id for workflow instance") @PathParam("id") int id, @Valid @ApiParam("Expected states") WakeupRequest req) { WakeupResponse response = new WakeupResponse(); List<String> expectedStates = req.expectedStates != null ? req.expectedStates : emptyList(); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return response; }

Target:
public WakeupResponse wakeup(@ApiParam("Internal id for workflow instance") @PathParam("id") int id, @Valid @ApiParam("Expected states") WakeupRequest req) { WakeupResponse response = new WakeupResponse(); List<String> expectedStates = ofNullable(req.expectedStates).orElseGet(Collections::emptyList); response.wakeupSuccess = workflowInstances.wakeupWorkflowInstance(id, expectedStates); return response; }
Source:
private String resolveProjectName(final Path resourcePath) { KieModule kieModule = moduleService.resolveModule(resourcePath); if (kieModule == null) { throw new IllegalStateException("Failed to resolve KieProject (" + kieModule + ")."); } return kieModule.getModuleName(); }

Target:
private String resolveProjectName(final Path resourcePath) { KieModule kieModule = moduleService.resolveModule(resourcePath); if (kieModule == null) { throw new IllegalStateException("Failed to resolve KieModule (" + kieModule + ")."); } return kieModule.getModuleName(); }
Source:
public Status insert(String table, String key, HashMap<String, ByteIterator> values) { try { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", key); for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { doc.addField(entry.getKey(), entry.getValue()); } if (cloudMode) { cloudClient.add(table, doc); cloudClient.commit(table); } else { httpClient.add(table, doc); httpClient.commit(table); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }

Target:
public Status insert(String table, String key, HashMap<String, ByteIterator> values) { try { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", key); for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { doc.addField(entry.getKey(), entry.getValue()); } UpdateResponse response; if (batchMode) { response = client.add(table, doc, commitTime); } else { response = client.add(table, doc); client.commit(table); } return checkStatus(response.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }
Source:
public void testImportSimpleData() throws Exception { System.out.println("testImportSimpleData"); List<String> expectedMessageList = new ArrayList<>(); Properties props = new Properties(); props.put("metadata.broker.list", KAFKA_HOST_PORT); props.put("serializer.class", "kafka.serializer.StringEncoder"); ProducerConfig config = new ProducerConfig(props); Producer<String, String> producer = new Producer<String, String>(config); for (int i = 0; i < 10; i++) { String message = "test-message-" + i + ", " + i; System.out.println("Producing message: " + message); expectedMessageList.add(message); KeyedMessage<String, String> data = new KeyedMessage<String, String>(TEST_TOPIC, message); producer.send(data); } Client client = getClientToHostId(0); Stopwatch sw = Stopwatch.createStarted(); boolean findImportedData = false; while (sw.elapsed(TimeUnit.SECONDS) < (30)) { VoltTable vt = client.callProcedure("@AdHoc", "Select * from tmap order by val;").getResults()[0]; System.out.println("Elapsed " + sw.elapsed(TimeUnit.SECONDS) + " seconds, Test table contents: " + vt); if (10 == vt.getRowCount()) { findImportedData = true; break; } Thread.sleep(1000); } assertTrue("VoltDB Kafka importer does not import enough data", findImportedData); producer.close(); }

Target:
public void testImportSimpleData() throws Exception { System.out.println("testImportSimpleData"); List<String> expectedMessageList = new ArrayList<>(); Properties props = new Properties(); props.put("metadata.broker.list", KAFKA_HOST_PORT); props.put("serializer.class", "kafka.serializer.StringEncoder"); ProducerConfig config = new ProducerConfig(props); Producer<String, String> producer = new Producer<String, String>(config); for (int i = 0; i < 10; i++) { String message = "test-message-" + i + ", " + i; System.out.println("Producing message: " + message); expectedMessageList.add(message); KeyedMessage<String, String> data = new KeyedMessage<String, String>(TEST_TOPIC, message); producer.send(data); } Client client = getClientToHostId(0); Stopwatch sw = Stopwatch.createStarted(); boolean foundImportData = false; while (sw.elapsed(TimeUnit.SECONDS) < (30)) { VoltTable vt = client.callProcedure("@AdHoc", "Select * from tmap order by val;").getResults()[0]; System.out.println("Elapsed " + sw.elapsed(TimeUnit.SECONDS) + " seconds, Test table contents: " + vt); if (10 == vt.getRowCount()) { foundImportData = true; break; } Thread.sleep(1000); } assertTrue("VoltDB Kafka importer did not import enough data", foundImportData); producer.close(); }
Source:
public Object apply(AccountResource.Email rsrc, Input input) throws AuthException, ResourceNotFoundException, OrmException { if (!(self.get() instanceof IdentifiedUser)) { throw new AuthException("Authentication required"); } IdentifiedUser s = (IdentifiedUser) self.get(); if (s.getAccountId().get() != rsrc.getUser().getAccountId().get() && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set preferred email address"); } Account a = dbProvider.get().accounts().get(rsrc.getUser().getAccountId()); if (a == null) { throw new ResourceNotFoundException("No such account: " + rsrc.getUser().getAccountId()); } if (rsrc.getEmail().equals(a.getPreferredEmail())) { return Response.ok(""); } a.setPreferredEmail(rsrc.getEmail()); dbProvider.get().accounts().update(Collections.singleton(a)); byIdCache.evict(a.getId()); return Response.created(""); }

Target:
public Object apply(AccountResource.Email rsrc, Input input) throws AuthException, ResourceNotFoundException, OrmException { IdentifiedUser s = (IdentifiedUser) self.get(); if (s.getAccountId().get() != rsrc.getUser().getAccountId().get() && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to set preferred email address"); } Account a = dbProvider.get().accounts().get(rsrc.getUser().getAccountId()); if (a == null) { throw new ResourceNotFoundException("No such account: " + rsrc.getUser().getAccountId()); } if (rsrc.getEmail().equals(a.getPreferredEmail())) { return Response.ok(""); } a.setPreferredEmail(rsrc.getEmail()); dbProvider.get().accounts().update(Collections.singleton(a)); byIdCache.evict(a.getId()); return Response.created(""); }
Source:
public void testNextElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); Element element1 = doc.getElementById("c"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNull(elementSiblings1); }

Target:
public void testNextElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); assertEquals("b", elementSiblings.get(0).id()); assertEquals("c", elementSiblings.get(1).id()); Element element1 = doc.getElementById("b"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNotNull(elementSiblings1); assertEquals(1, elementSiblings1.size()); assertEquals("c", elementSiblings1.get(0).id()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.nextElementSiblings(); assertEquals(0, elementSiblings2.size()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.nextElementSiblings(); assertNotNull(elementSiblings3); assertEquals(1, elementSiblings3.size()); assertEquals("div", elementSiblings3.get(0).id()); Element div = doc.getElementById("div"); List<Element> elementSiblings4 = div.nextElementSiblings(); try { Element elementSibling = elementSiblings4.get(0); fail("This element should has no next siblings"); } catch (IndexOutOfBoundsException e) { } }
Source:
public void executePatchRequest() throws Exception { final String rname = RandomStringUtils.randomAlphanumeric(5); final Release release = releases().create(rname); final String name = "name"; final String nvalue = "v.1.1.1"; final String body = "body"; final String bvalue = "Description of the release"; try { release.patch(Json.createObjectBuilder().add(name, nvalue) .add(body, bvalue).build() ); MatcherAssert.assertThat( release.json().getString(name), Matchers.startsWith(nvalue) ); MatcherAssert.assertThat( release.json().getString(body), Matchers.startsWith(bvalue) ); } finally { release.delete(); } }

Target:
public void executePatchRequest() throws Exception { final String rname = RandomStringUtils.randomAlphanumeric(5); final Release release = releases().create(rname); final String name = "name"; final String nvalue = RandomStringUtils.randomAlphanumeric(5); final String body = "body"; final String bvalue = "Description of the release"; try { release.patch(Json.createObjectBuilder().add(name, nvalue) .add(body, bvalue).build() ); MatcherAssert.assertThat( release.json().getString(name), Matchers.startsWith(nvalue) ); MatcherAssert.assertThat( release.json().getString(body), Matchers.startsWith(bvalue) ); } finally { release.delete(); } }
Source:
private void dateFromDefaultInit() { final Calendar calendarFrom = Calendar.getInstance(); calendarFrom.add(Calendar.WEEK_OF_MONTH, -1); dateFrom = calendarFrom.getTime(); dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); }

Target:
private void dateFromDefaultInit() { Calendar calendarFrom = Calendar.getInstance(); calendarFrom.add(Calendar.WEEK_OF_MONTH, -1); dateFrom = calendarFrom.getTime(); dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); }
Source:
protected char[] getBufferContent() throws ModelException { IFile file = (IFile) this.getResource(); if (file == null || !file.exists() || !file.getLocation().toFile().exists()) { throw newNotPresentException(); } return Util.getResourceContentsAsCharArray(file); }

Target:
protected char[] getBufferContent() throws ModelException { IFile file = (IFile) this.getResource(); if (file == null || !file.exists()) { throw newNotPresentException(); } IPath location = file.getLocation(); if (location != null && !location.toFile().exists()) { throw newNotPresentException(); } return Util.getResourceContentsAsCharArray(file); }
Source:
public static List<Throwable> getThrowableList(Throwable throwable) { final List<Throwable> list = new ArrayList<Throwable>(); while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = getCause(throwable); } return list; }

Target:
public static List<Throwable> getThrowableList(Throwable throwable) { final List<Throwable> list = new ArrayList<>(); while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = getCause(throwable); } return list; }
Source:
public void multiIndex_incompatibleAnalyzer_skipAnalysis() { StubMappingSearchScope scope = indexManager.createSearchScope( incompatibleAnalyzerIndexManager ); String absoluteFieldPath = indexMapping.analyzedStringField.relativeFieldName; IndexSearchQuery<DocumentReference> query = scope.query().asReference() .predicate( f -> f.match().onField( absoluteFieldPath ).matching( "fox" ) .skipAnalysis() ) .toQuery(); assertThat( query ).assertThat( query ).hasDocRefHitsAnyOrder( b -> { b.doc( INDEX_NAME, DOCUMENT_1 ); b.doc( INCOMPATIBLE_ANALYZER_INDEX_NAME, INCOMPATIBLE_ANALYZER_INDEX_DOCUMENT_1 ); } ); }

Target:
public void multiIndex_incompatibleAnalyzer_skipAnalysis() { StubMappingSearchScope scope = indexManager.createSearchScope( incompatibleAnalyzerIndexManager ); String absoluteFieldPath = indexMapping.analyzedStringField.relativeFieldName; IndexSearchQuery<DocumentReference> query = scope.query().asReference() .predicate( f -> f.match().onField( absoluteFieldPath ).matching( "fox" ) .skipAnalysis() ) .toQuery(); assertThat( query ).hasDocRefHitsAnyOrder( b -> { b.doc( INDEX_NAME, DOCUMENT_1 ); b.doc( INCOMPATIBLE_ANALYZER_INDEX_NAME, INCOMPATIBLE_ANALYZER_INDEX_DOCUMENT_1 ); } ); }
Source:
public synchronized long skip(long n) throws IOException { if (n <= 0) return 0; long pos = remoteOffset; long seek = Math.min(pos + n, length()); remoteOffset = seek; return seek - pos; }

Target:
public synchronized long skip(long n) throws IOException { if (n <= 0) return 0; long pos = remoteOffset; long seek = Math.min(pos + n, getMaxRead(remoteOffset, n)); remoteOffset = seek; return seek - pos; }
Source:
public void showDialog(final int id, final int sideForDialog, final int positionForDialog) throws IllegalStateException { if (!this.isVisible()) { return; } removeDialog(getFragmentManager()); if (id == TradeDialogFragment.DIALOG_SORT) { SortOrderDialogFragment newFragment = new SortOrderDialogFragment(); Bundle args = new Bundle(); args.putString(SortOrderDialogFragment.SAVED_SORT_ORDER, getFamiliarActivity().mPreferenceAdapter.getTradeSortOrder()); args.putBoolean(SortOrderDialogFragment.SAVED_DONT_SORT, getFamiliarActivity().mPreferenceAdapter.getTradeDontSort()); newFragment.setArguments(args); newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG); } else { TradeDialogFragment newFragment = new TradeDialogFragment(); Bundle arguments = new Bundle(); arguments.putInt(FamiliarDialogFragment.ID_KEY, id); arguments.putInt(TradeDialogFragment.ID_SIDE, sideForDialog); arguments.putInt(TradeDialogFragment.ID_POSITION, positionForDialog); newFragment.setArguments(arguments); newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG); } }

Target:
public void showDialog(final int id, final int sideForDialog, final int positionForDialog) throws IllegalStateException { if (!this.isVisible()) { return; } removeDialog(getFragmentManager()); if (id == TradeDialogFragment.DIALOG_SORT) { SortOrderDialogFragment newFragment = new SortOrderDialogFragment(); Bundle args = new Bundle(); args.putString(SortOrderDialogFragment.SAVED_SORT_ORDER, getFamiliarActivity().mPreferenceAdapter.getTradeSortOrder()); newFragment.setArguments(args); newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG); } else { TradeDialogFragment newFragment = new TradeDialogFragment(); Bundle arguments = new Bundle(); arguments.putInt(FamiliarDialogFragment.ID_KEY, id); arguments.putInt(TradeDialogFragment.ID_SIDE, sideForDialog); arguments.putInt(TradeDialogFragment.ID_POSITION, positionForDialog); newFragment.setArguments(arguments); newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG); } }
Source:
private void waitBetweenPolls() { while (timestampOfEndOfPreviousInvocation != null && System.currentTimeMillis() - timestampOfEndOfPreviousInvocation < POLLING_BREAK) { try { Thread.sleep(POLLING_BREAK); } catch (InterruptedException e) { } } }

Target:
private void waitBetweenPolls() { while (timestampOfEndOfPreviousInvocation != null && currentTimestamp() - timestampOfEndOfPreviousInvocation < POLLING_BREAK) { try { Thread.sleep(POLLING_BREAK); } catch (InterruptedException e) { } } }
Source:
FastAnnotatedTypeLoader(BeanManagerImpl manager, ClassTransformer transformer, ClassFileServices classFileServices, ContainerLifecycleEvents events, FastProcessAnnotatedTypeResolver resolver) { super(manager, transformer, events); this.fallback = new AnnotatedTypeLoader(manager, transformer, events); this.classFileServices = classFileServices; this.resolver = resolver; this.checkTypeModifiers = initCheckTypeModifiers(); if (!checkTypeModifiers) { BootstrapLogger.LOG.usingOldJandexVersion(); } }

Target:
FastAnnotatedTypeLoader(BeanManagerImpl manager, ClassTransformer transformer, ClassFileServices classFileServices, ContainerLifecycleEvents events, FastProcessAnnotatedTypeResolver resolver) { super(manager, transformer, events); this.fallback = new AnnotatedTypeLoader(manager, transformer, events); this.classFileServices = classFileServices; this.resolver = resolver; this.checkTypeModifiers = initCheckTypeModifiers(); }
Source:
public OptimizerAssert(Metadata metadata, StatsCalculator statsCalculator, Session session, PlanOptimizer optimizer, TransactionManager transactionManager, AccessControl accessControl) { this.metadata = metadata; this.statsCalculator = new TestingStatsCalculator(statsCalculator); this.session = session; this.optimizer = optimizer; this.transactionManager = transactionManager; this.accessControl = accessControl; }

Target:
public OptimizerAssert(Metadata metadata, StatsCalculator statsCalculator, Session session, PlanOptimizer optimizer, TransactionManager transactionManager, AccessControl accessControl) { this.metadata = requireNonNull(metadata, "metadata is null"); this.statsCalculator = new TestingStatsCalculator(requireNonNull(statsCalculator, "statsCalculator is null")); this.session = requireNonNull(session, "session is null"); this.optimizer = requireNonNull(optimizer, "optimizer is null"); this.transactionManager = requireNonNull(transactionManager, "transactionManager is null"); this.accessControl = requireNonNull(accessControl, "access control is null"); }
Source:
public void setValue(String value, boolean fireEvents) { String oldValue = current; current = value; if (current.equals("0")) { view.setLocalTimeZone(); } else { view.setValue(current); } if (fireEvents) { ValueChangeEvent.fireIfNotEqual(this, oldValue, value); } }

Target:
public void setValue(String value, boolean fireEvents) { String oldValue = current; current = value; view.setValue(current); if (fireEvents) { ValueChangeEvent.fireIfNotEqual(this, oldValue, value); } }
Source:
public boolean equals(Object other) { if (other == this) { return true; } if(!other.getClass().equals(Gff3BaseData.class)) { return false; } final Gff3BaseData otherBaseData = (Gff3BaseData) other; boolean ret = otherBaseData.getContig().equals(getContig()) && otherBaseData.getSource().equals(getSource()) && otherBaseData.getType().equals(getType()) && otherBaseData.getStart() == getStart() && otherBaseData.getEnd() == getEnd() && otherBaseData.getScore().equals(score) && otherBaseData.getPhase() == getPhase() && otherBaseData.getStrand().equals(getStrand()) && otherBaseData.getAttributes().equals(getAttributes()); if (getId() == null) { ret = ret && otherBaseData.getId() == null; } else { ret = ret && otherBaseData.getId() != null && otherBaseData.getId().equals(getId()); } if (getName() == null) { ret = ret && otherBaseData.getName() == null; } else { ret = ret && otherBaseData.getName() != null && otherBaseData.getName().equals(getName()); } if (getAlias() == null) { ret = ret && otherBaseData.getAlias() == null; } else { ret = ret && otherBaseData.getAlias() != null && otherBaseData.getAlias().equals(getAlias()); } return ret; }

Target:
public boolean equals(Object other) { if (other == this) { return true; } if(!other.getClass().equals(Gff3BaseData.class)) { return false; } final Gff3BaseData otherBaseData = (Gff3BaseData) other; boolean ret = otherBaseData.getContig().equals(getContig()) && otherBaseData.getSource().equals(getSource()) && otherBaseData.getType().equals(getType()) && otherBaseData.getStart() == getStart() && otherBaseData.getEnd() == getEnd() && ((Double)otherBaseData.getScore()).equals(score) && otherBaseData.getPhase() == getPhase() && otherBaseData.getStrand().equals(getStrand()) && otherBaseData.getAttributes().equals(getAttributes()); if (getId() == null) { ret = ret && otherBaseData.getId() == null; } else { ret = ret && otherBaseData.getId() != null && otherBaseData.getId().equals(getId()); } if (getName() == null) { ret = ret && otherBaseData.getName() == null; } else { ret = ret && otherBaseData.getName() != null && otherBaseData.getName().equals(getName()); } if (getAlias() == null) { ret = ret && otherBaseData.getAlias() == null; } else { ret = ret && otherBaseData.getAlias() != null && otherBaseData.getAlias().equals(getAlias()); } return ret; }
Source:
private TransactionSynchronizationRegistry locateTransactionSynchronizationRegistry() { if (transactionSynchronizationRegistry == null) { synchronized (WildFlyCustomJtaPlatform.class) { if (transactionSynchronizationRegistry == null) { transactionSynchronizationRegistry = (TransactionSynchronizationRegistry) jndiService().locate(TSR_NAME); } } } return transactionSynchronizationRegistry; }

Target:
private TransactionSynchronizationRegistry locateTransactionSynchronizationRegistry() { TransactionSynchronizationRegistry curTsr = transactionSynchronizationRegistry; return curTsr != null ? curTsr : (TransactionSynchronizationRegistry) jndiService().locate(TSR_NAME); }
Source:
public Collection<AsyncQuery> deleteAsyncQueryAndResultCollection(String filterExpression) { log.debug("deleteAsyncQueryAndResultCollection"); EntityDictionary dictionary = elide.getElideSettings().getDictionary(); RSQLFilterDialect filterParser = new RSQLFilterDialect(dictionary); Collection<AsyncQuery> asyncQueryList = (Collection<AsyncQuery>) executeInTransaction(dataStore, (tx, scope) -> { try { FilterExpression filter = filterParser.parseFilterExpression(filterExpression, AsyncQuery.class, false); EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filter) .build(); Iterable<Object> loaded = tx.loadObjects(asyncQueryCollection, scope); Iterator<Object> itr = loaded.iterator(); while(itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); if(query != null) { tx.delete(query, scope); } } return null; } catch (ParseException e) { log.error("Exception: {}", e); } return null; }); return asyncQueryList; }

Target:
public Collection<AsyncQuery> deleteAsyncQueryAndResultCollection(String filterExpression) { log.debug("deleteAsyncQueryAndResultCollection"); EntityDictionary dictionary = elide.getElideSettings().getDictionary(); RSQLFilterDialect filterParser = new RSQLFilterDialect(dictionary); try { FilterExpression filter = filterParser.parseFilterExpression(filterExpression, AsyncQuery.class, false); executeInTransaction(dataStore, (tx, scope) -> { EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filter) .build(); Iterable<Object> loaded = tx.loadObjects(asyncQueryCollection, scope); Iterator<Object> itr = loaded.iterator(); while (itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); if (query != null) { tx.delete(query, scope); } } return null; }); } catch (ParseException e) { log.error("Exception: {}", e); } return null; }