auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void fireReturnCallback(final Invoker<?> invoker, final Invocation invocation, final Object result) { final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) return; final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); if (onReturnMethod == null && onReturnInst == null) { return; } if (onReturnMethod == null || onReturnInst == null) { throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } Object[] args = invocation.getArguments(); Object[] params; Class<?>[] rParaTypes = onReturnMethod.getParameterTypes(); if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = result; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = result; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[]{result}; } try { onReturnMethod.invoke(onReturnInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } }

Target:
private void fireReturnCallback(final Invoker<?> invoker, final Invocation invocation, final Object result) { final ConsumerMethodModel.AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); if (onReturnMethod == null && onReturnInst == null) { return; } if (onReturnMethod == null || onReturnInst == null) { throw new IllegalStateException("service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } Object[] args = invocation.getArguments(); Object[] params; Class<?>[] rParaTypes = onReturnMethod.getParameterTypes(); if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = result; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = result; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[]{result}; } try { onReturnMethod.invoke(onReturnInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } }
Source:
public void testOracleExportAction() throws Exception { Path outputDir = dfsCluster.getFileSystem().getHomeDirectory(); OracleExportAction.OracleExportActionConfig oracleExportActionConfig = new OracleExportAction.OracleExportActionConfig(sshServer.getHost(), sshServer.getPort(), USER, PASSPHRASE, "system", "cask", "home", "sid", outputDir.toUri().toString() + "/tmp/OracleExportJunitTemp.csv", "select * from test;", "csv"); OracleExportAction oracleExportAction = new OracleExportAction(oracleExportActionConfig); MockActionContext mockActionContext = new MockActionContext(); oracleExportAction.run(mockActionContext); Assert.assertTrue(fileSystem.exists(new Path(outputDir.toUri().toString() + "/tmp/OracleExportJunitTemp.csv"))); }

Target:
public void testOracleExportAction() throws Exception { Path outputDir = dfsCluster.getFileSystem().getHomeDirectory(); OracleExportAction.OracleExportActionConfig oracleExportActionConfig = new OracleExportAction.OracleExportActionConfig(sshServer.getHost(), sshServer.getPort(), USER, "Password", PASSPHRASE, "", "", "system", "cask", "home", "sid", outputDir.toUri().toString() + "/tmp/OracleExportJunitTemp.csv", "select * from test;", "", "/tmp", "CSV"); OracleExportAction oracleExportAction = new OracleExportAction(oracleExportActionConfig); MockActionContext mockActionContext = new MockActionContext(); oracleExportAction.run(mockActionContext); Assert.assertTrue(fileSystem.exists(new Path(outputDir.toUri().toString() + "/tmp/OracleExportJunitTemp.csv"))); }
Source:
protected String[] fillTypeCombo() { ArrayList<String> list = new ArrayList<>(); if(null != getType()) { for (AdapterTypePaletteEntry adaptertype : getAdapterTypes(getPalette())){ list.add(adaptertype.getLabel()); } } return list.toArray(new String[list.size()]); }

Target:
protected String[] fillTypeCombo() { List<String> list = new ArrayList<>(); if(null != getType()) { for (AdapterTypePaletteEntry adaptertype : getAdapterTypes(getPalette())){ list.add(adaptertype.getLabel()); } } return list.toArray(new String[list.size()]); }
Source:
private synchronized User getOrCreateUser(String id, String email, String username) throws ServletException { try { return userManager.getById(id); } catch (NotFoundException e) { final UserImpl cheUser = new UserImpl(id, email, username, generate("", 12), emptyList()); try { return userManager.create(cheUser, false); } catch (ConflictException ex) { try { cheUser.setName(generate(cheUser.getName(), 4)); return userManager.create(cheUser, false); } catch (ServerException | ConflictException e1) { throw new ServletException("Unable to create new user", e1); } } catch (ServerException ex) { throw new ServletException("Unable to create new user", ex); } } catch (ServerException e) { throw new ServletException("Unable to get user", e); } }

Target:
private User getOrCreateUser(String id, String email, String username) throws ServerException, ConflictException { try { return userManager.getById(id); } catch (NotFoundException e) { synchronized (this) { final UserImpl cheUser = new UserImpl(id, email, username, generate("", 12), emptyList()); try { return userManager.create(cheUser, false); } catch (ConflictException ex) { cheUser.setName(generate(cheUser.getName(), 4)); return userManager.create(cheUser, false); } } } }
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); Long _id = System.currentTimeMillis(); return PendingIntent.getBroadcast(context, _id.intValue(), intent, PendingIntent.FLAG_CANCEL_CURRENT); }

