auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>RSocketServer( DuplexConnection connection, RSocket requestHandler, Function<Frame, ? extends Payload> frameDecoder, Consumer<Throwable> errorConsumer, long tickPeriod, long ackTimeout) { if (requestHandler instanceof RequestHandler) { this.optimizedRequestHandler = (RequestHandler) requestHandler; this.hasOptimizedRequestHandler = true; <START> this.requestHandler = null; <END> } else { this.hasOptimizedRequestHandler = false; this.requestHandler = requestHandler; this.optimizedRequestHandler = null; } this.connection = connection; this.frameDecoder = frameDecoder; this.errorConsumer = errorConsumer; this.sendingSubscriptions = Collections.synchronizedMap(new IntObjectHashMap<>()); this.channelProcessors = Collections.synchronizedMap(new IntObjectHashMap<>()); this.sendProcessor = new UnboundedProcessor<>(); connection .send(sendProcessor) .doFinally(this::handleSendProcessorCancel) .subscribe(null, this::handleSendProcessorError); Disposable receiveDisposable = connection.receive().subscribe(this::handleFrame, errorConsumer); this.connection .onClose() .doFinally( s -> { cleanup(); receiveDisposable.dispose(); }) .subscribe(null, errorConsumer); if (tickPeriod != 0) { keepAliveHandler = KeepAliveHandler.ofServer(new KeepAliveHandler.KeepAlive(tickPeriod, ackTimeout)); keepAliveHandler .timeout() .subscribe( keepAlive -> { String message = String.format("No keep-alive acks for %d ms", keepAlive.getTimeoutMillis()); errorConsumer.accept(new ConnectionErrorException(message)); connection.dispose(); }); keepAliveHandler.send().subscribe(sendProcessor::onNext); } else { keepAliveHandler = null; } }</code><technical_language>I requestHandler assigned for consistency</technical_language>

Target:
RSocketServer( DuplexConnection connection, RSocket requestHandler, Function<Frame, ? extends Payload> frameDecoder, Consumer<Throwable> errorConsumer, long tickPeriod, long ackTimeout) { this.requestHandler = requestHandler; this.responderRSocket = (requestHandler instanceof ResponderRSocket) ? (ResponderRSocket) requestHandler : null; this.connection = connection; this.frameDecoder = frameDecoder; this.errorConsumer = errorConsumer; this.sendingSubscriptions = Collections.synchronizedMap(new IntObjectHashMap<>()); this.channelProcessors = Collections.synchronizedMap(new IntObjectHashMap<>()); this.sendProcessor = new UnboundedProcessor<>(); connection .send(sendProcessor) .doFinally(this::handleSendProcessorCancel) .subscribe(null, this::handleSendProcessorError); Disposable receiveDisposable = connection.receive().subscribe(this::handleFrame, errorConsumer); this.connection .onClose() .doFinally( s -> { cleanup(); receiveDisposable.dispose(); }) .subscribe(null, errorConsumer); if (tickPeriod != 0) { keepAliveHandler = KeepAliveHandler.ofServer(new KeepAliveHandler.KeepAlive(tickPeriod, ackTimeout)); keepAliveHandler .timeout() .subscribe( keepAlive -> { String message = String.format("No keep-alive acks for %d ms", keepAlive.getTimeoutMillis()); errorConsumer.accept(new ConnectionErrorException(message)); connection.dispose(); }); keepAliveHandler.send().subscribe(sendProcessor::onNext); } else { keepAliveHandler = null; } }
Source:
<code>public static boolean shouldAnimateFormSubmitButton() { SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); <START> return properties.getString(ANIMATE_FORM_SUBMIT_BUTTON, CommCarePreferences.YES).equals(CommCarePreferences.YES); <END> }</code><technical_language>@phillipm this properties.getString(ANIMATE_FORM_SUBMIT_BUTTON, CommCarePreferences.NO) in order default</technical_language>

Target:
public static boolean shouldAnimateFormSubmitButton() { SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); return properties.getString(ANIMATE_FORM_SUBMIT_BUTTON, CommCarePreferences.NO).equals(CommCarePreferences.YES); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ParseUser.logOut(); if (ParseUser.getCurrentUser() == null) { startActivity(new Intent(this, SignUpOrLogInActivity.class)); } <START> else { <END> startActivity(new Intent(this, PersistToCloudActivity.class)); } }</code><technical_language>else line closing parent</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (ParseUser.getCurrentUser() == null) { startActivity(new Intent(this, SignUpOrLogInActivity.class)); } else { startActivity(new Intent(this, PersistToCloudActivity.class)); } }
Source:
<code>public InfluxDB enableBatch(final int flushActions, final int flushIntervalMin, final int flushIntervalMax, final TimeUnit flushIntervalTimeUnit) { <START> enableBatch(0, <END> flushActions, flushIntervalMin, flushIntervalMax, flushIntervalTimeUnit, BufferFailBehaviour.THROW_EXCEPTION, true, flushActions); return this; }</code><technical_language>"Capacity > 0 NULL", change null</technical_language>

