auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Override public RelNode enforce( final RelNode input, final RelTraitSet required) { RelNode rel = input; if (input.getConvention() != INSTANCE) { rel = ConventionTraitDef.INSTANCE.convert( input.getCluster().getPlanner(), input, INSTANCE, true); } RelCollation collation = required.getTrait(RelCollationTraitDef.INSTANCE); if (collation != null && !collation.getFieldCollations().isEmpty()) { rel = EnumerableSort.create(rel, collation, null, null); } return rel; }

Target:
@Override public RelNode enforce( final RelNode input, final RelTraitSet required) { RelNode rel = input; if (input.getConvention() != INSTANCE) { rel = ConventionTraitDef.INSTANCE.convert( input.getCluster().getPlanner(), input, INSTANCE, true); } RelCollation collation = required.getTrait(RelCollationTraitDef.INSTANCE); if (collation != null) { assert !collation.getFieldCollations().isEmpty(); rel = EnumerableSort.create(rel, collation, null, null); } return rel; }
Source:
public Response components() throws IOException { JsonArray array = new JsonArray(); for (Component component : Component.getComponents()) { JsonObject obj = new JsonObject(); ToolkitComponent annotation = component.getClass().getAnnotation(ToolkitComponent.class); obj.addProperty("key", annotation.key()); obj.addProperty("name", annotation.name()); obj.addProperty("description", annotation.description()); JsonArray array2 = new JsonArray(); for (String file : annotation.editorFiles()) { JsonPrimitive element = new JsonPrimitive(file); array2.add(element); } obj.add("files", array2); array.add(obj); } return Response.ok(toJson(array)).build(); }

Target:
public Response components() throws IOException { if (cachedResponse == null) { cachedResponse = new JsonArray(); for (Component component : Component.getComponents()) { JsonObject obj = new JsonObject(); ToolkitComponent annotation = component.getClass() .getAnnotation(ToolkitComponent.class); obj.addProperty("key", annotation.key()); obj.addProperty("name", annotation.name()); obj.addProperty("description", annotation.description()); JsonArray array2 = new JsonArray(); for (String file : annotation.editorFiles()) { JsonPrimitive element = new JsonPrimitive(file); array2.add(element); } obj.add("files", array2); cachedResponse.add(obj); } } return Response.ok(toJson(cachedResponse)).build(); }
Source:
public static Money of(double amount) { return new Money(org.joda.money.BigMoney.of(CurrencyManager.getInstance().getDefaultCurrency(), amount)); }

Target:
public static Money of(double amount) { return Money.of(amount, CurrencyManager.getInstance().getDefaultCurrency()); }
Source:
private HiveMetaStoreClient getHive() throws IOException { if (mHive != null) { return mHive; } mHive = newHiveClient(); return mHive; }

Target:
private HiveMetaStoreClient getHive() throws IOException { if (mHive != null) { return mHive; } newHiveClient(); return mHive; }
Source:
public void bucketTypeUpdate(String bucketTypeName, String bucketTypeProperties) { ScriptHelper bucketTypeStatusScript = newScript("bucket-type_update") .body.append(sudo(format("%s bucket-type update %s %s", getRiakAdminCmd(), bucketTypeName, escapeLiteralForDoubleQuotedBash(bucketTypeProperties)))) .noExtraOutput() .failOnNonZeroResultCode(); if (!isRiakOnPath()) { addRiakOnPath(bucketTypeStatusScript); } bucketTypeStatusScript.execute(); }

Target:
public void bucketTypeUpdate(String bucketTypeName, String bucketTypeProperties) { ScriptHelper bucketTypeStatusScript = newScript("bucket-type_update") .body.append(sudo(format("%s bucket-type update %s %s", getRiakAdminCmd(), bucketTypeName, escapeLiteralForDoubleQuotedBash(bucketTypeProperties)))) .failOnNonZeroResultCode(); if (!isRiakOnPath()) { addRiakOnPath(bucketTypeStatusScript); } bucketTypeStatusScript.execute(); }
Source:
protected void addPermissionSubjectForAdminLevelProperties(List<PermissionSubject> permissionList) { VmStatic vmFromParams = getParameters().getVmStaticData(); if (vmFromParams != null && getVmTemplate() != null) { if (!StringUtils.isEmpty(vmFromParams.getCustomProperties())) { permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } Set<Guid> dedicatedVmForVdsFromUser = new HashSet<>(vmFromParams.getDedicatedVmForVdsList()); Set<Guid> dedicatedVmForVdsFromTemplate = new HashSet<>(getVmTemplate().getDedicatedVmForVdsList()); if (dedicatedVmForVdsFromUser.size() != dedicatedVmForVdsFromTemplate.size() || !dedicatedVmForVdsFromUser.containsAll(dedicatedVmForVdsFromTemplate) || !StringUtils.isEmpty(vmFromParams.getCpuPinning())) { permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.EDIT_ADMIN_VM_PROPERTIES)); } } }

Target:
protected void addPermissionSubjectForAdminLevelProperties(List<PermissionSubject> permissionList) { VmStatic vmFromParams = getParameters().getVmStaticData(); if (vmFromParams != null && getVmTemplate() != null) { if (!StringUtils.isEmpty(vmFromParams.getCustomProperties())) { permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } Set<Guid> dedicatedVmForVdsFromUser = new HashSet<>(vmFromParams.getDedicatedVmForVdsList()); Set<Guid> dedicatedVmForVdsFromTemplate = new HashSet<>(getVmTemplate().getDedicatedVmForVdsList()); if (!dedicatedVmForVdsFromUser.equals(dedicatedVmForVdsFromTemplate) || !StringUtils.isEmpty(vmFromParams.getCpuPinning())) { permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, ActionGroup.EDIT_ADMIN_VM_PROPERTIES)); } } }
Source:
public static void createStartDebugSurveyLink(JComponent parent) { String programmingExperienceParam = "&entry.962486075="; try { programmingExperienceParam += URLEncoder.encode(Preferences.getInstance().getProgrammingExperience(), "UTF-8"); } catch (UnsupportedEncodingException e) { programmingExperienceParam = ""; } String surveyLink = "<LINK_0>" + Preferences.getInstance().getUserId() + programmingExperienceParam + "&entry.87074017=Java&entry.1002919343=IntelliJ&entry.2010347695&entry.2084367812"; UIUtils.createHyperLinkLabel(parent, "Share your thoughts on debugging and win an additional Amazon voucher!", surveyLink); }

