auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void solve(Class<?> in) throws InvalidChainException { InvokableMethod[] methods = typeof.getMethodsMatchingInput(in); if (methods.length == 0) { throw new InvalidChainException( "Cannot find any valid path in operation chain - no method found for operation '" + typeof.getId() + "' and for first input type '" + in.getName() + "'"); } if (next == null) { method = methods[0]; return; } for (InvokableMethod m : methods) { Class<?> nextIn = m.getOutputType(); if (nextIn == Void.TYPE || nextIn.equals(Object.class)) { nextIn = in; } try { next.solve(nextIn); method = m; return; } catch (InvalidChainException cause) { log.error(cause, cause); } } throw new InvalidChainException( "Cannot find any valid path in operation chain - no method found for operation '" + typeof.getId() + "' and for first input type '" + in.getName() + "'"); }

Target:
void solve(Class<?> in) throws InvalidChainException { InvokableMethod[] methods = typeof.getMethodsMatchingInput(in); if (methods.length == 0) { throw new InvalidChainException( "Cannot find any valid path in operation chain - no method found for operation '" + typeof.getId() + "' and for first input type '" + in.getName() + "'"); } if (next == null) { method = methods[0]; return; } for (InvokableMethod m : methods) { Class<?> nextIn = m.getOutputType(); if (nextIn == Void.TYPE || nextIn.equals(Object.class)) { nextIn = in; } try { next.solve(nextIn); method = m; return; } catch (InvalidChainException cause) { } } throw new InvalidChainException( "Cannot find any valid path in operation chain - no method found for operation '" + typeof.getId() + "' and for first input type '" + in.getName() + "'"); }
Source:
public Map<Integer, GermplasmFolderMetadata> getSampleFolderMetadata(final List<Integer> folderIds) { if (folderIds.isEmpty()) { return Collections.emptyMap(); } final String folderMetaDataQuery = "SELECT parent.list_id AS listId, COUNT(child.list_id) AS numberOfChildren " + "FROM sample_list parent LEFT OUTER JOIN sample_list child ON child.hierarchy = parent.list_id " + "WHERE parent.list_id IN (:folderIds) GROUP BY parent.list_id"; final SQLQuery setResultTransformer = this.getSession().createSQLQuery(folderMetaDataQuery); setResultTransformer.setParameterList("folderIds", folderIds); setResultTransformer.addScalar("listId", new IntegerType()); setResultTransformer.addScalar("numberOfChildren", new IntegerType()); setResultTransformer.setResultTransformer(Transformers.aliasToBean(GermplasmFolderMetadata.class)); final List<GermplasmFolderMetadata> list = setResultTransformer.list(); return Maps.uniqueIndex(list, new Function<GermplasmFolderMetadata, Integer>() { @Override public Integer apply(final GermplasmFolderMetadata folderMetaData) { return folderMetaData.getListId(); } }); }

Target:
public Map<Integer, GermplasmFolderMetadata> getSampleFolderMetadata(final List<Integer> folderIds) { final List<GermplasmFolderMetadata> list; if (folderIds.isEmpty()) { return Collections.emptyMap(); } try { final String folderMetaDataQuery = "SELECT parent.list_id AS listId, COUNT(child.list_id) AS numberOfChildren " + "FROM sample_list parent LEFT OUTER JOIN sample_list child ON child.hierarchy = parent.list_id " + "WHERE parent.list_id IN (:folderIds) GROUP BY parent.list_id"; final SQLQuery setResultTransformer = this.getSession().createSQLQuery(folderMetaDataQuery); setResultTransformer.setParameterList("folderIds", folderIds); setResultTransformer.addScalar("listId", new IntegerType()); setResultTransformer.addScalar("numberOfChildren", new IntegerType()); setResultTransformer.setResultTransformer(Transformers.aliasToBean(GermplasmFolderMetadata.class)); list = setResultTransformer.list(); } catch (final HibernateException e) { throw new MiddlewareQueryException("Error with getSampleFolderMetadata(folderIds=" + folderIds.toString() + ") query from sample_list: " + e.getMessage(), e); } return Maps.uniqueIndex(list, new Function<GermplasmFolderMetadata, Integer>() { @Override public Integer apply(final GermplasmFolderMetadata folderMetaData) { return folderMetaData.getListId(); } }); }
Source:
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { super.processBindingConfiguration(context, item, bindingConfig); ExpireBindingConfig config = new ExpireBindingConfig(); Duration expiresAfter = parseDuration(bindingConfig); config.expiresAfterMs = expiresAfter.toMillis(); config.expiresAfterAsText = formatDuration(expiresAfter); addBindingConfig(item, config); }

Target:
public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { super.processBindingConfiguration(context, item, bindingConfig); ExpireBindingConfig config = new ExpireBindingConfig(); String[] durationAndState = bindingConfig.split(",", 2); Duration expiresAfter = parseDuration(durationAndState[0].trim()); config.expiresAfterMs = expiresAfter.toMillis(); config.expiresAfterAsText = formatDuration(expiresAfter); if (durationAndState.length > 1) { String stateAsString = durationAndState[1].trim(); config.expiredState = TypeParser.parseState(item.getAcceptedDataTypes(), stateAsString); if (config.expiredState == null) { throw new BindingConfigParseException("The string '" + stateAsString + "' does not represent a valid state for item " + item.getName()); } } addBindingConfig(item, config); }
Source:
public int leave(IASTDeclaration declaration) { if (getClassMethod(declaration) != null) { ContextInfo currentContext = methodsStack.peek(); switch (currentContext.checkerMode) { case MODE_CONST: if (!currentContext.classMembersAreUsed && !isVirtual(currentContext.method)) { reportProblem(ER_ID_MethodShouldBeStatic, declaration, currentContext.method.getName()); } break; case MODE_NON_CONST: if (!currentContext.classMembersAreUsed && !isVirtual(currentContext.method)) { reportProblem(ER_ID_MethodShouldBeStatic, declaration, currentContext.method.getName()); } else if (!currentContext.classMembersAreWritten && !isVirtual(currentContext.method)) { reportProblem(ER_ID_MethodShouldBeConst, declaration, currentContext.method.getName()); } break; case MODE_STATIC: break; } lastCachedContextInfo = methodsStack.pop(); } return PROCESS_CONTINUE; }

