auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<String, String> unwrap(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { ModelNode modelProps = model.get(getName()); return unwrapModel(context, modelProps); }

Target:
public Map<String, String> unwrap(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { if (!model.hasDefined(getName())){ return Collections.emptyMap(); } ModelNode modelProps = model.get(getName()); return unwrapModel(context, modelProps); }
Source:
public URI visit(AstLocationExpression value, ELContext environment) throws Exception { Object location; try { synchronized (environment) { ValueExpression expression = value.getValue(); location = expression.getValue(environment); } } catch (javax.el.PropertyNotFoundException e) { LOGGER.warn(e.getMessage()); location = null; } if (location == null) { throw new NullPointerException("Location expression result is null"); } return (URI) location; }

Target:
public URI visit(AstLocationExpression value, ELContext environment) throws Exception { Object location; try { synchronized (environment) { ValueExpression expression = value.getValue(); location = expression.getValue(environment); } } catch (PropertyNotFoundException e) { LOGGER.warn(e.getMessage(), e); location = null; } if (location == null) { throw new NullPointerException("Location expression result is null"); } return (URI) location; }
Source:
public void testRebaseInteractiveSquashFirstCommitShouldFail() throws Exception { writeTrashFile(FILE1, FILE1); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("Add file1\nnew line").call(); assertTrue(new File(db.getWorkTree(), FILE1).exists()); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("Add file2\nnew line").call(); assertTrue(new File(db.getWorkTree(), "file2").exists()); git.rebase().setUpstream("HEAD~1") .runInteractively(new InteractiveHandler() { public void prepareSteps(List<RebaseTodoLine> steps) { steps.get(0).setAction(Action.SQUASH); } public String modifyCommitMessage(String commit) { fail("No callback to modify commit message expected for single fixup"); return commit; } }).call(); }

Target:
public void testRebaseInteractiveSquashFirstCommitShouldFail() throws Exception { writeTrashFile(FILE1, FILE1); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("Add file1\nnew line").call(); assertTrue(new File(db.getWorkTree(), FILE1).exists()); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("Add file2\nnew line").call(); assertTrue(new File(db.getWorkTree(), "file2").exists()); git.rebase().setUpstream("HEAD~1") .runInteractively(new InteractiveHandler() { public void prepareSteps(List<RebaseTodoLine> steps) { steps.get(0).setAction(Action.SQUASH); } public String modifyCommitMessage(String commit) { return commit; } }).call(); }
Source:
protected void addClassPathEntries() throws MalformedURLException { String internalLib = System.getProperty("carbon.internal.lib.dir.path"); if (internalLib == null) { addFileUrl(new File(ROOT + File.separator + "lib" + File.separator)); addJarFileUrls(new File(ROOT + File.separator + "lib")); } else { addFileUrl(new File(internalLib + File.separator)); addJarFileUrls(new File(internalLib)); } }

Target:
protected void addClassPathEntries() throws MalformedURLException { String internalLib = System.getProperty(INTERNAL_CARBON_LIB_DIR_PATH); if (internalLib == null) { File libFile = Paths.get(ROOT, "lib").toFile(); addFileUrl(libFile); addJarFileUrls(libFile); } else { addFileUrl(new File(internalLib)); addJarFileUrls(new File(internalLib)); } }
Source:
private List<WorkerSlot> toSlots(Offer offer, double cpu, double mem, boolean supervisorExists) { double executorCpuDemand = supervisorExists ? 0 : MesosCommon.executorCpu(_conf); double executorMemDemand = supervisorExists ? 0 : MesosCommon.executorMem(_conf); OfferResources resources = getResources( offer, executorCpuDemand, executorMemDemand, cpu, mem); List<WorkerSlot> ret = new ArrayList<WorkerSlot>(); int availableSlots = Math.min(resources.cpuSlots, resources.memSlots); availableSlots = Math.min(availableSlots, resources.ports.size() - 1); for (int i = 0; i < availableSlots; i++) { ret.add(new WorkerSlot(offer.getHostname(), resources.ports.get(i))); } return ret; }

Target:
private List<WorkerSlot> toSlots(Offer offer, double cpu, double mem, boolean supervisorExists) { double executorCpuDemand = supervisorExists ? 0 : MesosCommon.executorCpu(_conf); double executorMemDemand = supervisorExists ? 0 : MesosCommon.executorMem(_conf); OfferResources resources = getResources( offer, executorCpuDemand, executorMemDemand, cpu, mem); List<WorkerSlot> ret = new ArrayList<WorkerSlot>(); int availableSlots = Math.min(resources.cpuSlots, resources.memSlots); availableSlots = Math.min(availableSlots, resources.ports.size()); for (int i = 0; i < availableSlots; i++) { ret.add(new WorkerSlot(offer.getHostname(), resources.ports.get(i))); } return ret; }
Source:
public ParseQuery<T> whereContainsAllStartsWith(String key, Collection<String> values) { checkIfRunning(); ArrayList<Pattern> regexValues = new ArrayList<>(); for (String value : values) { regexValues.add(Pattern.compile(buildStartsWithRegex(value))); } return whereContainsAll(key, regexValues); }

Target:
public ParseQuery<T> whereContainsAllStartsWith(String key, Collection<String> values) { ArrayList<KeyConstraints> startsWithConstraints = new ArrayList<>(); for (String value : values) { KeyConstraints keyConstraints = new KeyConstraints(); keyConstraints.put("$regex", buildStartsWithRegex(value)); startsWithConstraints.add(keyConstraints); } return whereContainsAll(key, startsWithConstraints); }
Source:
private ITokenCacheStore wrapCache(@NonNull final ITokenCacheStore originalCache) { return new ITokenCacheStore() { @Override public TokenCacheItem getItem(final String key) { return originalCache.getItem(key); } @Override public Iterator<TokenCacheItem> getAll() { return originalCache.getAll(); } @Override public boolean contains(final String key) { return originalCache.contains(key); } @Override public void setItem(final String key, final TokenCacheItem item) { originalCache.setItem(key, item); } @Override public void removeItem(final String key) { originalCache.removeItem(key); } @Override public void removeAll() { originalCache.removeAll(); getMsalOAuth2TokenCache(mContext).clearAll(); } }; }

Target:
private ITokenCacheStore wrapCache(@NonNull final ITokenCacheStore originalCache) { return new ITokenCacheStore() { @Override public synchronized TokenCacheItem getItem(final String key) { return originalCache.getItem(key); } @Override public synchronized Iterator<TokenCacheItem> getAll() { return originalCache.getAll(); } @Override public synchronized boolean contains(final String key) { return originalCache.contains(key); } @Override public synchronized void setItem(final String key, final TokenCacheItem item) { originalCache.setItem(key, item); } @Override public synchronized void removeItem(final String key) { originalCache.removeItem(key); } @Override public synchronized void removeAll() { originalCache.removeAll(); getMsalOAuth2TokenCache(mContext).clearAll(); } }; }
Source:
private void setCloudEnabled(boolean enabled) { _record.setBooleanField(CloudConfigProperty.CLOUD_ENABLED.name(), enabled); }

Target:
public void setCloudEnabled(boolean enabled) { _record.setBooleanField(CloudConfigProperty.CLOUD_ENABLED.name(), enabled); }
Source:
public String getDiscriminatingValue(ILoggingEvent o) { return Thread.currentThread().getName().equals(PERSISTENCE_THREAD) ? "jclouds-persister" : "jclouds"; }

Target:
public String getDiscriminatingValue(ILoggingEvent o) { return Thread.currentThread().getName().startsWith(PERSISTENCE_THREAD) ? "persistence" : "jclouds"; }
Source:
private I_C_Order createOrder() { final I_C_Order order = newInstance(I_C_Order.class); order.setIsSOTrx(true); order.setC_BPartner_ID(createPartner("Partner 3").getC_BPartner_ID()); order.setAD_User_ID(createUser("User 3").getAD_User_ID()); order.setDatePromised(de.metas.common.util.time.SystemTime.asDayTimestamp()); order.setC_DocTypeTarget_ID(createDocType().getC_DocType_ID()); save(order); return order; }

Target:
private I_C_Order createOrder() { final I_C_Order order = newInstance(I_C_Order.class); order.setIsSOTrx(true); order.setC_BPartner_ID(createPartner("Partner 3").getC_BPartner_ID()); order.setAD_User_ID(createUser("User 3").getAD_User_ID()); order.setDatePromised(de.metas.common.util.time.SystemTime.asDayTimestamp()); order.setC_DocType_ID(createDocType().getC_DocType_ID()); save(order); return order; }
Source:
public boolean attach() { if (!attached) { attached = true; if (isLocalBeanStoreSyncNeeded() && !isAttributeLazyLoadingAllowed()) { for (BeanIdentifier id : beanStore) { ContextualInstance<?> instance = beanStore.get(id); String prefixedId = getNamingScheme().prefix(id); ContextLogger.LOG.updatingStoreWithContextualUnderId(instance, id); setAttribute(prefixedId, instance); } readAttributes(); } return true; } else { return false; } }

Target:
public boolean attach() { if (!attached) { attached = true; if (isLocalBeanStoreSyncNeeded()) { if (!beanStore.delegate().isEmpty()) { for (BeanIdentifier id : beanStore) { ContextualInstance<?> instance = beanStore.get(id); String prefixedId = getNamingScheme().prefix(id); ContextLogger.LOG.updatingStoreWithContextualUnderId(instance, id); setAttribute(prefixedId, instance); } } if (!isAttributeLazyFetchingEnabled()) { fetchUninitializedAttributes(); } } return true; } else { return false; } }
Source:
public Handler decorateHandler(Handler base, Class<?> sqlObjectType, Method method) { Handler handler = base; List<Class<? extends Annotation>> annotationTypes = Stream.of(method.getAnnotations()) .map(Annotation::annotationType) .filter(type -> type.isAnnotationPresent(SqlMethodDecoratingAnnotation.class)) .collect(toList()); Stream.of(method, sqlObjectType) .map(e -> e.getAnnotation(DecoratorOrder.class)) .filter(Objects::nonNull) .findFirst() .ifPresent(order -> { annotationTypes.sort(createDecoratorComparator(order).reversed()); }); List<HandlerDecorator> decorators = annotationTypes.stream() .map(type -> type.getAnnotation(SqlMethodDecoratingAnnotation.class)) .map(a -> buildDecorator(a.value())) .collect(toList()); for (HandlerDecorator decorator : decorators) { handler = decorator.decorateHandler(handler, sqlObjectType, method); } return handler; }

Target:
public Handler decorateHandler(Handler base, Class<?> sqlObjectType, Method method) { Handler handler = base; List<Class<? extends Annotation>> annotationTypes = Stream.of(method.getAnnotations()) .map(Annotation::annotationType) .filter(type -> type.isAnnotationPresent(SqlMethodDecoratingAnnotation.class)) .collect(toList()); Stream.of(method, sqlObjectType) .map(e -> e.getAnnotation(DecoratorOrder.class)) .filter(Objects::nonNull) .findFirst() .ifPresent(order -> annotationTypes.sort(createDecoratorComparator(order).reversed())); List<HandlerDecorator> decorators = annotationTypes.stream() .map(type -> type.getAnnotation(SqlMethodDecoratingAnnotation.class)) .map(a -> buildDecorator(a.value())) .collect(toList()); for (HandlerDecorator decorator : decorators) { handler = decorator.decorateHandler(handler, sqlObjectType, method); } return handler; }
Source:
private void callExecuteListener(Message message, long deliveryTag) throws Exception { boolean channelLocallyTransacted = isChannelLocallyTransacted(); try { executeListener(getChannel(), message); handleAck(deliveryTag, channelLocallyTransacted); } catch (ImmediateAcknowledgeAmqpException e) { if (this.logger.isDebugEnabled()) { this.logger.debug("User requested ack for failed delivery"); } handleAck(deliveryTag, channelLocallyTransacted); } catch (Exception e) { if (causeChainHasImmediateAcknowledgeAmqpException(e)) { if (this.logger.isDebugEnabled()) { this.logger.debug("User requested ack for failed delivery"); } } else { this.logger.error("Failed to invoke listener", e); if (this.transactionManager != null) { if (this.transactionAttribute.rollbackOn(e)) { rollback(deliveryTag, e); throw e; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("No rollback for " + e); } } } else { rollback(deliveryTag, e); } } } }

Target:
private void callExecuteListener(Message message, long deliveryTag) throws Exception { boolean channelLocallyTransacted = isChannelLocallyTransacted(); try { executeListener(getChannel(), message); handleAck(deliveryTag, channelLocallyTransacted); } catch (ImmediateAcknowledgeAmqpException e) { if (this.logger.isDebugEnabled()) { this.logger.debug("User requested ack for failed delivery: " + deliveryTag); } handleAck(deliveryTag, channelLocallyTransacted); } catch (Exception e) { if (causeChainHasImmediateAcknowledgeAmqpException(e)) { if (this.logger.isDebugEnabled()) { this.logger.debug("User requested ack for failed delivery: " + deliveryTag); } handleAck(deliveryTag, channelLocallyTransacted); } else { this.logger.error("Failed to invoke listener", e); if (this.transactionManager != null) { if (this.transactionAttribute.rollbackOn(e)) { throw e; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("No rollback for " + e); } } } else { rollback(deliveryTag, e); } } } }
Source:
public static String createConsumer (final String topic, final String group, final int minConsumersInGroup) { String consumerUuid = generateConsumerId(); LOG.info(format("create message stream by consumerid [%s] with groupid [%s]", consumerUuid, group)); final String consumerIdString = group + "_" + consumerUuid; ConsumerConnector connector = ConsumerConnector.getInstance(); connector.registerConsumer(consumerIdString, topic, minConsumersInGroup); return consumerIdString; }

