auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGetChildrenOnLargeNumChildren() throws Exception { String path = "/" + TestHelper.getTestMethodName(); int toCreateChildrenCount = 110; _zkClient.createPersistent(path); for (int i = 0; i < toCreateChildrenCount; i++) { List<Op> ops = new ArrayList<>(1000); for (int j = 0; j < 1000; j++) { String child = path + "/" + UUID.randomUUID().toString(); ops.add(Op.create(child, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)); } _zkClient.multi(ops); } try { _zkClient.getChildren(path); Assert.fail("Should not successfully get children because of connection loss."); } catch (ZkException expected) { Assert.assertEquals(expected.getMessage(), "org.apache.zookeeper.KeeperException$MarshallingErrorException: " + "KeeperErrorCode = MarshallingError"); } finally { _zkClient.close(); _zkClient = new ZkClient(ZkTestBase.ZK_ADDR); Assert.assertTrue(TestHelper.verify(() -> { <START> _zkClient.delete(path); <END> return !_zkClient.exists(path); }, TestHelper.WAIT_DURATION)); } }</code><technical_language>delete parent path child node deleted</technical_language>

Target:
public void testGetChildrenOnLargeNumChildren() throws Exception { final String methodName = TestHelper.getTestMethodName(); System.out.println("Start test: " + methodName); String path = "/" + methodName; _zkClient.createPersistent(path); for (int i = 0; i < 110; i++) { List<Op> ops = new ArrayList<>(1000); for (int j = 0; j < 1000; j++) { String childPath = path + "/" + UUID.randomUUID().toString(); ops.add( Op.create(childPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)); } _zkClient.multi(ops); } try { _zkClient.getChildren(path); Assert.fail("Should not successfully get children because of connection loss."); } catch (ZkException expected) { Assert.assertEquals(expected.getMessage(), "org.apache.zookeeper.KeeperException$MarshallingErrorException: " + "KeeperErrorCode = MarshallingError"); } finally { _zkClient.close(); _zkClient = new ZkClient(ZkTestBase.ZK_ADDR); Assert.assertTrue(TestHelper.verify(() -> { try { return _zkClient.delete(path); } catch (ZkException e) { return false; } }, TestHelper.WAIT_DURATION)); } System.out.println("End test: " + methodName); }
Source:
<code><START> public Set<String> getRepositoryKeys() { <END> checkRunning(); final Lock lock = this.lock.readLock(); try { lock.lock(); return new HashSet<String>(repositories.keySet()); } finally { lock.unlock(); } }</code><technical_language>issue change in visibility of this method JcrRepository.start()</technical_language>

Target:
protected Set<String> getRepositoryKeys() { checkRunning(); final Lock lock = this.lock.readLock(); try { lock.lock(); return new HashSet<String>(repositories.keySet()); } finally { lock.unlock(); } }
Source:
<code>private int getKeySize() { <START> return _keySize; <END> }</code><technical_language>If _keySize is Integer return get unboxed reboxed. int Integer everywhere</technical_language>

Target:
private Integer getKeySize() { return _keySize; }
Source:
<code>protected void reportSizeLimitExceeded(final SizeLimitExceededException e, Validator validator) { validator.add(new I18nMessage("upload", "file.limit.exceeded", e.getActualSize(), e.getPermittedSize())); <START> logger.warn("The file size limit was exceeded."); <END> }</code><technical_language>helpful actual file size. logging exception here</technical_language>

Target:
protected void reportSizeLimitExceeded(final SizeLimitExceededException e, Validator validator) { validator.add(new I18nMessage("upload", "file.limit.exceeded", e.getActualSize(), e.getPermittedSize())); logger.warn("The file size limit was exceeded. Actual permitted {}", e.getActualSize(), e.getPermittedSize()); }
Source:
<code>protected Object getFailurePayload(P payload, Optional<BackupRestoreContext> flowContext, Exception ex) { <START> return null; <END> }</code><technical_language>afraid of this NullPointerException somewhere. If check failure handling action payload, if is a null pointer I flow stuck for a while</technical_language>

Target:
protected Object getFailurePayload(P payload, Optional<BackupRestoreContext> flowContext, Exception ex) { return new StackFailureEvent(payload.getResourceId(), ex); }
Source:
<code>public boolean hasRequiredProperties(MessageAddressingProperties map) { if (map.getAction() == null) { return false; } if ((map.getReplyTo() != null && !hasAnonymousAddress(map.getReplyTo()) && !hasNoneAddress(map.getReplyTo())) || (map.getFaultTo() != null && !hasAnonymousAddress(map.getFaultTo()) && !hasNoneAddress(map.getFaultTo()))){ <START> return map.getMessageId() != null; <END> } return true; }</code><technical_language>Reading boolean expressions chained in collection of "ands", "ors" "nots" takes logical gate construction need a Venn diagram grok. extract some functions embody intent more readable</technical_language>

Target:
public boolean hasRequiredProperties(MessageAddressingProperties map) { if (map.getAction() == null) { return false; } if (map.getReplyTo() != null || map.getFaultTo() != null) { return map.getMessageId() != null; } return true; }
Source:
<code>public void testUDPconnection() throws Exception { Subject<Object,Object> sub = PublishSubject.create(); SimpleChan <START> smpladapter = <END> new SimpleChan(sub); TestAwaitableObserver<Object> monitor = new TestAwaitableObserver<>(); sub.subscribe(monitor); int port = rand.nextInt(100) + 8000; ServerFrontEnd udpSrv = new ServerFrontEnd(smpladapter, port, true); udpSrv.startAsync().awaitRunning(); DatagramPacket msg = sendMSG(MSG, port); monitor.awaitOnNext(1, TIMEOUT); Assert.assertNotNull(monitor.getOnNextEvents().get(0)); }</code><technical_language>typo</technical_language>