Target:
public int leave(IASTDeclaration declaration) { if (getClassMethod(declaration) != null) { ContextInfo currentContext = methodsStack.peek(); if (currentContext.hasProblems) { lastCachedContextInfo = methodsStack.pop(); return PROCESS_CONTINUE; } switch (currentContext.checkerMode) { case MODE_CONST: if (!currentContext.classMembersAreUsed && !isVirtual(currentContext)) { reportProblem(ER_ID_MethodShouldBeStatic, getMethodName(declaration), currentContext.method.getName()); } break; case MODE_NON_CONST: if (!currentContext.classMembersAreUsed && !isVirtual(currentContext)) { reportProblem(ER_ID_MethodShouldBeStatic, getMethodName(declaration), currentContext.method.getName()); } else if (!currentContext.classMembersAreWritten && !isVirtual(currentContext)) { reportProblem(ER_ID_MethodShouldBeConst, getMethodName(declaration), currentContext.method.getName()); } break; case MODE_STATIC: break; } lastCachedContextInfo = methodsStack.pop(); } return PROCESS_CONTINUE; }
Source:
public void resolveTest() { final String baseUri = "<LINK_0>"; final String pathToResolve = "picture.jpg"; String resolve = ""; try { resolve = JsonLdUrl.resolve(baseUri, pathToResolve); } catch (final Exception e) { assertTrue(false); } assertEquals(baseUri + "/" + pathToResolve, resolve); }

Target:
public void resolveTest() { final String baseUri = "<LINK_0>"; final String pathToResolve = "picture.jpg"; String resolve = ""; try { resolve = JsonLdUrl.resolve(baseUri, pathToResolve); assertEquals(baseUri + "/" + pathToResolve, resolve); } catch (final Exception e) { assertTrue(false); } }
Source:
private static boolean liesInRange(double point, double rangeStart, double rangeEnd) { return point >= rangeStart && point <= rangeEnd; }

Target:
private static boolean liesInRange(double point, double rangeStart, double rangeEnd) { return Double.compare(point, rangeStart) > 0 && Double.compare(point, rangeEnd) < 0; }
Source:
public static boolean isMailReceivedBySubject(String emailSubject, String folder) throws ESBMailTransportIntegrationTestException { Store store = null; boolean emailReceived = false; try { store = getConnection(); long startTime = System.currentTimeMillis(); while (!emailReceived && (System.currentTimeMillis() - startTime) < WAIT_TIME_MS) { Folder mailFolder = store.getFolder(folder); mailFolder.open(Folder.READ_WRITE); SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject)); Message[] messages = mailFolder.search(searchTerm); for (Message message : messages) { if (message.getSubject().contains(emailSubject)) { log.info("Found the email emailSubject : " + emailSubject); emailReceived = true; break; } } } return emailReceived; } catch (MessagingException ex) { log.error("Error when getting mail count ", ex); throw new ESBMailTransportIntegrationTestException("Error when getting mail count ", ex); } finally { if (store != null) { try { store.close(); } catch (MessagingException e) { log.error("Error when closing the store ", e); } } } }