Target:
public static void createStartDebugSurveyLink(JComponent parent) { UIUtils.createHyperLinkLabel(parent, "Share your thoughts on debugging and win an additional Amazon voucher!", WatchDogUtils.getDebugSurveyLink()); }
Source:
private void notifyCallbackWithSuccess(RealmResults<PermissionOffer> permissions) { callback.onSuccess(permissions); activeTasks.remove(this); }

Target:
private void notifyCallbackWithSuccess(RealmResults<PermissionOffer> permissions) { try { callback.onSuccess(permissions); } finally { activeTasks.remove(this); } }
Source:
Analyzer getKbIndexAnalyzer() throws Exception { if (kbIndexAnalyzer == null) { kbIndexAnalyzer = new EnglishAnalyzer(); } return kbIndexAnalyzer; }

Target:
Analyzer getKbIndexAnalyzer() { if (kbIndexAnalyzer == null) { kbIndexAnalyzer = new EnglishAnalyzer(CharArraySet.EMPTY_SET); } return kbIndexAnalyzer; }
Source:
public static boolean remove(String key) { if (!isHawkInitialised()) { return false; } return hawkBuilder.getStorage().remove(key); }

Target:
public static boolean remove(String key) { Utils.validateBuild(); return internal.getStorage().remove(key); }
Source:
public LockResource lockShared() throws InterruptedException { if (mSafeMode) { throw new IllegalStateException("Cannot acquire lock shared during safe-mode."); } try { mSharedWaiters.add(Thread.currentThread()); mStateLock.readLock().lockInterruptibly(); } finally { mSharedWaiters.remove(Thread.currentThread()); } mSharedHolders.add(Thread.currentThread()); return new LockResource(mStateLock.readLock(), false, false, () -> { mSharedHolders.remove(Thread.currentThread()); }); }

Target:
public LockResource lockShared() throws InterruptedException { long exclusiveOnlyRemainingMs = mExclusiveOnlyDeadlineMs - System.currentTimeMillis(); if (exclusiveOnlyRemainingMs > 0) { String safeModeMsg = String.format( "Master still in exclusive-only phase (%dms remaining) for the state-lock. " + "Please see documentation for %s.", exclusiveOnlyRemainingMs, PropertyKey.Name.MASTER_BACKUP_STATE_LOCK_EXCLUSIVE_DURATION); throw new IllegalStateException(safeModeMsg); } mSharedWaitersAndHolders.add(Thread.currentThread()); mStateLock.readLock().lockInterruptibly(); return new LockResource(mStateLock.readLock(), false, false, () -> { mSharedWaitersAndHolders.remove(Thread.currentThread()); }); }
Source:
public boolean validateUser(String username, String password) { if (defaultUser.equals(username) && defaultPassword.equals(password)) return true; if (this.securityDomain == null) throw MessagingLogger.ROOT_LOGGER.elytronSecurityDomainNotSet(); ServerAuthenticationContext context = this.securityDomain.createNewAuthenticationContext(); PasswordGuessEvidence evidence = new PasswordGuessEvidence(password != null ? password.toCharArray() : null); try { context.setAuthenticationName(username); if (context.verifyEvidence(evidence)) { return true; } else { MessagingLogger.ROOT_LOGGER.failedAuthentication(username); } } catch (IllegalArgumentException | IllegalStateException | RealmUnavailableException e) { MessagingLogger.ROOT_LOGGER.failedAuthenticationWithException(e, username, e.getMessage()); } finally { evidence.destroy(); } return false; }

Target:
public boolean validateUser(String username, String password) { if (defaultUser.equals(username) && defaultPassword.equals(password)) return true; return this.authenticate(username, password) != null; }
Source:
private boolean executeSshPowerdown(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH power down session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH power down command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshVdsPowerdownCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH power down command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut.toString(), cmdErr.toString()); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }

Target:
private boolean executeSshPowerdown(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH power down session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH power down command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshVdsPowerdownCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH power down command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }
Source:
public void resolve() { if (entry == null) { return; } NetworkBootProtocol bootproto = NetworkBootProtocol.NONE; String ipAddress = fetchIpAddress(); if (bootProtocolDhcp()) { bootproto = NetworkBootProtocol.DHCP; } else if (bootProtocolStatic()) { if (StringUtils.isNotEmpty(ipAddress)) { bootproto = NetworkBootProtocol.STATIC_IP; } } else if (StringUtils.isNotEmpty(ipAddress)) { bootproto = NetworkBootProtocol.STATIC_IP; } if (bootproto == NetworkBootProtocol.STATIC_IP) { String gateway = fetchGateway(); if (StringUtils.isNotEmpty(gateway)) { VdsBrokerObjectsBuilder.setGatewayIfNecessary(iface, host, gateway.toString()); } } iface.setBootProtocol(bootproto); }