Target:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); return PendingIntent.getBroadcast(context, (int)keyId, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
Source:
public void commit(final Xid xid, final boolean onePhase) throws XAException { try { if (commitToEnlistment()) lookup(xid).commit(onePhase); } catch (XAException | RuntimeException exception) { if (resourceRegistry != null) resourceRegistry.resourceInDoubt(this); throw exception; } if (resourceRegistry != null) { resourceRegistry.removeResource(this); } else { for (XAResource xares : XAResourceRegistryProviderHolder.getInstance().getInDoubtXAResources()) { if (xares instanceof SubordinateXAResource) { SubordinateXAResource subordinateXares = (SubordinateXAResource) xares; if (subordinateXares.resourceRegistry != null && subordinateXares.xid !=null && SimpleXid.of(xid).equals(SimpleXid.of(subordinateXares.xid))) { subordinateXares.resourceRegistry.removeResource(subordinateXares); } } } } }

Target:
public void commit(final Xid xid, final boolean onePhase) throws XAException { try { if (commitToEnlistment()) lookup(xid).commit(onePhase); } catch (XAException | RuntimeException exception) { if (resourceRegistry != null) resourceRegistry.resourceInDoubt(this); throw exception; } if (resourceRegistry != null) { resourceRegistry.removeResource(this); } else { for (XAResource xares : XAResourceRegistryProviderHolder.getInstance().getInDoubtXAResources()) { if (xares instanceof SubordinateXAResource) { SubordinateXAResource subordinateXares = (SubordinateXAResource) xares; if (SimpleXid.of(xid).equals(SimpleXid.of(subordinateXares.xid))) { subordinateXares.resourceRegistry.removeResource(subordinateXares); } } } } }
Source:
public void partDeactivated(IWorkbenchPart part) { String id = part.getSite().getId(); if (id.equals(getSite().getId())) { try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(bout)) { XMLMemento memento = XMLMemento.createWriteRoot("DebugViewMemento"); saveViewerState(memento); memento.save(writer); IPreferenceStore store = DebugUIPlugin.getDefault().getPreferenceStore(); String xmlString = bout.toString(); store.putValue(PREF_STATE_MEMENTO, xmlString); } catch (IOException e) { } } StringBuilder buffer= new StringBuilder(); for (String string : fDebugToolbarPerspectives) { buffer.append(string).append(','); } getPreferenceStore().setValue(IDebugPreferenceConstants.DEBUG_VIEW_TOOLBAR_HIDDEN_PERSPECTIVES, buffer.toString()); super.partDeactivated(part); }

Target:
public void partDeactivated(IWorkbenchPart part) { String id = part.getSite().getId(); if (id.equals(getSite().getId())) { try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(bout)) { XMLMemento memento = XMLMemento.createWriteRoot("DebugViewMemento"); saveViewerState(memento); memento.save(writer); IPreferenceStore store = DebugUIPlugin.getDefault().getPreferenceStore(); String xmlString = bout.toString(); store.putValue(PREF_STATE_MEMENTO, xmlString); } catch (IOException e) { } } StringBuilder buffer= new StringBuilder(); for (String perspectiveId : fDebugToolbarPerspectives) { buffer.append(perspectiveId).append(','); } getPreferenceStore().setValue(IDebugPreferenceConstants.DEBUG_VIEW_TOOLBAR_HIDDEN_PERSPECTIVES, buffer.toString()); super.partDeactivated(part); }
Source:
public Builder addInitializerBlock(CodeBlock block) { if (!(kind == Kind.CLASS || kind == Kind.ENUM)) { throw new UnsupportedOperationException(kind + " can't have initializer blocks"); } initializerBlock.add("{\n") .indent() .add(block) .unindent() .add("}\n"); return this; }

Target:
public Builder addInitializerBlock(CodeBlock block) { if ((kind != Kind.CLASS && kind != Kind.ENUM)) { throw new UnsupportedOperationException(kind + " can't have initializer blocks"); } initializerBlock.add("{\n") .indent() .add(block) .unindent() .add("}\n"); return this; }
Source:
public void init() { orchestrator.resetData(); ItUtils.restoreProfile(orchestrator, getClass().getResource("/authorisation/one-issue-per-line-profile.xml")); orchestrator.getServer().provisionProject("privateProject", "PrivateProject"); ItUtils.newAdminWsClient(orchestrator).projects().changeVisibility(new ChangeVisibilityRequest("privateProject", PRIVATE)); orchestrator.getServer().associateProjectToQualityProfile("privateProject", "xoo", "one-issue-per-line"); SonarScanner privateProject = SonarScanner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.projectKey", "privateProject") .setProperty("sonar.projectName", "PrivateProject"); orchestrator.executeBuild(privateProject); orchestrator.getServer().provisionProject("publicProject", "PublicProject"); orchestrator.getServer().associateProjectToQualityProfile("publicProject", "xoo", "one-issue-per-line"); SonarScanner publicProject = SonarScanner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.projectKey", "publicProject") .setProperty("sonar.projectName", "PublicProject"); orchestrator.executeBuild(publicProject); }

Target:
public void init() { orchestrator.resetData(); ItUtils.restoreProfile(orchestrator, getClass().getResource("/authorisation/one-issue-per-line-profile.xml")); orchestrator.getServer().provisionProject("privateProject", "PrivateProject"); ItUtils.newAdminWsClient(orchestrator).projects().updateVisibility(new UpdateVisibilityRequest("privateProject", PRIVATE)); orchestrator.getServer().associateProjectToQualityProfile("privateProject", "xoo", "one-issue-per-line"); SonarScanner privateProject = SonarScanner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.projectKey", "privateProject") .setProperty("sonar.projectName", "PrivateProject"); orchestrator.executeBuild(privateProject); orchestrator.getServer().provisionProject("publicProject", "PublicProject"); orchestrator.getServer().associateProjectToQualityProfile("publicProject", "xoo", "one-issue-per-line"); SonarScanner publicProject = SonarScanner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.projectKey", "publicProject") .setProperty("sonar.projectName", "PublicProject"); orchestrator.executeBuild(publicProject); }
Source:
public BuildCommand updateTo(String baseDir, RevisionContext revisionContext) { Revision revision = revisionContext.getLatestRevision(); String workingDir = material.workingdir(new File(baseDir)).getPath(); UrlArgument url = material.getUrlArgument(); return compose( echoWithPrefix(format("Start updating %s at revision %s from %s", material.updatingTarget(), revision.getRevision(), url.forDisplay())), secret(url.forCommandline(), url.forDisplay()), secret(material.getPassword(), "*********************"), secret(material.currentPassword(), "*********************"), cleanupAndUpdate(workingDir, revision).setTest(shouldDoCleanupAndUpdate(workingDir)), freshCheckout(workingDir, revision).setTest(isNotRepository(workingDir)), freshCheckout(workingDir, revision).setTest(test("-nd", workingDir)), freshCheckout(workingDir, revision).setTest(repoUrlChanged(workingDir)), echoWithPrefix(format("Done.\n")) ); }

