auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void updateSubs(ArrayList<String> subs) { if (subs.isEmpty() && !NetworkUtil.isConnected(this)) { d = new MaterialDialog.Builder(MainActivity.this) .title("No offline content found") .positiveText("Enter online mode") .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Reddit.appRestart.edit().remove("forceoffline").apply(); ((Reddit) getApplication()).forceRestart(MainActivity.this); } }).show(); } else { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); try { Field mDragger = drawerLayout.getClass().getSuperclass().getDeclaredField( "mLeftDragger"); mDragger.setAccessible(true); ViewDragHelper draggerObj = (ViewDragHelper) mDragger .get(drawerLayout); Field mEdgeSize = draggerObj.getClass().getDeclaredField( "mEdgeSize"); mEdgeSize.setAccessible(true); int edge = mEdgeSize.getInt(draggerObj); mEdgeSize.setInt(draggerObj, edge * DRAWER_EDGE_FACTOR); } catch (Exception e) { <START> LogUtil.v("exception while changing side drawer edge" + e); <END> } if (loader != null) { header.setVisibility(View.VISIBLE); setDataSet(subs); doDrawer(); try { setDataSet(subs); } catch (Exception ignored) { } loader.finish(); loader = null; } else { setDataSet(subs); doDrawer(); } } }</code><technical_language>Change this LogUtil.e(e + ": Exception thrown while changing navdrawer edge size"), delete white space lines this (line 627 628). that, more good merge</technical_language>

Target:
public void updateSubs(ArrayList<String> subs) { if (subs.isEmpty() && !NetworkUtil.isConnected(this)) { d = new MaterialDialog.Builder(MainActivity.this) .title("No offline content found") .positiveText("Enter online mode") .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Reddit.appRestart.edit().remove("forceoffline").apply(); ((Reddit) getApplication()).forceRestart(MainActivity.this); } }).show(); } else { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); try { Field mDragger = drawerLayout.getClass().getSuperclass().getDeclaredField( "mLeftDragger"); mDragger.setAccessible(true); ViewDragHelper draggerObj = (ViewDragHelper) mDragger .get(drawerLayout); Field mEdgeSize = draggerObj.getClass().getDeclaredField( "mEdgeSize"); mEdgeSize.setAccessible(true); int edge = mEdgeSize.getInt(draggerObj); mEdgeSize.setInt(draggerObj, edge * DRAWER_EDGE_FACTOR); } catch (Exception e) { LogUtil.e(e + ": Exception thrown while changing navdrawer edge size"); } if (loader != null) { header.setVisibility(View.VISIBLE); setDataSet(subs); doDrawer(); try { setDataSet(subs); } catch (Exception ignored) { } loader.finish(); loader = null; } else { setDataSet(subs); doDrawer(); } } }
Source:
<code>public void testTimeout() throws SystemException, RemoteException { <START> log.info("Method stateful #testTimeout called"); <END> Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); try { TxTestUtil.waitForTimeout(tm); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RemoteException("Interupted during waiting for transaction timeout", ie); } }</code><technical_language>log.tracef</technical_language>

Target:
public void testTimeout() throws SystemException, RemoteException { log.trace("Method stateful #testTimeout called"); Transaction txn; txn = tm.getTransaction(); TxTestUtil.enlistTestXAResource(txn); TxTestUtil.enlistTestXAResource(txn); try { TxTestUtil.waitForTimeout(tm); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RemoteException("Interupted during waiting for transaction timeout", ie); } }
Source:
<code>public WritableByteChannel create(final StorageResourceId resourceId, CreateObjectOptions options) throws IOException { logger.atFine().log("create(%s)", resourceId); Preconditions.checkArgument( resourceId.isStorageObject(), "Expected full StorageObject id, got %s", resourceId); Optional<Long> overwriteGeneration = resourceId.hasGenerationId() ? Optional.of(resourceId.getGenerationId()) : Optional.of(getWriteGeneration(resourceId, options.overwriteExisting())); ObjectWriteConditions writeConditions = new ObjectWriteConditions(overwriteGeneration, Optional.<Long>absent()); Map<String, String> rewrittenMetadata = encodeMetadata(options.getMetadata()); GoogleCloudStorageWriteChannel channel = new GoogleCloudStorageWriteChannel( backgroundTasksThreadPool, gcs, clientRequestHelper, resourceId.getBucketName(), resourceId.getObjectName(), options.getContentType(), options.getContentEncoding(), null, storageOptions.getWriteChannelOptions(), writeConditions, rewrittenMetadata) { @Override public Storage.Objects.Insert createRequest(InputStreamContent inputStream) throws IOException { <START> Storage.Objects.Insert insertObject = super.createRequest(inputStream); <END> return configureRequest(insertObject, resourceId.getBucketName()); } }; channel.initialize(); return channel; }</code><technical_language>Revert</technical_language>

Target:
public WritableByteChannel create(final StorageResourceId resourceId, CreateObjectOptions options) throws IOException { logger.atFine().log("create(%s)", resourceId); Preconditions.checkArgument( resourceId.isStorageObject(), "Expected full StorageObject id, got %s", resourceId); Optional<Long> overwriteGeneration = resourceId.hasGenerationId() ? Optional.of(resourceId.getGenerationId()) : Optional.of(getWriteGeneration(resourceId, options.overwriteExisting())); ObjectWriteConditions writeConditions = new ObjectWriteConditions(overwriteGeneration, Optional.<Long>absent()); Map<String, String> rewrittenMetadata = encodeMetadata(options.getMetadata()); GoogleCloudStorageWriteChannel channel = new GoogleCloudStorageWriteChannel( backgroundTasksThreadPool, gcs, clientRequestHelper, resourceId.getBucketName(), resourceId.getObjectName(), options.getContentType(), options.getContentEncoding(), null, storageOptions.getWriteChannelOptions(), writeConditions, rewrittenMetadata) { @Override public Storage.Objects.Insert createRequest(InputStreamContent inputStream) throws IOException { return configureRequest(super.createRequest(inputStream), resourceId.getBucketName()); } }; channel.initialize(); return channel; }
Source:
<code>private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new HashMap<>(); lifecycleBeans.forEach((beanName, bean) -> { if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) { int phase = getPhase(bean); LifecycleGroup group = phases.computeIfAbsent(phase, <START> p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly)); <END> group.add(beanName, bean); } }); if (!phases.isEmpty()) { List<Integer> keys = new ArrayList<>(phases.keySet()); Collections.sort(keys); for (Integer key : keys) { phases.get(key).start(); } } }</code><technical_language>sorry, explain "but I added a judgment reduce execution of iterator automatic code" - this means? I get it. thank</technical_language>