Target:
public InfluxDB enableBatch(final int flushActions, final int flushIntervalMin, final int flushIntervalMax, final TimeUnit flushIntervalTimeUnit) { enableBatch(null, flushActions, flushIntervalMin, flushIntervalMax, flushIntervalTimeUnit, BufferFailBehaviour.THROW_EXCEPTION, true, flushActions); return this; }
Source:
<code>public double getArmorRemainingPercent() { if (getPosition() == null) { return 1.0; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if ((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 1.0; } <START> return (1.0 * (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition()))) <END> / (initialBuildingCF + initialBuildingArmor); }</code><technical_language>Is this a bug fix</technical_language>

Target:
public double getArmorRemainingPercent() { if (getPosition() == null) { return 1.0; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if ((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 1.0; } return (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition())) / ((double) (initialBuildingCF + initialBuildingArmor)); }
Source:
<code>private void checkReportsWebAppStatus() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/" + BaseContextPathData.getInstance().getRelativePath() + "services/reports-status"); try { requestBuilder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { setXmlInitialized(); } @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == Response.SC_OK <START> && response.getText().trim().equals(REPORTS_WEBAPP_DEPLOYED_MSG)) { <END> reportsWebappDeployed = true; parseReportsXML(); } } }); } catch (RequestException e) { setXmlInitialized(); } }</code><technical_language>longer need part in this if, right</technical_language>

Target:
private void checkReportsWebAppStatus() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/" + BaseContextPathData.getInstance().getRelativePath() + "services/reports-status"); try { requestBuilder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { setXmlInitialized(); } @Override public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == Response.SC_OK) { reportsWebappDeployed = true; parseReportsXML(); } } }); } catch (RequestException e) { setXmlInitialized(); } }
Source:
<code>private Results analyzeRawContext(final WebDriver webDriver, final Object rawContextArg, boolean injectAxe) { validateNotNullParameter(webDriver); String rawOptionsArg = getOptions().equals("{}") ? AxeReporter.serialize(runOptions) : getOptions(); Object[] rawArgs = new Object[] {rawContextArg, rawOptionsArg}; if (injectAxe) { try { WebDriverInjectorExtensions.inject( webDriver, builderOptions.getScriptProvider()); <START> } catch (IOException e) { <END> throw new RuntimeException("Unable to inject axe script", e); } catch (OperationNotSupportedException e) { throw new RuntimeException("Unable to inject axe script", e); } } webDriver.manage().timeouts() .setScriptTimeout(timeout, TimeUnit.SECONDS); Object response = ((JavascriptExecutor) webDriver) .executeAsyncScript(axeRunScript, rawArgs); Results results = objectMapper.convertValue(response, Results.class); return results; }</code><technical_language>catch exceptions do for both</technical_language>

Target:
private Results analyzeRawContext(final WebDriver webDriver, final Object rawContextArg, boolean injectAxe) { validateNotNullParameter(webDriver); String rawOptionsArg = getOptions().equals("{}") ? AxeReporter.serialize(runOptions) : getOptions(); Object[] rawArgs = new Object[] {rawContextArg, rawOptionsArg}; if (injectAxe) { try { WebDriverInjectorExtensions.inject( webDriver, builderOptions.getScriptProvider()); } catch (Exception e) { throw new RuntimeException("Unable to inject axe script", e); } } webDriver.manage().timeouts() .setScriptTimeout(timeout, TimeUnit.SECONDS); Object response = ((JavascriptExecutor) webDriver) .executeAsyncScript(axeRunScript, rawArgs); Results results = objectMapper.convertValue(response, Results.class); return results; }
Source:
<code>public Department() { <START> this.lastModification = ZonedDateTime.now(UTC).toLocalDate(); <END> }</code><technical_language>this.lastModification = LocalDate.now(UTC);</technical_language>

Target:
public Department() { this.lastModification = LocalDate.now(UTC); }
Source:
<code>public void verify(SparkContext sparkContext, Session session) { verify(!isDistributedSortEnabled(session), "distributed sort is not supported"); verify(getExchangeMaterializationStrategy(session) == NONE, "exchange materialization is not supported"); verify(getPartitioningProviderCatalog(session).equals(GlobalSystemConnector.NAME), "partitioning provider other that system is not supported"); verify(!isGroupedExecutionForEligibleTableScansEnabled(session) && !isGroupedExecutionForAggregationEnabled(session) && !isRecoverableGroupedExecutionEnabled(session) && !isDynamicScheduleForGroupedExecution(session) && !isColocatedJoinEnabled(session), "grouped execution is not supported"); verify(!isRedistributeWrites(session), "redistribute writes is not supported"); verify(!isScaleWriters(session), "scale writes is not supported"); <START> verify(!isPreferDistributedUnion(session), "prefer distributed union is expected to be disabled"); <END> }</code><technical_language>I thinking set PREFER_DISTRIBUTED_UNION false in production -- this fail user query loudly instead of run slow... PREFER_DISTRIBUTED_UNION entertain test</technical_language>

Target:
public void verify(SparkContext sparkContext, Session session) { verify(!isDistributedSortEnabled(session), "distributed sort is not supported"); verify(getExchangeMaterializationStrategy(session) == NONE, "exchange materialization is not supported"); verify(getPartitioningProviderCatalog(session).equals(GlobalSystemConnector.NAME), "partitioning provider other that system is not supported"); verify(!isGroupedExecutionForEligibleTableScansEnabled(session) && !isGroupedExecutionForAggregationEnabled(session) && !isRecoverableGroupedExecutionEnabled(session) && !isDynamicScheduleForGroupedExecution(session) && !isColocatedJoinEnabled(session), "grouped execution is not supported"); verify(!isRedistributeWrites(session), "redistribute writes is not supported"); verify(!isScaleWriters(session), "scale writes is not supported"); }
Source:
<code>public Command getSetStringValueCommand( final TransactionalEditingDomain domain, Object columnElement, Object rowElement, String newValue, AbstractStringValueConverter valueSolver, INattableModelManager tableManager) { if (columnElement instanceof EStructuralFeatureAxis) { final EStructuralFeature structuralFeature = (EStructuralFeature) ((EStructuralFeatureAxis) columnElement) .getElement(); <START> if (structuralFeature.getEType().equals( <END> UMLPackage.Literals.VALUE_SPECIFICATION)) { final EObject element = ((EObjectAxis) rowElement).getElement(); CompositeCommand result = ValueSpecificationSetCommand .getInstance().createSetCommand(getInjector(), element, structuralFeature, newValue); return result.isEmpty() ? null : new GMFtoEMFCommandWrapper( result); } } return null; }</code><technical_language>== operator constant element operand</technical_language>

Target:
public Command getSetStringValueCommand( final TransactionalEditingDomain domain, Object columnElement, Object rowElement, String newValue, AbstractStringValueConverter valueSolver, INattableModelManager tableManager) { if (columnElement instanceof EStructuralFeatureAxis) { final EStructuralFeature structuralFeature = (EStructuralFeature) ((EStructuralFeatureAxis) columnElement) .getElement(); if (UMLPackage.Literals.VALUE_SPECIFICATION == structuralFeature .getEType()) { final EObject element = ((EObjectAxis) rowElement).getElement(); CompositeCommand result = ValueSpecificationSetCommand .getInstance().createSetCommand(getInjector(), element, structuralFeature, newValue); return result.isEmpty() ? null : new GMFtoEMFCommandWrapper( result); } } return null; }
Source:
<code>public void populateDAG(DAG dag, Configuration conf) { FileSplitterInput fileSplitter = dag.addOperator("FileSplitter", createFileSplitter()); FSSliceReader blockReader = dag.addOperator("BlockReader", createBlockReader()); dag.addStream("BlockMetadata", fileSplitter.blocksMetadataOutput, blockReader.blocksMetadataInput); filesMetadataOutput.set(fileSplitter.filesMetadataOutput); blocksMetadataOutput.set(blockReader.blocksMetadataOutput); messages.set(blockReader.messages); if (sequencialFileRead) { dag.setInputPortAttribute(blockReader.blocksMetadataInput, Context.PortContext.STREAM_CODEC, new SequentialFileBlockMetadataCodec()); } if (blockSize != 0) { fileSplitter.setBlockSize(blockSize); } FileSplitterInput.TimeBasedDirectoryScanner fileScanner = fileSplitter.getScanner(); fileScanner.setFiles(files); if (scanIntervalMillis != 0) { fileScanner.setScanIntervalMillis(scanIntervalMillis); } fileScanner.setRecursive(recursive); if (filePatternRegularExp != null) { fileSplitter.getScanner().setFilePatternRegularExp(filePatternRegularExp); } blockReader.setBasePath(files); if (readersCount != 0) { dag.setAttribute(blockReader, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<FSSliceReader>(readersCount)); fileSplitter.setBlocksThreshold(readersCount); } <START> if (blocksThreshold != 0) { <END> fileSplitter.setBlocksThreshold(blocksThreshold); } }</code><technical_language>Do need this check blocksThreshold is >=1 constraint</technical_language>

Target:
public void populateDAG(DAG dag, Configuration conf) { FileSplitterInput fileSplitter = dag.addOperator("FileSplitter", createFileSplitter()); FSSliceReader blockReader = dag.addOperator("BlockReader", createBlockReader()); dag.addStream("BlockMetadata", fileSplitter.blocksMetadataOutput, blockReader.blocksMetadataInput); filesMetadataOutput.set(fileSplitter.filesMetadataOutput); blocksMetadataOutput.set(blockReader.blocksMetadataOutput); messages.set(blockReader.messages); if (sequencialFileRead) { dag.setInputPortAttribute(blockReader.blocksMetadataInput, Context.PortContext.STREAM_CODEC, new SequentialFileBlockMetadataCodec()); } if (blockSize != 0) { fileSplitter.setBlockSize(blockSize); } FileSplitterInput.TimeBasedDirectoryScanner fileScanner = fileSplitter.getScanner(); fileScanner.setFiles(files); if (scanIntervalMillis != 0) { fileScanner.setScanIntervalMillis(scanIntervalMillis); } fileScanner.setRecursive(recursive); if (filePatternRegularExp != null) { fileSplitter.getScanner().setFilePatternRegularExp(filePatternRegularExp); } blockReader.setBasePath(files); if (readersCount != 0) { dag.setAttribute(blockReader, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<FSSliceReader>(readersCount)); } if (blocksThreshold != 0) { fileSplitter.setBlocksThreshold(blocksThreshold); } }
Source:
<code>public void testRouterRequestTimeoutAllFailure() throws Exception { doPut(); operationsCount.incrementAndGet(); GetBlobOperation op = new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, operationFuture, null, operationCompleteCallback, time); requestRegistrationCallback.requestListToFill = new ArrayList<>(); op.poll(requestRegistrationCallback); <START> while (!op.isOperationComplete()) { <END> time.sleep(routerConfig.routerRequestTimeoutMs + 1); op.poll(requestRegistrationCallback); } Assert.assertEquals("Must have attempted sending requests to all replicas", replicasCount, correlationIdToGetOperation.size()); RouterException routerException = (RouterException) op.getOperationException(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); }</code><technical_language>Feels bit hacky. set error code MockServer throw for requests</technical_language>

Target:
public void testRouterRequestTimeoutAllFailure() throws Exception { doPut(); operationsCount.incrementAndGet(); GetBlobOperation op = new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, operationFuture, null, operationCompleteCallback, blobIdFactory, time); requestRegistrationCallback.requestListToFill = new ArrayList<>(); op.poll(requestRegistrationCallback); while (!op.isOperationComplete()) { time.sleep(routerConfig.routerRequestTimeoutMs + 1); op.poll(requestRegistrationCallback); } Assert.assertEquals("Must have attempted sending requests to all replicas", replicasCount, correlationIdToGetOperation.size()); RouterException routerException = (RouterException) op.getOperationException(); Assert.assertEquals(RouterErrorCode.OperationTimedOut, routerException.getErrorCode()); }
Source:
<code>public Handle<?> upload(LogFilePath localPath) throws Exception { String prefix = FileUtil.getPrefix(localPath.getTopic(), mConfig); LogFilePath path = localPath.withPrefix(prefix); final String localLogFilename = localPath.getLogFilePath(); final String logFileName; if (FileUtil.s3PathPrefixIsAltered(path.getLogFilePath(), mConfig)) { logFileName = localPath.withPrefix(FileUtil.getS3AlternativePrefix(mConfig)).getLogFilePath(); LOG.info("Will upload file to alternative s3 prefix path {}", logFileName); } else { logFileName = path.getLogFilePath(); } LOG.info("uploading file to {}", localLogFilename, logFileName); final Future<?> f = executor.submit(new Runnable() { final int totalRetries = Integer.parseInt(mConfig.getUploaderRetries()); @Override public void run() { int retriesLeft = totalRetries; boolean success = false; while (retriesLeft > 0 && !success) { try { FileUtil.moveToCloud(localLogFilename, logFileName); success = true; } catch (IOException e) { success = false; <START> retriesLeft--; <END> if (retriesLeft > 0) LOG.warn("Error uploading files to s3. Will retry times. Exception {}", retriesLeft, e); else Throwables.propagate(e); } } } }); return new FutureHandle(f); }</code><technical_language>people add exponential backup delay retries (e.g. 100ms, 200ms, 400ms ...) adding delay random intervals if a lot of workers concurrently running facing similar retries</technical_language>