Target:
public void resolve() { if (entry == null) { return; } NetworkBootProtocol bootproto = NetworkBootProtocol.NONE; String ipAddress = fetchIpAddress(); if (bootProtocolDhcp()) { bootproto = NetworkBootProtocol.DHCP; } else if (StringUtils.isNotEmpty(ipAddress)) { bootproto = NetworkBootProtocol.STATIC_IP; } if (bootproto == NetworkBootProtocol.STATIC_IP) { String gateway = fetchGateway(); if (StringUtils.isNotEmpty(gateway)) { VdsBrokerObjectsBuilder.setGatewayIfNecessary(iface, host, gateway.toString()); } } iface.setBootProtocol(bootproto); }
Source:
public void oldestKeyAfter() throws Exception { long now = Utils.currentTimeSeconds(); Utils.setMockClock(now); final ECKey key1 = new ECKey(); key1.setCreationTimeSeconds(now); Utils.rollMockClock(86400); final ECKey key2 = new ECKey(); final ArrayList<ECKey> keys = Lists.newArrayList(key1, key2); assertEquals(2, chain.importKeys(keys)); assertNull(chain.findOldestKeyAfter(now + 86400 * 2)); assertEquals(key1, chain.findOldestKeyAfter(now - 1)); assertEquals(key2, chain.findOldestKeyAfter(now + 86400 - 1)); }

Target:
public void oldestKeyAfter() throws Exception { Utils.setMockClock(); long now = Utils.currentTimeSeconds(); final ECKey key1 = new ECKey(); Utils.rollMockClock(86400); final ECKey key2 = new ECKey(); final ArrayList<ECKey> keys = Lists.newArrayList(key1, key2); assertEquals(2, chain.importKeys(keys)); assertNull(chain.findOldestKeyAfter(now + 86400 * 2)); assertEquals(key1, chain.findOldestKeyAfter(now - 1)); assertEquals(key2, chain.findOldestKeyAfter(now + 86400 - 1)); }
Source:
public static Rotation findReverse(Rotation rotation) { Side frontResult = rotation.rotate(Side.FRONT); Side topResult = rotation.rotate(Side.TOP); for (Rotation possibility : values()) { if (possibility.rotate(frontResult) == Side.FRONT && possibility.rotate(topResult) == Side.TOP) { return possibility; } } return null; }

Target:
public static Rotation findReverse(Rotation rotation) { Preconditions.checkNotNull(rotation); return REVERSE_ROTATIONS_MAP.get(rotation); }
Source:
protected boolean runVm(Guid vmId, EngineLock lock) { return backend.runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); }

Target:
private boolean runVm(Guid vmId, EngineLock lock) { return backend.runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); }
Source:
public List<SqlOperator> getOperatorList() { final ImmutableList.Builder<SqlOperator> b = ImmutableList.builder(); for (List<String> schemaPath : schemaPaths) { CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, nameMatcher); if (schema != null) { for (String name : schema.getFunctionNames()) { schema.getFunctions(name, true).forEach(f -> b.add(toOp(new SqlIdentifier(name, SqlParserPos.ZERO), f))); } } } return b.build(); }

Target:
public List<SqlOperator> getOperatorList() { final ImmutableList.Builder<SqlOperator> builder = ImmutableList.builder(); for (List<String> schemaPath : schemaPaths) { CalciteSchema schema = SqlValidatorUtil.getSchema(rootSchema, schemaPath, nameMatcher); if (schema != null) { for (String name : schema.getFunctionNames()) { schema.getFunctions(name, true).forEach(f -> builder.add(toOp(new SqlIdentifier(name, SqlParserPos.ZERO), f))); } } } return builder.build(); }
Source:
public void testPostEmptyMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); boolean badStatus = false; try { builder.post(Control.class, new Metric[]{}); } catch (UniformInterfaceException e) { badStatus = true; assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } if (!badStatus){ fail("expected 400 status"); } }

Target:
public void testPostEmptyMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); try { builder.post(Control.class, new Metric[]{}); fail("expected 400 status"); } catch (UniformInterfaceException e) { assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } }
Source:
protected static boolean sendFtpFile(String host, String username, String password, String directory, String filename, byte[] content) { try { FTPClient ftp = TransmissionUtils.ftpConnect(host, username, password); if (ftp == null || !ftp.isConnected()) { log.error("FTP client isn't connected. Please supply a client that has connected to the host."); return false; } if (directory == null) { } else if (!ftp.changeWorkingDirectory(directory)) { log.error("Desired path does not exist on the server"); ftp.logout(); ftp.disconnect(); return false; } try (OutputStream stream = ftp.storeFileStream(filename)) { stream.write(content); } if (!ftp.completePendingCommand() || !FTPReply.isPositiveCompletion(ftp.getReplyCode())) { log.error("Error storing file"); ftp.logout(); ftp.disconnect(); return false; } ftp.logout(); ftp.disconnect(); return true; } catch (IOException e) { log.error("Failed to FTP", e); } return false; }

Target:
protected static boolean sendFtpFile(String host, String username, String password, String directory, String filename, byte[] content) { try { FTPClient ftp = TransmissionUtils.ftpConnect(host, username, password); if (ftp == null || !ftp.isConnected()) { log.error("FTP client isn't connected. Please supply a client that has connected to the host."); return false; } try { if (directory == null) { } else if (!ftp.changeWorkingDirectory(directory)) { log.error("Desired path does not exist on the server"); return false; } try (OutputStream stream = ftp.storeFileStream(filename)) { stream.write(content); } if (!ftp.completePendingCommand() || !FTPReply.isPositiveCompletion(ftp.getReplyCode())) { log.error("Error storing file"); return false; } return true; } finally { ftp.logout(); ftp.disconnect(); } } catch (IOException e) { log.error("Failed to FTP", e); } return false; }
Source:
private void reportTaskStats() { ClientResponse cr = null; try { cr = client.callProcedure("@Statistics", "TASK", 0); } catch (Exception e) { log.error(e.getStackTrace()); } if (cr.getStatus() != ClientResponse.SUCCESS) { log.error("Failed to call Statistics proc at startup. Exiting."); log.error(((ClientResponseImpl) cr).toJSONString()); printJStack(); System.exit(-1); } long failures = 0; VoltTable t = cr.getResults()[0]; log.info(String.format("%15s%15s%15s%15s", "TASK NAME", "PARTITION ID", "INVOCATIONS", "FAILURES")); while (t.advanceRow()) { long f = t.getLong("PROCEDURE_FAILURES"); log.info(String.format("%15s%15s%15s%15s", t.getString("TASK_NAME"), t.getLong("PARTITION_ID"), t.getLong("SCHEDULER_INVOCATIONS"), f)); if (f > 0) failures += f; } if (failures > 0) { log.error(failures + " unexpected TASK failures"); System.exit(-1); } }