Target:
public BuildCommand updateTo(String baseDir, RevisionContext revisionContext) { Revision revision = revisionContext.getLatestRevision(); String workingDir = material.workingdir(new File(baseDir)).getPath(); UrlArgument url = material.getUrlArgument(); return compose( echoWithPrefix(format("Start updating %s at revision %s from %s", material.updatingTarget(), revision.getRevision(), url.forDisplay())), secret(url.forCommandline(), url.forDisplay()), secret(material.getPassword(), "*********************"), cleanupAndUpdate(workingDir, revision).setTest(shouldDoCleanupAndUpdate(workingDir)), freshCheckout(workingDir, revision).setTest(isNotRepository(workingDir)), freshCheckout(workingDir, revision).setTest(test("-nd", workingDir)), freshCheckout(workingDir, revision).setTest(repoUrlChanged(workingDir)), echoWithPrefix(format("Done.\n")) ); }
Source:
public void preLightning(EntityLightningBolt lightningBolt, CallbackInfo callbackInfo) { if (!this.world.isRemote) { this.originalLightning = DamageSource.LIGHTNING_BOLT; DamageSource.IN_FIRE = new EntityDamageSource("lightningBolt", lightningBolt); } }

Target:
public void preLightning(EntityLightningBolt lightningBolt, CallbackInfo callbackInfo) { if (!this.world.isRemote) { this.originalLightning = DamageSource.LIGHTNING_BOLT; DamageSource.LIGHTNING_BOLT = new EntityDamageSource("lightningBolt", lightningBolt); } }
Source:
V get() { final V poolVal; synchronized (this) { while (!closed && objectMap.size() == 0 && deficit == 0) { try { this.wait(); } catch (InterruptedException e) { Thread.interrupted(); return null; } } if (closed) { log.info(String.format("get() called even though I'm closed. key[%s]", key)); return null; } else if (!objectMap.isEmpty()) { Map.Entry<Long,V> firstEntry = objectMap.pollFirstEntry(); if(System.nanoTime() - firstEntry.getKey() > maxTimeInNanosToHold) { factory.close(firstEntry.getValue()); poolVal = factory.generate(key); } else{ poolVal = firstEntry.getValue(); } } else if (deficit > 0) { deficit --; poolVal = null; } else { throw new IllegalStateException("WTF?! No objects left, and no object deficit. This is probably a bug."); } } final V retVal; try { if (poolVal != null && factory.isGood(poolVal)) { retVal = poolVal; } else { if (poolVal != null) { factory.close(poolVal); } retVal = factory.generate(key); } } catch (Throwable e) { synchronized (this) { deficit++; this.notifyAll(); } throw Throwables.propagate(e); } return retVal; }

Target:
V get() { final V poolVal; synchronized (this) { while (!closed && resourceHolderList.size() == 0 && deficit == 0) { try { this.wait(); } catch (InterruptedException e) { Thread.interrupted(); return null; } } if (closed) { log.info(String.format("get() called even though I'm closed. key[%s]", key)); return null; } else if (!resourceHolderList.isEmpty()) { ResourceHolder<V> holder = resourceHolderList.removeFirst(); if (System.currentTimeMillis() - holder.getLastAccessedTime() > unusedResourceTimeoutMillis) { factory.close(holder.getResource()); poolVal = factory.generate(key); } else { poolVal = holder.getResource(); } } else if (deficit > 0) { deficit--; poolVal = null; } else { throw new IllegalStateException("WTF?! No objects left, and no object deficit. This is probably a bug."); } } final V retVal; try { if (poolVal != null && factory.isGood(poolVal)) { retVal = poolVal; } else { if (poolVal != null) { factory.close(poolVal); } retVal = factory.generate(key); } } catch (Throwable e) { synchronized (this) { deficit++; this.notifyAll(); } throw Throwables.propagate(e); } return retVal; }
Source:
private void updateVmTemplate() { vmHandler.updateVmInitToDB(getVmTemplate()); vmTemplateDao.update(getVmTemplate()); getVmDeviceUtils().updateSmartcardDevice(getVmTemplateId(), getParameters().getVmTemplateData().isSmartcardEnabled()); getVmDeviceUtils().updateSoundDevice(oldTemplate, getVmTemplate(), getVmTemplate().getCompatibilityVersion(), getParameters().isSoundDeviceEnabled()); getVmDeviceUtils().updateConsoleDevice(getVmTemplateId(), getParameters().isConsoleEnabled()); getVmDeviceUtils().updateUsbSlots(oldTemplate, getVmTemplate()); getVmDeviceUtils().updateVirtioScsiController(getVmTemplate(), getParameters().isVirtioScsiEnabled()); if (getParameters().isBalloonEnabled() != null) { getVmDeviceUtils().updateMemoryBalloon(getVmTemplateId(), getParameters().isBalloonEnabled()); } if (getParameters().getVmTemplateData().getDefaultDisplayType() == DisplayType.none) { getVmDeviceUtils().removeVideoDevices(getVmTemplateId()); } }