Target:
public Handle<?> upload(LogFilePath localPath) throws Exception { String prefix = FileUtil.getPrefix(localPath.getTopic(), mConfig); LogFilePath path = localPath.withPrefix(prefix); final String localLogFilename = localPath.getLogFilePath(); final String logFileName; if (FileUtil.s3PathPrefixIsAltered(path.getLogFilePath(), mConfig)) { logFileName = localPath.withPrefix(FileUtil.getS3AlternativePrefix(mConfig)).getLogFilePath(); LOG.info("Will upload file to alternative s3 prefix path {}", logFileName); } else { logFileName = path.getLogFilePath(); } LOG.info("uploading file to {}", localLogFilename, logFileName); final Future<?> f = executor.submit(new Runnable() { final int totalRetries = Integer.parseInt(mConfig.getUploaderRetries()); final long backoffMillis = Long.parseLong(mConfig.getUploaderRetryBackoffMillis()); @Override public void run() { IOException uploadException = null; long millisToSleep = backoffMillis; int retriesLeft = totalRetries; boolean success = false; while (retriesLeft >= 0 && !success) { try { FileUtil.moveToCloud(localLogFilename, logFileName); success = true; } catch (IOException e) { success = false; retriesLeft--; uploadException = e; LOG.warn("Error uploading files to s3. Will retry times. Exception {}", retriesLeft, e); try { LOG.info("Sleeping millis, will retry upload after sleep", millisToSleep); Thread.sleep(millisToSleep); millisToSleep = millisToSleep*2; } catch(InterruptedException ie) { LOG.info("Interrupted when sleeping for retry."); } } } if (!success) throw new RuntimeException(uploadException); } }); return new FutureHandle(f); }
Source:
<code>public void deleteScheme(final WorkflowScheme scheme, final User user) throws DotDataException, DotSecurityException, AlreadyExistException { <START> if (null == scheme || SYSTEM_WORKFLOW_ID.equals(scheme.getId()) || !scheme.isArchived()) { <END> Logger.warn(this, "Can not delete workflow Id:" + scheme.getId()); throw new DotWorkflowException("Can not delete workflow Id:" + scheme.getId()); } this.submitter.execute(() -> deleteSchemeTask(scheme, user)); }</code><technical_language>I this null == scheme validation opens door for a NPE. arise operations scheme.getId() scheme.isArchived() if scheme is null condition true get a NPE line 330 e.g</technical_language>