Target:
public void testUDPconnection() throws Exception { Subject<Object,Object> sub = PublishSubject.create(); SimpleChan simpleadapter = new SimpleChan(sub); TestAwaitableObserver<Object> monitor = new TestAwaitableObserver<>(); sub.subscribe(monitor); int port = rand.nextInt(100) + 8000; ServerFrontEnd udpSrv = ServerFrontEnd.udp(simpleadapter, port); udpSrv.startAsync().awaitRunning(); sendMSG(MSG, port); monitor.awaitOnNext(1, TIMEOUT); Assert.assertNotNull(monitor.getOnNextEvents().get(0)); }
Source:
<code>private static TLSClientParameters constructTLSClient(TLSClientParameters tlsClientParameters) { boolean isDisableCNCheck = false; try { isDisableCNCheck = PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, DISABLE_CN_CHECK); } catch (PropertyAccessException ex) { LOG.error("Not able to read 'disableCNCheck' from the property file: {}", ex.getLocalizedMessage(), ex); } try { SSLSocketFactory factory = SSLUtils.getSSLContext(tlsClientParameters).getSocketFactory(); if (factory != null) { tlsClientParameters.setSSLSocketFactory(factory); } else { throw new SecurityException("Couldn't get the SSLSocketFactory."); } tlsClientParameters.setDisableCNCheck(isDisableCNCheck); <START> LOG.info("tlsClientParameters--disableCNCheck-is-set: '{}'", isDisableCNCheck); <END> } catch (GeneralSecurityException | IllegalStateException e) { LOG.error("Could not get TLS client parameters: ", e.getLocalizedMessage(), e); throw new SecurityException("Could not create SSL Context.", e); } return tlsClientParameters; }</code><technical_language>Optional: remove single quotes log statement</technical_language>

Target:
private static TLSClientParameters constructTLSClient(TLSClientParameters tlsClientParameters) { boolean isDisableCNCheck = false; try { isDisableCNCheck = PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, DISABLE_CN_CHECK); } catch (PropertyAccessException ex) { LOG.error("Not able to read 'disableCNCheck' from the property file: {}", ex.getLocalizedMessage(), ex); } try { SSLSocketFactory factory = SSLUtils.getSSLContext(tlsClientParameters).getSocketFactory(); if (factory != null) { tlsClientParameters.setSSLSocketFactory(factory); } else { throw new SecurityException("Couldn't get the SSLSocketFactory."); } tlsClientParameters.setDisableCNCheck(isDisableCNCheck); LOG.info("tlsClientParameters--disableCNCheck-is-set: {}", isDisableCNCheck); } catch (GeneralSecurityException | IllegalStateException e) { LOG.error("Could not get TLS client parameters: ", e.getLocalizedMessage(), e); throw new SecurityException("Could not create SSL Context.", e); } return tlsClientParameters; }
Source:
<code>protected void internalReceiveUpdate(String itemName, State newState) { try { String property = getProperty(itemName); String xbmcInstance = getXbmcInstance(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received update ({}) for item but no XBMC connector found for {}, ignoring", newState.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received update ({}) for item but the connection to the XBMC instance is down, ignoring", newState.toString(), itemName, xbmcInstance); return; } if (property.equals("GUI.ShowNotification")) connector.showNotification("openHAB", newState.toString()); if (property.equals("Player.Open")) connector.playerOpen(newState.toString()); if (property.equals("Application.SetVolume")) <START> connector.applicationSetVolume(newState.toString()); <END> } catch (Exception e) { logger.error("Error handling update", e); } }</code><technical_language>please "else if" option valid a time</technical_language>

Target:
protected void internalReceiveUpdate(String itemName, State newState) { try { String property = getProperty(itemName); String xbmcInstance = getXbmcInstance(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received update ({}) for item but no XBMC connector found for {}, ignoring", newState.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received update ({}) for item but the connection to the XBMC instance is down, ignoring", newState.toString(), itemName, xbmcInstance); return; } if (property.equals("GUI.ShowNotification")) { connector.showNotification("openHAB", newState.toString()); } else if (property.equals("Player.Open")) { connector.playerOpen(newState.toString()); } else if (property.equals("Application.SetVolume")) { connector.applicationSetVolume(newState.toString()); } } catch (Exception e) { logger.error("Error handling update", e); } }
Source:
<code>public void updateCustom(SolApplication solApplication, SolInputManager.InputPointer[] inputPointers, boolean clickedOutside) { if (clickedOutside) { closeControl.maybeFlashPressed(solApplication.getOptions().getKeyClose()); return; } SolGame game = solApplication.getGame(); Hero hero = game.getHero(); SolInputManager inputManager = solApplication.getInputManager(); if (closeControl.isJustOff() || isTargetFar(hero)) { inputManager.setScreen(solApplication, game.getScreens().mainScreen); return; } boolean station = target.getHull().config.getType() == HullConfig.Type.STATION; shipsControl.setEnabled(station); hireControl.setEnabled(station); InventoryScreen inventoryScreen = game.getScreens().inventoryScreen; boolean sell = sellControl.isJustOff(); boolean buy = buyControl.isJustOff(); boolean sellShips = shipsControl.isJustOff(); boolean hire = hireControl.isJustOff(); if (sell || buy || sellShips || hire) { inventoryScreen.setOperations(sell ? inventoryScreen.sellItems : buy ? inventoryScreen.buyItems <START> : sellShips ? inventoryScreen.changeShip : inventoryScreen.hireShips); <END> inputManager.setScreen(solApplication, game.getScreens().mainScreen); inputManager.addScreen(solApplication, inventoryScreen); } }</code><technical_language>This clearer like: InventoryOperations inventoryOperations = inventoryScreen.hireShips; if (sell) { inventoryOperations = inventoryScreen.sellItems; } else if (buy) { inventoryOperations = inventoryScreen.buyItems; } else if (sellShips) { inventoryOperations = inventoryScreen.changeShip; } inventoryScreen.setOperations(inventoryOperations);</technical_language>