Target:
private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new TreeMap<>(); lifecycleBeans.forEach((beanName, bean) -> { if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) { int phase = getPhase(bean); phases.computeIfAbsent( phase, p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly) ).add(beanName, bean); } }); if (!phases.isEmpty()) { phases.forEach((key, value) -> value.start()); } }
Source:
<code>private CertificationResultSvapEntity getCertificationResultSvapEntityById(Long certificationResultSvapId) { Query query = entityManager.createQuery( "SELECT s " + "FROM CertificationResultSvapEntity s " <START> + "LEFT OUTER JOIN FETCH s.svap " <END> + "WHERE s.deleted <> true " + "AND s.id = :certificationResultSvapId ", CertificationResultSvapEntity.class); query.setParameter("certificationResultSvapId", certificationResultSvapId); List<CertificationResultSvapEntity> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } else { return null; } }</code><technical_language>this need a left join JOIN FETCH sufficient? I entry in this table if association there</technical_language>

Target:
private CertificationResultSvapEntity getCertificationResultSvapEntityById(Long certificationResultSvapId) { Query query = entityManager.createQuery( "SELECT s " + "FROM CertificationResultSvapEntity s " + "JOIN FETCH s.svap " + "WHERE s.deleted <> true " + "AND s.id = :certificationResultSvapId ", CertificationResultSvapEntity.class); query.setParameter("certificationResultSvapId", certificationResultSvapId); List<CertificationResultSvapEntity> result = query.getResultList(); if (result.size() > 0) { return result.get(0); } else { return null; } }
Source:
<code>public CapableIndexReference index( int label, int... properties ) { ktx.assertOpen(); <START> if ( label == KeyReadOperations.NO_SUCH_LABEL <END> || Arrays.contains( properties, KeyReadOperations.NO_SUCH_PROPERTY_KEY ) ) { return CapableIndexReference.NO_INDEX; } LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel( label, properties ); SchemaIndexDescriptor indexDescriptor = storeReadLayer.indexGetForSchema( descriptor ); if ( ktx.hasTxStateWithChanges() ) { ReadableDiffSets<SchemaIndexDescriptor> diffSets = ktx.txState().indexDiffSetsByLabel( label ); if ( indexDescriptor != null ) { if ( diffSets.isRemoved( indexDescriptor ) ) { return CapableIndexReference.NO_INDEX; } else { return indexGetCapability( indexDescriptor ); } } else { Iterator<SchemaIndexDescriptor> fromTxState = filter( SchemaDescriptor.equalTo( descriptor ), diffSets.apply( emptyResourceIterator() ) ); if ( fromTxState.hasNext() ) { return fromDescriptor( fromTxState.next() ); } else { return CapableIndexReference.NO_INDEX; } } } return indexDescriptor != null ? indexGetCapability( indexDescriptor ) : CapableIndexReference.NO_INDEX; }</code><technical_language>deep this level need check for label property id validity</technical_language>

Target:
public CapableIndexReference index( int label, int... properties ) { ktx.assertOpen(); LabelSchemaDescriptor descriptor; try { descriptor = SchemaDescriptorFactory.forLabel( label, properties ); } catch ( IllegalArgumentException ignore ) { return CapableIndexReference.NO_INDEX; } SchemaIndexDescriptor indexDescriptor = storeReadLayer.indexGetForSchema( descriptor ); if ( ktx.hasTxStateWithChanges() ) { ReadableDiffSets<SchemaIndexDescriptor> diffSets = ktx.txState().indexDiffSetsByLabel( label ); if ( indexDescriptor != null ) { if ( diffSets.isRemoved( indexDescriptor ) ) { return CapableIndexReference.NO_INDEX; } else { return indexGetCapability( indexDescriptor ); } } else { Iterator<SchemaIndexDescriptor> fromTxState = filter( SchemaDescriptor.equalTo( descriptor ), diffSets.apply( emptyResourceIterator() ) ); if ( fromTxState.hasNext() ) { return DefaultCapableIndexReference.fromDescriptor( fromTxState.next() ); } else { return CapableIndexReference.NO_INDEX; } } } return indexDescriptor != null ? indexGetCapability( indexDescriptor ) : CapableIndexReference.NO_INDEX; }
Source:
<code>public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { float x = Float.parseFloat(xValue); float y = Float.parseFloat(yValue); return new Entry(x, y); } catch (NumberFormatException e) { } <START> } catch (Exception e) { <END> } return null; }</code><technical_language>Is a more specific exception caught here</technical_language>