Target:
private void reportTaskStats() { ClientResponse cr = null; try { cr = client.callProcedure("@Statistics", "TASK", 0); } catch (Exception e) { log.error("Fetching TASK statistics failed:", e); } if (cr.getStatus() != ClientResponse.SUCCESS) { log.error("Failed to call Statistics proc at startup. Exiting."); printJStack(); hardStop(((ClientResponseImpl) cr).toJSONString()); } long failures = 0; VoltTable t = cr.getResults()[0]; log.info(String.format("%15s%15s%15s%15s", "TASK NAME", "PARTITION ID", "INVOCATIONS", "FAILURES")); while (t.advanceRow()) { long f = t.getLong("PROCEDURE_FAILURES"); log.info(String.format("%15s%15s%15s%15s", t.getString("TASK_NAME"), t.getLong("PARTITION_ID"), t.getLong("SCHEDULER_INVOCATIONS"), f)); if (f > 0) failures += f; } if (failures > 0) { hardStop(failures + " unexpected TASK failures"); } }
Source:
private void showCreateCloverDirectoryDialog() { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { showMessage(context.getString(R.string.error_external_storage_is_not_mounted)); return; } if (getPermissionHelper().hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (settingsFile.getParentFile().exists()) { return; } } if (!AndroidUtils.isApi16()) { onPermissionGrantedForDirectoryCreation(); return; } AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(context.getString(R.string.clover_directory_may_not_exist_title)) .setMessage(context.getString(R.string.clover_directory_may_not_exist_message)) .setPositiveButton(context.getString(R.string.create), (dialog1, which) -> { getPermissionHelper().requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, granted -> { if (granted) { onPermissionGrantedForDirectoryCreation(); } }); }) .setNegativeButton(context.getString(R.string.do_not), null) .create(); dialog.show(); }

Target:
private void showCreateCloverDirectoryDialog() { String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { showMessage(context.getString(R.string.error_external_storage_is_not_mounted)); return; } if (getPermissionHelper().hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (settingsFile.getParentFile().exists()) { return; } } if (!AndroidUtils.isApi16()) { onPermissionGrantedForDirectoryCreation(); return; } AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(context.getString(R.string.clover_directory_may_not_exist_title)) .setMessage(context.getString(R.string.clover_directory_may_not_exist_message)) .setPositiveButton(context.getString(R.string.create), (dialog1, which) -> { getPermissionHelper().requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, granted -> { if (granted) { onPermissionGrantedForDirectoryCreation(); } }); }) .setNegativeButton(context.getString(R.string.do_not), null) .create(); dialog.show(); }
Source:
public RequestManager get(View view) { if (view.getContext() == null) { throw new IllegalArgumentException("Unable to obtain a request manager for a view without" + " a Context"); } Activity activity = findActivity(view.getContext()); if (activity == null) { return get(view.getContext().getApplicationContext()); } if (activity instanceof FragmentActivity) { Fragment fragment = findSupportFragment(view, (FragmentActivity) activity); if (fragment == null) { return get(activity); } return get(fragment); } android.app.Fragment fragment = findFragment(view, activity); if (fragment == null) { return get(activity); } return get(fragment); }

Target:
public RequestManager get(View view) { if (Util.isOnBackgroundThread()) { return get(view.getContext().getApplicationContext()); } Preconditions.checkNotNull(view); Preconditions.checkNotNull(view.getContext(), "Unable to obtain a request manager for a view without a Context"); Activity activity = findActivity(view.getContext()); if (activity == null) { return get(view.getContext().getApplicationContext()); } if (activity instanceof FragmentActivity) { Fragment fragment = findSupportFragment(view, (FragmentActivity) activity); if (fragment == null) { return get(activity); } return get(fragment); } android.app.Fragment fragment = findFragment(view, activity); if (fragment == null) { return get(activity); } return get(fragment); }
Source:
private boolean isNestedNewResourceCreation(ExpressionTree expr) { if (expr.is(Tree.Kind.NEW_CLASS)) { Arguments arguments = ((NewClassTree) expr).arguments(); if (arguments.stream().noneMatch(UnclosedResourcesCheck::isCloseable)) { return true; } return arguments.stream().filter(UnclosedResourcesCheck::isCloseable).allMatch(this::isNestedNewResourceCreation); } return false; }

Target:
private boolean isNestedNewResourceCreation(ExpressionTree expr) { if (expr.is(Tree.Kind.NEW_CLASS)) { return ((NewClassTree) expr).arguments().stream() .filter(UnclosedResourcesCheck::isCloseable) .allMatch(this::isNestedNewResourceCreation); } return false; }
Source:
private int completeZNode(String buffer, String token, List<String> candidates) { String path = token; int idx = path.lastIndexOf("/") + 1; String prefix = path.substring(idx); try { String dir = idx == 1 ? "/" : path.substring(0, idx - 1); List<String> children = zk.getChildren(dir, false); candidates = children.stream().filter(child -> child.startsWith(prefix)).collect(Collectors.toList()); } catch (InterruptedException e) { return 0; } catch (KeeperException e) { return 0; } Collections.sort(candidates); return candidates.size() == 0 ? buffer.length() : buffer.lastIndexOf("/") + 1; }