Target:
private void updateVmTemplate() { vmHandler.updateVmInitToDB(getVmTemplate()); vmTemplateDao.update(getVmTemplate()); getVmDeviceUtils().updateSmartcardDevice(getVmTemplateId(), getParameters().getVmTemplateData().isSmartcardEnabled()); getVmDeviceUtils().updateSoundDevice(oldTemplate, getVmTemplate(), getVmTemplate().getCompatibilityVersion(), getParameters().isSoundDeviceEnabled()); getVmDeviceUtils().updateConsoleDevice(getVmTemplateId(), getParameters().isConsoleEnabled()); if (oldTemplate.getUsbPolicy() != getVmTemplate().getUsbPolicy()) { getVmDeviceUtils().updateUsbSlots(oldTemplate, getVmTemplate()); } getVmDeviceUtils().updateVirtioScsiController(getVmTemplate(), getParameters().isVirtioScsiEnabled()); if (getParameters().isBalloonEnabled() != null) { getVmDeviceUtils().updateMemoryBalloon(getVmTemplateId(), getParameters().isBalloonEnabled()); } if (getParameters().getVmTemplateData().getDefaultDisplayType() == DisplayType.none) { getVmDeviceUtils().removeVideoDevices(getVmTemplateId()); } }
Source:
public void call(final Subscriber<? super T> subscriber) { subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { if (selection.choice.get() != null) { selection.choice.get().unsubscribe(); } if(!selection.ambSubscribers.isEmpty()) { for (AmbSubscriber<T> other : selection.ambSubscribers) { other.unsubscribe(); } selection.ambSubscribers.clear(); } } })); subscriber.setProducer(new Producer() { private final AtomicBoolean subscribedToSources = new AtomicBoolean(false); @Override public void request(long n) { if (selection.choice.get() != null) { selection.choice.get().requestMore(n); } else if (subscribedToSources.compareAndSet(false, true)){ for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { return; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection); selection.ambSubscribers.add(ambSubscriber); if (selection.choice.get() != null) { selection.unsubscribeOthers(selection.choice.get()); return; } source.unsafeSubscribe(ambSubscriber); } } else { for (AmbSubscriber<T> ambSubscriber: selection.ambSubscribers) { if (!ambSubscriber.isUnsubscribed()) { if (selection.choice.get() == ambSubscriber) { ambSubscriber.requestMore(n); return; } else { ambSubscriber.requestMore(n); } } } } } }); }

Target:
public void call(final Subscriber<? super T> subscriber) { subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { AmbSubscriber<T> c; if ((c = choice.get()) != null) { c.unsubscribe(); } unsubscribeAmbSubscribers(selection.ambSubscribers); } })); for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { break; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(0, subscriber, selection); selection.ambSubscribers.add(ambSubscriber); AmbSubscriber<T> c; if ((c = choice.get()) != null) { selection.unsubscribeOthers(c); return; } source.unsafeSubscribe(ambSubscriber); } if (subscriber.isUnsubscribed()) { unsubscribeAmbSubscribers(selection.ambSubscribers); } subscriber.setProducer(new Producer() { @Override public void request(long n) { final AmbSubscriber<T> c; if ((c = choice.get()) != null) { c.requestMore(n); } else { for (AmbSubscriber<T> ambSubscriber: selection.ambSubscribers) { if (!ambSubscriber.isUnsubscribed()) { if (choice.get() == ambSubscriber) { ambSubscriber.requestMore(n); return; } else { ambSubscriber.requestMore(n); } } } } } }); }
Source:
public void handleNonExpiry403NoReason() throws Exception { mockWebServer.enqueue(MockWebServerResources.OK_COOKIE); mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody ("{\"error\":\"403_not_expired_test\"}\r\n")); try { CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .username("a") .password("b") .build(); c.executeRequest(Http.GET(c.getBaseUri())); fail("A 403 not due to cookie expiry should result in a CouchDbException"); } catch (CouchDbException e) { e.printStackTrace(); assertNotNull("The error should not be null", e.getError()); assertEquals("The error message should be the expected one", "403_not_expired_test", e .getError()); } }

Target:
public void handleNonExpiry403NoReason() throws Exception { basic403Test("403_not_expired_test", null, 2); }
Source:
private EhcacheEntityResponse invokeServerStoreOperation(ServerStoreOpMessage message) { try { switch (message.operation()) { case GET: return EhcacheEntityResponse.response(stores.get(message.getCacheId()).get(message.getKey())); case APPEND: stores.get(message.getCacheId()).append(message.getKey(), ((ServerStoreOpMessage.AppendMessage)message).getPayload()); return EhcacheEntityResponse.success(); case GETANDAPPEND: return EhcacheEntityResponse.response(stores.get(message.getCacheId()).getAndAppend(message.getKey(), ((ServerStoreOpMessage.GetAndAppendMessage)message).getPayload())); case REPLACE: ServerStoreOpMessage.ReplaceAtHeadMessage replaceAtHeadMessage = (ServerStoreOpMessage.ReplaceAtHeadMessage)message; stores.get(replaceAtHeadMessage.getCacheId()).replaceAtHead(replaceAtHeadMessage.getKey(), replaceAtHeadMessage.getExpect(), replaceAtHeadMessage.getUpdate()); return EhcacheEntityResponse.success(); default: throw new IllegalArgumentException("Unknown Server Store operation " + message); } } catch (Exception e) { return EhcacheEntityResponse.failure(e); } }