Target:
public void deleteScheme(final WorkflowScheme scheme, final User user) throws DotDataException, DotSecurityException, AlreadyExistException { this.isUserAllowToModifiedWorkflow(user); if (null == scheme){ Logger.warn(this, "Can not delete a null workflow"); throw new DotWorkflowException("Can not delete a null workflow"); } if( SYSTEM_WORKFLOW_ID.equals(scheme.getId()) || !scheme.isArchived()) { Logger.warn(this, "Can not delete workflow Id:" + scheme.getId()); throw new DotWorkflowException("Can not delete workflow Id:" + scheme.getId()); } this.submitter.execute(() -> deleteSchemeTask(scheme, user)); }
Source:
<code>public void boundaryOpenCloseDisposedOnComplete() { <START> PublishProcessor<Integer> pp0 = PublishProcessor.create(); <END> PublishProcessor<Integer> pp1 = PublishProcessor.create(); PublishProcessor<Integer> pp2 = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = pp0 .buffer(pp1, Functions.justFunction(pp2)) .test(); assertTrue(pp0.hasSubscribers()); assertTrue(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); pp1.onNext(1); assertTrue(pp1.hasSubscribers()); assertTrue(pp2.hasSubscribers()); pp0.onComplete(); ts.assertResult(Collections.<Integer>emptyList()); assertFalse(pp1.hasSubscribers()); assertFalse(pp2.hasSubscribers()); }</code><technical_language>nit: upstream</technical_language>