Target:
public void updateCustom(SolApplication solApplication, SolInputManager.InputPointer[] inputPointers, boolean clickedOutside) { if (clickedOutside) { closeControl.maybeFlashPressed(solApplication.getOptions().getKeyClose()); return; } SolGame game = solApplication.getGame(); Hero hero = game.getHero(); SolInputManager inputManager = solApplication.getInputManager(); if (closeControl.isJustOff() || isTargetFar(hero)) { inputManager.setScreen(solApplication, game.getScreens().mainScreen); return; } boolean station = target.getHull().config.getType() == HullConfig.Type.STATION; shipsControl.setEnabled(station); hireControl.setEnabled(station); InventoryScreen inventoryScreen = game.getScreens().inventoryScreen; boolean sell = sellControl.isJustOff(); boolean buy = buyControl.isJustOff(); boolean sellShips = shipsControl.isJustOff(); boolean hire = hireControl.isJustOff(); if (sell || buy || sellShips || hire) { if (sell) { inventoryScreen.setOperations(inventoryScreen.sellItems); } else if (buy) { inventoryScreen.setOperations(inventoryScreen.buyItems); } else if (sellShips) { inventoryScreen.setOperations(inventoryScreen.changeShip); } else { inventoryScreen.setOperations(inventoryScreen.hireShips); } inputManager.setScreen(solApplication, game.getScreens().mainScreen); inputManager.addScreen(solApplication, inventoryScreen); } }
Source:
<code>private void invokeBlockingCallToLifeCycleEvent(final String lifeCycleEventName) { <START> final CordovaPluginTest me = this; <END> final Activity activity = this.testActivity; Runnable blockingRunnable = new Runnable() { public void run() { try { Method method = me.getInstrumentation().getClass().getMethod(lifeCycleEventName, Activity.class); method.invoke(me.getInstrumentation(), activity); } catch (Exception e) { fail("An Exception occurred in invokeBlockingCallToLifeCycleEvent while invoking " + lifeCycleEventName); } me.getInstrumentation().callActivityOnStart(testActivity); synchronized(this) { this.notify(); } } }; synchronized( blockingRunnable ) { testActivity.runOnUiThread(blockingRunnable); try { blockingRunnable.wait(); } catch (InterruptedException e) { fail("An InterruptedException occurred in invokeBlockingCallToLifeCycleEvent while waiting for " + lifeCycleEventName); } } }</code><technical_language>nit: need alias scope. getInstrumention() me.getInstrumentation(). If want explicit, CordovaPluginTest.this.getInstrumentation()</technical_language>

Target:
private void invokeBlockingCallToLifeCycleEvent(final String lifeCycleEventName) { final Activity activity = getActivity(); activity.runOnUiThread( new Runnable() { public void run() { try { Method method = getInstrumentation().getClass().getMethod(lifeCycleEventName, Activity.class); method.invoke(getInstrumentation(), activity); } catch (Exception e) { fail("An Exception occurred in invokeBlockingCallToLifeCycleEvent while invoking " + lifeCycleEventName); } } }); getInstrumentation().waitForIdleSync(); }
Source:
<code>public static Slice parse(String query) { Iterable<String> tokens = Splitter.on(CharMatcher.anyOf(":-")).omitEmptyStrings().trimResults().split(query); Iterator<String> it = tokens.iterator(); int count = Iterators.size(tokens.iterator()); Slice result = null; try { switch (count) { case 1: result = new Slice(it.next()); break; case 2: <START> result = new Slice(it.next(), Integer.parseInt(it.next().replace(",", ""))); <END> break; case 3: result = new Slice(it.next(), Integer.parseInt(it.next().replace(",", "")), Integer.parseInt(it.next().replace(",", ""))); break; default: throw new IllegalArgumentException(String.format("Unrecognizable region %s", query)); } } catch (NumberFormatException nfe) { throw new IllegalArgumentException(String.format("Invalid region specified %s", query), nfe); } return result; }</code><technical_language>Integer.parseInt(it.next().replace(",", ""))) repeats 3 times. Please create a parseNumber similar</technical_language>

Target:
public static Slice parse(String query) { Iterable<String> tokens = queryScrubber.split(query); Iterator<String> it = tokens.iterator(); int count = Iterators.size(tokens.iterator()); Slice result = null; try { switch (count) { case 1: result = new Slice(it.next()); break; case 2: result = new Slice(it.next(), parseIntArgument(it.next())); break; case 3: result = new Slice(it.next(), parseIntArgument(it.next()), parseIntArgument(it.next())); break; default: throw new IllegalArgumentException(String.format("Unrecognizable region %s", query)); } } catch (NumberFormatException nfe) { throw new IllegalArgumentException(String.format("Invalid region specified %s", query), nfe); } return result; }
Source:
<code>private static void runPartialSyncRegistrationCallback(@Nullable String error, long nativeResultsPtr, PartialSyncCallback callback) { if (error != null) { callback.onError(new RealmException(error)); } else { @SuppressWarnings("ConstantConditions") <START> Table table = callback.sharedRealm.getTable(Table.getTableNameForClass(callback.className)); <END> Collection results = new Collection(callback.sharedRealm, table, nativeResultsPtr, true); callback.onSuccess(results); } }</code><technical_language>making runPartialSyncRegistrationCallback static, longer need sharedRealm in callback</technical_language>

Target:
private void runPartialSyncRegistrationCallback(@Nullable String error, long nativeResultsPtr, PartialSyncCallback callback) { if (error != null) { callback.onError(new RealmException(error)); } else { @SuppressWarnings("ConstantConditions") Table table = getTable(Table.getTableNameForClass(callback.className)); Collection results = new Collection(this, table, nativeResultsPtr, true); callback.onSuccess(results); } }
Source:
<code>public final void putObject(String address, Object object) throws IOException { String json = jsonService.serialize(object); HttpPut put = buildRequest(address, HttpPut::new); try { put.setEntity(new StringEntity(json)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } put.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); try (CloseableHttpResponse ignored = cachedRemoteReader.getResponse(put)) { <START> } <END> }</code><technical_language>refactor out duplicated code postObject</technical_language>