Target:
public static String createConsumer (final String topic, final String group, final int minConsumersInGroup) { String consumerUuid = generateConsumerId(); LOG.info("create message stream by consumerid " + consumerUuid + " with groupid " + group); final String consumerIdString = group + "_" + consumerUuid; ConsumerConnector connector = ConsumerConnector.getInstance(); connector.registerConsumer(consumerIdString, topic, minConsumersInGroup); return consumerIdString; }
Source:
public StartIdentifiedAtlasDbTransactionResponse startIdentifiedAtlasDbTransaction( StartIdentifiedAtlasDbTransactionRequest request) { return timelockService(defaultClient, request.requestorId()) .startIdentifiedAtlasDbTransaction(ImmutableIdentifiedTimeLockRequest.of(request.requestId())); }

Target:
public StartIdentifiedAtlasDbTransactionResponse startIdentifiedAtlasDbTransaction( StartIdentifiedAtlasDbTransactionRequest request) { return rpcClient(defaultClient).startIdentifiedAtlasDbTransaction(request); }
Source:
void shutdown() throws InterruptedException, StoreException, IOException { if (running.get()) { running.set(false); boolean isPaused = isPaused(); if (isPaused) { reentrantLock.lock(); paused.set(false); pauseCondition.signal(); reentrantLock.unlock(); } else { synchronized (reentrantLock) { reentrantLock.notify(); } } throttler.close(); shutdownLatch.await(); if (isPaused) { paused.set(true); } pruneHardDeleteRecoveryRange(); persistCleanupToken(); } }