Target:
public void boundaryOpenCloseDisposedOnComplete() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); assertTrue(source.hasSubscribers()); assertTrue(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); openIndicator.onNext(1); assertTrue(openIndicator.hasSubscribers()); assertTrue(closeIndicator.hasSubscribers()); source.onComplete(); ts.assertResult(Collections.<Integer>emptyList()); assertFalse(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); }
Source:
<code>public void click() { waitUntilIsDisplayed(); scrollIntoScreenIfNeeded(); final View view = getView(); final int[] xy = new int[2]; if (Build.VERSION.SDK_INT < 19 || view.isLaidOut()) { if (Build.VERSION.SDK_INT < 19) { try { Thread.sleep(300); } catch (InterruptedException e) } view.getLocationOnScreen(xy); <START> clickOnScreen(xy[0] + view.getWidth() / 2.0f, xy[1] + view.getHeight() / 2.0f); <END> return; } final AndroidWait wait = instrumentation.getAndroidWait(); final BooleanWrapper isLaidOut = new BooleanWrapper(); final ViewTreeObserver observer = view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { try { isLaidOut.value = true; } finally { if (observer.isAlive()) { removeOnGlobalLayoutListener(observer, this); } else { removeOnGlobalLayoutListener(view.getViewTreeObserver(), this); } } } }); try { wait.until(new Function<Void, Boolean>() { @Override public Boolean apply(Void input) { return isLaidOut.value; } }); } catch (TimeoutException e) { throw new SelendroidException("View was never laid out", e); } view.getLocationOnScreen(xy); clickOnScreen(xy[0] + view.getWidth() / 2.0f, xy[1] + view.getHeight() / 2.0f); }</code><technical_language>useful lines a separate function repeated get out of sync if changes other</technical_language>

Target:
public void click() { waitUntilIsDisplayed(); scrollIntoScreenIfNeeded(); final View view = getView(); if (Build.VERSION.SDK_INT < 19 || view.isLaidOut()) { if (Build.VERSION.SDK_INT < 19) { try { Thread.sleep(300); } catch (InterruptedException e) } doClick(); return; } final AndroidWait wait = instrumentation.getAndroidWait(); final AtomicBoolean isLaidOut = new AtomicBoolean(false); final ViewTreeObserver observer = view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { try { isLaidOut.set(true); } finally { if (observer.isAlive()) { removeOnGlobalLayoutListener(observer, this); } else { removeOnGlobalLayoutListener(view.getViewTreeObserver(), this); } } } }); try { wait.until(new Function<Void, Boolean>() { @Override public Boolean apply(Void input) { return isLaidOut.get(); } }); } catch (TimeoutException e) { throw new SelendroidException("View was never laid out", e); } doClick(); }
Source:
<code>protected Set<String> getMdcTags(Dsn dsn) { String val = Lookup.lookup(MDCTAGS_OPTION, dsn); if (Util.isNullOrEmpty(val)) { <START> val = Lookup.lookup(EXTRATAGS_OPTION, dsn); <END> } return Util.parseMdcTags(val); }</code><technical_language>Is do warn this is deprecated</technical_language>

Target:
protected Set<String> getMdcTags(Dsn dsn) { String val = Lookup.lookup(MDCTAGS_OPTION, dsn); if (Util.isNullOrEmpty(val)) { val = Lookup.lookup(EXTRATAGS_OPTION, dsn); if (!Util.isNullOrEmpty(val)) { logger.warn("The '" + EXTRATAGS_OPTION + "' option is deprecated, please use" + " the '" + MDCTAGS_OPTION + "' option instead."); } } return Util.parseMdcTags(val); }
Source:
<code>private static void parseTtsElements(Element element, List<LocalisedText> textsToRead) { if ("tts".equalsIgnoreCase(1element.tagName()) && <START> "android".equalsIgnoreCase(element.attr("service"))) { <END> textsToRead.add(new LocalisedText(element.text(), element.attr("voice"))); return; } for (Element child : element.children()) { parseTtsElements(child, textsToRead); } }</code><technical_language>(off-topic): this code work in tr-TR</technical_language>

Target:
private static void parseTtsElements(Element element, List<LocalisedText> textsToRead) { if ("tts".equalsIgnoreCase(element.tagName()) && "android".equalsIgnoreCase(element.attr("service"))) { textsToRead.add(new LocalisedText(element.text(), element.attr("voice"))); return; } for (Element child : element.children()) { parseTtsElements(child, textsToRead); } }
Source:
<code>protected boolean canDoAction() { if (getParameters() == null || (getParameters().getQuotaId() == null)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); } Quota quota = getQuota(); if (quota == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } if (getStoragePoolDAO().get(quota.getStoragePoolId()).getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED && quota.getIsDefaultQuota()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_CAN_NOT_HAVE_DEFAULT_INDICATION); return false; } List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(quota.getStoragePoolId()); if (quotaList.size() <= 1) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_MUST_HAVE_AT_LEAST_ONE_QUOTA); return false; } if (getVmDAO().getAllVmsRelatedToQuotaId(quota.getId()) != null && !getVmDAO().getAllVmsRelatedToQuotaId(quota.getId()).isEmpty()) { <START> addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID); <END> } return true; }</code><technical_language>return false here</technical_language>

Target:
protected boolean canDoAction() { if (getParameters() == null || (getParameters().getQuotaId() == null)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } Quota quota = getQuota(); if (quota == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } if (getStoragePoolDAO().get(quota.getStoragePoolId()).getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED && quota.getIsDefaultQuota()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_CAN_NOT_HAVE_DEFAULT_INDICATION); return false; } List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(quota.getStoragePoolId()); if (quotaList.size() <= 1) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_MUST_HAVE_AT_LEAST_ONE_QUOTA); return false; } if (getVmDAO().getAllVmsRelatedToQuotaId(quota.getId()) != null && !getVmDAO().getAllVmsRelatedToQuotaId(quota.getId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID); return false; } return true; }
Source:
<code><START> private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { <END> int spmIndicator = 0; if (spmStatus != VdsSpmStatus.None) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }</code><technical_language>TimeUnit.SECONDS.toMillis return long, return type long well</technical_language>