Target:
public final void putObject(String address, Object object) throws IOException { uploadObject(address, object, HttpPut::new); }
Source:
<code><START> public void registerClient(ScoreBoardClockClient client) { <END> clients.add(client); }</code><technical_language>This synchronized</technical_language>

Target:
public synchronized void registerClient(ScoreBoardClockClient client) { clients.add(client); }
Source:
<code>public boolean chkCollabWorkspaceAccess(String userName,String workspaceId,String collaboratorRole) throws QuadrigaStorageException { List<IWorkspaceCollaborator> workspaceCollaboratorList = null; List<IQuadrigaRole> collaboratorRoles = null; boolean chkAccess; chkAccess = false; workspaceCollaboratorList = wsCollabManager.getWorkspaceCollaborators(workspaceId); if(workspaceCollaboratorList != null){ for(IWorkspaceCollaborator workspaceCollaborator : workspaceCollaboratorList) { if(workspaceCollaborator.getCollaborator() != null){ if(workspaceCollaborator.getCollaborator().getUserObj().getUserName().equals(userName)) { collaboratorRoles = workspaceCollaborator.getCollaborator().getCollaboratorRoles(); if(collaboratorRoles != null){ for(IQuadrigaRole role : collaboratorRoles) { if(role.getId().equals(collaboratorRole)) { chkAccess = true; <START> break; <END> } } } break; } } } } return chkAccess; }</code><technical_language>please reformat file</technical_language>

Target:
public boolean chkCollabWorkspaceAccess(String userName, String workspaceId, String collaboratorRole) throws QuadrigaStorageException { boolean chkAccess = false; List<IWorkspaceCollaborator> workspaceCollaboratorList = wsCollabManager.getWorkspaceCollaborators(workspaceId); if (workspaceCollaboratorList != null) { for (IWorkspaceCollaborator workspaceCollaborator : workspaceCollaboratorList) { if (workspaceCollaborator.getCollaborator() != null) { if (workspaceCollaborator.getCollaborator().getUserObj().getUserName().equals(userName)) { List<IQuadrigaRole> collaboratorRoles = workspaceCollaborator.getCollaborator().getCollaboratorRoles(); if (collaboratorRoles != null) { for (IQuadrigaRole role : collaboratorRoles) { if (role.getId().equals(collaboratorRole)) { chkAccess = true; break; } } } break; } } } } return chkAccess; }
Source:
<code>protected void before() throws UnknownHostException, IOException{ MongodStarter runtime = MongodStarter.getDefaultInstance(); IMongodConfig config = new MongodConfigBuilder(). version(immsAnnotation.version()). net(new Net(immsAnnotation.port(), Network.localhostIsIPv6())). build(); mongodExe = runtime.prepare(config); try{ mongod = mongodExe.start(); } catch(IOException e){ <START> System.err.println("Mongo failed to start for the previously stated reason. A single retry will be attempted."); <END> mongod = mongodExe.start(); } }</code><technical_language>2nd attempt of start, I put stderr. useful, try if works works. If start fails</technical_language>

Target:
protected void before() throws UnknownHostException, IOException{ MongodStarter runtime = MongodStarter.getDefaultInstance(); IMongodConfig config = new MongodConfigBuilder(). version(immsAnnotation.version()). net(new Net(immsAnnotation.port(), Network.localhostIsIPv6())). build(); mongodExe = runtime.prepare(config); try{ mongod = mongodExe.start(); } catch(IOException e){ mongod = mongodExe.start(); } }
Source:
<code>public <T> Action getAction(T subjectMap) { if (!canHandle(subjectMap)) { return null; } String logoutUrlString = ""; URL logoutUrl = null; try { @SuppressWarnings("unchecked") Object subject = ((Map) subjectMap).get(SecurityConstants.SECURITY_SUBJECT); String nameId = SubjectUtils.getName((Subject) subject, "You", true); String nameIdTimestamp = nameId + "\n" + System.currentTimeMillis(); nameIdTimestamp = URLEncoder.encode( encryptionService.encrypt(nameIdTimestamp), StandardCharsets.UTF_8.name()); logoutUrlString = SystemBaseUrl.EXTERNAL.constructUrl( "/saml/logout/request?EncryptedNameIdTime=" + nameIdTimestamp, true); logoutUrl = new URL(logoutUrlString); } catch (MalformedURLException e) { LOGGER.info("Unable to resolve URL: {}", LogSanitizer.cleanAndEncode(logoutUrlString)); } catch (ClassCastException e) { LOGGER.debug( "Unable to cast parameter to Map<String, Object>, {}", LogSanitizer.cleanAndEncode(subjectMap), e); } catch (UnsupportedEncodingException e) { LOGGER.debug( <START> "Unable to encode the encrypted timestamp.", LogSanitizer.cleanAndEncode(subjectMap), e); <END> } return new ActionImpl(ID, TITLE, DESCRIPTION, logoutUrl); }</code><technical_language>logging statement contains remove subjectMap argument</technical_language>