Target:
void shutdown() throws InterruptedException, StoreException, IOException { if (enabled.get()) { enabled.set(false); hardDeleteLock.lock(); try { pauseCondition.signal(); } finally { hardDeleteLock.unlock(); } throttler.close(); shutdownLatch.await(); pruneHardDeleteRecoveryRange(); persistCleanupToken(); } }
Source:
public void startup() throws Exception { super.startup(); client.startup(); JsonObject properties = readTrackingFile(); if (properties != null && properties.getString(NATSClient.SERVER_HOST_PROPERTY) == client.getServerHost() && properties.getString(NATSClient.SERVER_PORT_PROPERTY) == client.getServerPort() && properties.getString(NATSClient.CLUSTER_ID_PROPERTY) == client.getClusterId() && properties.getString(NATSClient.CLIENT_ID_PROPERTY) == client.getClientId() && properties.getString(NATSClient.SUBJECT_PROPERTY) == client.getSubject()) { sequence = Long.parseLong(properties.getString(SEQUENCE_PROPERTY)); } subscription = client.getConnection().subscribe( client.getSubject(), this, new SubscriptionOptions.Builder().startAtSequence(sequence).build()); }

Target:
public void startup() throws Exception { super.startup(); client.startup(); JsonObject properties = readTrackingFile(); if (properties != null && properties.getString(NATSClient.SERVER_HOST_PROPERTY).equals(client.getServerHost()) && properties.getString(NATSClient.SERVER_PORT_PROPERTY).equals(client.getServerPort()) && properties.getString(NATSClient.CLUSTER_ID_PROPERTY).equals(client.getClusterId()) && properties.getString(NATSClient.CLIENT_ID_PROPERTY).equals(client.getClientId()) && properties.getString(NATSClient.SUBJECT_PROPERTY).equals(subject)) { sequence = Long.parseLong(properties.get(SEQUENCE_PROPERTY).toString()); } subscription = client.getConnection().subscribe( subject, this, new SubscriptionOptions.Builder().startAtSequence(sequence).build()); }
Source:
public static Optional<WifiInfo> createWifiInfofromDynamoDBItem(final Map<String, AttributeValue> item, final String senseId) { if (item == null) { LOGGER.warn("Sense does not have wifi info", senseId); return Optional.absent(); } final Set<String> requiredAttributes = Sets.newHashSet(SSID_ATTRIBUTE_NAME, RSSI_ATTRIBUTE_NAME); final Set<String> itemAttributes = item.keySet(); if (!itemAttributes.containsAll(requiredAttributes)) { return Optional.absent(); } final Long lastUpdated = item.containsKey(LAST_UPDATED_ATTRIBUTE_NAME) ? Long.valueOf(item.get(LAST_UPDATED_ATTRIBUTE_NAME).getN()) : 0L; return Optional.of(WifiInfo.create( item.get(SENSE_ATTRIBUTE_NAME).getS(), item.get(SSID_ATTRIBUTE_NAME).getS(), Integer.valueOf(item.get(RSSI_ATTRIBUTE_NAME).getN()), lastUpdated) ); }