Target:
public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { float x = Float.parseFloat(xValue); float y = Float.parseFloat(yValue); return new Entry(x, y); } catch (NumberFormatException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INVALID_CHART_ENTRY_VALUES, xValue, yValue); } } catch (NullPointerException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_NULL_CHART_ENTRY_VALUES); } catch (IndexOutOfBoundsException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INSUFFICIENT_CHART_ENTRY_VALUES, getTupleSize(), tuple.size()); } return null; }
Source:
<code>private void compareTracedItems(Resource changedResource) { TracePersistenceAdapter persistenceAdapter = ExtensionPointHelper.getTracePersistenceAdapter().get(); ResourceSetImpl newResourceSet = new ResourceSetImpl(); EObject traceModel = persistenceAdapter.getTraceModel(newResourceSet); <START> if (!(traceModel == null)) { <END> IPath path = new Path(EcoreUtil.getURI(traceModel).toPlatformString(false)); IFile traceContainer = ResourcesPlugin.getWorkspace().getRoot().getFile(path); TraceMetaModelAdapter traceMetamodelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); List<Connection> connections = traceMetamodelAdapter .getAllTraceLinks(persistenceAdapter.getTraceModel(new ResourceSetImpl())); if (!connections.isEmpty()) { for (Connection c : connections) { List<EObject> tempList = new ArrayList<>(); tempList.add(c.getOrigin()); tempList.addAll(c.getTargets()); for (EObject tracedItem : tempList) { Resource oldResource = tracedItem.eResource(); if (oldResource == null) oldResource = newResourceSet.getResource(EcoreUtil.getURI(tracedItem).trimFragment(), true); if (oldResource != null) { if (CapraNotificationHelper.getFileUri(oldResource) .equals(CapraNotificationHelper.getFileUri(changedResource))) { IComparisonScope scope = new DefaultComparisonScope(changedResource, oldResource, null); Comparison comparison = EMFCompare.builder().build().compare(scope); for (Match match : comparison.getMatches()) resolveMatch(tracedItem, match, null, traceContainer); } } } } } } }</code><technical_language>if (traceModel != null) {</technical_language>

Target:
private void compareTracedItems(Resource changedResource) { TracePersistenceAdapter persistenceAdapter = ExtensionPointHelper.getTracePersistenceAdapter().get(); ResourceSetImpl newResourceSet = new ResourceSetImpl(); EObject traceModel = persistenceAdapter.getTraceModel(newResourceSet); if (traceModel != null) { IPath path = new Path(EcoreUtil.getURI(traceModel).toPlatformString(false)); IFile traceContainer = ResourcesPlugin.getWorkspace().getRoot().getFile(path); TraceMetaModelAdapter traceMetamodelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); List<Connection> connections = traceMetamodelAdapter .getAllTraceLinks(persistenceAdapter.getTraceModel(new ResourceSetImpl())); if (!connections.isEmpty()) { for (Connection c : connections) { List<EObject> tempList = new ArrayList<>(); tempList.add(c.getOrigin()); tempList.addAll(c.getTargets()); for (EObject tracedItem : tempList) { Resource oldResource = tracedItem.eResource(); if (oldResource == null) oldResource = newResourceSet.getResource(EcoreUtil.getURI(tracedItem).trimFragment(), true); if (oldResource != null) { if (CapraNotificationHelper.getFileUri(oldResource) .equals(CapraNotificationHelper.getFileUri(changedResource))) { IComparisonScope scope = new DefaultComparisonScope(changedResource, oldResource, null); Comparison comparison = EMFCompare.builder().build().compare(scope); for (Match match : comparison.getMatches()) resolveMatch(tracedItem, match, null, traceContainer); } } } } } } }
Source:
<code>public void subscribe(Collection<String> topics, ConsumerRebalanceListener listener) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); if (topics == null) throw new IllegalArgumentException("Topic collection to subscribe to cannot be null"); if (topics.isEmpty()) { this.unsubscribe(); } else { for (String topic : topics) { if (topic == null || topic.trim().isEmpty()) throw new IllegalArgumentException("Topic collection to subscribe to cannot contain null or empty topic"); } throwIfNoAssignorsConfigured(); fetcher.clearBufferedDataForUnassignedTopics(topics); log.info("Subscribed to topic(s): {}", Utils.join(topics, ", ")); <START> System.out.println("start subscription to new"); <END> if (this.subscriptions.subscribe(new HashSet<>(topics), listener)) metadata.requestUpdateForNewTopics(); } } finally { release(); } }</code><technical_language>This for debugging only, remove</technical_language>

Target:
public void subscribe(Collection<String> topics, ConsumerRebalanceListener listener) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); if (topics == null) throw new IllegalArgumentException("Topic collection to subscribe to cannot be null"); if (topics.isEmpty()) { this.unsubscribe(); } else { for (String topic : topics) { if (topic == null || topic.trim().isEmpty()) throw new IllegalArgumentException("Topic collection to subscribe to cannot contain null or empty topic"); } throwIfNoAssignorsConfigured(); fetcher.clearBufferedDataForUnassignedTopics(topics); log.info("Subscribed to topic(s): {}", Utils.join(topics, ", ")); if (this.subscriptions.subscribe(new HashSet<>(topics), listener)) metadata.requestUpdateForNewTopics(); } } finally { release(); } }
Source:
<code>protected void begin() { <START> DataContainer dataContainer = scene.getDataContainer(); <END> List<UserVariable> variableList = dataContainer.getProjectVariables(); Map<Sprite, List<UserVariable>> spriteVariableMap = dataContainer.getSpriteVariableMap(); setVariablesVisible(variableList); if (sprite != null) { List<UserVariable> spriteVariableList = spriteVariableMap.get(sprite); setVariablesVisible(spriteVariableList); } if (userBrick != null) { List<UserVariable> userBrickVariableList = dataContainer.getOrCreateVariableListForUserBrick(userBrick); setVariablesVisible(userBrickVariableList); } }</code><technical_language>getSceneToPlay() here! do need getSceneOfSprite Method</technical_language>