Target:
public static boolean isMailReceivedBySubject(String emailSubject, String folder) throws ESBMailTransportIntegrationTestException { boolean emailReceived = false; Folder mailFolder; Store store = getConnection(); try { mailFolder = store.getFolder(folder); mailFolder.open(Folder.READ_WRITE); SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject)); Message[] messages = mailFolder.search(searchTerm); for (Message message : messages) { if (message.getSubject().contains(emailSubject)) { log.info("Found the email emailSubject : " + emailSubject); emailReceived = true; break; } } return emailReceived; } catch (MessagingException ex) { log.error("Error when getting the unread emails ", ex); throw new ESBMailTransportIntegrationTestException("Error when getting the unread emails ", ex); } finally { if (store != null) { try { store.close(); } catch (MessagingException e) { log.warn("Error when closing the store ", e); } } } }
Source:
private static String getCpuAbi() { String cpuAbi = Build.CPU_ABI; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cpuAbi = SupportedAbiWrapper.getSupportedAbis(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { cpuAbi = Abi2Wrapper.getAbi1andAbi2(); } return cpuAbi; }

Target:
private static String[] getCpuAbi() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return SupportedAbiWrapper.getSupportedAbis(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { return Abi2Wrapper.getAbi1andAbi2(); } return new String[]{Build.CPU_ABI}; }
Source:
public Response requestTranslatorStatus(@PathParam("code") String code, @HeaderParam("deviceId") String deviceIdHeader, @QueryParam("deviceId") String deviceIdParam) throws ParserConfigurationException, SAXException,IOException { DateTime currentTime = clock.currentDateTime(); AccessCodeRecord accessCodeRecord = authorizationService.getAccessCode(code); authorizationRecord.setAuthToken(authorizationService.createAuthToken()); String device = deviceIdHeader == null ? deviceIdParam : deviceIdHeader; authorizationRecord.setDeviceId(device); authorizationRecord.setId(authorizationService.createUUID()); if(accessCodeRecord != null && accessCodeRecord.isCurrentlyActive(currentTime)) { authorizationRecord.setDraftAccess(true); } else { authorizationRecord.setDraftAccess(false); } authorizationService.recordNewAuthorization(authorizationRecord); return Response.ok() .header("authToken", authorizationRecord.getAuthToken()) .build(); }

Target:
public Response requestTranslatorStatus(@PathParam("code") String code, @HeaderParam("deviceId") String deviceIdHeader, @QueryParam("deviceId") String deviceIdParam) throws ParserConfigurationException, SAXException,IOException { DateTime currentTime = clock.currentDateTime(); AccessCodeRecord accessCodeRecord = authorizationService.getAccessCode(code); AuthorizationRecord authorizationRecord = new AuthorizationRecord(); authorizationRecord.setAuthToken(AuthTokenGenerator.generate()); String device = deviceIdHeader == null ? deviceIdParam : deviceIdHeader; authorizationRecord.setDeviceId(device); authorizationRecord.setId(UUID.randomUUID()); if(accessCodeRecord != null && accessCodeRecord.isCurrentlyActive(currentTime)) { authorizationRecord.setDraftAccess(true); } else { authorizationRecord.setDraftAccess(false); } authorizationService.recordNewAuthorization(authorizationRecord); return Response.noContent() .header("authToken", authorizationRecord.getAuthToken()) .build(); }
Source:
private void setCurrentTagFromEmptyViewButton(ActionableEmptyViewButtonType button) { ReaderTag tag = ReaderUtils.getDefaultTag(); switch (button) { case DISCOVER: tag = ReaderUtils.getTagFromEndpoint(ReaderTag.DISCOVER_PATH); break; case FOLLOWED: tag = ReaderUtils.getTagFromEndpoint(ReaderTag.FOLLOWING_PATH); break; } mRecyclerView.refreshFilterCriteriaOptions(); if (!ReaderTagTable.tagExists(tag)) { tag = ReaderTagTable.getFirstTag(); } setCurrentTag(tag); }

Target:
private void setCurrentTagFromEmptyViewButton(ActionableEmptyViewButtonType button) { ReaderTag tag; switch (button) { case DISCOVER: tag = ReaderUtils.getTagFromEndpoint(ReaderTag.DISCOVER_PATH); break; case FOLLOWED: tag = ReaderUtils.getTagFromEndpoint(ReaderTag.FOLLOWING_PATH); break; default: tag = ReaderUtils.getDefaultTag(); } mRecyclerView.refreshFilterCriteriaOptions(); if (!ReaderTagTable.tagExists(tag)) { tag = ReaderTagTable.getFirstTag(); } setCurrentTag(tag); }
Source:
public Where<Message, Object> modWhere(Where<Message, Object> where) throws SQLException { where.like(Message.MESSAGE_STAR_FIELD, new SelectArg(isStarred)); return where; }

Target:
public Where<Message, Object> modWhere(Where<Message, Object> where) throws SQLException { where.eq(Message.MESSAGE_STAR_FIELD, new SelectArg(isStarred)); return where; }
Source:
public List<OrganizationHistory> getLastVistited() { String userId = userInfoService.currentUser().getUserId(); Optional<UserOrganizationsHistory> userOrganizationsHistories = userOrganizationsHistoryRepository.findById(userId); UserOrganizationsHistory userOrganizationsHistory = new UserOrganizationsHistory(); if (userOrganizationsHistories.isPresent()) { userOrganizationsHistory = userOrganizationsHistories.get(); return userOrganizationsHistory.getOrganizationsHistory(); }else{ return null; } }

Target:
public List<OrganizationHistory> getLastVistited() { String userId = userInfoService.currentUser().getUserId(); Optional<UserOrganizationsHistory> userOrganizationsHistories = userOrganizationsHistoryRepository.findById(userId); return userOrganizationsHistories .map(UserOrganizationsHistory::getOrganizationsHistory) .orElse(new ArrayList<>()); }
Source:
public void visitMethodInvocation(MethodInvocationTree mit) { if (maybeRaiseIssue(mit)) { return; } if (FEST_ASSERTIONS.anyMatch(mit) && !FEST_EXCLUSIONS.anyMatch(mit)) { chainedTo.push(ChainedMethods.FEST); } else if (!FEST_EXCLUSIONS.anyMatch(mit)) { chainedTo.push(ChainedMethods.ANY_BUT_NOT_FEST_EXCLUSIONS); } else { chainedTo.push(ChainedMethods.ANY); } super.visitMethodInvocation(mit); chainedTo.pop(); }

Target:
public void visitMethodInvocation(MethodInvocationTree mit) { if (incompleteAssertion(mit)) { return; } Boolean previous = chainedToAnyMethodButFestExclusions; chainedToAnyMethodButFestExclusions = !FEST_EXCLUSIONS.anyMatch(mit); scan(mit.methodSelect()); chainedToAnyMethodButFestExclusions = previous; }
Source:
public String getBearerToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); if (authorization == null) { throw new IllegalArgumentException("No access_token submitted!"); } return authorization.substring("Bearer ".length(), authorization.length()); }

Target:
public static String getBearerToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); if (authorization == null) { throw new IllegalArgumentException("No access_token submitted!"); } return authorization.substring("Bearer ".length(), authorization.length()); }
Source:
public List<NetworkStatementsDTO> getNetworkNodes(List<String> statementIds) throws QuadrigaStorageException{ try { Query query = sessionFactory.getCurrentSession() .createSQLQuery("select ns.* from tbl_project p, tbl_project_workspace pw, tbl_network_workspace nw, tbl_networks n, tbl_network_statements ns where p.projectid = pw.projectid and pw.workspaceid = nw.workspaceid and nw.networkid = n.networkid and ns.networkid = n.networkid and p.accessibility = 'PUBLIC' and n.status = 'APPROVED' and ns.statementid in (:statementids)") .setResultTransformer(Transformers.aliasToBean(NetworkStatementsDTO.class)); query.setParameterList("statementids", statementIds) ; @SuppressWarnings("unchecked") List<NetworkStatementsDTO> listNetworkStatementsDTO = query.list(); return listNetworkStatementsDTO; } catch (HibernateException e) { throw new QuadrigaStorageException(e); } }