Target:
private int completeZNode(String buffer, String token, List<String> candidates) { String path = token; int idx = path.lastIndexOf("/") + 1; String prefix = path.substring(idx); try { String dir = idx == 1 ? "/" : path.substring(0, idx - 1); List<String> children = zk.getChildren(dir, false); for (String child : children) { if (child.startsWith(prefix)) { candidates.add(child); } } } catch (InterruptedException e) { return 0; } catch (KeeperException e) { return 0; } Collections.sort(candidates); return candidates.size() == 0 ? buffer.length() : buffer.lastIndexOf("/") + 1; }
Source:
private static <S extends OafEntity, T extends SpecificRecord>JavaRDD<T> filterAndParseToAvro(JavaRDD<S> source, ResultApprover resultApprover, OafEntityToAvroConverter<S, T> entityConverter) { return parseToAvro(source.filter(x -> resultApprover.approve(x)), entityConverter); }

Target:
private static <S extends OafEntity, T extends SpecificRecord>JavaRDD<T> filterAndParseToAvro(JavaRDD<S> source, ResultApprover resultApprover, OafEntityToAvroConverter<S, T> entityConverter) { return parseToAvro(source.filter(resultApprover::approve), entityConverter); }
Source:
public List<Blob> render(DocumentModel doc, RenditionDefinition definition) { if (log.isDebugEnabled()) { log.debug(String.format("Asking \"%s\" rendition lazy rendering for document %s (id=%s).", definition.getName(), doc.getPathAsString(), doc.getId())); } String key = buildRenditionKey(doc, definition); String sourceDocumentModificationDate = getSourceDocumentModificationDate(doc, definition); List<Blob> blobs = null; TransientStore ts = getTransientStore(); if (!ts.exists(key)) { blobs = handleNewRendition(key, doc, definition, sourceDocumentModificationDate); } else { String storedSourceDocumentModificationDate = (String) ts.getParameter(key, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY); blobs = ts.getBlobs(key); if (ts.isCompleted(key)) { handleCompletedRendition(key, doc, definition, sourceDocumentModificationDate, storedSourceDocumentModificationDate, blobs); } else { handleIncompleteRendition(key, doc, definition, sourceDocumentModificationDate, storedSourceDocumentModificationDate); } } if (log.isDebugEnabled()) { String blobInfo; if (blobs == null) { blobInfo = null; } else if (blobs.size() == 1) { Blob blob = blobs.get(0); blobInfo = String.format("[filename=%s, MIME type=%s]", blob.getFilename(), blob.getMimeType()); } else { blobInfo = blobs.toString(); } log.debug(String.format("Returning blobs: %s.", blobInfo)); } return blobs; }

Target:
public List<Blob> render(DocumentModel doc, RenditionDefinition definition) { if (log.isDebugEnabled()) { log.debug(String.format("Asking \"%s\" rendition lazy rendering for document %s (id=%s).", definition.getName(), doc.getPathAsString(), doc.getId())); } String key = buildRenditionKey(doc, definition); String sourceDocumentModificationDate = getSourceDocumentModificationDate(doc, definition); List<Blob> blobs = null; TransientStore ts = getTransientStore(); if (!ts.exists(key)) { blobs = handleNewRendition(key, doc, definition, sourceDocumentModificationDate); } else { String storedSourceDocumentModificationDate = (String) ts.getParameter(key, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY); blobs = ts.getBlobs(key); if (ts.isCompleted(key)) { handleCompletedRendition(key, doc, definition, sourceDocumentModificationDate, storedSourceDocumentModificationDate, blobs); } else { handleIncompleteRendition(key, doc, definition, sourceDocumentModificationDate, storedSourceDocumentModificationDate); } } if (log.isDebugEnabled()) { String blobInfo = null; if (blobs != null) { blobInfo = blobs.stream() .map(blob -> String.format("{filename=%s, MIME type=%s}", blob.getFilename(), blob.getMimeType())) .collect(Collectors.joining(",", "[", "]")); } log.debug(String.format("Returning blobs: %s.", blobInfo)); } return blobs; }
Source:
public RoundDecimalExpression(List<Expression> children) { super(children); int numChildren = children.size(); LiteralExpression secondChild = null; if(numChildren > 1) { secondChild = (LiteralExpression)children.get(1); } if(secondChild != null && secondChild.getValue() instanceof Integer) { scale = (Integer)secondChild.getValue(); } }