Target:
protected void begin() { DataContainer dataContainer = ProjectManager.getInstance().getSceneToPlay().getDataContainer(); List<UserVariable> variableList = dataContainer.getProjectVariables(); Map<Sprite, List<UserVariable>> spriteVariableMap = dataContainer.getSpriteVariableMap(); setVariablesVisible(variableList); if (sprite != null) { List<UserVariable> spriteVariableList = spriteVariableMap.get(sprite); setVariablesVisible(spriteVariableList); } if (userBrick != null) { List<UserVariable> userBrickVariableList = dataContainer.getOrCreateVariableListForUserBrick(userBrick); setVariablesVisible(userBrickVariableList); } }
Source:
<code>public static File getCredentialsDir() { String dir = System.getenv(CREDENTIALS_DIR_PROP); if (dir == null) { dir = System.getProperty(CREDENTIALS_DIR_PROP); if (dir == null) { if (new File(DEFAULT_CREDENTIALS_DIR).exists() && new File(DEFAULT_CREDENTIALS_DIR).isDirectory()) { return new File(DEFAULT_CREDENTIALS_DIR); } else { throw new IllegalStateException( <START> String.format("environment variable %s not set and default '/meta/credentials' not exists or not a directory.", CREDENTIALS_DIR_PROP)); <END> } } } return new File(dir); }</code><technical_language>. exist is a directory. Also: put %s /meta/credentials constant</technical_language>

Target:
public static File getCredentialsDir() { String dir = System.getenv(CREDENTIALS_DIR_PROP); if (dir == null) { dir = System.getProperty(CREDENTIALS_DIR_PROP); if (dir == null) { if (new File(DEFAULT_CREDENTIALS_DIR).exists() && new File(DEFAULT_CREDENTIALS_DIR).isDirectory()) { return new File(DEFAULT_CREDENTIALS_DIR); } else { throw new IllegalStateException( String.format("environment variable %s not set and default '%s' does not exist or is not a directory.", CREDENTIALS_DIR_PROP, DEFAULT_CREDENTIALS_DIR)); } } } return new File(dir); }
Source:
<code>public void testApplicationCreationWithValidMandatoryValues(String applicationName, String tier, String description) throws Exception { HttpResponse addApplicationResponse = apiStore .addApplication(URLEncoder.encode(applicationName, UTF_8), URLEncoder.encode(tier, UTF_8), "", URLEncoder.encode(description, UTF_8)); applicationsList.add(applicationName); assertEquals(addApplicationResponse.getResponseCode(), Response.Status.OK.getStatusCode(), ERROR_APPLICATION_CREATION_RESPONSE_CODE + applicationName); JSONObject addApplicationJsonObject = new JSONObject(addApplicationResponse.getData()); assertFalse(addApplicationJsonObject.getBoolean(ERROR), ERROR_APPLICATION_CREATION_WITH_VALID_INPUT + applicationName); assertEquals(addApplicationJsonObject.get(STATUS), STATUS_APPROVED, ERROR_APPLICATION_CREATION_WITH_VALID_INPUT + applicationName); validateApplicationWithValidMandatoryValues(applicationName, tier, description); <START> destroy(); <END> }</code><technical_language>reason for call this explicitly</technical_language>

Target:
public void testApplicationCreationWithValidMandatoryValues(String applicationName, String tier, String description) throws Exception { HttpResponse addApplicationResponse = apiStore .addApplication(URLEncoder.encode(applicationName, UTF_8), URLEncoder.encode(tier, UTF_8), "", URLEncoder.encode(description, UTF_8)); applicationsList.add(applicationName); assertEquals(addApplicationResponse.getResponseCode(), Response.Status.OK.getStatusCode(), ERROR_APPLICATION_CREATION_RESPONSE_CODE + applicationName); JSONObject addApplicationJsonObject = new JSONObject(addApplicationResponse.getData()); assertFalse(addApplicationJsonObject.getBoolean(ERROR), ERROR_APPLICATION_CREATION_WITH_VALID_INPUT + applicationName); assertEquals(addApplicationJsonObject.get(STATUS), STATUS_APPROVED, ERROR_APPLICATION_CREATION_WITH_VALID_INPUT + applicationName); validateApplicationWithValidMandatoryValues(applicationName, tier, description); }
Source:
<code>public void acceptsIso8601Dates () { Param<LocalDate> localDate = Param.localDate("start", "export_start_date", "Export start date"); <START> assertThat(localDate.map("2018-01-20").isEqual(LocalDate.of(2018, 01,20)), is(true)); <END> }</code><technical_language>assertions leveraging Hamcrest matchers correctly. that, change expected local date produce a test failure error message: xunit java.lang.AssertionError: Expected: is <true> but: <false> Expected :is <true> Actual :<false> compare change assertion this: java assertThat(localDate.map("2018-01-20"), is(LocalDate.of(2018, 2,20))); java.lang.AssertionError: Expected: is <2018-02-20> but: <2018-01-20> Expected :is <2018-02-20> Actual :<2018-01-20> failure message is more useful</technical_language>