Target:
private EhcacheEntityResponse invokeServerStoreOperation(ServerStoreOpMessage message) { try { ServerStore cacheStore = stores.get(message.getCacheId()); if (cacheStore == null) { throw new IllegalStateException("Server Store not present for cacheId :" + message.getCacheId()); } switch (message.operation()) { case GET: return EhcacheEntityResponse.response(cacheStore.get(message.getKey())); case APPEND: cacheStore.append(message.getKey(), ((ServerStoreOpMessage.AppendMessage)message).getPayload()); return EhcacheEntityResponse.success(); case GET_AND_APPEND: return EhcacheEntityResponse.response(cacheStore.getAndAppend(message.getKey(), ((ServerStoreOpMessage.GetAndAppendMessage)message).getPayload())); case REPLACE: ServerStoreOpMessage.ReplaceAtHeadMessage replaceAtHeadMessage = (ServerStoreOpMessage.ReplaceAtHeadMessage)message; cacheStore.replaceAtHead(replaceAtHeadMessage.getKey(), replaceAtHeadMessage.getExpect(), replaceAtHeadMessage.getUpdate()); return EhcacheEntityResponse.success(); default: throw new IllegalArgumentException("Unknown Server Store operation " + message); } } catch (Exception e) { return EhcacheEntityResponse.failure(e); } }
Source:
public void addLink(Context context) { final Builder spanBuilder = getSpanBuilder(PARENT_SPAN_KEY, context); final SpanContext spanContext = getSpanContext(context); if (spanContext == null) { logger.warning("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); spanBuilder.startSpan(); }

Target:
public void addLink(Context context) { final Builder spanBuilder = getSpanBuilder(PARENT_SPAN_KEY, context); final SpanContext spanContext = getSpanContext(context); if (spanContext == null) { logger.warning("Failed to find span context to link it."); return; } spanBuilder.addLink(spanContext); }
Source:
public boolean hasBackCameraFlash() { if (hasBackCamera()) { return backCameraInformation.flashAvailable; } return false; }

Target:
public boolean hasBackCameraFlash() { return (hasBackCamera() && backCameraInformation.flashAvailable); }
Source:
public Links getLinks() { if (groups.size() == 0) { return null; } return groups.get(0).getLinks(); }

Target:
public Links getLinks() { if (groups.isEmpty()) { return null; } return groups.get(0).getLinks(); }
Source:
public void init(final ImmutableMap<String, Object> execEnvVars) { uniqueTupleIndices = new IntObjectHashMap<IntArrayList>(); uniqueTuples = new MutableTupleBuffer(getSchema()); tupleCounts = new MutableTupleBuffer(Schema.of(Arrays.asList(new Type[] { Type.INT_TYPE }), Arrays .asList(new String[] { "count" }))); doCount = new CountProcedure(); }

Target:
public void init(final ImmutableMap<String, Object> execEnvVars) { uniqueTupleIndices = new IntObjectHashMap<IntArrayList>(); uniqueTuples = new MutableTupleBuffer(getSchema()); tupleCounts = new MutableTupleBuffer(Schema.ofFields(Type.INT_TYPE, "count")); doCount = new CountProcedure(); }
Source:
public void adjustOffset(Message message, boolean isLegacyConsumer) throws IOException { TopicPartition topicPartition = new TopicPartition(message.getTopic(), message.getKafkaPartition()); long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition); if (isLegacyConsumer && message.getOffset() < lastSeenOffset + 1) { StatsUtil.incr("secor.consumer_rebalance_count." + topicPartition.getTopic()); LOG.info("offset of message does not follow sequentially the last seen offset {}. " + "Deleting files in topic partition {}", message, lastSeenOffset, topicPartition.getTopic(), topicPartition.getPartition()); mFileRegistry.deleteTopicPartition(topicPartition); if (mDeterministicUploadPolicyTracker != null) { mDeterministicUploadPolicyTracker.reset(topicPartition); } } mOffsetTracker.setLastSeenOffset(topicPartition, message.getOffset()); }

Target:
public void adjustOffset(Message message, boolean isLegacyConsumer) throws IOException { TopicPartition topicPartition = new TopicPartition(message.getTopic(), message.getKafkaPartition()); long lastSeenOffset = mOffsetTracker.getLastSeenOffset(topicPartition); if (isLegacyConsumer && message.getOffset() != lastSeenOffset + 1) { StatsUtil.incr("secor.consumer_rebalance_count." + topicPartition.getTopic()); LOG.info("offset of message does not follow sequentially the last seen offset {}. " + "Deleting files in topic partition {}", message, lastSeenOffset, topicPartition.getTopic(), topicPartition.getPartition()); mFileRegistry.deleteTopicPartition(topicPartition); if (mDeterministicUploadPolicyTracker != null) { mDeterministicUploadPolicyTracker.reset(topicPartition); } } mOffsetTracker.setLastSeenOffset(topicPartition, message.getOffset()); }
Source:
private byte countOfNeighbour(int x, int y) { byte count = 0; short posX, posY; for (int i = 0; i < 8; i++) { posX = X((short) (x + neighbourCell[i][0])); posY = Y((short) (y + neighbourCell[i][1])); count += currentGeneration[posX][posY]; } return count; }

Target:
private byte countOfNeighbour(int x, int y) { byte count = 0; short posX, posY; int neighbourCount = 8; for (int i = 0; i < neighbourCount; i++) { posX = X((short) (x + neighbourCell[i][0])); posY = Y((short) (y + neighbourCell[i][1])); count += currentGeneration[posX][posY]; } return count; }
Source:
protected List<LUNs> getLunsToUpdateInDb(List<LUNs> lunsFromVgInfo, List<LUNs> lunsFromDb) { List<LUNs> lunsToUpdateInDb = new LinkedList<>(); Map<String, LUNs> lunsFromDbLunIdMap = lunsFromDb.stream().collect(Collectors.toMap(LUNs::getLUNId, Function.identity())); Map<String, LUNs> lunsFromDbPvIdMap = lunsFromDb.stream().collect(Collectors.toMap(LUNs::getPhysicalVolumeId, Function.identity())); for (LUNs lunFromVgInfo : lunsFromVgInfo) { boolean lunIdExistsInDb = lunsFromDbLunIdMap.containsKey(lunFromVgInfo.getLUNId()); boolean pvIdExistsInDb = lunsFromDbPvIdMap.containsKey(lunFromVgInfo.getPhysicalVolumeId()); if (lunIdExistsInDb && pvIdExistsInDb) { LUNs lunFromDb = lunsFromDbLunIdMap.get(lunFromVgInfo.getLUNId()); if (lunFromDb.getDeviceSize() != lunFromVgInfo.getDeviceSize()) { lunsToUpdateInDb.add(lunFromVgInfo); } } else { lunsToUpdateInDb.add(lunFromVgInfo); } } return lunsToUpdateInDb; }

Target:
protected Map<Consumer<List<LUNs>>, List<LUNs>> getLunsToUpdateInDb(List<LUNs> lunsFromVgInfo, List<LUNs> lunsFromDb) { Map<String, LUNs> lunsFromDbMap = lunsFromDb.stream().collect(Collectors.toMap(LUNs::getLUNId, Function.identity())); return lunsFromVgInfo.stream().collect(Collectors.groupingBy(lunFromVgInfo -> { LUNs lunFromDb = lunsFromDbMap.get(lunFromVgInfo.getLUNId()); if (lunFromDb == null) { return saveNewLuns; } boolean lunFromDbHasSamePvId = Objects.equals( lunFromDb.getPhysicalVolumeId(), lunFromVgInfo.getPhysicalVolumeId()); if (lunFromDbHasSamePvId) { if (lunFromDb.getDeviceSize() != lunFromVgInfo.getDeviceSize()) { return updateExistingLuns; } return noOp; } return updateExistingLuns; })); }
Source:
private boolean updateShape(BundledImage bundledImage) { boolean updated = false; if (bundledImage != null && bundledImage.getShape() != null) { String newShapeName = bundledImage.getShape().getName(); if (!StringUtil.isEmpty(newShapeName) && !newShapeName.equals(getShapeName())) { if (newShapeName.equals(BundledImageShape.PROVIDED_SHAPE_LITERAL.getName())) { String providedShapeURI = bundledImage.getProvidedShapeURI(); IExtensionRegistry reg1 = Platform.getExtensionRegistry(); IConfigurationElement[] elements = reg1.getConfigurationElementsFor("org.eclipse.sirius.diagram.bundleImageShape"); for (IConfigurationElement configurationElement : elements) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { final String path = configurationElement.getAttribute("imagePath"); String imageFileURI = "platform:/plugin" + path; this.setURI(imageFileURI, false); this.setShapeName(configurationElement.getAttribute("label")); } } } else { this.setURI(getImageFileURI(newShapeName), false); this.setShapeName(newShapeName); } updated = true; } } return updated; }

Target:
private boolean updateShape(BundledImage bundledImage) { boolean updated = false; if (bundledImage != null && bundledImage.getShape() != null) { String newShapeName = bundledImage.getShape().getName(); if (!StringUtil.isEmpty(newShapeName) && !newShapeName.equals(getShapeName())) { if (newShapeName.equals(BundledImageShape.PROVIDED_SHAPE_LITERAL.getName())) { String providedShapeURI = bundledImage.getProvidedShapeURI(); IConfigurationElement extension = getBundledImageExtensionQuery().getExtensionDefiningProvidedShapeURI(providedShapeURI); if (extension != null) { final String path = bundledImageExtensionQuery.getImagePath(extension); String imageFileURI = "platform:/plugin" + path; this.setURI(imageFileURI, false); this.setShapeName(BundledImageShape.PROVIDED_SHAPE_LITERAL.getName()); } } else { this.setURI(getImageFileURI(newShapeName), false); this.setShapeName(newShapeName); } updated = true; } } return updated; }
Source:
private Summary(Builder b) { super(b); this.quantiles = Collections.unmodifiableList(new ArrayList<Double>(b.quantiles)); this.highestToLowestValueRatio = b.highestToLowestValueRatio; this.numberOfSignificantValueDigits = b.numberOfSignificantValueDigits; this.maxAgeSeconds = b.maxAgeSeconds; this.ageBuckets = b.ageBuckets; initializeNoLabelsChild(); }

Target:
Summary(Builder b) { super(b); this.quantiles = Collections.unmodifiableList(new ArrayList<Double>(b.quantiles)); this.highestToLowestValueRatio = b.highestToLowestValueRatio; this.numberOfSignificantValueDigits = b.numberOfSignificantValueDigits; this.maxAgeSeconds = b.maxAgeSeconds; this.ageBuckets = b.ageBuckets; initializeNoLabelsChild(); }
Source:
public String convertToDatabaseColumn(List<Checksum> checksums) { StringBuilder sb = new StringBuilder(); if (!checksums.isEmpty() && checksums != null) { try { for (Checksum c : checksums) { sb.append(c.getType().trim() + ":" + c.getChecksum().trim()); sb.append(","); } } catch (NullPointerException ex) { LOG.error("Could not convert checksum(s) to string for database", ex); return null; } return sb.toString().replaceAll(",$", ""); } return null; }

Target:
public String convertToDatabaseColumn(List<Checksum> checksums) { if (checksums != null && !checksums.isEmpty()) { try { return checksums.stream().map(checksum -> checksum.getType().trim() + ":" + checksum.getChecksum().trim()).collect(Collectors.joining(",")); } catch (NullPointerException ex) { LOG.error("Could not convert checksum(s) to string for database", ex); return null; } } return null; }
Source:
public void testNotificationSerialisation() throws Throwable { JsonNode payload = BugsnagTestUtils.mapReportToJson(config, this.report); JsonNode notifier = payload.get("notifier"); assertEquals("Bugsnag Spring", notifier.get("name").asText()); assertEquals("<LINK_0>", notifier.get("url").asText()); assertNotNull(notifier.get("version").asText()); }

Target:
public void testNotificationSerialisation() throws Throwable { JsonNode payload = BugsnagTestUtils.mapReportToJson(config, this.report); JsonNode notifier = payload.get("notifier"); assertEquals("Bugsnag Spring", notifier.get("name").asText()); assertEquals("<LINK_0>", notifier.get("url").asText()); assertFalse(notifier.get("version").asText().isEmpty()); }
Source:
private boolean doSend(MessageChannel channel, final Message<?> messageToSend) { try { this.messagingTemplate.send(channel, messageToSend); return true; } catch (MessagingException e) { if (!this.ignoreSendFailures) { throw e; } else if (this.logger.isDebugEnabled()) { this.logger.debug(e); } return false; } }

Target:
private boolean doSend(MessageChannel channel, final Message<?> messageToSend) { try { this.messagingTemplate.send(channel, messageToSend); return true; } catch (MessagingException e) { if (!this.ignoreSendFailures) { throw e; } this.logger.debug("Send failure ignored", e); return false; } }
Source:
public void accumulate(final long[] values, final int from, final int to) { if (double_accumulator == null && long_accumulator == null) { long_accumulator = Arrays.copyOfRange(values, from, to); return; } if (long_accumulator != null) { } else { if (to - from != double_accumulator.length) { throw new IllegalArgumentException("Values of length " + (to - from) + " did not match the original lengh of " + double_accumulator.length); } int idx = 0; for (int i = from; i < to; i++) { if (Double.isNaN(double_accumulator[idx])) { double_accumulator[idx] = values[i]; } idx++; } } }

Target:
public void accumulate(final long[] values, final int from, final int to) { if (double_accumulator == null && long_accumulator == null) { long_accumulator = Arrays.copyOfRange(values, from, to); return; } if (long_accumulator == null) { if (to - from != double_accumulator.length) { throw new IllegalArgumentException("Values of length " + (to - from) + " did not match the original lengh of " + double_accumulator.length); } int idx = 0; for (int i = from; i < to; i++) { if (Double.isNaN(double_accumulator[idx])) { double_accumulator[idx] = values[i]; } idx++; } } }
Source:
public void renameScriptShell(String newName) throws PartInitException { Display.getDefault().asyncExec(() -> { try { final ScriptShell scriptShellView = (ScriptShell) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .showView(ScriptShell.VIEW_ID); scriptShellView.changePartName(newName); } catch (final PartInitException e) { throw new RuntimeException(e); } }); }

Target:
public void renameScriptShell(String newName) throws PartInitException { Display.getDefault().asyncExec(() -> { final IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); if (part instanceof ScriptShell) { ((ScriptShell) part).changePartName(newName); } else { ScriptShell scriptShellView = null; try { scriptShellView = (ScriptShell) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ScriptShell.VIEW_ID); } catch (final PartInitException e) { e.printStackTrace(); } scriptShellView.changePartName(newName); } }); }
Source:
public void onSlotClick(int slotId, int clickedButton, int mode, EntityPlayer player, CallbackInfoReturnable<net.minecraft.item.ItemStack> ci) { if (slotId >= inventorySlots.size()) { if (player instanceof EntityPlayerMP) { ((EntityPlayerMP) player).playerNetServerHandler .kickPlayerFromServer("You have been kicked for attempting to click an out of bounds slot."); ci.setReturnValue(null); ci.cancel(); } } }