Target:
public static Optional<WifiInfo> createWifiInfofromDynamoDBItem(final Map<String, AttributeValue> item, final String senseId) { if (item == null) { LOGGER.warn("Sense does not have wifi info", senseId); return Optional.absent(); } final Set<String> requiredAttributes = Sets.newHashSet(SSID_ATTRIBUTE_NAME, RSSI_ATTRIBUTE_NAME); final Set<String> itemAttributes = item.keySet(); if (!itemAttributes.containsAll(requiredAttributes)) { return Optional.absent(); } final DateTime lastUpdated = item.containsKey(LAST_UPDATED_ATTRIBUTE_NAME) ? DateTime.parse(item.get(LAST_UPDATED_ATTRIBUTE_NAME).getS(), DateTimeFormat.forPattern(DateTimeUtil.DYNAMO_DB_DATETIME_FORMAT)) : DateTime.now(DateTimeZone.UTC); return Optional.of(WifiInfo.create( item.get(SENSE_ATTRIBUTE_NAME).getS(), item.get(SSID_ATTRIBUTE_NAME).getS(), Integer.valueOf(item.get(RSSI_ATTRIBUTE_NAME).getN()), lastUpdated) ); }
Source:
public QueryBuilder fromBranch(long branchUuid) throws OseeCoreException { return fromBranch(TokenFactory.createBranch(branchUuid, String.format("uuid:[%s] name:[N/A] - %s:%s", branchUuid, getClass().getSimpleName(), "fromBranch"))); }

Target:
public QueryBuilder fromBranch(long branchUuid) throws OseeCoreException { String name = String.format("uuid:[%s] name:[N/A] - %s.fromBranch(long)", branchUuid, getClass().getSimpleName()); IOseeBranch branch = TokenFactory.createBranch(branchUuid, name); return fromBranch(branch); }
Source:
public void onExit() { uncommittedOffsets = offsets.entrySet().stream() .filter(e -> !e.getValue().isCommitted()) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSentOffset())); if (null != topologyChangeSubscription) { try { topologyChangeSubscription.cancel(); } catch (final RuntimeException ex) { getLog().warn("Failed to cancel topology subscription", ex); } finally { topologyChangeSubscription = null; new HashSet<>(offsets.keySet()).forEach(this::removeFromStreaming); } } if (null != kafkaConsumer) { try { kafkaConsumer.close(); } finally { kafkaConsumer = null; } } getLog().debug("Unregister cursor reset listener"); if (cursorResetSubscription != null) { cursorResetSubscription.cancel(); cursorResetSubscription = null; } }

Target:
public void onExit() { uncommittedOffsets = offsets.entrySet().stream() .filter(e -> !e.getValue().isCommitted()) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getSentOffset())); if (null != topologyChangeSubscription) { try { topologyChangeSubscription.cancel(); } catch (final RuntimeException ex) { getLog().warn("Failed to cancel topology subscription", ex); } finally { topologyChangeSubscription = null; new HashSet<>(offsets.keySet()).forEach(this::removeFromStreaming); } } if (null != kafkaConsumer) { try { kafkaConsumer.close(); } finally { kafkaConsumer = null; } } if (cursorResetSubscription != null) { cursorResetSubscription.cancel(); cursorResetSubscription = null; } }
Source:
private static FacesMessage msgForSelectDelete(String ofType) { return HelperUtil.getMsgWarn(MessageFormat.format("Select a {0} for delete.", ofType.toLowerCase())); }

Target:
private static FacesMessage msgForSelectDelete(String ofType) { return HelperUtil.getMsgWarn(MessageFormat.format("Select {0} for delete.", ofType.toLowerCase())); }
Source:
private void remove( final Collection<Unit> killedUnits, final IDelegateBridge bridge, final Territory battleSite) { if (killedUnits.isEmpty()) { return; } final Collection<Unit> killed = getUnitsWithDependents(killedUnits); final KillUnits killUnits = new KillUnits(battleSite, killed); killUnits.perform(bridge); final Collection<IBattle> dependentBattles = battleTracker.getBlocked(AirBattle.this); removeFromDependents(killed, bridge, dependentBattles, false); }

Target:
private void remove( final Collection<Unit> killedUnits, final IDelegateBridge bridge, final Territory battleSite) { if (killedUnits.isEmpty()) { return; } final Collection<Unit> killed = getUnitsWithDependents(killedUnits); final RemoveUnitsHistoryChange removeUnitsHistoryChange = HistoryChangeFactory.removeUnitsFromTerritory(battleSite, killed); removeUnitsHistoryChange.perform(bridge); final Collection<IBattle> dependentBattles = battleTracker.getBlocked(AirBattle.this); removeFromDependents(killed, bridge, dependentBattles, false); }
Source:
public static String getLastKnownCczLocation() { return CommCareApplication.instance().getCurrentApp().getAppPreferences() .getString(LAST_KNOWN_CCZ_LOCATION, null); }

Target:
public static String getLastKnownCczLocation() { return PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance()) .getString(LAST_KNOWN_CCZ_LOCATION, null); }
Source:
public SQLDatabaseQueue(final File file, KeyProvider provider) throws IOException, SQLException { queue = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "SQLDatabaseQueue - "+ file); } }); this.db = SQLDatabaseFactory.openOrCreateSQLDatabase(file, provider); queue.submit(new Runnable() { @Override public void run() { db.open(); } }); }