Target:
public <T> Action getAction(T subjectMap) { if (!canHandle(subjectMap)) { return null; } String logoutUrlString = ""; URL logoutUrl = null; try { @SuppressWarnings("unchecked") Object subject = ((Map) subjectMap).get(SecurityConstants.SECURITY_SUBJECT); String nameId = SubjectUtils.getName((Subject) subject, "You", true); String nameIdTimestamp = nameId + "\n" + System.currentTimeMillis(); nameIdTimestamp = URLEncoder.encode( encryptionService.encrypt(nameIdTimestamp), StandardCharsets.UTF_8.name()); logoutUrlString = SystemBaseUrl.EXTERNAL.constructUrl( "/saml/logout/request?EncryptedNameIdTime=" + nameIdTimestamp, true); logoutUrl = new URL(logoutUrlString); } catch (MalformedURLException e) { LOGGER.info("Unable to resolve URL: {}", LogSanitizer.sanitize(logoutUrlString)); } catch (ClassCastException e) { LOGGER.debug( "Unable to cast parameter to Map<String, Object>, {}", LogSanitizer.sanitize(subjectMap), e); } catch (UnsupportedEncodingException e) { LOGGER.debug("Unable to encode the encrypted timestamp.", e); } return new ActionImpl(ID, TITLE, DESCRIPTION, logoutUrl); }
Source:
<code>public void controller(FragmentConfiguration config, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("baseIdentifierSourceService") IdentifierSourceService identifierSourceService, @FragmentParam("patient") Object patient, @InjectBeans PatientDomainWrapper wrapper, @SpringBean("adtService") AdtService adtService, UiSessionContext sessionContext) { if (patient instanceof Patient) { wrapper.setPatient((Patient) patient); config.addAttribute("patient", wrapper); } VisitDomainWrapper activeVisit = (VisitDomainWrapper) config.getAttribute("activeVisit"); if (activeVisit == null) { Location sessionLocation = sessionContext.getSessionLocation(); <START> if (sessionLocation == null) <END> sessionLocation = LocationUtility.getDefaultLocation(); Location visitLocation = sessionLocation; activeVisit = adtService.getActiveVisit((Patient) patient, visitLocation); } if (activeVisit != null) config.addAttribute("activeVisit", activeVisit); List<ExtraPatientIdentifierType> extraPatientIdentifierTypes = new ArrayList<ExtraPatientIdentifierType>(); for (PatientIdentifierType type : emrApiProperties.getExtraPatientIdentifierTypes()) { AutoGenerationOption option = identifierSourceService.getAutoGenerationOption(type); extraPatientIdentifierTypes.add(new ExtraPatientIdentifierType(type, option != null ? option .isManualEntryEnabled() : true)); } config.addAttribute("extraPatientIdentifierTypes", extraPatientIdentifierTypes); }</code><technical_language>Get rid of this here. ensure a sessionLocation is set login</technical_language>

Target:
public void controller(FragmentConfiguration config, @SpringBean("emrApiProperties") EmrApiProperties emrApiProperties, @SpringBean("baseIdentifierSourceService") IdentifierSourceService identifierSourceService, @FragmentParam("patient") Object patient, @InjectBeans PatientDomainWrapper wrapper, @SpringBean("adtService") AdtService adtService, UiSessionContext sessionContext) { if (patient instanceof Patient) { wrapper.setPatient((Patient) patient); config.addAttribute("patient", wrapper); } VisitDomainWrapper activeVisit = (VisitDomainWrapper) config.getAttribute("activeVisit"); if (activeVisit == null) { Location visitLocation = adtService.getLocationThatSupportsVisits(sessionContext.getSessionLocation()); activeVisit = adtService.getActiveVisit((Patient) patient, visitLocation); } if (activeVisit != null) config.addAttribute("activeVisit", activeVisit); List<ExtraPatientIdentifierType> extraPatientIdentifierTypes = new ArrayList<ExtraPatientIdentifierType>(); for (PatientIdentifierType type : emrApiProperties.getExtraPatientIdentifierTypes()) { AutoGenerationOption option = identifierSourceService.getAutoGenerationOption(type); extraPatientIdentifierTypes.add(new ExtraPatientIdentifierType(type, option != null ? option .isManualEntryEnabled() : true)); } config.addAttribute("extraPatientIdentifierTypes", extraPatientIdentifierTypes); }
Source:
<code>void mustBeOpen() { if (c4db == null) <START> throw new CouchbaseLiteRuntimeException("Database is not open."); <END> }</code><technical_language>I throw IllegalStateException instead of CouchbaseLiteRuntimeException this is in inconsistent illegal state users do. CouchbaseLiteRuntimeException LC thrown expected</technical_language>

Target:
void mustBeOpen() { if (c4db == null) throw new IllegalStateException("Database is not open."); }
Source:
<code>Object call(final String command, final List<String> args) throws IOException { final List<String> argsList = new ArrayList<String>(); argsList.add(command); argsList.add(ClientHelper.getCurrentSeconds()); for (final String arg : args) { argsList.add(arg); } <START> final List<String> keysList = new ArrayList<String>(); <END> if (Client.LOGGER.isDebugEnabled()) { Client.LOGGER.debug("{}", argsList); } return this.luaScript.call(keysList, argsList); }</code><technical_language>This a static final member, important</technical_language>

Target:
Object call(final String command, final List<String> args) throws IOException { final List<String> argsList = new ArrayList<String>(); argsList.add(command); argsList.add(ClientHelper.getCurrentSeconds()); for (final String arg : args) { argsList.add(arg); } Client.LOGGER.debug("{}", argsList); return this.luaScript.call(Client.KEYS_LIST, argsList); }
Source:
<code>public void verifyElementsOnPage() { verifyH1(); <START> PageObjectLogging.log("verifyElements", "verify that H1 is present", true); <END> verifyAddVideoButton(); PageObjectLogging.log("verifyElements", "verify that Add Video button is present", true); verifySortDropdown(); PageObjectLogging.log("verifyElements", "verify that sort dropdown is present", true); verifyNewestVideo(); PageObjectLogging.log("verifyElements", "verify that there is at least one video present", true); }</code><technical_language>"verifyElementsOnPage". logging complete method name for argument</technical_language>

Target:
public void verifyElementsOnPage() { verifyH1(); PageObjectLogging.log("verifyElementsOnPage", "verify that H1 is present", true); verifyAddVideoButton(); PageObjectLogging.log("verifyElementsOnPage", "verify that Add Video button is present", true); verifySortDropdown(); PageObjectLogging.log("verifyElementsOnPage", "verify that sort dropdown is present", true); verifyNewestVideo(); PageObjectLogging.log("verifyElementsOnPage", "verify that there is at least one video present", true); }
Source:
<code>public void testRollbackExceptionStrategyNumberOfRetries() throws Exception { <START> System.setProperty("RollBackExceptionStrategy", "true"); <END> final CountDownLatch latch = new CountDownLatch(8); LocalMuleClient client = muleContext.getClient(); muleContext.registerListener(new ExceptionNotificationListener<ExceptionNotification>() { @Override public void onNotification(ExceptionNotification notification) { latch.countDown(); } }); client.dispatch("vm://in8", "test", null); client.dispatch("vm://in8", "test", null); if (!latch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS)) { fail("message should have been delivered at least 5 times"); } MuleMessage response = client.request("vm://dlqCounter", 20000); assertThat(response, IsNull.notNullValue()); AtomicInteger counter = muleContext.getRegistry().lookupObject("counter"); assertThat(counter.get(), Is.is(8)); }</code><technical_language>set this false in a @after, if other test fail depending order of execution</technical_language>