Target:
public void onSlotClick(int slotId, int clickedButton, int mode, EntityPlayer player, CallbackInfoReturnable<net.minecraft.item.ItemStack> ci) { if (slotId >= inventorySlots.size()) { if (player instanceof EntityPlayerMP) { ((EntityPlayerMP) player).playerNetServerHandler .kickPlayerFromServer("You have been kicked for attempting to click an out of bounds slot."); ci.setReturnValue(null); } } }
Source:
public DirectPipelineWriter(long destConglomerate, TxnView txn, byte[] token, OperationContext opCtx, boolean skipIndex, String tableVersion){ this.destConglomerate=destConglomerate; this.txn=txn; this.token=token; this.opCtx=opCtx; this.skipIndex=skipIndex; }

Target:
public DirectPipelineWriter(long destConglomerate, TxnView txn, byte[] token, OperationContext opCtx, boolean skipIndex, String tableVersion){ this.destConglomerate=destConglomerate; this.txn=txn; this.token=token; this.opCtx=opCtx; this.skipIndex=skipIndex; this.tableVersion = tableVersion; }
Source:
public NetworkInstance loadNetwork(ClaudiaData claudiaData, NetworkInstance network, String region) throws EntityNotFoundException { if (network.getIdNetwork() == null ) { String netId = getNetworkId (claudiaData, network, region); if (netId == null) { String msm = "Error to obtain the network infromation " + network.getNetworkName(); log.error(msm); throw new EntityNotFoundException(Network.class, msm, new Exception()); } network.setIdNetwork(netId); } log.debug("Load network " + network.getIdNetwork() + " in region " + region + " vdc " + claudiaData.getVdc()); String response = ""; try { String token = claudiaData.getUser().getToken(); String vdc = claudiaData.getVdc(); response = openStackUtil.getNetworkDetails(network.getIdNetwork(), region, token, vdc); JSONObject jsonNet = new JSONObject(response); JSONObject aux =(JSONObject)jsonNet.get("network"); NetworkInstance netInst = NetworkInstance.fromJson(aux, region); JSONArray jsonSubNetworks = aux.getJSONArray("subnets"); for (int i = 0; i < jsonSubNetworks.length(); i++) { SubNetworkInstance subNet = loadSubNetwork(claudiaData, jsonSubNetworks.getString (i), region); subNet.setIdNetwork(network.getIdNetwork()); netInst.addSubNet(subNet); } return netInst; } catch (OpenStackException e) { String msm = "Error to obtain the network information " + network.getNetworkName() + ":" + e.getMessage(); log.error(msm); throw new EntityNotFoundException(Network.class, msm, e); } catch (JSONException e) { String msm = "Error to obtain the network instance from json " + network.getNetworkName() + ":" + e.getMessage(); log.error(msm); } return network; }