Target:
public SQLDatabaseQueue(final File file, KeyProvider provider) throws IOException, SQLException { queue = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "SQLDatabaseQueue - "+ file); } }); this.db = SQLDatabaseFactory.openSQLDatabase(file, provider); queue.submit(new Runnable() { @Override public void run() { db.open(); } }); }
Source:
public void addListener(Runnable listener, Executor executor) { if (!isDone() && hasListeners.compareAndSet(false, true)) { refreshListeners.put(this, true); } super.addListener(listener, executor); }

Target:
public void addListener(Runnable listener, Executor executor) { if (!isDone()) { notDoneNrtFutures.add(this); } super.addListener(listener, executor); }
Source:
public Link assertHasLinkWithRel(String rel, MockHttpServletResponse response) throws Exception { String content = response.getContentAsString(); Link link = getDiscoverer(response).findLinkWithRel(rel, content); assertThat("Expected to find link with rel " + rel + " but found none in " + content + "!", link, is(notNullValue())); return link; }

Target:
public Link assertHasLinkWithRel(String rel, MockHttpServletResponse response) throws Exception { String content = response.getContentAsString(); Link link = getDiscoverer(response).findLinkWithRel(rel, content); assertThat(link) .describedAs("Expected to find link with rel " + rel + " but found none in " + content + "!") .isNotNull(); return link; }
Source:
public void uniqueValues(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String workspace = request.getParameter("workspace"); String layer = request.getParameter("layer"); String propertyName = request.getParameter("propertyName"); if(workspace==null) { workspace = splitLayerName(layer)[0]; layer = splitLayerName(layer)[1]; } if (! uniqueValuesAllowed(workspace, layer, propertyName)) { throw new RuntimeException(String.format("uniqueValues not allowed for '%s:%s/%s'", workspace, layer, propertyName)); } try { respondWithDocument(response, getUniqueValuesDocument(workspace, layer, propertyName)); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void uniqueValues(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String workspace = request.getParameter("workspace"); String layer = request.getParameter("layer"); String propertyName = request.getParameter("propertyName"); if(workspace==null) { String[] splitLayerArray = splitLayerName(layer); workspace = splitLayerArray[0]; layer = splitLayerArray[1]; } if (! uniqueValuesAllowed(workspace, layer, propertyName)) { throw new RuntimeException(String.format("uniqueValues not allowed for '%s:%s/%s'", workspace, layer, propertyName)); } try { respondWithDocument(response, getUniqueValuesDocument(workspace, layer, propertyName)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public static void rateApp(Context context) { final String appPackageName = BuildConfig.class.getPackage().getName(); try { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Urls.PLAY_STORE_PREFIX + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { handleWebUrl(context, Uri.parse(Urls.PLAY_STORE_URL_PREFIX + appPackageName)); } }

Target:
public static void rateApp(Context context) { final String appPackageName = context.getPackageName(); try { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Urls.PLAY_STORE_PREFIX + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { handleWebUrl(context, Uri.parse(Urls.PLAY_STORE_URL_PREFIX + appPackageName)); } }
Source:
public Iterator<Bucket> iterator() { final int bucketCount = getBucketCount(); final double min = getMin(); final double max = getMax(); return new Iterator<Bucket>() { private int currentIndex; @Override public boolean hasNext() { return currentIndex < bucketCount; } @Override public Bucket next() { if (!hasNext()) { throw new NoSuchElementException(); } final Bucket value = new Bucket( getLeftValueForIndex(bucketCount, min, max, currentIndex), getRightValueForIndex(bucketCount, min, max, currentIndex), weights[currentIndex]); ++currentIndex; return value; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }

Target:
public Iterator<Bucket> iterator() { int bucketCount = getBucketCount(); double min = getMin(); double max = getMax(); return new Iterator<Bucket>() { private int currentIndex; @Override public boolean hasNext() { return currentIndex < bucketCount; } @Override public Bucket next() { if (!hasNext()) { throw new NoSuchElementException(); } Bucket value = new Bucket( getLeftValueForIndex(bucketCount, min, max, currentIndex), getRightValueForIndex(bucketCount, min, max, currentIndex), weights[currentIndex]); currentIndex++; return value; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
public boolean shouldUseBitmapIndex(BitmapIndexSelector selector) { return Filters.shouldUseBitmapIndex(this, selector, filterTuning); }

Target:
public boolean shouldUseBitmapIndex(BitmapIndexSelector selector) { return false; }
Source:
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata, GenericFutureListener<ChannelFuture> listener) { long writeProcessingStartTime = System.currentTimeMillis(); boolean writtenThisTime = false; if (responseMetadataWriteInitiated.compareAndSet(false, true) && ctx.channel().isActive()) { if (!HttpUtil.isContentLengthSet(responseMetadata) && (responseMetadata.status().equals(HttpResponseStatus.OK) || responseMetadata.status().equals(HttpResponseStatus.PARTIAL_CONTENT))) { HttpUtil.setTransferEncodingChunked(responseMetadata, true); } else if (HttpUtil.isContentLengthSet(responseMetadata) && HttpUtil.getContentLength(responseMetadata) == 0 && !(responseMetadata instanceof FullHttpResponse)) { FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseMetadata.status()); fullHttpResponse.headers().set(responseMetadata.headers()); responseMetadata = fullHttpResponse; } logger.info("Sending response with status on channel {}", responseMetadata.status(), ctx.channel()); finalResponseMetadata = responseMetadata; ChannelPromise writePromise = ctx.newPromise().addListener(listener); ctx.writeAndFlush(responseMetadata, writePromise); writtenThisTime = true; long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime; nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime); if (request != null) { request.getMetricsTracker().nioMetricsTracker.markFirstByteSent(); } } return writtenThisTime; }

Target:
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata, GenericFutureListener<ChannelFuture> listener) { long writeProcessingStartTime = System.currentTimeMillis(); boolean writtenThisTime = false; if (responseMetadataWriteInitiated.compareAndSet(false, true) && ctx.channel().isActive()) { if (!HttpUtil.isContentLengthSet(responseMetadata) && (responseMetadata.status().equals(HttpResponseStatus.OK) || responseMetadata.status().equals(HttpResponseStatus.PARTIAL_CONTENT))) { HttpUtil.setTransferEncodingChunked(responseMetadata, true); } else if (HttpUtil.isContentLengthSet(responseMetadata) && HttpUtil.getContentLength(responseMetadata) == 0 && !(responseMetadata instanceof FullHttpResponse)) { FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseMetadata.status()); fullHttpResponse.headers().set(responseMetadata.headers()); responseMetadata = fullHttpResponse; } logger.trace("Sending response with status on channel {}", responseMetadata.status(), ctx.channel()); finalResponseMetadata = responseMetadata; ChannelPromise writePromise = ctx.newPromise().addListener(listener); ctx.writeAndFlush(responseMetadata, writePromise); writtenThisTime = true; long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime; nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime); if (request != null) { request.getMetricsTracker().nioMetricsTracker.markFirstByteSent(); } } return writtenThisTime; }
Source:
public void testScaleDownInvalidScaleFactor() throws Exception { topologyConfig.setComponentRam(BOLT_NAME, instanceDefaultResources.getRam()); topologyConfig.setComponentRam(SPOUT_NAME, instanceDefaultResources.getRam()); PackingPlan packingPlan = getFirstFitDecreasingPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), 2); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); AssertPacking.assertNumInstances(packingPlan.getContainers(), BOLT_NAME, 3); AssertPacking.assertNumInstances(packingPlan.getContainers(), SPOUT_NAME, 4); int spoutScalingDown = -5; Map<String, Integer> componentChanges = new HashMap<>(); componentChanges.put(SPOUT_NAME, spoutScalingDown); getFirstFitDecreasingPackingPlanRepack(topology, packingPlan, componentChanges); }

Target:
public void testScaleDownInvalidScaleFactor() throws Exception { int spoutScalingDown = -5; Map<String, Integer> componentChanges = new HashMap<>(); componentChanges.put(SPOUT_NAME, spoutScalingDown); int numContainersBeforeRepack = 2; doDefaultScalingTest(componentChanges, numContainersBeforeRepack); }
Source:
public void subscribeTo(final InternalChannel channel, final ChannelEventListener listener, final String... eventNames) { synchronized (channelNameToChannelMap){ validateArgumentsAndBindEvents(channel, listener, eventNames); channelNameToChannelMap.put(channel.getName(), channel); sendOrQueueSubscribeMessage(channel); } }

Target:
public void subscribeTo(final InternalChannel channel, final ChannelEventListener listener, final String... eventNames) { validateArgumentsAndBindEvents(channel, listener, eventNames); channelNameToChannelMap.put(channel.getName(), channel); sendOrQueueSubscribeMessage(channel); }
Source:
private static void setBondingOptions(VDS vds, List<VdsNetworkInterface> oldInterfaces) { oldInterfaces.stream(). filter(iface -> iface.getBondOptions() != null). forEach(iface -> vds.getInterfaces() .stream() .filter(newIface -> iface.getName().equals(newIface.getName()) && newIface.getBondOptions() == null) .findFirst() .ifPresent(newIface -> newIface.setBondOptions(iface.getBondOptions()))); }

Target:
private static void setBondingOptions(VDS vds, List<VdsNetworkInterface> oldInterfaces) { oldInterfaces.stream(). filter(iface -> iface.getBondOptions() != null). forEach(iface -> vds.getInterfaces() .stream() .filter(newIface -> iface.getName().equals(newIface.getName())) .filter(newIface -> newIface.getBondOptions() == null) .findFirst() .ifPresent(newIface -> newIface.setBondOptions(iface.getBondOptions()))); }
Source:
public boolean onPreferenceChange(Preference preference, Object objValue) { if (preference == mButtonPreferredNetworkMode) { mButtonPreferredNetworkMode.setValue((String) objValue); int buttonNetworkMode; buttonNetworkMode = Integer.valueOf((String) objValue).intValue(); int settingsNetworkMode = android.provider.Settings.System.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.System.PREFERRED_NETWORK_MODE, preferredNetworkMode); if (buttonNetworkMode != settingsNetworkMode) { int modemNetworkMode; switch(buttonNetworkMode) { case RILConstants.NETWORK_MODE_GSM_UMTS: modemNetworkMode = RILConstants.NETWORK_MODE_GSM_UMTS; break; case RILConstants.NETWORK_MODE_CDMA: modemNetworkMode = RILConstants.NETWORK_MODE_CDMA; break; case RILConstants.NETWORK_MODE_GLOBAL: modemNetworkMode = RILConstants.NETWORK_MODE_GLOBAL; break; default: modemNetworkMode = RILConstants.PREFERRED_NETWORK_MODE; } UpdatePreferredNetworkModeSummary(buttonNetworkMode); android.provider.Settings.System.putInt(mPhone.getContext().getContentResolver(), android.provider.Settings.System.PREFERRED_NETWORK_MODE, buttonNetworkMode ); mPhone.setPreferredNetworkType(modemNetworkMode, mHandler .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE)); } } return true; }

Target:
public boolean onPreferenceChange(Preference preference, Object objValue) { if (preference == mButtonPreferredNetworkMode) { mButtonPreferredNetworkMode.setValue((String) objValue); int buttonNetworkMode; buttonNetworkMode = Integer.valueOf((String) objValue).intValue(); int settingsNetworkMode = android.provider.Settings.System.getInt( mPhone.getContext().getContentResolver(), android.provider.Settings.System.PREFERRED_NETWORK_MODE, preferredNetworkMode); if (buttonNetworkMode != settingsNetworkMode) { int modemNetworkMode; switch(buttonNetworkMode) { case Phone.NT_MODE_GSM_UMTS: modemNetworkMode = Phone.NT_MODE_GSM_UMTS; break; case Phone.NT_MODE_CDMA: modemNetworkMode = Phone.NT_MODE_CDMA; break; case Phone.NT_MODE_GLOBAL: modemNetworkMode = Phone.NT_MODE_GLOBAL; break; default: modemNetworkMode = Phone.PREFERRED_NT_MODE; } UpdatePreferredNetworkModeSummary(buttonNetworkMode); android.provider.Settings.System.putInt(mPhone.getContext().getContentResolver(), android.provider.Settings.System.PREFERRED_NETWORK_MODE, buttonNetworkMode ); mPhone.setPreferredNetworkType(modemNetworkMode, mHandler .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE)); } } return true; }
Source:
private String createJsonStringEntity(Object data) { String entity; if (data instanceof String && isJson(data.toString())) { entity = data.toString(); } else { entity = gson.toJson(data); } JsonElement el = new JsonParser().parse(entity); log.debug("request body to json - " + System.getProperty("line.separator") + new GsonBuilder().setPrettyPrinting().create().toJson(el)); return entity; }