Target:
private long calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus != VdsSpmStatus.None) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }
Source:
<code>public void testRenameWithNestedSnapshottableDirs() throws Exception { final Path sdir1 = new Path("/dir1"); final Path sdir2 = new Path("/dir2"); final Path foo = new Path(sdir1, "foo"); final Path bar = new Path(sdir2, "bar"); hdfs.mkdirs(foo); hdfs.mkdirs(bar); hdfs.allowSnapshot(foo); hdfs.allowSnapshot(sdir2); try { hdfs.rename(foo, bar, Rename.OVERWRITE); <START> } catch (IOException e) { <END> GenericTestUtils.assertExceptionContains("Unable to rename because " + foo.toString() + " has snapshottable descendant directories and " + sdir2.toString() + " is a descent of a snapshottable directory, " + "and HDFS does not support nested snapshottable directory.", e); } hdfs.disallowSnapshot(foo); hdfs.rename(foo, bar, Rename.OVERWRITE); SnapshottableDirectoryStatus[] dirs = fsn.getSnapshottableDirListing(); assertEquals(1, dirs.length); assertEquals(sdir2, dirs[0].getFullPath()); }</code><technical_language>a fail() rename() succeed. Other patch is +1 me</technical_language>

Target:
public void testRenameWithNestedSnapshottableDirs() throws Exception { final Path sdir1 = new Path("/dir1"); final Path sdir2 = new Path("/dir2"); final Path foo = new Path(sdir1, "foo"); final Path bar = new Path(sdir2, "bar"); hdfs.mkdirs(foo); hdfs.mkdirs(bar); hdfs.allowSnapshot(foo); hdfs.allowSnapshot(sdir2); try { hdfs.rename(foo, bar, Rename.OVERWRITE); fail("Except exception since " + "Unable to rename because " + foo.toString() + " has snapshottable descendant directories and " + sdir2.toString() + " is a descent of a snapshottable directory, " + "and HDFS does not support nested snapshottable directory."); } catch (IOException e) { GenericTestUtils.assertExceptionContains("Unable to rename because " + foo.toString() + " has snapshottable descendant directories and " + sdir2.toString() + " is a descent of a snapshottable directory, " + "and HDFS does not support nested snapshottable directory.", e); } hdfs.disallowSnapshot(foo); hdfs.rename(foo, bar, Rename.OVERWRITE); SnapshottableDirectoryStatus[] dirs = fsn.getSnapshottableDirListing(); assertEquals(1, dirs.length); assertEquals(sdir2, dirs[0].getFullPath()); }
Source:
<code>private static Icon generateThemedIcon(Context context, int iconId, int foregroundColor, int backgroundColor) { Drawable vectorDrawable = Util.getTintedVectorDrawable(context, iconId, foregroundColor); Drawable backgroundDrawable = Util.getTintedVectorDrawable(context, R.drawable.ic_app_shortcut_background, backgroundColor); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ AdaptiveIconDrawable adaptiveIconDrawable = new AdaptiveIconDrawable(backgroundDrawable, vectorDrawable); <START> return Icon.createWithAdaptiveBitmap(drawableToBitmap(adaptiveIconDrawable)); <END> } else { LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{backgroundDrawable, vectorDrawable}); return Icon.createWithBitmap(drawableToBitmap(layerDrawable)); } }</code><technical_language>good rely IconCompat, actually</technical_language>

Target:
private static IconCompat generateThemedIcon(Context context, int iconId, int foregroundColor, int backgroundColor) { Drawable vectorDrawable = Util.getTintedVectorDrawable(context, iconId, foregroundColor); Drawable backgroundDrawable = Util.getTintedVectorDrawable(context, R.drawable.ic_app_shortcut_background, backgroundColor); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ AdaptiveIconDrawable adaptiveIconDrawable = new AdaptiveIconDrawable(backgroundDrawable, vectorDrawable); return IconCompat.createWithAdaptiveBitmap(drawableToBitmap(adaptiveIconDrawable)); } else { LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{backgroundDrawable, vectorDrawable}); return IconCompat.createWithBitmap(drawableToBitmap(layerDrawable)); } }
Source:
<code>public void testIt() { <START> PropertyInfo pc = TypeCompat.GetProperty(this.getClass(), "someValue"); <END> String result = (String) pc.GetValue(this, "JarJar"); assertEquals("Standard", "Anakin", result); this.someValue = null; result = (String) pc.GetValue(this, "JarJar"); assertEquals("Null Value", "JarJar", result); }</code><technical_language>change variable name - pc of PropertyCompat, weird of new class name. propertyInfo a suggestion</technical_language>

Target:
public void testIt() { PropertyInfo propInfo = TypeCompat.GetProperty(this.getClass(), "someValue"); String result = (String) propInfo.GetValue(this, "JarJar"); assertEquals("Standard", "Anakin", result); this.someValue = null; result = (String) propInfo.GetValue(this, "JarJar"); assertEquals("Null Value", "JarJar", result); }
Source:
<code>public List<Method> visibleMethods() { if (fVisibleMethods != null) { return fVisibleMethods; } Set<String> namesAndSignatures = new HashSet<>(); List<Method> visibleMethods = new ArrayList<>(); for (Method <START> method2 : <END> methods()) { MethodImpl method = (MethodImpl) method2; namesAndSignatures.add(method.name() + method.signature()); visibleMethods.add(method); } Iterator<InterfaceType> interfaces = interfaces().iterator(); InterfaceType inter; while (interfaces.hasNext()) { inter = interfaces.next(); addVisibleMethods(inter.visibleMethods(), namesAndSignatures, visibleMethods); } if (this instanceof ClassType) { ClassType superclass = ((ClassType) this).superclass(); if (superclass != null) { addVisibleMethods(superclass.visibleMethods(), namesAndSignatures, visibleMethods); } } fVisibleMethods = visibleMethods; return fVisibleMethods; }</code><technical_language>rename m</technical_language>