Target:
public NetworkInstance loadNetwork(ClaudiaData claudiaData, NetworkInstance network, String region) throws EntityNotFoundException { String message="Error loading the network: "; if (network.getIdNetwork() == null ) { String netId = getNetworkId (claudiaData, network, region); if (netId == null) { String msm = message + network.getNetworkName(); log.error(msm); throw new EntityNotFoundException(Network.class, msm, new Exception()); } network.setIdNetwork(netId); } log.debug("Load network " + network.getIdNetwork() + " in region " + region + " vdc " + claudiaData.getVdc()); String response = ""; try { String token = claudiaData.getUser().getToken(); String vdc = claudiaData.getVdc(); response = openStackUtil.getNetworkDetails(network.getIdNetwork(), region, token, vdc); JSONObject jsonNet = new JSONObject(response); JSONObject aux =(JSONObject)jsonNet.get("network"); NetworkInstance netInst = NetworkInstance.fromJson(aux, region); JSONArray jsonSubNetworks = aux.getJSONArray("subnets"); for (int i = 0; i < jsonSubNetworks.length(); i++) { SubNetworkInstance subNet = loadSubNetwork(claudiaData, jsonSubNetworks.getString (i), region); subNet.setIdNetwork(network.getIdNetwork()); netInst.addSubNet(subNet); } return netInst; } catch (OpenStackException e) { String msm = message + network.getNetworkName() + ":" + e.getMessage(); log.error(msm); throw new EntityNotFoundException(Network.class, msm, e); } catch (JSONException e) { String msm = message + network.getNetworkName() + ":" + e.getMessage(); log.error(msm); } return network; }
Source:
public void init() { if (org.bridj.Platform.isWindows() && WindowsUtil.isAdmin()) { CountDownLatch waitForUserInput = new CountDownLatch(1); Platform.runLater(() -> { Alert alert = new Alert(AlertType.WARNING, "Please don't run the client as admin. Because if you do you might need to delete C:\\ProgramData\\FAForever to be able to run it as a normal user again. Do you want to ignore the warning and continue?", ButtonType.YES, ButtonType.NO); Optional<ButtonType> buttonType = alert.showAndWait(); if (!buttonType.isPresent() || (buttonType.get() == ButtonType.NO)) { System.exit(EXIT_STATUS_RAN_AS_ADMIN); } waitForUserInput.countDown(); }); noCatch((NoCatchRunnable) waitForUserInput::await); } Font.loadFont(FafClientApplication.class.getResourceAsStream("/font/dfc-icons.ttf"), 10); JavaFxUtil.fixTooltipDuration(); applicationContext = new SpringApplicationBuilder(FafClientApplication.class, ForgedAlliancePrefs.class) .profiles(getAdditionalProfiles()) .bannerMode(Mode.OFF) .run(getParameters().getRaw().toArray(new String[0])); }