Target:
protected String createJsonStringEntity(Object data) { String entity; if (data instanceof String && isJson(data.toString())) { entity = data.toString(); } else { entity = gson.toJson(data); } log.debug("request body - "+ entity); return entity; }
Source:
public TestRunner addInputStream(CollectionStream stream) { Preconditions.checkNotNull(stream); Preconditions.checkNotNull(stream.getCollectionStreamSystem()); CollectionStreamSystem system = stream.getCollectionStreamSystem(); registerSystem(system); system.addInput(stream.getStreamName(), stream.getInitPartitions()); if (configs.containsKey(TaskConfig.INPUT_STREAMS())) { configs.put(TaskConfig.INPUT_STREAMS(), configs.get(TaskConfig.INPUT_STREAMS()).concat("," + system.getSystemName() + "." + stream.getStreamName())); } else { configs.put(TaskConfig.INPUT_STREAMS(), system.getSystemName() + "." + stream.getStreamName()); } stream.getStreamConfig().forEach((key, val) -> { configs.putIfAbsent((String) key, (String) val); }); return this; }

Target:
public TestRunner addInputStream(CollectionStream stream) { Preconditions.checkNotNull(stream); registerSystem(stream.getSystemName()); initializeInput(stream); stream.setTestId(testId); if (configs.containsKey(TaskConfig.INPUT_STREAMS())) { configs.put(TaskConfig.INPUT_STREAMS(), configs.get(TaskConfig.INPUT_STREAMS()).concat("," + stream.getSystemName() + "." + stream.getPhysicalName())); } else { configs.put(TaskConfig.INPUT_STREAMS(), stream.getSystemName() + "." + stream.getPhysicalName()); } stream.getStreamConfig().forEach((key, val) -> { configs.putIfAbsent((String) key, (String) val); }); return this; }
Source:
public EAccessLevel getEAccessLevel(String xwikiRight) { return EAccessLevel.getAccessLevel(xwikiRight).get(); }