Target:
public List<NetworkStatementsDTO> getNetworkNodes(List<String> statementIds) throws QuadrigaStorageException{ try { Query query = sessionFactory.getCurrentSession() .createSQLQuery("select ns.* from tbl_project p, tbl_project_workspace pw, tbl_network_workspace nw, tbl_networks n, tbl_network_statements ns where p.projectid = pw.projectid and pw.workspaceid = nw.workspaceid and nw.networkid = n.networkid and ns.networkid = n.networkid and p.accessibility = 'PUBLIC' and n.status = 'APPROVED' and ns.statementid in (:statementids)") .setResultTransformer(Transformers.aliasToBean(NetworkStatementsDTO.class)); query.setParameterList("statementids", statementIds) ; return (List<NetworkStatementsDTO>)query.list(); } catch (HibernateException e) { throw new QuadrigaStorageException(e); } }
Source:
private String getAttribute(String attrId) { Map<String, List<String>> attributes = dataObject.getProject().getAttributes(); List<String> values = attributes.get(attrId); if (values == null || values.isEmpty()) { return ""; } return MoreObjects.firstNonNull(values.get(0), ""); }

Target:
private String getAttribute(String attrId) { Map<String, List<String>> attributes = dataObject.getProject().getAttributes(); List<String> values = attributes.get(attrId); if (values == null || values.isEmpty()) { return ""; } return firstNonNull(values.get(0), ""); }
Source:
public void addProblemMarker(ProblemMarkerInfo problemMarkerInfo){ fErrors.add(problemMarkerInfo); fMarkerGenerator.addMarker(problemMarkerInfo); if (problemMarkerInfo.severity == IMarkerGenerator.SEVERITY_ERROR_RESOURCE) hasErrors = true; }

Target:
public void addProblemMarker(ProblemMarkerInfo problemMarkerInfo){ fErrors.add(problemMarkerInfo); fMarkerGenerator.addMarker(problemMarkerInfo); if (problemMarkerInfo.severity == IMarkerGenerator.SEVERITY_ERROR_RESOURCE) { hasErrors = true; } }
Source:
public void onCreate() { super.onCreate(); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.insertProviderAt(new BouncyCastleProvider(), 1); PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) { } } brandGlowEffect(getApplicationContext(), FormattingUtils.getColorFromAttr(getApplicationContext(), R.attr.colorPrimary)); createAccountIfNecessary(this); if (Preferences.getPreferences(this).isAppExecutedFirstTime()) { Preferences.getPreferences(this).setAppExecutedFirstTime(false); KeyserverSyncAdapterService.enableKeyserverSync(this); ContactSyncAdapterService.enableContactsSync(this); Preferences.getPreferences(this).setPrefVersionToCurrentVersion(); } if (Preferences.getKeyserverSyncEnabled(this)) { KeyserverSyncAdapterService.enableKeyserverSync(this); } Preferences.getPreferences(this).upgradePreferences(this); TlsCertificatePinning.addPinnedCertificate("hkps.pool.sks-keyservers.net", getAssets(), "hkps.pool.sks-keyservers.net.CA.cer"); TlsCertificatePinning.addPinnedCertificate("pgp.mit.edu", getAssets(), "pgp.mit.edu.cer"); TlsCertificatePinning.addPinnedCertificate("api.keybase.io", getAssets(), "api.keybase.io.CA.cer"); TemporaryFileProvider.cleanUp(this); }

Target:
public void onCreate() { super.onCreate(); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.insertProviderAt(new BouncyCastleProvider(), 1); PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) { } } brandGlowEffect(getApplicationContext(), FormattingUtils.getColorFromAttr(getApplicationContext(), R.attr.colorPrimary)); createAccountIfNecessary(this); Preferences preferences = Preferences.getPreferences(this); if (preferences.isAppExecutedFirstTime()) { preferences.setAppExecutedFirstTime(false); KeyserverSyncAdapterService.enableKeyserverSync(this); ContactSyncAdapterService.enableContactsSync(this); preferences.setPrefVersionToCurrentVersion(); } if (Preferences.getKeyserverSyncEnabled(this)) { KeyserverSyncAdapterService.updateInterval(this); } preferences.upgradePreferences(this); TlsCertificatePinning.addPinnedCertificate("hkps.pool.sks-keyservers.net", getAssets(), "hkps.pool.sks-keyservers.net.CA.cer"); TlsCertificatePinning.addPinnedCertificate("pgp.mit.edu", getAssets(), "pgp.mit.edu.cer"); TlsCertificatePinning.addPinnedCertificate("api.keybase.io", getAssets(), "api.keybase.io.CA.cer"); TemporaryFileProvider.cleanUp(this); }
Source:
@Benchmark public void writeRequest_singleSpan() throws IOException { BulkCallBuilder.write(Unpooled.compositeBuffer(Integer.MAX_VALUE), entry, true); }

Target:
@Benchmark public void writeRequest_singleSpan() { BulkCallBuilder.write(Unpooled.compositeBuffer(Integer.MAX_VALUE), entry, true); }
Source:
public LogInScreenInteractor observeLogInScreen() { final MainApplication app = MainApplication.instance(); final CharSequence title = ResourceUtil.getFormattedString(app.getResources(), R.string.login_title, "platform_name", app.getInjector().getInstance(Config.class).getPlatformName()); onUsernameView().check(matches(isCompletelyDisplayed())); onPasswordView().check(matches(isCompletelyDisplayed())); onLogInButton().check(matches(isCompletelyDisplayed())); return this; }

Target:
public LogInScreenInteractor observeLogInScreen() { final MainApplication app = MainApplication.instance(); final CharSequence title = ResourceUtil.getFormattedString(app.getResources(), R.string.login_title, "platform_name", app.getInjector().getInstance(Config.class).getPlatformName()); onView(allOf(isInActionBar(), withText(title.toString()))).check(matches(isCompletelyDisplayed())); onUsernameView().check(matches(isCompletelyDisplayed())); onPasswordView().check(matches(isCompletelyDisplayed())); onLogInButton().check(matches(isCompletelyDisplayed())); return this; }
Source:
public static Object getStringIDValue(Object idValue) { Assert.notNull(idValue, "id should not be null"); if (idValue instanceof String) { Assert.hasText(idValue.toString(), "id should not be empty or only whitespaces."); return idValue; } else if (idValue instanceof Integer) { return Integer.toString((Integer) idValue); } else if (idValue instanceof Long) { return Long.toString((Long) idValue); } else { throw new IllegalQueryException("Type of id field must be String or Integer or Long"); } }