Target:
public List<Method> visibleMethods() { if (fVisibleMethods != null) { return fVisibleMethods; } Set<String> namesAndSignatures = new HashSet<>(); List<Method> visibleMethods = new ArrayList<>(); for (Method m : methods()) { MethodImpl method = (MethodImpl) m; namesAndSignatures.add(method.name() + method.signature()); visibleMethods.add(method); } Iterator<InterfaceType> interfaces = interfaces().iterator(); InterfaceType inter; while (interfaces.hasNext()) { inter = interfaces.next(); addVisibleMethods(inter.visibleMethods(), namesAndSignatures, visibleMethods); } if (this instanceof ClassType) { ClassType superclass = ((ClassType) this).superclass(); if (superclass != null) { addVisibleMethods(superclass.visibleMethods(), namesAndSignatures, visibleMethods); } } fVisibleMethods = visibleMethods; return fVisibleMethods; }
Source:
<code>public void notB(final org.apache.datasketches.theta.Sketch skB) { if (empty_) { return; } if ((skB == null) || skB.isEmpty()) { return; } final long thetaLongB = skB.getThetaLong(); thetaLong_ = Math.min(thetaLong_, thetaLongB); final int countB = skB.getRetainedEntries(); final long[] hashTableKeysB = convertToHashTable(extractThetaHashArray(skB, countB), countB, thetaLong_); final long[] tmpKeysA = new long[count_]; final S[] tmpSummariesA = (S[]) Array.newInstance(summaries_.getClass().getComponentType(), count_); int nonMatches = 0; for (int i = 0; i < count_; i++) { final long key = keys_[i]; <START> if ((key != 0) && (key < thetaLong_)) { END> final int index = HashOperations.hashSearch(hashTableKeysB, simpleIntLog2(hashTableKeysB.length), key); if (index == -1) { tmpKeysA[nonMatches] = key; tmpSummariesA[nonMatches] = summaries_[i]; nonMatches++; } } } keys_ = Arrays.copyOfRange(tmpKeysA, 0, nonMatches); summaries_ = Arrays.copyOfRange(tmpSummariesA, 0, nonMatches); count_ = nonMatches; }</code><technical_language>do interpret a hashed key equals 0</technical_language>

Target:
public void notB(final org.apache.datasketches.theta.Sketch skB) { if (empty_ || (skB == null) || skB.isEmpty()) { return; } final long thetaLongB = skB.getThetaLong(); thetaLong_ = Math.min(thetaLong_, thetaLongB); final int countB = skB.getRetainedEntries(); final long[] hashTableKeysB = convertToHashTable(extractThetaHashArray(skB, countB), countB, thetaLong_); final long[] tmpKeysA = new long[count_]; final S[] tmpSummariesA = (S[]) Array.newInstance(summaries_.getClass().getComponentType(), count_); int nonMatches = 0; for (int i = 0; i < count_; i++) { final long key = keys_[i]; if ((key > 0) && (key < thetaLong_)) { final int index = HashOperations.hashSearch(hashTableKeysB, simpleIntLog2(hashTableKeysB.length), key); if (index == -1) { tmpKeysA[nonMatches] = key; tmpSummariesA[nonMatches] = summaries_[i]; nonMatches++; } } } keys_ = Arrays.copyOfRange(tmpKeysA, 0, nonMatches); summaries_ = Arrays.copyOfRange(tmpSummariesA, 0, nonMatches); count_ = nonMatches; }
Source:
<code>public SingleInputGate create( @Nonnull String owningTaskName, int gateIndex, @Nonnull InputGateDeploymentDescriptor igdd, @Nonnull PartitionProducerStateProvider partitionProducerStateProvider, @Nonnull InputChannelMetrics metrics) { SupplierWithException<BufferPool, IOException> bufferPoolFactory = createBufferPoolFactory( networkBufferPool, networkBuffersPerChannel, floatingNetworkBuffersPerGate, igdd.getShuffleDescriptors().length, igdd.getConsumedPartitionType()); BufferDecompressor bufferDecompressor = null; if (igdd.getConsumedPartitionType().isBlocking() && blockingShuffleCompressionEnabled) { bufferDecompressor = new BufferDecompressor(networkBufferSize, compressionCodec); } <START> SingleInputGate inputGate = new SingleInputGateImpl( <END> owningTaskName, gateIndex, igdd.getConsumedResultId(), igdd.getConsumedPartitionType(), igdd.getConsumedSubpartitionIndex(), igdd.getShuffleDescriptors().length, partitionProducerStateProvider, bufferPoolFactory, bufferDecompressor); createInputChannels(owningTaskName, igdd, inputGate, metrics); return inputGate; }</code><technical_language>hotfix commits in PR? (Introducing interfaces for gates/channels?)</technical_language>

Target:
public SingleInputGate create( @Nonnull String owningTaskName, int gateIndex, @Nonnull InputGateDeploymentDescriptor igdd, @Nonnull PartitionProducerStateProvider partitionProducerStateProvider, @Nonnull InputChannelMetrics metrics) { SupplierWithException<BufferPool, IOException> bufferPoolFactory = createBufferPoolFactory( networkBufferPool, networkBuffersPerChannel, floatingNetworkBuffersPerGate, igdd.getShuffleDescriptors().length, igdd.getConsumedPartitionType()); BufferDecompressor bufferDecompressor = null; if (igdd.getConsumedPartitionType().isBlocking() && blockingShuffleCompressionEnabled) { bufferDecompressor = new BufferDecompressor(networkBufferSize, compressionCodec); } SingleInputGate inputGate = new SingleInputGate( owningTaskName, gateIndex, igdd.getConsumedResultId(), igdd.getConsumedPartitionType(), igdd.getConsumedSubpartitionIndex(), igdd.getShuffleDescriptors().length, partitionProducerStateProvider, bufferPoolFactory, bufferDecompressor, networkBufferPool); createInputChannels(owningTaskName, igdd, inputGate, metrics); return inputGate; }
Source:
<code>public void checkPreviewUpdatedAfterDestroyRecreate() { IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); <START> pressBackButton(); <END> mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.getActivity().startActivity(mIntent); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }</code><technical_language>consider wait for preview ready press key. step, test Preview in previous activity start stop correctly. verify next activity Preview successfully</technical_language>