Target:
public EAccessLevel getEAccessLevel(String xwikiRight) { return EAccessLevel.getAccessLevel(xwikiRight).orNull(); }
Source:
public void canLogin() throws IOException { final String token = "GitHubToken"; final String code = "GitHubCode"; final int userid = 1; final String login = "octocat"; final String avatar = "<LINK_1>"; final String lgattr = "login"; final String acattr = "access_token"; final Take take = new TkFork( new FkRegex( "/login/oauth/access_token", new Take() { @Override public Response act(final Request req) throws IOException { return new RsXembly( new XeDirectives( new Directives().add("OAuth") .add("token_type").set("bearer").up() .add("scope").set("repo,gist").up() .add(acattr).set(token).toString() ) ); } } ), new FkRegex( "/user", new Take() { @Override public Response act(final Request req) throws IOException { MatcherAssert.assertThat( new RqHref.Base(req).href().param( acattr ).iterator().next(), Matchers.containsString(token) ); return new RsJSON( Json.createObjectBuilder() .add(lgattr, login) .add("id", userid) .add("avatar_url", avatar) .build() ); } } ) ); new FtRemote(take).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { final Iterator<Identity> itr = new PsGithub( "app", "key", home.toString(), home.toString() ).enter(new RqFake("GET", String.format("?code=%s", code))); final Identity identity = itr.next(); MatcherAssert.assertThat( identity.urn(), Matchers.equalTo(String.format("urn:github:%d", userid)) ); MatcherAssert.assertThat( identity.properties().get(lgattr), Matchers.equalTo(login) ); MatcherAssert.assertThat( identity.properties().get("avatar"), Matchers.equalTo(avatar) ); } } ); }