Target:
public void acceptsIso8601Dates () { Param<LocalDate> localDate = Param.localDate("start", "export_start_date", "Export start date"); assertThat(localDate.map("2018-01-20"), is(LocalDate.of(2018, 1,20))); }
Source:
<code>public void resetRecords() { if (loader.getStatus() == Status.RUNNING) { loader.cancel(false); loader = loader.spawn(); } else if (loader.getStatus() == Status.FINISHED) { loader = loader.spawn(); } SqlStorage<FormRecord> storage = CommCareApplication.instance().getUserStorage(FormRecord.class); if (filter == null) { filter = FormRecordFilter.SubmittedAndPending; } records.clear(); String currentAppId = CommCareApplication.instance().getCurrentApp().getAppRecord().getApplicationId(); for (String status : filter.getStatus()) { records.addAll(storage.getRecordsForValues( new String[]{FormRecord.META_STATUS, FormRecord.META_APP_ID}, new Object[]{status, currentAppId})); } Collections.sort(records, (left, right) -> { if (!filter.equals(FormRecordFilter.Pending)) { long leftModTime = left.lastModified().getTime(); long rightModTime = right.lastModified().getTime(); if (leftModTime > rightModTime) { return -1; } else if (leftModTime == rightModTime) { return 0; } else { return 1; } } else { <START> int leftSubmissionOrderNum = left.getSubmissionOrderingNumber(); <END> int rightSubmissionOrderNum = right.getSubmissionOrderingNumber(); if (leftSubmissionOrderNum < rightSubmissionOrderNum) { return -1; } else if (leftSubmissionOrderNum == rightSubmissionOrderNum) { return 0; } else { return 1; } } }); searchCache.clear(); current.clear(); notifyDataSetChanged(); loader.init(searchCache, names); loader.executeParallel(records.toArray(new FormRecord[records.size()])); }</code><technical_language>do this [sorting](<LINK_0> sending forms server. great if utilize code here</technical_language>

Target:
public void resetRecords() { if (loader.getStatus() == Status.RUNNING) { loader.cancel(false); loader = loader.spawn(); } else if (loader.getStatus() == Status.FINISHED) { loader = loader.spawn(); } SqlStorage<FormRecord> storage = CommCareApplication.instance().getUserStorage(FormRecord.class); if (filter == null) { filter = FormRecordFilter.SubmittedAndPending; } records.clear(); String currentAppId = CommCareApplication.instance().getCurrentApp().getAppRecord().getApplicationId(); Vector recordsVector = new Vector(); for (String status : filter.getStatus()) { recordsVector.addAll(storage.getRecordsForValues( new String[]{FormRecord.META_STATUS, FormRecord.META_APP_ID}, new Object[]{status, currentAppId})); } if (filter.equals(FormRecordFilter.Pending)) { StorageUtils.sortRecordsBySubmissionOrderingNumber(recordsVector); } else { StorageUtils.sortRecordsByLastModifiedTimeDescending(recordsVector); } records.addAll(recordsVector); searchCache.clear(); current.clear(); notifyDataSetChanged(); loader.init(searchCache, names); loader.executeParallel(records.toArray(new FormRecord[records.size()])); }
Source:
<code>public void getAllTickersByCurrencyShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final TickerService tickerService = adapter.create(TickerService.class); final String currency = "foobar"; tickerService.getAllTickersByCurrency(currency, new RetrofitPromise<List<Ticker>>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/ticker/%s", MOCK_URL, currency)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); }</code><technical_language>Add newline return</technical_language>

Target:
public void getAllTickersByCurrencyShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final TickerService tickerService = adapter.create(TickerService.class); tickerService.getAllTickersByCurrency("foobar", new RetrofitPromise<List<Ticker>>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/ticker/%s", MOCK_URL, "foobar")); }
Source:
<code>protected void onResume() { super.onResume(); mIALocationManager.lockIndoors(false); <START> mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mListener); <END> mIALocationManager.registerRegionListener(mRegionListener); }</code><technical_language>change this this: IALocationRequest locReq = IALocationRequest.create(); locReq.setPriority(IALocationRequest.PRIORITY_HIGH_ACCURACY); // default mode // locReq.setPriority(IALocationRequest.PRIORITY_LOW_POWER); // power, accuracy e.g. for background tracking // locReq.setPriority(IALocationRequest.PRIORITY_CART_MODE); // device is mounted a shopping cart similar platform wheels mIALocationManager.requestLocationUpdates(locReq, mListener);</technical_language>

Target:
protected void onResume() { super.onResume(); mIALocationManager.lockIndoors(false); IALocationRequest locReq = IALocationRequest.create(); locReq.setPriority(IALocationRequest.PRIORITY_HIGH_ACCURACY); mIALocationManager.requestLocationUpdates(locReq, mListener); mIALocationManager.registerRegionListener(mRegionListener); }
Source:
<code>private void setClientTimeout(WorkItem workItem, Client client) { HTTPConduit conduit = (HTTPConduit) client.getConduit(); <START> HTTPClientPolicy policy = (HTTPClientPolicy) conduit.getClient(); <END> long connectionTimeout = defaultJbpmCxfClientConnectionTimeout; String connectionTimeoutStr = (String) workItem.getParameter("ConnectionTimeout"); if (connectionTimeoutStr != null && !connectionTimeoutStr.trim().isEmpty()) { connectionTimeout = Long.valueOf(connectionTimeoutStr); } long receiveTimeout = defaultJbpmCxfClientReceiveTimeout; String receiveTimeoutStr = (String) workItem.getParameter("ReceiveTimeout"); if (receiveTimeoutStr != null && !receiveTimeoutStr.trim().isEmpty()) { receiveTimeout = Long.valueOf(receiveTimeoutStr); } logger.info("connectionTimeout = {}, receiveTimeout = {}", connectionTimeout, receiveTimeout); policy.setConnectionTimeout(connectionTimeout); policy.setReceiveTimeout(receiveTimeout); }</code><technical_language>IDE told this cast is redundant</technical_language>

Target:
private void setClientTimeout(WorkItem workItem, Client client) { HTTPConduit conduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy policy = conduit.getClient(); long connectionTimeout = defaultJbpmCxfClientConnectionTimeout; String connectionTimeoutStr = (String) workItem.getParameter("ConnectionTimeout"); if (connectionTimeoutStr != null && !connectionTimeoutStr.trim().isEmpty()) { connectionTimeout = Long.valueOf(connectionTimeoutStr); } long receiveTimeout = defaultJbpmCxfClientReceiveTimeout; String receiveTimeoutStr = (String) workItem.getParameter("ReceiveTimeout"); if (receiveTimeoutStr != null && !receiveTimeoutStr.trim().isEmpty()) { receiveTimeout = Long.valueOf(receiveTimeoutStr); } logger.debug("connectionTimeout = {}, receiveTimeout = {}", connectionTimeout, receiveTimeout); policy.setConnectionTimeout(connectionTimeout); policy.setReceiveTimeout(receiveTimeout); }
Source:
<code>private DateTime getTimeBoundary(StorageAdapter adapter, TimeBoundaryQuery legacyQuery, boolean descending) { final Sequence<Result<DateTime>> resultSequence = QueryRunnerHelper.makeCursorBasedQuery( adapter, legacyQuery.getQuerySegmentSpec().getIntervals(), Filters.toFilter(legacyQuery.getDimensionsFilter()), VirtualColumns.EMPTY, descending, <START> new AllGranularity(), <END> this.skipToFirstMatching ); final List<Result<DateTime>> resultList = Sequences.toList( Sequences.limit(resultSequence, 1), Lists.<Result<DateTime>>newArrayList() ); if (resultList.size() > 0) { return resultList.get(0).getValue(); } return null; }</code><technical_language>Granularities.ALL here</technical_language>

Target:
private DateTime getTimeBoundary(StorageAdapter adapter, TimeBoundaryQuery legacyQuery, boolean descending) { final Sequence<Result<DateTime>> resultSequence = QueryRunnerHelper.makeCursorBasedQuery( adapter, legacyQuery.getQuerySegmentSpec().getIntervals(), Filters.toFilter(legacyQuery.getDimensionsFilter()), VirtualColumns.EMPTY, descending, Granularities.ALL, this.skipToFirstMatching ); final List<Result<DateTime>> resultList = Sequences.toList( Sequences.limit(resultSequence, 1), Lists.<Result<DateTime>>newArrayList() ); if (resultList.size() > 0) { return resultList.get(0).getValue(); } return null; }
Source:
<code><START> public void failedCreation() throws Exception { <END> final NewAccessPoint ap = new NewAccessPoint("operatorId", "ip", new MacAddress("aa:bb"), "sn", "model"); final NewAccessPointDTO dto = new NewAccessPointDTO("operatorId", "ip", "aa:bb", "sn", "model"); context.checking(new Expectations() {{ oneOf(repository).create(with(matching(ap))); will(throwException(new NotFoundException("missing operator"))); }}); Request request = makeRequestThatContains(dto); service.create(request); }</code><technical_language>do test this? Nothing...</technical_language>

Target:
public void failedCreation() throws Exception { VenueDTO venueDTO = new VenueDTO("group", "type", Lists.newArrayList(new VenueNameDTO("info", "en"))); Venue venue = new Venue(new VenueGroup(venueDTO.group), new VenueType(venueDTO.type), Lists.newArrayList(new VenueName("info", new Language("en")))); final NewAccessPoint ap = new NewAccessPoint("operatorId", "ip", new MacAddress("aa:bb"), "sn", "model", venue); final NewAccessPointDTO dto = new NewAccessPointDTO("operatorId", "ip", "aa:bb", "sn", "model", venueDTO); context.checking(new Expectations() {{ oneOf(repository).create(with(matching(ap))); will(throwException(new NotFoundException("missing operator"))); }}); Request request = makeRequestThatContains(dto); service.create(request); }
Source:
<code>private static LoadBalancingPolicy loadBalancingPolicy(CassandraKeyValueServiceConfig config, <START> Set<InetSocketAddress> servers) { <END> LoadBalancingPolicy policy = LatencyAwarePolicy.builder(new RoundRobinPolicy()).build(); if (!config.autoRefreshNodes()) { policy = new WhiteListPolicy(policy, servers); } return new TokenAwarePolicy(policy, TokenAwarePolicy.ReplicaOrdering.RANDOM); }</code><technical_language>nit: matter of preference, I write else blocks returning end of branch</technical_language>

Target:
private static LoadBalancingPolicy loadBalancingPolicy(CassandraKeyValueServiceConfig config, Set<InetSocketAddress> servers) { LoadBalancingPolicy policy = LatencyAwarePolicy.builder(new RoundRobinPolicy()).build(); if (!config.autoRefreshNodes()) { policy = new WhiteListPolicy(policy, servers); } return new TokenAwarePolicy(policy); }
Source:
<code>private void handleQueue(MemberStateImpl memberState, Config config, Map<String, LocalQueueStats> queues) { <START> Set<String> mapsWithStats = createHashSet(queues.size()); <END> for (String name : queues.keySet()) { if (config.findQueueConfig(name).isStatisticsEnabled()) { mapsWithStats.add(name); } } memberState.setQueuesWithStats(mapsWithStats); }</code><technical_language>Minor: maps -> queue</technical_language>

Target:
private void handleQueue(MemberStateImpl memberState, Config config, Map<String, LocalQueueStats> queues) { Set<String> queuesWithStats = createHashSet(queues.size()); for (String name : queues.keySet()) { if (config.findQueueConfig(name).isStatisticsEnabled()) { queuesWithStats.add(name); } } memberState.setQueuesWithStats(queuesWithStats); }
Source:
<code>private MetacardMapper lookupMetacardAttributeToFeaturePropertyMapper(QName featureType) { MetacardMapper metacardAttributeToFeaturePropertyMapper = null; if (this.metacardToFeatureMappers != null) { for (MetacardMapper mapper : this.metacardToFeatureMappers) { if (mapper != null && StringUtils.equals(mapper.getFeatureType(), featureType.toString())) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( <START> "Found for feature type {}.", <END> MetacardMapper.class.getSimpleName(), featureType.toString()); } metacardAttributeToFeaturePropertyMapper = mapper; break; } } if (metacardAttributeToFeaturePropertyMapper == null && LOGGER.isDebugEnabled()) { LOGGER.debug( "Unable to find a for feature type {}.", MetacardMapper.class.getSimpleName(), featureType.toString()); } } return metacardAttributeToFeaturePropertyMapper; }</code><technical_language>remove call .toString() simply hardcode 'MetacardMapper avoid call if</technical_language>