Target:
public void testRollbackExceptionStrategyNumberOfRetries() throws Exception { System.setProperty(MULE_FORCE_REDELIVERY, "true"); final CountDownLatch latch = new CountDownLatch(8); LocalMuleClient client = muleContext.getClient(); muleContext.registerListener(new ExceptionNotificationListener<ExceptionNotification>() { @Override public void onNotification(ExceptionNotification notification) { latch.countDown(); } }); client.dispatch("vm://in8", "test", null); client.dispatch("vm://in8", "test", null); if (!latch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS)) { fail("message should have been delivered at least 5 times"); } MuleMessage response = client.request("vm://dlqCounter", 20000); assertThat(response, IsNull.notNullValue()); AtomicInteger counter = muleContext.getRegistry().lookupObject("counter"); assertThat(counter.get(), Is.is(8)); }
Source:
<code>public InstructorFeedbacksPage clickDoneEditingLink() { <START> WebElement doneEditingLink = browser.driver.findElement(By.id("button_done_editing")); <END> doneEditingLink.click(); waitForPageToLoad(); return changePageType(InstructorFeedbacksPage.class); }</code><technical_language>I prefer this a field of InstructorFeedbackEditPage itself. @FindBy annotation this a field</technical_language>

Target:
public InstructorFeedbacksPage clickDoneEditingLink() { doneEditingButton.click(); waitForPageToLoad(); return changePageType(InstructorFeedbacksPage.class); }
Source:
<code>public void testHelloWorld() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { String Url = url.toExternalForm(); HttpGet httpget = new HttpGet(Url); <START> httpclient.execute(httpget); HttpResponse response = httpclient.execute(httpget); Assert.assertEquals("Operation failed", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); <END> HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); Assert.assertThat("Hello World is in place", result, CoreMatchers.containsString("Hello World!")); } }</code><technical_language>httpclient.execute(httpget) requests here, is unnecessary perform this test</technical_language>

Target:
public void testHelloWorld() throws Exception { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { String Url = url.toExternalForm(); HttpGet httpget = new HttpGet(Url); HttpResponse response = httpclient.execute(httpget); Assert.assertEquals("JSF deployment failed due to UnsupportedOperationException when javax.faces.FACELETS_VIEW_MAPPINGS valued wrong", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); Assert.assertThat("Hello World is in place", result, CoreMatchers.containsString("Hello World!")); } }
Source:
<code>private void updateDynamicWarning() { if (getIsPlugged().getEntity().equals(Boolean.TRUE)) { List<EntityModel<DiskModel>> selectedDisks = getSelectedDisks(); if (selectedDisks != null && isIDEDiskSelected(selectedDisks)) { getDynamicWarning().setEntity(CONSTANTS.ideDisksWillBeAttachedButNotActivated()); getDynamicWarning().setIsAvailable(true); } else { <START> getDynamicWarning().setIsAvailable(false); <END> } } else { getDynamicWarning().setIsAvailable(false); } }</code><technical_language>move line 211 instead</technical_language>

Target:
private void updateDynamicWarning() { getDynamicWarning().setIsAvailable(false); if (getIsPlugged().getEntity().equals(Boolean.TRUE)) { List<EntityModel<DiskModel>> selectedDisks = getSelectedDisks(); if (selectedDisks != null && isSelectedDiskInterfaceIDE(selectedDisks)) { getDynamicWarning().setEntity(CONSTANTS.ideDisksWillBeAttachedButNotActivated()); getDynamicWarning().setIsAvailable(true); } } }
Source:
<code>private void resizeWindow(Object drone, InjectionPoint<?> injectionPoint) { if (!WebDriver.class.isAssignableFrom(drone.getClass())) { return; } DroneContext context = droneContext.get(); WebDriver driver = (WebDriver) drone; Validate.stateNotNull(context, "DroneContext must not be null"); WebDriverConfiguration configuration = context.getDroneConfiguration(injectionPoint, WebDriverConfiguration .class); <START> Validate.stateNotNull(configuration, "WebDriver configuration mus null"); <END> String dimensions = configuration.getDimensions(); if (dimensions != null) { Matcher m = DIMENSIONS_PATTERN.matcher(dimensions); if (m.matches()) { int width = Integer.valueOf(m.group(1)); int height = Integer.valueOf(m.group(2)); safelyResizeWindow(driver, width, height, injectionPoint); } } }</code><technical_language>typo "mus"</technical_language>