Target:
public static String getStringIDValue(Object idValue) { Assert.notNull(idValue, "id should not be null"); if (idValue instanceof String) { Assert.hasText(idValue.toString(), "id should not be empty or only whitespaces."); return (String) idValue; } else if (idValue instanceof Integer) { return Integer.toString((Integer) idValue); } else if (idValue instanceof Long) { return Long.toString((Long) idValue); } else { throw new IllegalQueryException("Type of id field must be String or Integer or Long"); } }
Source:
public static int compare(byte[] a, byte[] b) { for (int i=0; i < Math.min(a.length, b.length); i++) if (a[i] != b[i]) return a[i] & 0xff - b[i] & 0xff; return 0; }

Target:
public static int compare(byte[] a, byte[] b) { if (a.length != b.length) return a.length - b.length; for (int i=0; i < a.length; i++) if (a[i] != b[i]) return a[i] & 0xff - b[i] & 0xff; return 0; }
Source:
public String shortestExample(String pattern) { if (reCache != null) { return reCache.get(pattern); } return shortestExampleCalc(pattern); }

Target:
public static String shortestExample(String pattern) { if (isRE(pattern)) { return toRegExp(pattern).toAutomaton().getShortestExample(true); } else if (pattern.endsWith("/*")) { return pattern.substring(0, pattern.length() - 1) + '1'; } else { return pattern; } }
Source:
private Set<Integer> parseStatusCodes(String statusCodesString) { if (statusCodesString == null || statusCodesString.isEmpty()) { return Collections.emptySet(); } Set<Integer> codes = new HashSet<Integer>(); for (String codeString: statusCodesString.split(",")) { codes.add(Integer.parseInt(codeString)); } return codes; }

Target:
static Set<Integer> parseStatusCodes(String statusCodesString) { if (statusCodesString == null || statusCodesString.isEmpty()) { return Collections.emptySet(); } Set<Integer> codes = new LinkedHashSet<Integer>(); for (String codeString: statusCodesString.split(",")) { codes.add(Integer.parseInt(codeString)); } return codes; }
Source:
public void connect() throws IOException { lock.lock(); try { if (jmxc != null) return; JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port)); Map<String, Object> env = new HashMap<String, Object>(); if (username != null) { String[] creds = {username, password}; env.put(JMXConnector.CREDENTIALS, creds); } jmxc = JMXConnectorFactory.connect(jmxUrl, env); mbeanServerConn = jmxc.getMBeanServerConnection(); } finally { lock.unlock(); } }

Target:
private void connect() throws IOException { lock.lock(); try { if (jmxc != null) return; JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port)); Map<String, Object> env = new HashMap<>(); if (username != null) { String[] creds = {username, password}; env.put(JMXConnector.CREDENTIALS, creds); } jmxc = JMXConnectorFactory.connect(jmxUrl, env); mbeanServerConn = jmxc.getMBeanServerConnection(); } finally { lock.unlock(); } }
Source:
public void setBinaryClassificationProperties(Iterable<? extends AbstractInstance> trainingData) { HashMap<Serializable, MutableInt> classifications = Maps.newHashMap(); for (AbstractInstance instance : trainingData) { Serializable classification = instance.getClassification(); if (classifications.containsKey(classification)) { classifications.get(classification).increment(); } else classifications.put(classification, new MutableInt(1)); if (classifications.size() > 2) { binaryClassifications = false; return; } } minorityClassification = null; double minorityClassificationCount = 0; for (Serializable val : classifications.keySet()) if (minorityClassification == null || classifications.get(val).doubleValue() < minorityClassificationCount) { minorityClassification = val; minorityClassificationCount = classifications.get(val).doubleValue(); } }

Target:
private void setBinaryClassificationProperties(Iterable<? extends AbstractInstance> trainingData) { HashMap<Serializable, MutableInt> classifications = Maps.newHashMap(); for (AbstractInstance instance : trainingData) { Serializable classification = instance.getClassification(); if (classifications.containsKey(classification)) { classifications.get(classification).increment(); } else classifications.put(classification, new MutableInt(1)); if (classifications.size() > 2) { binaryClassifications = false; return; } } minorityClassification = null; double minorityClassificationCount = 0; for (Serializable val : classifications.keySet()) if (minorityClassification == null || classifications.get(val).doubleValue() < minorityClassificationCount) { minorityClassification = val; minorityClassificationCount = classifications.get(val).doubleValue(); } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fConfiguration == null) ? 0 : fConfiguration.hashCode()); result = prime * result + ((file == null) ? 0 : file.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fTraceTypeId == null) ? 0 : fTraceTypeId.hashCode()); result = prime * result + ((fFile == null) ? 0 : fFile.hashCode()); return result; }
Source:
private boolean hasDescriptor(Context context) { Boolean value = false; if ((context.getName() != null && !context.getName().equals(""))) { for (ContextDescriptor descriptor : preferences.getContexts()) { if (descriptor.getName().equals(context.getName())) { value = true; } } } return value; }

Target:
private boolean hasDescriptor(Context context) { Boolean value = false; if ((context.getName() != null && !context.getName().equals(""))) { Iterator<ContextDescriptor> contextIterator = preferences.getContexts().iterator(); while (contextIterator.hasNext() && !value) { if (contextIterator.next().getName().equals(context.getName())) { value = true; } } } return value; }
Source:
private static boolean isLoadRunnerFileType(String line) throws IOException { final char[] magic = new char[]{ 0x00, 0x01, 0x00, 0x00, 0x53, 0x74, 0x61, 0x6E, 0x64, 0x61, 0x72, 0x64, 0x20, 0x4A, 0x65, 0x74, 0x20, 0x44, 0x42 }; return line.length() > magic.length && Arrays.equals(magic, line.substring(0, magic.length).toCharArray()); }