Target:
public void checkPreviewUpdatedAfterDestroyRecreate() { IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); pressBackButton(); mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.launchActivity(mIntent); IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }
Source:
<code>private void hideQuickAccess( @Optional @UIEventTopic(UIEvents.ApplicationElement.TOPIC_TAGS) Event event) { if (event == null) { return; } Object origin = event.getProperty(UIEvents.EventTags.ELEMENT); if (!(origin instanceof MToolControl)) { return; } MToolControl control = (MToolControl) origin; if (!QUICK_ACCESS_ID.equals(control.getElementId())) { return; } if (UIEvents.isADD(event)) { if (UIEvents.contains(event, UIEvents.EventTags.NEW_VALUE, IPresentationEngine.HIDDEN_EXPLICITLY)) { if (!model.getTags().contains(QUICK_ACCESS_HIDDEN)) { model.getTags().add(QUICK_ACCESS_HIDDEN); } } <START> } else { <END> if (UIEvents.contains(event, UIEvents.EventTags.OLD_VALUE, IPresentationEngine.HIDDEN_EXPLICITLY)) { model.getTags().remove(QUICK_ACCESS_HIDDEN); } } }</code><technical_language>Standard pattern is moment check for removal event in else statement. else if (UIEvents.isREMOVE(event)) {</technical_language>

Target:
private void hideQuickAccess( @Optional @UIEventTopic(UIEvents.ApplicationElement.TOPIC_TAGS) Event event) { if (event == null) { return; } Object origin = event.getProperty(UIEvents.EventTags.ELEMENT); if (!(origin instanceof MToolControl)) { return; } MToolControl control = (MToolControl) origin; if (!QUICK_ACCESS_ID.equals(control.getElementId())) { return; } if (UIEvents.isADD(event)) { if (UIEvents.contains(event, UIEvents.EventTags.NEW_VALUE, IPresentationEngine.HIDDEN_EXPLICITLY)) { if (!model.getTags().contains(QUICK_ACCESS_HIDDEN)) { model.getTags().add(QUICK_ACCESS_HIDDEN); } } } else if (UIEvents.isREMOVE(event)) { if (UIEvents.contains(event, UIEvents.EventTags.OLD_VALUE, IPresentationEngine.HIDDEN_EXPLICITLY)) { model.getTags().remove(QUICK_ACCESS_HIDDEN); } } }
Source:
<code>public static String regionOfDomain(UserPreferences userPrefs, String domain) throws URISyntaxException, IOException { HttpUtility http = new HttpUtility(userPrefs, false); URI versionApiUri = new URI("https://" + DatasetUtils.getDomainWithoutScheme(domain) + VERSION_API_ENDPOINT); try(CloseableHttpResponse response = http.get(versionApiUri, ContentType.APPLICATION_JSON.getMimeType())) { Header[] headers = response.getHeaders(X_SOCRATA_REGION); if(headers.length == 0) return "development"; <START> else return headers[0].getValue(); <END> } }</code><technical_language>This is hard read, please curly braces</technical_language>

Target:
public static String regionOfDomain(UserPreferences userPrefs, String domain) throws URISyntaxException, IOException { HttpUtility http = new HttpUtility(userPrefs, false); URI versionApiUri = new URI("https://" + DatasetUtils.getDomainWithoutScheme(domain) + VERSION_API_ENDPOINT); try(CloseableHttpResponse response = http.get(versionApiUri, ContentType.APPLICATION_JSON.getMimeType())) { Header[] headers = response.getHeaders(X_SOCRATA_REGION); if(headers.length == 0) { return "development"; } else { return headers[0].getValue(); } } }
Source:
<code>public void testOrderResourceFields() throws HTTPError { Order order = createOrder(); assertNotNull(order.buyers); assertNotNull(order.credits); assertNotNull(order.debits); assertNotNull(order.merchant); assertNotNull(order.refunds); assertNotNull(order.reversals); assertNotNull(order.amount_escrowed); assertNotNull(order.amount); assertNotNull(order.created_at); assertNotNull(order.currency); assertNotNull(order.delivery_address); assertNull(order.description); assertNotNull(order.href); assertNotNull(order.id); assertNotNull(order.meta); assertNotNull(order.updated_at); <START> } <END></code><technical_language>Assert values</technical_language>

Target:
public void testOrderResourceFields() throws HTTPError { Order order = createOrder(); Map<String, String> meta = new HashMap<String, String>(); meta.put("facebook", "0192837465"); order.description = "New description for order"; order.meta = meta; order.save(); assertTrue(order.buyers instanceof Customer.Collection); assertTrue(order.credits instanceof Credit.Collection); assertTrue(order.debits instanceof Debit.Collection); assertTrue(order.merchant instanceof Customer); assertTrue(order.refunds instanceof Refund.Collection); assertTrue(order.reversals instanceof Reversal.Collection); assertTrue(order.href.contains("/orders/OR")); assertTrue(order.id.startsWith("OR")); assertEquals(order.delivery_address.toString(), "{city=null, line2=null, " + "line1=null, state=null, postal_code=null, country_code=null}"); assertNotNull(order.created_at); assertNotNull(order.updated_at); assertEquals(order.currency, "USD"); assertEquals(order.description, "New description for order"); assertEquals(order.meta.get("facebook"), "0192837465"); assertEquals(order.amount_escrowed.intValue(), 0); assertEquals(order.amount.intValue(), 5000); }