Target:
private void resizeWindow(Object drone, InjectionPoint<?> injectionPoint) { if (!WebDriver.class.isAssignableFrom(drone.getClass())) { return; } DroneContext context = droneContext.get(); WebDriver driver = (WebDriver) drone; Validate.stateNotNull(context, "DroneContext must not be null"); WebDriverConfiguration configuration = context.getDroneConfiguration(injectionPoint, WebDriverConfiguration .class); Validate.stateNotNull(configuration, "WebDriver configuration must not be null"); String dimensions = configuration.getDimensions(); if (dimensions != null) { Matcher m = DIMENSIONS_PATTERN.matcher(dimensions); if (m.matches()) { int width = Integer.valueOf(m.group(1)); int height = Integer.valueOf(m.group(2)); safelyResizeWindow(driver, width, height, injectionPoint); } } }
Source:
<code>public void execute(ClusterEvent event) { Map<String, WorkflowConfig> workflowConfigMap = event.getAttribute(AttributeName.WORKFLOW_CONFIG_MAP.name()); Map<String, ZNRecord> resourceContextMap = event.getAttribute(AttributeName.RESOURCE_CONTEXT_MAP.name()); HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); if (manager == null) { LOG.warn( <START> " HelixManager is null for event {}({}) in cluster {}. Skip TaskGarbageCollectionStage.", <END> event.getEventId(), event.getEventType(), event.getClusterName()); return; } Set<WorkflowConfig> existingWorkflows = new HashSet<>(workflowConfigMap.values()); for (WorkflowConfig workflowConfig : existingWorkflows) { if (workflowConfig != null && (!workflowConfig.isTerminable() || workflowConfig .isJobQueue())) { String workflowId = workflowConfig.getWorkflowId(); if (resourceContextMap.containsKey(workflowId) && resourceContextMap.get(workflowId) != null) { try { TaskUtil.purgeExpiredJobs(workflowId, workflowConfig, new WorkflowContext(resourceContextMap.get(workflowId)), manager, _rebalanceScheduler); } catch (Exception e) { LOG.warn(String.format("Failed to purge job for workflow %s with reason %s", workflowId, e.toString())); } } else { LOG.warn(String.format("Workflow %s context does not exist!", workflowId)); } } } TaskUtil.workflowGarbageCollection(workflowConfigMap, resourceContextMap, manager); }</code><technical_language>starting a space</technical_language>

Target:
public void execute(ClusterEvent event) { HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); if (manager == null) { LOG.warn( "HelixManager is null for event {}({}) in cluster {}. Skip TaskGarbageCollectionStage async execution.", event.getEventId(), event.getEventType(), event.getClusterName()); return; } Map<String, Set<String>> expiredJobsMap = event.getAttribute(AttributeName.TO_BE_PURGED_JOBS_MAP.name()); Set<String> toBePurgedWorkflows = event.getAttribute(AttributeName.TO_BE_PURGED_WORKFLOWS.name()); for (Map.Entry<String, Set<String>> entry : expiredJobsMap.entrySet()) { try { TaskUtil.purgeExpiredJobs(entry.getKey(), entry.getValue(), manager, _rebalanceScheduler); } catch (Exception e) { LOG.warn("Failed to purge job for workflow {}!", entry.getKey(), e); } } TaskUtil.workflowGarbageCollection(toBePurgedWorkflows, manager); }
Source:
<code><START> private Object extractValue(DataValue value) throws IllegalArgumentException { <END> Variant variant = value.getValue(); if (variant == null) { throw new NoSuchElementException(message.errorNullResult()); } Object result = variant.getValue(); if (result == null) { throw new NoSuchElementException(message.errorNullResult()); } return result; }</code><technical_language>null. Add Precondition</technical_language>

Target:
private Object extractValue(DataValue value) throws IllegalArgumentException { Variant variant = value.getValue(); if (variant == null) { throw new NullPointerException(message.errorNullResult()); } Object result = variant.getValue(); if (result == null) { throw new NullPointerException(message.errorNullResult()); } return result; }
Source:
<code>public void mark() throws PublisherException { <START> marked.add(current); <END> if (marked.size() > markCapacity) { Node n = marked.remove(0); n.decrement(); } }</code><technical_language>check is contained in list. verify node.get() != null</technical_language>

Target:
public void mark() throws PublisherException { if (current.data.push != null) { if (marked.size() >= markCapacity) { Data data = marked.removeLast(); data.decrement(); } marked.addFirst(current.data); current = new ForwardingNode(Data.EMPTY, current); } }
Source:
<code>public void test_CreateJobFromPreset() throws Exception { <START> String jobName = String.format("projects/%s/locations/%s/jobs/", PROJECT_NUMBER, LOCATION); <END> try { CreateJobFromPreset.createJobFromPreset( PROJECT_ID, LOCATION, INPUT_URI, OUTPUT_URI_FOR_PRESET, PRESET); } catch (GoogleJsonResponseException gjre) { } String output = bout.toString(); assertThat(output, containsString(jobName)); String[] arr = output.split("/"); JOB_ID = arr[arr.length - 1].replace("\n", ""); bout.reset(); Thread.sleep(60000); try { GetJobState.getJobState(PROJECT_ID, LOCATION, JOB_ID); } catch (GoogleJsonResponseException gjre) { } output = bout.toString(); assertThat(output, containsString("SUCCEEDED")); bout.reset(); }</code><technical_language>is this PROJECT_NUMBER? supposed samples prefer PROJECT_ID</technical_language>

Target:
public void test_CreateJobFromPreset() throws Exception { String jobName = String.format("projects/%s/locations/%s/jobs/", PROJECT_NUMBER, LOCATION); CreateJobFromPreset.createJobFromPreset( PROJECT_ID, LOCATION, INPUT_URI, OUTPUT_URI_FOR_PRESET, PRESET); String output = bout.toString(); assertThat(output, containsString(jobName)); String[] arr = output.split("/"); JOB_ID = arr[arr.length - 1].replace("\n", ""); bout.reset(); Thread.sleep(60000); GetJobState.getJobState(PROJECT_ID, LOCATION, JOB_ID); output = bout.toString(); assertThat(output, containsString("SUCCEEDED")); bout.reset(); }
Source:
<code>public void doAfterTest() throws Exception { super.doAfterTest(); <START> if (fServicesTracker != null) fServicesTracker.dispose(); <END> }</code><technical_language>a recommended practice enclose statement condition in curly brackets</technical_language>