Target:
private MetacardMapper lookupMetacardAttributeToFeaturePropertyMapper(QName featureType) { MetacardMapper metacardAttributeToFeaturePropertyMapper = null; if (this.metacardToFeatureMappers != null) { for (MetacardMapper mapper : this.metacardToFeatureMappers) { if (mapper != null && StringUtils.equals(mapper.getFeatureType(), featureType.toString())) { LOGGER.debug("Found MetacardMapper for feature type {}.", featureType); metacardAttributeToFeaturePropertyMapper = mapper; break; } } if (metacardAttributeToFeaturePropertyMapper == null) { LOGGER.debug("Unable to find a MetacardMapper for feature type {}.", featureType); } } return metacardAttributeToFeaturePropertyMapper; }
Source:
<code>public static StandardEvaluationContext createStandardEvaluationContext(BeanFactory beanFactory) { ConversionService conversionService = null; if (beanFactory != null) { <START> IntegrationContextUtils.getConversionService(beanFactory); <END> } return createStandardEvaluationContext(beanFactory, conversionService); }</code><technical_language>is this missing assignment conversionService</technical_language>

Target:
public static StandardEvaluationContext createStandardEvaluationContext(BeanFactory beanFactory) { if (beanFactory == null) { logger.warn("Creating EvaluationContext with no beanFactory", new RuntimeException("No beanfactory")); } return doCreateContext(beanFactory); }
Source:
<code>public GridTimer getTimer() { if (gettimer() == null) { settimer(new GridTimer(getListName()) { @Override public void execute() { logger.fine(SearchableListModel.this.getClass().getName() + ": Executing search"); syncSearch(); gettimer().stop(); gettimer().setRefreshRate(gettimer().getRefreshRate()); <START> gettimer().start(); <END> } }); } return gettimer(); }</code><technical_language>suggest extract lines a separate protected method improve readability remove code duplication in EventListModel. For example: protected void updateRefreshRate(GridTimer timer) { ... } Also, this line a bit weird: gettimer().setRefreshRate(gettimer().getRefreshRate()); do need do that? AbstractRefreshManager is responsible for controlling refresh rate of a GridController, of yield call GridTimer#setRefreshRate: * user changing refresh rate drop-down in GUI = AbstractRefreshManager#setCurrentRefreshRate * application window losing/gaining focus = AbstractRefreshManager#onWindowFocusChange</technical_language>