Target:
public RoundDecimalExpression(List<Expression> children) { super(children); int numChildren = children.size(); LiteralExpression secondChild = null; if(numChildren > 1) { secondChild = (LiteralExpression)children.get(1); } if(secondChild != null && secondChild.getValue() != null) { Object obj = secondChild.getValue(); if(obj instanceof Integer) { scale = (Integer)obj; } else { throw new IllegalDataException("Invalid value " + obj + " of type " + secondChild.getDataType() + " passed at position 2 "); } } }
Source:
private void logProviderCall(String methodName, Uri uri) { String format = "%s.%s %s"; String path = uri == null ? null : uri.getPath(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { Timber.d(format, CardContentProvider.class.getSimpleName(), methodName, path); } else { format += " (%s)"; Timber.d(format, CardContentProvider.class.getSimpleName(), methodName, path, getCallingPackage()); } }

Target:
private void logProviderCall(String methodName, Uri uri) { String format = "%s.%s %s"; String path = uri == null ? null : uri.getPath(); String msg; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { msg = String.format(format, CardContentProvider.class.getSimpleName(), methodName, path); } else { msg = String.format(format + " (%s)", CardContentProvider.class.getSimpleName(), methodName, path, getCallingPackage()); } Timber.i(msg); Collection col = CollectionHelper.getInstance().getCol(getContext()); if (col != null) { col.log(msg); } }
Source:
private boolean isWrapperType(Class<?> clazz) { TypeResolver typeResolver = new TypeResolutionHelper().getTypeResolver(); for ( ValidatedValueUnwrapper<?> handler : validatedValueHandlers ) { ResolvedType handlerType = typeResolver.resolve( handler.getClass() ); List<ResolvedType> typeParameters = handlerType.typeParametersFor( ValidatedValueUnwrapper.class ); if ( TypeHelper.isAssignable( typeParameters.get( 0 ).getErasedType(), clazz ) ) { return true; } } return false; }

Target:
private boolean isWrapperType(Class<?> clazz) { if ( validatedValueHandlersManager.getValidatedValueHandler( clazz ) != null ) { return true; } return false; }
Source:
protected ISelection resolveSelection(IEditorPart part, ITextSelection changedSelection, StructuredViewer viewer) throws CoreException { Object elementToSelect = null; if (changedSelection instanceof TextSelection && part instanceof CEditor) { ICElement cdtElement = SelectionConverter.getElementAtOffset(CDTUiBridge.getInputCElement((CEditor) part), changedSelection); elementToSelect = cdtElement; } if (elementToSelect != null) { StructuredSelection currentSelection = (StructuredSelection) viewer.getSelection(); if (currentSelection.size() <= 1) { for (ViewerFilter filter : Arrays.asList(viewer.getFilters())) { if (filter instanceof CDTDeclarationsFilter && elementToSelect instanceof IMethod) { elementToSelect = ((IMethod) elementToSelect).getTranslationUnit(); } } } return new StructuredSelection(elementToSelect); } else { return null; } }

Target:
protected ISelection resolveSelection(IEditorPart part, ITextSelection changedSelection, StructuredViewer viewer) throws CoreException { Object elementToSelect = null; if (changedSelection instanceof TextSelection && part instanceof CEditor) { ICElement element = CDTUiBridge.getInputCElement((CEditor) part); if (element != null) { ICElement cdtElement = SelectionConverter.getElementAtOffset(element, changedSelection); elementToSelect = cdtElement; } } if (elementToSelect != null) { StructuredSelection currentSelection = (StructuredSelection) viewer.getSelection(); if (currentSelection.size() <= 1) { for (ViewerFilter filter : Arrays.asList(viewer.getFilters())) { if (filter instanceof CDTDeclarationsFilter && elementToSelect instanceof IMethod) { elementToSelect = ((IMethod) elementToSelect).getTranslationUnit(); } } } return new StructuredSelection(elementToSelect); } else { return null; } }
Source:
public void enableOkButton() { modal.enableOkButton(); }

Target:
void enableOkButton() { modal.enableOkButton(); }
Source:
public void testUnexpectedTaskManagerTerminationAfterRunnerCloseWillBeIgnored() throws Exception { final CompletableFuture<Void> terminationFuture = new CompletableFuture<>(); final TestingTaskExecutorService taskExecutorService = TestingTaskExecutorService.newBuilder() .setTerminationFuture(terminationFuture) .withManualTerminationFutureCompletion() .build(); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner( createConfiguration(), (configuration, resourceID, rpcService, highAvailabilityServices, heartbeatServices, metricRegistry, blobCacheService, localCommunicationOnly, externalResourceInfoProvider, fatalErrorHandler) -> taskExecutorService); taskManagerRunner.closeAsync(); terminationFuture.completeExceptionally(new FlinkException("Test exception.")); assertThat(systemExitTrackingSecurityManager.getSystemExitFuture(), willNotComplete(Duration.ofMillis(10L))); }

Target:
public void testUnexpectedTaskManagerTerminationAfterRunnerCloseWillBeIgnored() throws Exception { final CompletableFuture<Void> terminationFuture = new CompletableFuture<>(); final TestingTaskExecutorService taskExecutorService = TestingTaskExecutorService.newBuilder() .setTerminationFuture(terminationFuture) .withManualTerminationFutureCompletion() .build(); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner( createConfiguration(), createTaskExecutorServiceFactory(taskExecutorService)); taskManagerRunner.closeAsync(); terminationFuture.completeExceptionally(new FlinkException("Test exception.")); assertThat(systemExitTrackingSecurityManager.getSystemExitFuture(), willNotComplete(Duration.ofMillis(10L))); }
Source:
public String getSectionTitle(int position) { Speaker speaker = getItem(position); String name = speaker.getName(); return name.substring(0, 1); }

Target:
public String getSectionTitle(int position) { Speaker speaker = getItem(position); sortType = SharedPreferencesUtil.getInt(ConstantStrings.PREF_SORT_SPEAKER, SORTED_BY_NAME); String title; switch (sortType){ case SORTED_BY_NAME: title = speaker.getName(); break; case SORTED_BY_ORGANIZATION: title = speaker.getOrganisation(); break; default: title = speaker.getCountry(); break; } if (TextUtils.isEmpty(title)) { return "-"; } return String.valueOf(title.charAt(0)); }
Source:
private Provider<?> getProvider() { if (provider == null) { provider = providerDao.get(getNetwork().getProvidedBy().getProviderId()); } return provider; }

Target:
private Provider<?> getProvider() { if (provider == null ) { Network network = getNetwork(); if (network != null && network.isExternal()) provider = providerDao.get(network.getProvidedBy().getProviderId()); } return provider; }
Source:
public static UploadBlock blockFromJson(JSONObject jsonObject){ if (jsonObject == null){ return null; } long offset = 0; long size = 0; int index = 0; String context = null; ArrayList<UploadData> uploadDatas = new ArrayList<UploadData>(); try { offset = jsonObject.getLong("offset"); size = jsonObject.getLong("size"); index = jsonObject.getInt("index"); context = jsonObject.getString("context"); JSONArray dataJsonArray = jsonObject.getJSONArray("uploadDatas"); for (int i = 0; i < dataJsonArray.length(); i++) { JSONObject dataJson = dataJsonArray.getJSONObject(i); UploadData data = UploadData.dataFromJson(dataJson); if (data != null){ uploadDatas.add(data); } } } catch (JSONException e){}; UploadBlock block = new UploadBlock(offset, size, index, uploadDatas); if (context != null && context.length() > 0){ block.context = context; } return block; }

Target:
public static UploadBlock blockFromJson(JSONObject jsonObject){ if (jsonObject == null){ return null; } long offset = 0; long size = 0; int index = 0; String context = null; ArrayList<UploadData> uploadDataList = new ArrayList<UploadData>(); try { offset = jsonObject.getLong("offset"); size = jsonObject.getLong("size"); index = jsonObject.getInt("index"); context = jsonObject.getString("context"); JSONArray dataJsonArray = jsonObject.getJSONArray("uploadDataList"); for (int i = 0; i < dataJsonArray.length(); i++) { JSONObject dataJson = dataJsonArray.getJSONObject(i); UploadData data = UploadData.dataFromJson(dataJson); if (data != null){ uploadDataList.add(data); } } } catch (JSONException e){}; UploadBlock block = new UploadBlock(offset, size, index, uploadDataList); if (context != null && context.length() > 0){ block.context = context; } return block; }
Source:
public void addRemoveModuleTest() throws IOException, CommandFailedException, CliException, SAXException { File testJar = createTestJar(); AddModule addModule = new AddModule.Builder(TEST_MODULE_NAME) .resource(testJar) .resourceDelimiter(":") .dependency("org.hibernate") .dependency("org.jboss.as.controller") .mainClass("test.mainclass") .property("foo", "bar") .property("john", "doe") .build(); client.apply(addModule); File asRoot = new File(getPathToAs()); File module = new File(asRoot, "modules" + File.separator + TEST_MODULE_NAME.replaceAll("\\.", File.separator)); assertTrue("Module " + module.getAbsolutePath() + " doesn't exist on path", module.exists()); File moduleTestJar = new File(module, "main" + File.separator + testJar.getName()); assertTrue("File " + moduleTestJar.getAbsolutePath() + " doesn't exist", moduleTestJar.exists()); File moduleXml = new File(module, "main" + File.separator + "module.xml"); assertTrue("File " + moduleXml.getName() + " doesn't exist in " + module.getAbsolutePath(), moduleXml.exists()); assertXmlIdentical(EXPECTED_MODULE_XML, Files.toString(moduleXml, Charsets.UTF_8)); RemoveModule removeModule = new RemoveModule(TEST_MODULE_NAME); client.apply(removeModule); assertFalse("Module exists on path " + module.getAbsolutePath(), module.exists()); }

Target:
public void addRemoveModuleTest() throws IOException, CommandFailedException, CliException, SAXException { File testJar1 = createTestJar("testJar1.jar", "folder with spaces"); File testJar2 = createTestJar("testJar2.jar", null); AddModule addModule = new AddModule.Builder(TEST_MODULE_NAME) .resource(testJar1) .resource(testJar2) .resourceDelimiter(":") .dependency("org.hibernate") .dependency("org.jboss.as.controller") .mainClass("test.mainclass") .property("foo", "bar") .property("john", "doe") .build(); client.apply(addModule); File asRoot = new File(getPathToAs()); File module = new File(asRoot, "modules" + File.separator + TEST_MODULE_NAME.replaceAll("\\.", File.separator)); assertTrue("Module " + module.getAbsolutePath() + " should exist on path", module.exists()); File moduleTestJar1 = new File(module, "main" + File.separator + testJar1.getName()); assertTrue("File " + moduleTestJar1.getAbsolutePath() + " should exist", moduleTestJar1.exists()); File moduleTestJar2 = new File(module, "main" + File.separator + testJar2.getName()); assertTrue("File " + moduleTestJar2.getAbsolutePath() + " should exist", moduleTestJar2.exists()); File moduleXml = new File(module, "main" + File.separator + "module.xml"); assertTrue("File " + moduleXml.getName() + " should exist in " + module.getAbsolutePath(), moduleXml.exists()); assertXmlIdentical(EXPECTED_MODULE_XML, Files.toString(moduleXml, Charsets.UTF_8)); RemoveModule removeModule = new RemoveModule(TEST_MODULE_NAME); client.apply(removeModule); assertFalse("Module shouldn't exist on path " + module.getAbsolutePath(), module.exists()); }
Source:
public void setReorderMode(ReorderMode reorderMode) { if (reorderMode == ReorderMode.FAST && fastModeExtent == null) { throw new IllegalArgumentException("An EditSession without a fast mode tried to use it for reordering!"); } if (reorderMode == ReorderMode.MULTI_STAGE && reorderExtent == null) { throw new IllegalArgumentException("An EditSession without a reorder extent tried to use it for reordering!"); } flushSession(); this.reorderMode = reorderMode; switch (reorderMode) { case MULTI_STAGE: if (fastModeExtent != null) { fastModeExtent.setPostEditSimulationEnabled(false); } reorderExtent.setEnabled(true); break; case FAST: fastModeExtent.setPostEditSimulationEnabled(true); if (reorderExtent != null) { reorderExtent.setEnabled(false); } break; case NONE: if (fastModeExtent != null) { fastModeExtent.setPostEditSimulationEnabled(false); } if (reorderExtent != null) { reorderExtent.setEnabled(false); } break; } }

Target:
public void setReorderMode(ReorderMode reorderMode) { if (reorderMode == ReorderMode.FAST && fastModeExtent == null) { throw new IllegalArgumentException("An EditSession without a fast mode tried to use it for reordering!"); } if (reorderMode == ReorderMode.MULTI_STAGE && reorderExtent == null) { throw new IllegalArgumentException("An EditSession without a reorder extent tried to use it for reordering!"); } if (commitRequired()) { flushSession(); } this.reorderMode = reorderMode; switch (reorderMode) { case MULTI_STAGE: if (fastModeExtent != null) { fastModeExtent.setPostEditSimulationEnabled(false); } reorderExtent.setEnabled(true); break; case FAST: fastModeExtent.setPostEditSimulationEnabled(true); if (reorderExtent != null) { reorderExtent.setEnabled(false); } break; case NONE: if (fastModeExtent != null) { fastModeExtent.setPostEditSimulationEnabled(false); } if (reorderExtent != null) { reorderExtent.setEnabled(false); } break; } }
Source:
public EventPayload deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String type = event.get().getType(); Class clazz = EventPayload.class; if ("CommitCommentEvent".equals(type)) { clazz = CommitCommentPayload.class; } else if ("CreateEvent".equals(type)) { clazz = CreatePayload.class; } else if ("DeleteEvent".equals(type)) { clazz = DeletePayload.class; } else if ("DownloadEvent".equals(type)) { clazz = DownloadPayload.class; } else if ("FollowEvent".equals(type)) { clazz = FollowPayload.class; } else if ("ForkEvent".equals(type)) { clazz = ForkPayload.class; } else if ("ForkApplyEvent".equals(type)) { clazz = ForkApplyPayload.class; } else if ("GistEvent".equals(type)) { clazz = GistPayload.class; } else if ("GollumEvent".equals(type)) { clazz = GollumPayload.class; } else if ("IssueCommentEvent".equals(type)) { clazz = IssueCommentPayload.class; } else if ("IssuesEvent".equals(type)) { clazz = IssuesPayload.class; } else if ("MemberEvent".equals(type)) { clazz = MemberPayload.class; } else if ("PublicEvent".equals(type)) { clazz = PublicPayload.class; } else if ("PullRequestEvent".equals(type)) { clazz = PullRequestPayload.class; } else if ("PushEvent".equals(type)) { clazz = PushPayload.class; } else if ("TeamAddEvent".equals(type)) { clazz = TeamAddPayload.class; } else if ("WatchEvent".equals(type)) { clazz = WatchPayload.class; } if (clazz == EventPayload.class) { return new EventPayload(); } return context.deserialize(json, clazz); }