Target:
private static boolean isLoadRunnerFileType(String line) { String pattern = new String(new char[]{0x00, 0x01, 0x00, 0x00})+"Standard Jet DB"; return line.length() > pattern.length() && pattern.equals(line.substring(0, pattern.length())); }
Source:
DumpDataHelper(ClusterMap clusterMap, int bytesPerSec) { this._clusterMap = clusterMap; if(bytesPerSec != -1){ this.throttler = new Throttler(bytesPerSec, 100, true, SystemTime.getInstance()); } }

Target:
DumpDataHelper(ClusterMap clusterMap, int bytesPerSec) { this._clusterMap = clusterMap; if (bytesPerSec > 0) { this.throttler = new Throttler(bytesPerSec, 100, true, SystemTime.getInstance()); } else if (bytesPerSec < 0) { throw new IllegalArgumentException("BytesPerSec " + bytesPerSec + " cannot be negative "); } }
Source:
public void setInjectionTarget(InjectionTarget<X> injectionTarget) { checkWithinObserverNotification(); this.injectionTarget = injectionTarget; BootstrapLogger.LOG.setInjectionTargetCalled(getReceiver().getClass(), injectionTarget.getClass()); }

Target:
public void setInjectionTarget(InjectionTarget<X> injectionTarget) { checkWithinObserverNotification(); BootstrapLogger.LOG.setInjectionTargetCalled(getReceiver(), getInjectionTarget(), injectionTarget); this.injectionTarget = injectionTarget; }
Source:
protected Class<?> findClass(@Nonnull String name) throws ClassNotFoundException { VPath path = new VPath(name, '.'); path.addSuffix(".class"); InputVFile vFile; try { vFile = vfs.getRootInputVDir().getInputVFile(path); } catch (NotFileOrDirectoryException | NoSuchFileException e) { throw new ClassNotFoundException(name, e); } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { try (InputStream is = vFile.getInputStream()) { new LocationByteStreamSucker(is, byteStream, vFile.getLocation(), NoLocation.getInstance()) .suck(); } catch (IOException e) { throw new CannotCloseException(vFile, e); } } catch (CannotWriteException e) { throw new AssertionError(e); } catch (WrongPermissionException | CannotCloseException | CannotReadException e) { logger.log(Level.WARNING, "Failed to load class '" + name + "' from " + vfs.getLocation().getDescription(), e); throw new ClassNotFoundException(name, e); } byte[] byteArray = byteStream.toByteArray(); return defineClass(name, byteArray, 0, byteArray.length); }

Target:
protected Class<?> findClass(@Nonnull String name) throws ClassNotFoundException { VPath path = new VPath(name, '.'); path.addSuffix(".class"); InputVFile vFile; try { vFile = vfs.getRootInputVDir().getInputVFile(path); } catch (NotFileOrDirectoryException | NoSuchFileException e) { throw new ClassNotFoundException(name, e); } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { try (InputStream is = vFile.getInputStream()) { new LocationByteStreamSucker(is, byteStream, vFile.getLocation(), NoLocation.getInstance()) .suck(); } catch (IOException e) { throw new CannotCloseException(vFile, e); } } catch (CannotWriteException e) { throw new AssertionError(e); } catch (CannotCloseException | CannotReadException e) { logger.log(Level.SEVERE, "Failed to load class '" + name + "' from " + vfs.getLocation().getDescription(), e); throw new ClassNotFoundException(name, e); } catch (WrongPermissionException e) { logger.log(Level.INFO, "Failed to load class '" + name + "' from " + vfs.getLocation().getDescription(), e); throw new ClassNotFoundException(name, e); } byte[] byteArray = byteStream.toByteArray(); return defineClass(name, byteArray, 0, byteArray.length); }
Source:
public static void compileAndCompareSubsetOfActualToExpected( String goldenFileName, CompilerOptions options, String sourceFileName) throws Exception { List<SourceFile> sourceFiles = ImmutableList.of(readSource(sourceFileName)); List<SourceFile> externsFiles = ImmutableList.of(); String compiledSource = compile(externsFiles, sourceFiles, options); String referenceSource = readFile(toFullPath(goldenFileName)); String[] compiledLines = compiledSource.split("\n"); String[] goldenLines = referenceSource.split("\n"); int expectedNumberOfIdenticalLines = goldenLines.length; int identicalLinesBetweenFiles = 0; for (int i = 0; i < compiledLines.length; i++) { if (goldenLines[identicalLinesBetweenFiles].equals(compiledLines[i])) { identicalLinesBetweenFiles++; } } assertThat(identicalLinesBetweenFiles).isEqualTo(expectedNumberOfIdenticalLines); }

Target:
public static void compileAndCompareSubsetOfActualToExpected( String goldenFileName, CompilerOptions options, String sourceFileName) throws Exception { List<SourceFile> sourceFiles = ImmutableList.of(readSource(sourceFileName)); List<SourceFile> externsFiles = ImmutableList.of(); String compiledSource = compile(externsFiles, sourceFiles, options); String referenceSource = readFile(toFullPath(goldenFileName)); String[] compiledLines = compiledSource.split("\n"); String[] goldenLines = referenceSource.split("\n"); int expectedNumberOfIdenticalLines = goldenLines.length; int identicalLinesBetweenFiles = 0; for (int i = 0; i < compiledLines.length; i++) { if (goldenLines[identicalLinesBetweenFiles].equals(compiledLines[i])) { identicalLinesBetweenFiles++; } } assertWithMessage( "Line " + (identicalLinesBetweenFiles + 1) + " from Golden was not found in compiled version of source file") .that(identicalLinesBetweenFiles).isEqualTo(expectedNumberOfIdenticalLines); }
Source:
public Optional<List<Path>> getPathList(String key) { List<Path> pathList = new ArrayList<Path>(); try { String[] stringList = configuration.getStringArray(key); for (String pathStr : stringList) { pathList.add(Paths.get(pathStr)); } if (pathList.size() > 0) { return Optional.of(pathList); } } catch (ConversionException ce) { throw new IllegalStateException(String.format("requested key [%s] is not convertable to an array", key)); } return Optional.ofNullable((List<Path>)null); }