Target:
public GridTimer getTimer() { if (timer == null && getEventBus() != null) { setTimer(new GridTimer(getListName(), getEventBus()) { @Override public void execute() { doGridTimerExecute(); } }); addTimerChangeListener(); } return timer; }
Source:
<code><START> public synchronized void aggregate() <END> { final ArrayOfDoublesSketch update = selector.getObject(); if (update == null) { return; } union.update(update); }</code><technical_language>locks needed in Build Merge Aggregators alike</technical_language>

Target:
public void aggregate() { final ArrayOfDoublesSketch update = selector.getObject(); if (update == null) { return; } synchronized (this) { union.update(update); } }
Source:
<code>protected int doWork() { final MetricsFile<MetricBase, Comparable<?>> laneMetricsFile = this.getMetricsFile(); final MetricsFile<MetricBase, Comparable<?>> phasingMetricsFile = this.getMetricsFile(); if (INCLUDE_SKIPS_AND_MOLECULAR_BARCODES) { final List<ReadDescriptor> descriptors = READ_STRUCTURE.descriptors.stream().map(descriptor -> { if (descriptor.type == ReadType.Skip || descriptor.type == ReadType.MolecularIndex) { return new ReadDescriptor(descriptor.length, ReadType.Template); <START> } <END> else { return descriptor; } }).collect(Collectors.toList()); READ_STRUCTURE = new ReadStructure(descriptors); } IlluminaLaneMetricsCollector.collectLaneMetrics(RUN_DIRECTORY, OUTPUT_DIRECTORY, OUTPUT_PREFIX, laneMetricsFile, phasingMetricsFile, READ_STRUCTURE); return 0; }</code><technical_language>dropped :-)</technical_language>

Target:
protected int doWork() { final MetricsFile<MetricBase, Comparable<?>> laneMetricsFile = this.getMetricsFile(); final MetricsFile<MetricBase, Comparable<?>> phasingMetricsFile = this.getMetricsFile(); if (READ_STRUCTURE == null) { final File runInfo = new File(RUN_DIRECTORY + "/" + "RunInfo.xml"); IOUtil.assertFileIsReadable(runInfo); try { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(runInfo); final NodeList reads = document.getElementsByTagName("Read"); final List<ReadDescriptor> descriptors = new ArrayList<>(reads.getLength()); for (int i = 0; i < reads.getLength(); i++) { final Node read = reads.item(i); final NamedNodeMap attributes = read.getAttributes(); final int readNumber = Integer.parseInt(attributes.getNamedItem("Number").getNodeValue()); final int numCycles = Integer.parseInt(attributes.getNamedItem("NumCycles").getNodeValue()); final boolean isIndexedRead = attributes.getNamedItem("IsIndexedRead").getNodeValue().toUpperCase().equals("Y"); if (readNumber != i + 1) throw new PicardException("Read number in RunInfo.xml was out of order: " + (i+1) + " != " + readNumber); descriptors.add(new ReadDescriptor(numCycles, isIndexedRead ? ReadType.Barcode: ReadType.Template)); } READ_STRUCTURE = new ReadStructure(descriptors); } catch (final Exception e) { throw new PicardException(e.getMessage()); } } IlluminaLaneMetricsCollector.collectLaneMetrics(RUN_DIRECTORY, OUTPUT_DIRECTORY, OUTPUT_PREFIX, laneMetricsFile, phasingMetricsFile, READ_STRUCTURE); return 0; }
Source:
<code>private BlockReader seek(byte blockType, byte[] key, BlockReader idx, long startPos, long endPos) throws IOException { if (idx != null) { BlockReader block = idx; do { long position = block.seekKey(key) <= 0 ? block.readPositionFromIndex() <START> : ((blocksIn(startPos, endPos) - 1) * blockSize); <END> block = readBlock(position, endPos); } while (block.type() == INDEX_BLOCK_TYPE); block.seekKey(key); return block; } return binarySearch(blockType, key, startPos, endPos); }</code><technical_language>This appears seeking pas end of index, I understand</technical_language>