Target:
public EventPayload deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String type = event.get().getType(); Class<? extends EventPayload> clazz = EventPayload.class; if ("CommitCommentEvent".equals(type)) clazz = CommitCommentPayload.class; else if ("CreateEvent".equals(type)) clazz = CreatePayload.class; else if ("DeleteEvent".equals(type)) clazz = DeletePayload.class; else if ("DownloadEvent".equals(type)) clazz = DownloadPayload.class; else if ("FollowEvent".equals(type)) clazz = FollowPayload.class; else if ("ForkEvent".equals(type)) clazz = ForkPayload.class; else if ("ForkApplyEvent".equals(type)) clazz = ForkApplyPayload.class; else if ("GistEvent".equals(type)) clazz = GistPayload.class; else if ("GollumEvent".equals(type)) clazz = GollumPayload.class; else if ("IssueCommentEvent".equals(type)) clazz = IssueCommentPayload.class; else if ("IssuesEvent".equals(type)) clazz = IssuesPayload.class; else if ("MemberEvent".equals(type)) clazz = MemberPayload.class; else if ("PublicEvent".equals(type)) clazz = PublicPayload.class; else if ("PullRequestEvent".equals(type)) clazz = PullRequestPayload.class; else if ("PushEvent".equals(type)) clazz = PushPayload.class; else if ("TeamAddEvent".equals(type)) clazz = TeamAddPayload.class; else if ("WatchEvent".equals(type)) clazz = WatchPayload.class; if (clazz == EventPayload.class) return new EventPayload(); return context.deserialize(json, clazz); }
Source:
public HttpResponse doCompleteInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins j = Jenkins.getActiveInstance(); User u = j.getUser("admin"); if(u != null && u.getProperty(AuthenticationKey.class) != null) { Iterator<Map.Entry<Descriptor<UserProperty>,UserProperty>> entries = u.getProperties().entrySet().iterator(); while(entries.hasNext()) { Map.Entry<?, ?> entry = entries.next(); if(entry.getValue() instanceof AuthenticationKey) { entries.remove(); } } } j.setInstallState(InstallState.INITIAL_SETUP_COMPLETED); InstallUtil.saveLastExecVersion(); PluginServletFilter.removeFilter(FORCE_SETUP_WIZARD_FILTER); j.setSetupWizard(null); return HttpResponses.okJSON(); }

Target:
public HttpResponse doCompleteInstall(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins j = Jenkins.getActiveInstance(); User u = j.getUser("admin"); if(u != null && u.getProperty(AuthenticationKey.class) != null) { Iterator<Map.Entry<Descriptor<UserProperty>,UserProperty>> entries = u.getProperties().entrySet().iterator(); while(entries.hasNext()) { Map.Entry<?, ?> entry = entries.next(); if(entry.getValue() instanceof AuthenticationKey) { entries.remove(); } } u.save(); } j.setInstallState(InstallState.INITIAL_SETUP_COMPLETED); InstallUtil.saveLastExecVersion(); PluginServletFilter.removeFilter(FORCE_SETUP_WIZARD_FILTER); j.setSetupWizard(null); return HttpResponses.okJSON(); }