Target:
public void init() { if (org.bridj.Platform.isWindows() && WindowsUtil.isAdmin()) { CountDownLatch waitForUserInput = new CountDownLatch(1); Platform.runLater(() -> { Alert alert = new Alert(AlertType.WARNING, "Please don't run the client as admin. Because if you do you might need to delete C:\\ProgramData\\FAForever to be able to run it as a normal user again. Do you want to ignore the warning and continue?", ButtonType.YES, ButtonType.NO); Optional<ButtonType> buttonType = alert.showAndWait(); if (!buttonType.isPresent() || (buttonType.get() == ButtonType.NO)) { System.exit(EXIT_STATUS_RAN_AS_ADMIN); } waitForUserInput.countDown(); }); noCatch((NoCatchRunnable) waitForUserInput::await); } Font.loadFont(FafClientApplication.class.getResourceAsStream("/font/dfc-icons.ttf"), 10); JavaFxUtil.fixTooltipDuration(); applicationContext = new SpringApplicationBuilder(FafClientApplication.class) .profiles(getAdditionalProfiles()) .bannerMode(Mode.OFF) .run(getParameters().getRaw().toArray(new String[0])); }
Source:
public final Object getData(String sessionId, String key, boolean refresh) { Date now = new Date(); SessionInfo sessionInfo = getSessionInfo(sessionId); Object value = null; if (sessionInfo != null) { if (refresh) { synchronized (sessionInfo) { Date softLimit = (Date) sessionInfo.sessionMap.get(SOFT_LIMIT_PARAMETER_NAME); if (softLimit == null) { softLimit = now; } softLimit = DateUtils.addMinutes(softLimit, 2 * Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval)); sessionInfo.sessionMap.put(SOFT_LIMIT_PARAMETER_NAME, softLimit); } } value = sessionInfo.sessionMap.get(key); } return value; }

Target:
public final Object getData(String sessionId, String key, boolean refresh) { Date now = new Date(); SessionInfo sessionInfo = getSessionInfo(sessionId); Object value = null; if (sessionInfo != null) { if (refresh) { synchronized (sessionInfo) { Date softLimit = (Date) sessionInfo.contentOfSession.get(SOFT_LIMIT_PARAMETER_NAME); if (softLimit == null) { softLimit = now; } softLimit = DateUtils.addMinutes(softLimit, Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval)); sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, softLimit); } } value = sessionInfo.contentOfSession.get(key); } return value; }
Source:
public void testGetPrivateKeyAsHex() throws Exception { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); assertEquals("a", key.getPrivateKeyAsHex()); }

Target:
public void testGetPrivateKeyAsHex() throws Exception { ECKey key = ECKey.fromPrivate(BigInteger.TEN).decompress(); assertEquals("000000000000000000000000000000000000000000000000000000000000000a", key.getPrivateKeyAsHex()); }