Target:
private BlockReader seek(byte blockType, byte[] key, BlockReader idx, long startPos, long endPos) throws IOException { if (idx != null) { BlockReader block = idx; do { if (block.seekKey(key) > 0) { return null; } long pos = block.readPositionFromIndex(); block = readBlock(pos, endPos); } while (block.type() == INDEX_BLOCK_TYPE); block.seekKey(key); return block; } return binarySearch(blockType, key, startPos, endPos); }
Source:
<code>V call(Callable<V,T> callable) throws IOException, T, InterruptedException { if (isClosingOrClosed()) { <START> throw new IOException("Remote call on " + name + " failed. The channel is closing down or has closed down"); <END> } UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { if(request!=null) request.releaseExports(); } }</code><technical_language>I expect this ChannelClosedException. is Request.call thrown a bit this patch, right</technical_language>

Target:
V call(Callable<V,T> callable) throws IOException, T, InterruptedException { if (isClosingOrClosed()) { throw new ChannelClosedException("Remote call on " + name + " failed. " + "The channel is closing down or has closed down", getCloseRequestCause()); } UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { if(request!=null) request.releaseExports(); } }
Source:
<code>private FilterType buildPropertyIsFilterTypeForProperty( String propertyName, Object literal, PROPERTY_IS_OPS propertyIsType, boolean isCaseSensitive) { final String featurePropertyName = Optional.ofNullable(metacardMapper.getFeatureProperty(propertyName)).orElse(propertyName); <START> if (isWfsFeatureProperty(featurePropertyName)) { <END> final FeatureAttributeDescriptor featureAttributeDescriptor = (FeatureAttributeDescriptor) featureMetacardType.getAttributeDescriptor(featurePropertyName); if (featureAttributeDescriptor.isIndexed()) { final FilterType filter = new FilterType(); filter.setComparisonOps( createPropertyIsFilter( featureAttributeDescriptor.getPropertyName(), literal, propertyIsType, isCaseSensitive)); return filter; } else { throw new IllegalArgumentException( String.format(PROPERTY_NOT_QUERYABLE, featurePropertyName)); } } else { LOGGER.debug( "The property '{}' could not be mapped to a feature property of feature type '{}'.", propertyName, featureMetacardType.getFeatureType()); return null; } }</code><technical_language>This need addressed now, this class is big. great for readability if broken a series of smaller factory classes</technical_language>

Target:
private FilterType buildPropertyIsFilterTypeForProperty( String propertyName, Object literal, PROPERTY_IS_OPS propertyIsType, boolean isCaseSensitive) { final String featurePropertyName = mapQueryPropertyToFeatureProperty(propertyName, this::isWfsFeatureProperty); if (featurePropertyName != null) { final FilterType filter = new FilterType(); filter.setComparisonOps( createPropertyIsFilter(featurePropertyName, literal, propertyIsType, isCaseSensitive)); return filter; } return null; }
Source:
<code>private HashMap<String, String> getRequestHeaders() { <START> HashMap<String, String> headers = new HashMap<>(); <END> headers.put("Accept", "application/json"); return headers; }</code><technical_language>Map</technical_language>

Target:
private Map<String, String> getRequestHeaders() { final Map<String, String> headers = new HashMap<>(); headers.put("Accept", "application/json"); return headers; }
Source:
<code>private void verifyPartitionedBucketedTable(HiveStorageFormat storageFormat, String tableName) { TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, tableName); assertEquals(tableMetadata.getMetadata().getProperties().get(STORAGE_FORMAT_PROPERTY), storageFormat); assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("orderstatus")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey", "custkey2")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKET_COUNT_PROPERTY), 11); List<?> partitions = getPartitions(tableName); assertEquals(partitions.size(), 3); assertQuery("SELECT * from " + tableName, "SELECT custkey, custkey, comment, orderstatus FROM orders"); for (int i = 1; i <= 30; i++) { assertQuery( format("SELECT * from " + tableName + " where custkey = %d and custkey2 = %d", i, i), format("SELECT custkey, custkey, comment, orderstatus FROM orders where custkey = %d", i)); } assertThatThrownBy(() -> assertUpdate("INSERT INTO " + tableName + " VALUES (1, 1, 'comment', 'O')", 1)) .hasMessage(getExpectedErrorMessageForInsertExistingBucketedTable( <START> HiveSessionProperties.getInsertExistingPartitionsBehavior(getSession().toConnectorSession(tableMetadata.getConnectorId())), <END> "orderstatus=O")); }</code><technical_language>Static import</technical_language>

Target:
private void verifyPartitionedBucketedTable(HiveStorageFormat storageFormat, String tableName) { TableMetadata tableMetadata = getTableMetadata(catalog, TPCH_SCHEMA, tableName); assertEquals(tableMetadata.getMetadata().getProperties().get(STORAGE_FORMAT_PROPERTY), storageFormat); assertEquals(tableMetadata.getMetadata().getProperties().get(PARTITIONED_BY_PROPERTY), ImmutableList.of("orderstatus")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey", "custkey2")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKET_COUNT_PROPERTY), 11); List<?> partitions = getPartitions(tableName); assertEquals(partitions.size(), 3); assertQuery("SELECT * from " + tableName, "SELECT custkey, custkey, comment, orderstatus FROM orders"); for (int i = 1; i <= 30; i++) { assertQuery( format("SELECT * from " + tableName + " where custkey = %d and custkey2 = %d", i, i), format("SELECT custkey, custkey, comment, orderstatus FROM orders where custkey = %d", i)); } assertThatThrownBy(() -> assertUpdate("INSERT INTO " + tableName + " VALUES (1, 1, 'comment', 'O')", 1)) .hasMessage(getExpectedErrorMessageForInsertExistingBucketedTable( getInsertExistingPartitionsBehavior(getConnectorSession(getSession())), "orderstatus=O")); }