Target:
public void doAfterTest() throws Exception { super.doAfterTest(); if (fServicesTracker != null) { fServicesTracker.dispose(); } }
Source:
<code>public static ListWidgetEntry<ContainerDTO> create(ContainerDTO container) { <START> Optional<URI> shortcutMiniature = Optional.empty(); <END> final List<BufferedImage> miniatures = new ArrayList<>(); final int maxSegments = 4; int currentSegment = 0; for (ShortcutDTO shortcutDTO : container.getInstalledShortcuts()) { if (currentSegment >= maxSegments) { break; } try { miniatures.add(ImageIO.read(shortcutDTO.getMiniature().toURL())); currentSegment++; } catch (IOException e) { LOGGER.warn(String.format("Could not read miniature for shortcut \"%s\"", shortcutDTO.getName()), e); } } if (!miniatures.isEmpty()) { final int width = miniatures.get(0).getWidth(); final int height = miniatures.get(0).getHeight(); BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int numberOfSegments = miniatures.size(); final int segmentWidth = width / numberOfSegments; final int offset = (width - segmentWidth) / 2; final List<BufferedImage> segments = new ArrayList<>(); miniatures.forEach( miniature -> segments.add(miniature.getSubimage(offset, 0, offset + segmentWidth, height))); Graphics2D graphics = result.createGraphics(); for (int i = 0; i < segments.size(); i++) { graphics.drawImage(segments.get(i), 0 + i * segmentWidth, 0, null); } try { final Path temp = Files.createTempFile(container.getName(), ".png").toAbsolutePath(); final File tempFile = temp.toFile(); tempFile.deleteOnExit(); ImageIO.write(result, "png", tempFile); shortcutMiniature = Optional.of(temp.toUri()); } catch (IOException e) { LOGGER.warn( String.format("Could not create container miniature for container \"%s\"", container.getName()), e); } } return new ListWidgetEntry<>(container, shortcutMiniature, StaticMiniature.CONTAINER_MINIATURE, container.getName(), Optional.empty(), Optional.empty()); }</code><technical_language>introduce a new private method for shortcut miniature creation</technical_language>

Target:
public static ListWidgetEntry<ContainerDTO> create(ContainerDTO container) { final List<BufferedImage> miniatures = new ArrayList<>(); final int maxSegments = 4; int currentSegment = 0; for (ShortcutDTO shortcutDTO : container.getInstalledShortcuts()) { if (currentSegment >= maxSegments) { break; } try { miniatures.add(ImageIO.read(shortcutDTO.getMiniature().toURL())); currentSegment++; } catch (IOException e) { LOGGER.warn(String.format("Could not read miniature for shortcut \"%s\"", shortcutDTO.getName()), e); } } final BufferedImage segmentedMiniature = createSegmentedMiniature(miniatures); final Optional<URI> shortcutMiniature = saveBufferedImage(segmentedMiniature, container.getName()); return new ListWidgetEntry<>(container, shortcutMiniature, StaticMiniature.CONTAINER_MINIATURE, container.getName(), Optional.empty(), Optional.empty()); }
Source:
<code>public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (! cqTailer.moveToIndex(offset)) { <START> log.warn("Unable to move to the last committed offset, " + this); <END> } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }</code><technical_language>Is this important? throw instead? this a debug message if important? (same for seek)</technical_language>

Target:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { throw new IllegalStateException( "Unable to move to the last committed offset, " + this + " offset: " + offset); } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }
Source:
<code>public static AzureADToken getTokenFromMsi(final String authEndpoint, final String tenantGuid, final String clientId, String authority, boolean bypassCache) throws IOException { QueryParams qp = new QueryParams(); qp.add("api-version", "2018-02-01"); qp.add("resource", RESOURCE_NAME); if (tenantGuid != null && tenantGuid.length() > 0) { <START> authority = authority + tenantGuid; <END> qp.add("authority", authority); } if (clientId != null && clientId.length() > 0) { qp.add("client_id", clientId); } if (bypassCache) { qp.add("bypass_cache", "true"); } Hashtable<String, String> headers = new Hashtable<>(); headers.put("Metadata", "true"); LOG.debug("AADToken: starting to fetch token using MSI"); return getTokenCall(authEndpoint, qp.serialize(), headers, "GET"); }</code><technical_language>* adding a "/" needed; i this a common config problem. * do a check for authority valid is needed? request fail? add a debug level log is troubleshooting ths</technical_language>

Target:
public static AzureADToken getTokenFromMsi(final String authEndpoint, final String tenantGuid, final String clientId, String authority, boolean bypassCache) throws IOException { QueryParams qp = new QueryParams(); qp.add("api-version", "2018-02-01"); qp.add("resource", RESOURCE_NAME); if (tenantGuid != null && tenantGuid.length() > 0) { authority = authority + tenantGuid; LOG.debug("MSI authority : {}", authority); qp.add("authority", authority); } if (clientId != null && clientId.length() > 0) { qp.add("client_id", clientId); } if (bypassCache) { qp.add("bypass_cache", "true"); } Hashtable<String, String> headers = new Hashtable<>(); headers.put("Metadata", "true"); LOG.debug("AADToken: starting to fetch token using MSI"); return getTokenCall(authEndpoint, qp.serialize(), headers, "GET"); }
Source:
<code>public void setPhoto(Bitmap image) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream .toByteArray(); photo = android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT); <START> } <END></code><technical_language>requestBody shod : person: some_uuid
base64EncodedImage: soemstring right instead of uuid is Person object in POST. work do manually posting extend Resource.class done automatically ResourceSerializer. if this answer is enough :)</technical_language>

Target:
public void setPhoto(Bitmap image) { byte[] byteArray = bitmapToByteArray(image); base64EncodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT); }
Source:
<code><START> private Map<String, String> getParameters(IMethodInstance im) { <END> Map<String, String> params = m_xmlTest.getAllParameters(); Class<?> c = im.getMethod().getTestClass().getRealClass(); XmlClass xmlClass = m_xmlTest.getXmlClass(c); if (xmlClass != null) { params.putAll(xmlClass.getAllParameters()); } return params; }</code><technical_language>static if XmlTest im.getMethod().getXmlTest(). im.getMethod().findMethodParameters(im.getMethod().getXmlTest())</technical_language>

Target:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); return im.getMethod().findMethodParameters(xmlTest); }
Source:
<code>public void flush() throws IOException { <START> if (outputStream != null) <END> outputStream.flush(); }</code><technical_language>Please bring braces back</technical_language>

Target:
public void flush() throws IOException { if (outputStream != null) { outputStream.flush(); } }