Target:
public void canLogin() throws IOException { final Take take = new TkFork( new FkRegex( "/login/oauth/access_token", new Take() { @Override public Response act(final Request req) throws IOException { final Request greq = new RqGreedy(req); PsGithubTest.assertParam(greq, "code", "code"); PsGithubTest.assertParam(greq, "client_id", "app"); PsGithubTest.assertParam(greq, "client_secret", "key"); return new RsXembly( new XeDirectives( new Directives().add("OAuth") .add("token_type").set("bearer").up() .add("scope").set("repo,gist").up() .add("access_token").set("GitHubToken") .toString() ) ); } } ), new FkRegex( "/user", new Take() { @Override public Response act(final Request req) throws IOException { MatcherAssert.assertThat( new RqHref.Base(req).href().param("access_token") .iterator().next(), Matchers.containsString("GitHubToken") ); return new RsJSON( Json.createObjectBuilder() .add("login", "octocat") .add("id", 1) .add( "avatar_url", "<LINK_0>" ) .build() ); } } ) ); new FtRemote(take).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { final Identity identity = new PsGithub( "app", "key", home.toString(), home.toString() ).enter(new RqFake("GET", "?code=code")).next(); MatcherAssert.assertThat( identity.urn(), Matchers.equalTo("urn:github:1") ); MatcherAssert.assertThat( identity.properties().get("login"), Matchers.equalTo("octocat") ); MatcherAssert.assertThat( identity.properties().get("avatar"), Matchers.equalTo("<LINK_0>") ); } } ); }
Source:
private void assertStudentRowDisplayed(StudentAttributes student, InstructorAttributes instructorToMasquaradeAs, CourseAttributes course) { By by = By.xpath(" WebElement studentRow = browser.driver.findElement(by); assertStudentContentCorrect(studentRow, student, course); assertTrue(isStudentLinkCorrect(studentRow, student, instructorToMasquaradeAs)); }

Target:
private void assertStudentRowDisplayed(StudentAttributes student, InstructorAttributes instructorToMasquaradeAs, CourseAttributes course) { WebElement studentRow = searchPage.getStudentRow(student); assertStudentContentCorrect(studentRow, student, course); assertTrue(isStudentLinkCorrect(studentRow, student, instructorToMasquaradeAs)); }
Source:
public static double volatility(double forward, double strike, double timeToExpiry, double volatilityAtm, double rho, double eta) { ArgumentChecker.isTrue(strike > 0, "strike must be strctly positive"); ArgumentChecker.isTrue(forward > 0, "strike must be strctly positive"); ArgumentChecker.isTrue(timeToExpiry > 0, "time to expiration must be strctly positive"); double theta = volatilityAtm * volatilityAtm * timeToExpiry; double phi = eta * Math.sqrt(theta); double k = Math.log(strike / forward); double w = 0.5 * theta * (1.0d + rho * phi * k + Math.sqrt(1.0d + 2 * rho * phi * k + phi * k * phi * k)); return Math.sqrt(w / timeToExpiry); }

Target:
public static double volatility(double forward, double strike, double timeToExpiry, double volatilityAtm, double rho, double eta) { ArgumentChecker.isTrue(strike > 0, "strike must be strctly positive"); ArgumentChecker.isTrue(forward > 0, "strike must be strctly positive"); ArgumentChecker.isTrue(timeToExpiry > 0, "time to expiration must be strctly positive"); double theta = volatilityAtm * volatilityAtm * timeToExpiry; double phi = eta / Math.sqrt(theta); double k = Math.log(strike / forward); double w = 0.5 * theta * (1.0d + rho * phi * k + Math.sqrt(1.0d + 2 * rho * phi * k + phi * k * phi * k)); return Math.sqrt(w / timeToExpiry); }
Source:
public Object deepCopy(Object val) throws HibernateException { if (val == null) return null; if (val instanceof byte[]) { return new Guid((byte[]) val, true); } if (val instanceof UUID) return new Guid((UUID) val); if (val instanceof Guid) return new Guid(((Guid) val).getUuid()); throw new UnsupportedOperationException("Can't convert " + val.getClass() + " to GUID"); }

Target:
public Object deepCopy(Object val) throws HibernateException { if (val == null) return null; if (val instanceof byte[]) { return new Guid((byte[]) val, true); } if (val instanceof UUID) return new Guid((UUID) val); if (val instanceof Guid) return new Guid(((Guid) val).getUuid()); throw new HibernateException("Can't convert " + val.getClass() + " to GUID"); }
Source:
public void constructMergeTree( ArrayList<Stream> streamsToAddToDag, ArrayList<NamedMerger> operatorsToAdd) { if (streamsToMerge.size() < 2) { throw new IllegalArgumentException("Not enough streams to merge. Ensure `.merge` was called for each stream " + "to be added."); } Queue<SourcedOutputPort> unconnectedPorts = new ArrayQueue<>(); for (DefaultOutputPort<K> streamToAdd : streamsToMerge) { unconnectedPorts.add(new SourcedOutputPort(true, streamToAdd)); } long mergerCount = 0; while (!unconnectedPorts.isEmpty()) { if (unconnectedPorts.size() >= 2) { StreamMerger<K> merger = new StreamMerger<>(); SourcedOutputPort firstPort = unconnectedPorts.poll(); SourcedOutputPort secondPort = unconnectedPorts.poll(); streamsToAddToDag.add(new Stream("Merger_" + mergerCount + "_P1", firstPort, merger.data1)); streamsToAddToDag.add(new Stream("Merger_" + mergerCount + "_P2", secondPort, merger.data2)); operatorsToAdd.add(new NamedMerger("Merger_" + mergerCount++, merger)); unconnectedPorts.add(new SourcedOutputPort(merger.out)); } else { streamOutput = (operatorsToAdd.get(operatorsToAdd.size() - 1).merger.out); break; } } }

Target:
public void constructMergeTree( ArrayList<Stream> streamsToAddToDag, ArrayList<NamedMerger> operatorsToAdd) { if (streamsToMerge.size() < 2) { throw new IllegalArgumentException("Not enough streams to merge. Ensure `.merge` was called for each stream " + "to be added."); } Queue<SourcedOutputPort> unconnectedPorts = new LinkedList<>(); for (DefaultOutputPort<K> streamToAdd : streamsToMerge) { unconnectedPorts.add(new SourcedOutputPort(true, streamToAdd)); } long mergerCount = 0; while (!unconnectedPorts.isEmpty()) { if (unconnectedPorts.size() >= 2) { StreamMerger<K> merger = new StreamMerger<>(); SourcedOutputPort firstPort = unconnectedPorts.poll(); SourcedOutputPort secondPort = unconnectedPorts.poll(); streamsToAddToDag.add(new Stream("Merger_" + mergerCount + "_P1", firstPort, merger.data1)); streamsToAddToDag.add(new Stream("Merger_" + mergerCount + "_P2", secondPort, merger.data2)); operatorsToAdd.add(new NamedMerger("Merger_" + mergerCount++, merger)); unconnectedPorts.add(new SourcedOutputPort(merger.out)); } else { streamOutput = (operatorsToAdd.get(operatorsToAdd.size() - 1).merger.out); break; } } }