Target:
public List<Path> getPathList(String key) { List<Path> pathList = new ArrayList<Path>(); try { String[] stringList = configuration.getStringArray(key); for (String pathStr : stringList) { pathList.add(Paths.get(pathStr)); } } catch (ConversionException ce) { throw new IllegalStateException(String.format("requested key [%s] is not convertable to an array", key)); } return pathList; }
Source:
public static OVirtNodeInfo[] get() { final String delimiter = ":"; final String prefix[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); final String path[] = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String pattern = Config.<String> GetValue(ConfigValues.OvirtPattern); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); if (prefix.length != minimumVersion.length || prefix.length != path.length) { throw new IllegalArgumentException("Illegal Node Info"); } List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); for (int i=0;i<prefix.length;i++) { info.add(new OVirtNodeInfo(prefix[i], path[i], minimumVersion[i], pattern)); } return info.toArray(new OVirtNodeInfo[info.size()]); }

Target:
public static OVirtNodeInfo[] get() { final String delimiter = ":"; final String pattern = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix); final String path[] = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String prefix[]; Pattern exp = Pattern.compile("\\((.*?)\\)", Pattern.DOTALL); Matcher matcher = exp.matcher(Config.<String> GetValue(ConfigValues.OvirtIsoPrefix)); matcher.find(); log.debugFormat("matcher: {0}", Config.<String> GetValue(ConfigValues.OvirtIsoPrefix)); log.infoFormat("matcher group(1): prefix = [{0}]", matcher.group(1)); prefix = matcher.group(1).split("\\|"); log.debugFormat("NodeInfo: prefix length {0} minimum length {1} path length {2}", prefix.length, minimumVersion.length, path.length); if (prefix.length != minimumVersion.length || prefix.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); for (int i=0; i < prefix.length; i++) { log.debugFormat("NodeInfo Adding: prefix {0} path {1}, minimumVersion {2}, pattern {3}", prefix[i], path[i], minimumVersion[i], pattern); info.add(new OVirtNodeInfo(prefix[i], path[i], minimumVersion[i], pattern)); } return info.toArray(new OVirtNodeInfo[info.size()]); }
Source:
private List<ActionEventRequest> prepareProgramActionEventRequests() { ProgramActionBuilder builder = new ProgramActionBuilder(); List<ActionEventRequest> result = builder.build(programs, serverVersion); return result; }

Target:
private List<ActionEventRequest> prepareProgramActionEventRequests() { List<ActionEventRequest> result = new ArrayList<>(); for(Program program : programs) { result.add(prepareActionEventRequests(program.getName(), EventSubjects.ENROLL_IN_PROGRAM)); result.add(prepareActionEventRequests(program.getTrackedEntity().getName() + ", " + program.getName(), EventSubjects.CREATE_AND_ENROLL)); } return result; }
Source:
public static void ensureCurrentApprovalsLoaded(Iterable<ChangeData> changes) throws OrmException { List<ResultSet<PatchSetApproval>> pending = Lists.newArrayList(); for (ChangeData cd : changes) { if (!cd.notesMigration.readPatchSetApprovals()) { if (cd.currentApprovals == null && cd.limitedApprovals == null) { pending.add(cd.db.patchSetApprovals() .byPatchSet(cd.change().currentPatchSetId())); } } else { cd.change(); } } if (!pending.isEmpty()) { int idx = 0; for (ChangeData cd : changes) { if (cd.currentApprovals == null && cd.limitedApprovals == null) { cd.currentApprovals = sortApprovals(pending.get(idx++)); } } } }

Target:
public static void ensureCurrentApprovalsLoaded(Iterable<ChangeData> changes) throws OrmException { List<ResultSet<PatchSetApproval>> pending = Lists.newArrayList(); for (ChangeData cd : changes) { if (!cd.notesMigration.readPatchSetApprovals()) { if (cd.currentApprovals == null && cd.limitedApprovals == null) { pending.add(cd.db.patchSetApprovals() .byPatchSet(cd.change().currentPatchSetId())); } } else { cd.currentApprovals(); } } if (!pending.isEmpty()) { int idx = 0; for (ChangeData cd : changes) { if (cd.currentApprovals == null && cd.limitedApprovals == null) { cd.currentApprovals = sortApprovals(pending.get(idx++)); } } } }
Source:
protected Schema getMainSchema() throws MetaModelException { if (schema == null) { MutableSchema theSchema = new MutableSchema(getMainSchemaName()); for (SimpleTableDef tableDef: tableDefs) { MutableTable table = tableDef.toTable().setSchema(theSchema); theSchema.addTable(table); } schema = theSchema; } return schema; }

Target:
protected Schema getMainSchema() throws MetaModelException { MutableSchema theSchema = new MutableSchema(getMainSchemaName()); for (SimpleTableDef tableDef: tableDefs) { MutableTable table = tableDef.toTable().setSchema(theSchema); theSchema.addTable(table); } return theSchema; }
Source:
private void flipYifMag(String yunit) { try { if (SPVYQuantity.MAGNITUDE.getPossibleUnits() .contains(SPVYUnit.getFromUnitString(yunit))) { plotPreferences.setYflip(true); } } catch (SedException ex) { Logger.getLogger(SedPreferences.class.getName()) .log(Level.SEVERE, null, ex); } }

Target:
private void flipYifMag(String yunit) { try { if (SPVYQuantity.MAGNITUDE.getPossibleUnits() .contains(SPVYUnit.getFromUnitString(yunit))) { plotPreferences.setYflip(true); } else { plotPreferences.setYflip(false); } } catch (SedException ex) { Logger.getLogger(SedPreferences.class.getName()) .log(Level.SEVERE, null, ex); } }
Source:
public void testIllegalConstructionForTimeRange() { final long[][] illegalArgs = new long[][]{{0, -1}, {0, 1}, {-1, 0}, {-1, -1}, {Long.MAX_VALUE, 1}, {1, Long.MAX_VALUE}}; for (int i = 0; i < illegalArgs.length; i++) { try { new TimeRange(illegalArgs[i][0], illegalArgs[i][1]); fail("Expected IllegalArgumentException not thrown when constructing TimeRange with illegal arguments"); } catch (IllegalArgumentException e) { } } }

Target:
public void testIllegalConstructionForTimeRange() { long[][] illegalArgs = new long[][]{{0, -1}, {0, 1}, {-1, 0}, {-1, -1}, {Long.MAX_VALUE, 1}, {1, Long.MAX_VALUE}}; for (int i = 0; i < illegalArgs.length; i++) { try { new TimeRange(illegalArgs[i][0], illegalArgs[i][1]); fail("Expected IllegalArgumentException not thrown when constructing TimeRange with illegal arguments"); } catch (IllegalArgumentException e) { } } }
Source:
private void testActionWithNoParams() { ______TS("Failure case: no parameters given"); loginAsStudent(account.googleId); String[] submissionParams = new String[] {}; GetStudentProfilePictureAction action = getAction(submissionParams); assertThrows(NullHttpParameterException.class, () -> { action.execute(); }); }

Target:
private void testActionWithNoParams() { ______TS("Failure case: no parameters given"); loginAsStudent(account.googleId); String[] submissionParams = new String[] {}; GetStudentProfilePictureAction action = getAction(submissionParams); assertThrows(NullHttpParameterException.class, () -> action.execute()); }
Source:
public PreparedStatement toExternal(RowData rowData, PreparedStatement statement) throws SQLException { for (int index = 0; index < rowData.getArity(); index++) { toExternalConverters[index].convert(statement, index, fieldTypes[index], rowData); } return statement; }

Target:
public PreparedStatement toExternal(RowData rowData, PreparedStatement statement) throws SQLException { for (int index = 0; index < rowData.getArity(); index++) { toExternalConverters[index].serialize(rowData, index, statement); } return statement; }
Source:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { String result = detail.substring(0, maxDetailLength).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }

Target:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { String result = detail.substring(0, maxDetailLength - 3).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }
Source:
public void createTopics(int partitions, int replication, Properties topicProperties, String... topics) { checkState(started.get() && !stopped.get(), "not started!"); ZkClient zkClient = new ZkClient(getZookeeperConnectString(), 30_000, 30_000, ZKStringSerializer$.MODULE$); ZkUtils zkUtils = ZkUtils.apply(zkClient, false); try { for (String topic : topics) { AdminUtils.createTopic(zkUtils, topic, partitions, replication, topicProperties, RackAwareMode.Disabled$.MODULE$); } } finally { zkClient.close(); } }

Target:
public void createTopics(int partitions, int replication, Properties topicProperties, String... topics) { checkState(started.get() && !stopped.get(), "not started!"); ZkUtils zkUtils = ZkUtils.apply(getZookeeperConnectString(), 30_000, 30_000, false); try { for (String topic : topics) { AdminUtils.createTopic(zkUtils, topic, partitions, replication, topicProperties, RackAwareMode.Disabled$.MODULE$); } } finally { zkUtils.close(); } }
Source:
private void registerLongClickOnFavorites() { View.OnLongClickListener listener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int favNumber = Integer.parseInt((String) view.getTag()); ArrayList<Pojo> favorites = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve); if (favNumber >= favorites.size()) { Log.i(TAG, "Clicking on an unitialized favorite."); return false; } Pojo pojo = favorites.get(favNumber); final Result result = Result.fromPojo(MainActivity.this, pojo); result.getPopupMenu(MainActivity.this, adapter, view).show(); return true; } }; findViewById(R.id.favoriteBar0).setOnLongClickListener(listener); findViewById(R.id.favoriteBar1).setOnLongClickListener(listener); findViewById(R.id.favoriteBar2).setOnLongClickListener(listener); findViewById(R.id.favoriteBar3).setOnLongClickListener(listener); findViewById(R.id.favoriteBar4).setOnLongClickListener(listener); findViewById(R.id.favoriteBar5).setOnLongClickListener(listener); }

Target:
private void registerLongClickOnFavorites() { View.OnLongClickListener listener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int favNumber = Integer.parseInt((String) view.getTag()); ArrayList<Pojo> favorites = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve); if (favNumber >= favorites.size()) { Log.i(TAG, "Long clicking on an unitialized favorite."); return false; } Pojo pojo = favorites.get(favNumber); final Result result = Result.fromPojo(MainActivity.this, pojo); result.getPopupMenu(MainActivity.this, adapter, view).show(); return true; } }; for (int id : favBarIds) { findViewById(id).setOnLongClickListener(listener); } for (int id : favsIds) { findViewById(id).setOnLongClickListener(listener); } }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(fragmentResource, container, false); return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(fragmentResource, container, false); }
Source:
private MilliSpan() { this.begin = 0; this.name = null; this.traceId = 0; this.spanId = null; this.processId = null; this.parents = new ArrayList<>(); }

Target:
private MilliSpan() { this.begin = 0; this.name = null; this.traceId = 0; this.spanId = 0; this.processId = null; this.parents = new ArrayList<>(); }
Source:
public void run() { try { Thread.sleep(DELAY_MS); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while sleeping to simulate computation", e); } for (int i = 0; i < numberOfUpdates; i++) { for (int j = 0; j < numberOfKeys; j++) { parameterWorker.push(startKey + j, delta); final Vector value = parameterWorker.pull(startKey + j); LOG.log(Level.INFO, "Current value associated with key {0} is {1}", new Object[]{startKey + j, value}); } } final WorkerMetrics workerMetrics = buildMetricsMsg(memoryStore.getNumBlocks()); sendMetrics(workerMetrics); }

Target:
public void run() { for (int i = 0; i < numMiniBatchesPerItr; i++) { final List<Vector> valueList = parameterWorker.pull(keyList); LOG.log(Level.INFO, "Current values associated with keys {0} is {1}", new Object[]{keyList, valueList}); try { Thread.sleep(computeTime); } catch (final InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while sleeping to simulate computation", e); } for (final int key : keyList) { parameterWorker.push(key, delta); } } final WorkerMetrics workerMetrics = buildMetricsMsg(memoryStore.getNumBlocks()); sendMetrics(workerMetrics); }