auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public InputStream getInputStream() throws IOException { <START> if (data == null) { <END> synchronized (this) { if (data == null) { HttpRequests requests = new HttpRequests(new BasicHttpParams(), null, null); data = IOUtils.toByteArray(requests.get(attachmentURI)); } } } return new ByteArrayInputStream(data); }</code><technical_language>here? load data memory send a stream? This return InputStream returned requests.get(attachmentURI). If problems test pass this of things, is wrong</technical_language>

Target:
public InputStream getInputStream() throws IOException { if( data == null) { HttpRequests requests = new HttpRequests(new BasicHttpParams(), null, null); return requests.get(attachmentURI); } else { return new ByteArrayInputStream(data); } }
Source:
<code>public void testSlotAllocationNoResourceManager() throws Exception { <START> try (SlotPool pool = createAndSetUpSlotPool(false)) { <END> final CompletableFuture<PhysicalSlot> future = testMainThreadExecutor.execute(() -> pool.requestNewAllocatedSlot( new SlotRequestId(), ResourceProfile.UNKNOWN, fastTimeout)); try { future.get(); fail("We expected an ExecutionException."); } catch (ExecutionException e) { assertTrue(ExceptionUtils.stripExecutionException(e) instanceof TimeoutException); } } }</code><technical_language>prefer a createAndSetUpSlotPoolWithoutResourceManager() replace createAndSetUpSlotPool(false)</technical_language>

Target:
public void testSlotAllocationNoResourceManager() throws Exception { try (SlotPool pool = createAndSetUpSlotPoolWithoutResourceManager()) { final CompletableFuture<PhysicalSlot> future = testMainThreadExecutor.execute(() -> pool.requestNewAllocatedSlot( new SlotRequestId(), ResourceProfile.UNKNOWN, fastTimeout)); try { future.get(); fail("We expected an ExecutionException."); } catch (ExecutionException e) { assertTrue(ExceptionUtils.stripExecutionException(e) instanceof TimeoutException); } } }
Source:
<code>public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "OnStartCommand called"); final int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1); final boolean castDisconnect = intent.getBooleanExtra(EXTRA_CAST_DISCONNECT, false); Playable playable = intent.getParcelableExtra(EXTRA_PLAYABLE); if (keycode == -1 && playable == null && !castDisconnect) { Log.d(TAG, "PlaybackService was started with no arguments."); return Service.START_NOT_STICKY; } if (keycode != -1) { Log.d(TAG, "Received media button event"); boolean handled = handleKeycode(keycode, true); if (!handled) { serviceManager.stopService(); return Service.START_NOT_STICKY; } <START> } else if (!flavorHelper.castDisconnect(castDisconnect) && playable != null) { <END> boolean stream = intent.getBooleanExtra(EXTRA_SHOULD_STREAM, true); boolean startWhenPrepared = intent.getBooleanExtra(EXTRA_START_WHEN_PREPARED, false); boolean prepareImmediately = intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); flavorHelper.castDisconnect(playable instanceof ExternalMedia); if (playable instanceof FeedMedia) { playable = DBReader.getFeedMedia(((FeedMedia) playable).getId()); } mediaPlayer.playMediaObject(playable, stream, startWhenPrepared, prepareImmediately); } return Service.START_NOT_STICKY; }</code><technical_language>Removing this #2356, right</technical_language>

Target:
public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "OnStartCommand called"); final int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1); final boolean castDisconnect = intent.getBooleanExtra(EXTRA_CAST_DISCONNECT, false); Playable playable = intent.getParcelableExtra(EXTRA_PLAYABLE); if (keycode == -1 && playable == null && !castDisconnect) { Log.d(TAG, "PlaybackService was started with no arguments."); return Service.START_NOT_STICKY; } if (keycode != -1) { Log.d(TAG, "Received media button event"); boolean handled = handleKeycode(keycode, true); if (!handled) { return Service.START_NOT_STICKY; } } else if (!flavorHelper.castDisconnect(castDisconnect) && playable != null) { boolean stream = intent.getBooleanExtra(EXTRA_SHOULD_STREAM, true); boolean startWhenPrepared = intent.getBooleanExtra(EXTRA_START_WHEN_PREPARED, false); boolean prepareImmediately = intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); flavorHelper.castDisconnect(playable instanceof ExternalMedia); if (playable instanceof FeedMedia) { playable = DBReader.getFeedMedia(((FeedMedia) playable).getId()); } mediaPlayer.playMediaObject(playable, stream, startWhenPrepared, prepareImmediately); } return Service.START_NOT_STICKY; }
Source:
<code>public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { <START> X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); <END> String name = certs[0].getSubjectDN().getName(); Matcher m = REGEX_USERID.matcher(name); String userName = null; if (m.matches()) { userName = m.group(1); } else { throw new ServletException("Couldn't extract username from your certificate"); } final AuthRequest areq = AuthRequest.forUser(userName); final AuthResult arsp; try { arsp = accountManager.authenticate(areq); } catch (AccountException e) { String err = "Unable to authenticate user \"" + userName + "\""; log.error(err, e); throw new ServletException(err, e); } webSession.get().login(arsp, true); chain.doFilter(req, rsp); }</code><technical_language>NPE, lets record exception if certs == null certs.length == 0. administrator container working properly. happen, of error reports I get repo-discuss I happen. :-(</technical_language>

Target:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (certs == null || certs.length == 0) { throw new ServletException( "Couldn't get the attribute javax.servlet.request.X509Certificate from the request"); } String name = certs[0].getSubjectDN().getName(); Matcher m = REGEX_USERID.matcher(name); String userName; if (m.matches()) { userName = m.group(1); } else { throw new ServletException("Couldn't extract username from your certificate"); } final AuthRequest areq = AuthRequest.forUser(userName); final AuthResult arsp; try { arsp = accountManager.authenticate(areq); } catch (AccountException e) { String err = "Unable to authenticate user \"" + userName + "\""; log.error(err, e); throw new ServletException(err, e); } webSession.get().login(arsp, true); chain.doFilter(req, rsp); }
Source:
<code>protected void internalRefresh(Object element) { disableRedraw(); try { boolean layoutChanged = false; BreadcrumbItem item= (BreadcrumbItem) doFindItem(element); if (item == null || element != null && element.equals(getInput())) { for (BreadcrumbItem <START> item1 : <END> fBreadcrumbItems) { layoutChanged = refreshItem(item1) || layoutChanged; } } else { layoutChanged = refreshItem(item) || layoutChanged; } if (layoutChanged) { updateSize(); fContainer.layout(true, true); } } finally { enableRedraw(); } }</code><technical_language>rename currItem</technical_language>

Target:
protected void internalRefresh(Object element) { disableRedraw(); try { boolean layoutChanged = false; BreadcrumbItem item= (BreadcrumbItem) doFindItem(element); if (item == null || element != null && element.equals(getInput())) { for (BreadcrumbItem currItem : fBreadcrumbItems) { layoutChanged = refreshItem(currItem) || layoutChanged; } } else { layoutChanged = refreshItem(item) || layoutChanged; } if (layoutChanged) { updateSize(); fContainer.layout(true, true); } } finally { enableRedraw(); } }
Source:
<code>private List<ApplicableClass> fillApplicableClasses() { List<IConfigurationElement> ces = new ArrayList<>(); IConfigurationElement[] tracetypeCE = fCe.getChildren(TmfAnalysisModuleSourceConfigElement.TRACETYPE_ELEM); ces.addAll(Arrays.asList(tracetypeCE)); tracetypeCE = Platform.getExtensionRegistry().getConfigurationElementsFor(TmfAnalysisModuleSourceConfigElement.TMF_ANALYSIS_TYPE_ID); String id = getId(); for (IConfigurationElement element : tracetypeCE) { String elementName = element.getName(); if (elementName.equals(TmfAnalysisModuleSourceConfigElement.TRACETYPE_ELEM)) { String analysisId = element.getAttribute(TmfAnalysisModuleSourceConfigElement.ID_ATTR); if (id.equals(analysisId)) { ces.add(element); } } } List<ApplicableClass> list = new ArrayList<>(); ces.forEach(ce -> { ApplicableClass traceTypeApplies = parseTraceTypeElement(ce); if (traceTypeApplies != null) { list.add(traceTypeApplies); } <START> }); <END> return list; }</code><technical_language>in arbitrary order, leaving this is naive. analysis's tracetype specifics after. _That_ order is important</technical_language>

Target:
private List<ApplicableClass> fillApplicableClasses() { List<IConfigurationElement> ces = new ArrayList<>(); IConfigurationElement[] tracetypeCE = fCe.getChildren(TmfAnalysisModuleSourceConfigElement.TRACETYPE_ELEM); ces.addAll(Arrays.asList(tracetypeCE)); tracetypeCE = Platform.getExtensionRegistry().getConfigurationElementsFor(TmfAnalysisModuleSourceConfigElement.TMF_ANALYSIS_TYPE_ID); String id = getId(); for (IConfigurationElement element : tracetypeCE) { String elementName = element.getName(); if (elementName.equals(TmfAnalysisModuleSourceConfigElement.TRACETYPE_ELEM)) { String analysisId = element.getAttribute(TmfAnalysisModuleSourceConfigElement.ID_ATTR); if (id.equals(analysisId)) { ces.add(element); } } } Map<Class<?>, ApplicableClass> classMap = new HashMap<>(); ces.forEach(ce -> { ApplicableClass traceTypeApplies = parseTraceTypeElement(ce); if (traceTypeApplies != null) { classMap.put(traceTypeApplies.fClass, traceTypeApplies); } }); List<ApplicableClass> applicableClasses = new ArrayList<>(classMap.values()); applicableClasses.sort(APPLICABLE_CLASS_COMPARATOR); return applicableClasses; }
Source:
<code>public Block getBlock(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); <START> checkState(positionCount <= outputPositionCount, "Not enough values"); <END> if (allNulls) { return new RunLengthEncodedBlock(new DictionaryBlock(1, dictionaryBlock, new int[] {dictionaryBlock.getPositionCount() - 1}), positionCount); } if (positionCount == outputPositionCount) { Block block = new DictionaryBlock(positionCount, dictionaryBlock, values); values = null; outputPositions = null; return block; } int[] valuesCopy = new int[positionCount]; int positionIndex = 0; int nextPosition = positions[positionIndex]; for (int i = 0; i < outputPositionCount; i++) { if (outputPositions[i] < nextPosition) { continue; } assert outputPositions[i] == nextPosition; valuesCopy[positionIndex] = this.values[i]; positionIndex++; if (positionIndex >= positionCount) { break; } nextPosition = positions[positionIndex]; } return new DictionaryBlock(positionCount, dictionaryBlock, valuesCopy); }</code><technical_language>check valuesInUse</technical_language>

Target:
public Block getBlock(int[] positions, int positionCount) { checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero"); checkState(outputRequired, "This stream reader doesn't produce output"); checkState(positionCount <= outputPositionCount, "Not enough values"); checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (allNulls) { return new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount); } if (positionCount == outputPositionCount) { return new DictionaryBlock(positionCount, dictionaryBlock, values); } int[] valuesCopy = new int[positionCount]; int positionIndex = 0; int nextPosition = positions[positionIndex]; for (int i = 0; i < outputPositionCount; i++) { if (outputPositions[i] < nextPosition) { continue; } assert outputPositions[i] == nextPosition; valuesCopy[positionIndex] = this.values[i]; positionIndex++; if (positionIndex >= positionCount) { break; } nextPosition = positions[positionIndex]; } return new DictionaryBlock(positionCount, dictionaryBlock, valuesCopy); }
Source:
<code><START> private static void createCopy(SWTBotTreeItem traceItem, boolean copyAsLink) { <END> traceItem.contextMenu().menu("Copy...").click(); final String COPY_TRACE_DIALOG_TITLE = "Copy Trace"; fBot.waitUntil(Conditions.shellIsActive(COPY_TRACE_DIALOG_TITLE)); SWTBotShell shell = fBot.shell(COPY_TRACE_DIALOG_TITLE); SWTBotText text = shell.bot().textWithLabel("New Trace name:"); text.setText(RENAMED_TRACE_NAME); if (!copyAsLink) { shell.bot().radio(COPY_AS_NEW_TRACE_OPTION).click(); text.setText(RENAMED_AS_NEW_TRACE_NAME); } shell.bot().button("OK").click(); fBot.waitUntil(Conditions.shellCloses(shell)); }</code><technical_language>I suggest start setting focus ProjectExplorer view, calling method</technical_language>

Target:
private static void createCopy(SWTBotTreeItem traceItem, boolean copyAsLink) { SWTBotView viewBot = fBot.viewByTitle("Project Explorer"); viewBot.setFocus(); traceItem.contextMenu().menu("Copy...").click(); final String COPY_TRACE_DIALOG_TITLE = "Copy Trace"; fBot.waitUntil(Conditions.shellIsActive(COPY_TRACE_DIALOG_TITLE)); SWTBotShell shell = fBot.shell(COPY_TRACE_DIALOG_TITLE); SWTBotText text = shell.bot().textWithLabel("New Trace name:"); text.setText(RENAMED_TRACE_NAME); if (!copyAsLink) { shell.bot().radio(COPY_AS_NEW_TRACE_OPTION).click(); text.setText(RENAMED_AS_NEW_TRACE_NAME); } shell.bot().button("OK").click(); fBot.waitUntil(Conditions.shellCloses(shell)); }
Source:
<code>private StmtTargetTableScan simplifierForSubquery(AbstractParsedStmt subquery) { if (!(subquery instanceof ParsedSelectStmt)) { return null; } ParsedSelectStmt selectSubquery = (ParsedSelectStmt) subquery; if (selectSubquery.hasAggregateOrGroupby()) { return null; } if (selectSubquery.hasAggregateDistinct()) { return null; } if (selectSubquery.hasWindowFunctionExpression()) { return null; } if (selectSubquery.hasLimitOrOffset() || selectSubquery.hasLimitOrOffsetParameters()) { return null; } int tableCount = 0; StmtTargetTableScan simpler = null; for (Map.Entry<String, StmtTableScan> entry : selectSubquery.m_tableAliasMap.entrySet()) { <START> if (entry.getKey().contains(AbstractParsedStmt.TEMP_TABLE_NAME)) { <END> continue; } if (++tableCount > 1) { return null; } StmtTableScan scan = entry.getValue(); if (scan instanceof StmtTargetTableScan) { simpler = (StmtTargetTableScan) scan; } else { return null; } } return simpler; }</code><technical_language>This "already broken" startsWith more apropos contains</technical_language>

Target:
private StmtTargetTableScan simplifierForSubquery(AbstractParsedStmt subquery) { if (!(subquery instanceof ParsedSelectStmt)) { return null; } ParsedSelectStmt selectSubquery = (ParsedSelectStmt) subquery; if (selectSubquery.hasAggregateOrGroupby()) { return null; } if (selectSubquery.hasAggregateDistinct()) { return null; } if (selectSubquery.hasWindowFunctionExpression()) { return null; } if (selectSubquery.hasLimitOrOffset() || selectSubquery.hasLimitOrOffsetParameters()) { return null; } int tableCount = 0; StmtTargetTableScan simpler = null; for (Map.Entry<String, StmtTableScan> entry : selectSubquery.m_tableAliasMap.entrySet()) { if (entry.getKey().startsWith(AbstractParsedStmt.TEMP_TABLE_NAME)) { continue; } if (++tableCount > 1) { return null; } StmtTableScan scan = entry.getValue(); if (scan instanceof StmtTargetTableScan) { simpler = (StmtTargetTableScan) scan; } else { return null; } } return simpler; }
Source:
<code>public EmbeddedPostgres start() throws IOException { if (builderPort == 0) { builderPort = detectPort(); } if (builderDataDirectory == null) { builderDataDirectory = Files.createTempDirectory("epg").toFile(); } if (pgDirectoryResolver == null) { <START> pgDirectoryResolver = UncompressBundleDirectoryResolver.getDefault(); <END> } return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, config, localeConfig, builderPort, connectConfig, pgDirectoryResolver, errRedirector, outRedirector, pgStartupWait, overrideWorkingDirectory); }</code><technical_language>log.trace "No overriding pgDirectoryResolver, default UncompresssBundleDirectoryResolver"</technical_language>

Target:
public EmbeddedPostgres start() throws IOException { if (builderPort == 0) { builderPort = detectPort(); } if (builderDataDirectory == null) { builderDataDirectory = Files.createTempDirectory("epg").toFile(); } if (pgDirectoryResolver == null) { LOG.trace("pgDirectoryResolver not overriden, using default (UncompressBundleDirectoryResolver)"); pgDirectoryResolver = UncompressBundleDirectoryResolver.getDefault(); } return new EmbeddedPostgres(parentDirectory, builderDataDirectory, builderCleanDataDirectory, config, localeConfig, builderPort, connectConfig, pgDirectoryResolver, errRedirector, outRedirector, pgStartupWait, overrideWorkingDirectory); }
Source:
<code><START> public void addMetric(ReplicationMetric replicationMetric) throws SemanticException { <END> if (metricMap.size() > maxSize) { throw new SemanticException("Metrics are not getting collected. "); } else { if (metricMap.size() > 0.8 * maxSize) { LOG.error("Metrics cache is 80 % full. Will start dropping metrics once full. "); } metricMap.put(replicationMetric.getScheduledExecutionId(), replicationMetric); } }</code><technical_language>concurrent thread a time call this add metric? Is data copy progress part of this metric</technical_language>

Target:
public synchronized void addMetric(ReplicationMetric replicationMetric) throws SemanticException { if (metricMap.size() >= maxSize) { throw new SemanticException("Metrics are not getting collected. "); } else { if (metricMap.size() > 0.8 * maxSize) { LOG.warn("Metrics cache is more than 80 % full. Will start dropping metrics once full. "); } metricMap.put(replicationMetric.getScheduledExecutionId(), replicationMetric); } }
Source:
<code>abstract ServerLocator initLocator() throws Exception; abstract ClientSessionFactory initClientSessionFactory(ServerLocator locator) throws Exception; public ClientSessionFactory getFactory() { <START> synchronized (lock) { <END> try { if (this.locator == null) { this.locator = initLocator(); } if (this.factory == null || this.factory.isClosed()) { this.factory = initClientSessionFactory(this.locator); } } catch (Exception e) { log.error("Unable to create connection to message bus.", e); throw new RuntimeException(e); } return this.factory; } }</code><technical_language>this pattern before, usual reasons locking object simply synchronized keyword method definition (which effectively thing): public synchronized ClientSessionFactory getFactory() { basic here, allows subclasses other operations lock this well. bit desired, "not desired" case is typically private lock target in</technical_language>

Target:
abstract ServerLocator initLocator() throws Exception; abstract ClientSessionFactory initClientSessionFactory(ServerLocator locator) throws Exception; abstract ClientSession createClientSession() throws ActiveMQException; synchronized ClientSessionFactory getFactory() { try { if (this.locator == null) { this.locator = initLocator(); } if (this.factory == null || this.factory.isClosed()) { this.factory = initClientSessionFactory(this.locator); } } catch (Exception e) { log.error("Unable to create connection to message bus.", e); throw new RuntimeException(e); } return this.factory; }
Source:
<code><START> public void updateAlertTarget(Integer targetId, Map<String, Object> ambariAlertNotifications) { <END> ImmutableMap<String, Map<String, Object>> alertTargetRequest = ImmutableMap.of("AlertTarget", ambariAlertNotifications); restAdapter.create(AlertTargetEndpoint.class).editAlertNotification(targetId, alertTargetRequest); }</code><technical_language>If is indended outer world private protected</technical_language>

Target:
protected void updateAlertTarget(Integer targetId, Map<String, Object> ambariAlertNotifications) { ImmutableMap<String, Map<String, Object>> alertTargetRequest = ImmutableMap.of("AlertTarget", ambariAlertNotifications); restAdapter.create(AlertTargetEndpoint.class).editAlertNotification(targetId, alertTargetRequest); }
Source:
<code>private static RetrySettings buildIdempotentRetrySettings(RetrySettings retrySettings, BigtableOptions options) { RetryOptions retryOptions = options.getRetryOptions(); RetrySettings.Builder retryBuilder = retrySettings.toBuilder(); retryBuilder .setInitialRetryDelay(ofMillis(retryOptions.getInitialBackoffMillis())) .setRetryDelayMultiplier(retryOptions.getBackoffMultiplier()) .setMaxRetryDelay(ofMillis(retryOptions.getMaxElapsedBackoffMillis())) .setMaxAttempts(retryOptions.getMaxScanTimeoutRetries()); Duration shortRpcTimeout = ofMillis(options.getCallOptionsConfig().getShortRpcTimeoutMs()); retryBuilder .setInitialRpcTimeout(shortRpcTimeout) .setMaxRpcTimeout(shortRpcTimeout) <START> .setTotalTimeout(ofMillis(options.getCallOptionsConfig().getLongRpcTimeoutMs())); <END> if (retryOptions.allowRetriesWithoutTimestamp()) { LOG.warn("Retries without Timestamp does not support yet."); } return retryBuilder.build(); }</code><technical_language>This right. I for rpcs ReadRows (plural), mapping be: - if useTimeouts == true, initialRpcTimeout = maxRpcTimeout = shortRpcTimeout - if useTimeouts == false, initialRpcTimeout = maxRpcTimeout = [6 minutes?](<LINK_0> - totalTimeout = RetryOptions.getMaxElapsedBackoffMillis - maxAttempts = 0 (disabled) (@sduskis, I correct classic java client limit attempts for other rpcs?) For readRows - initialRpcTimeout = maxRpcTimeout = RetryOptions.readPartialRowTimeoutMillis - if (useTimeouts) totalTimeout = longRpcTimeoutMs - maxAttempts = RetryOptions.getMaxScanTimeoutRetries</technical_language>

Target:
private static RetrySettings buildIdempotentRetrySettings(RetrySettings retrySettings, BigtableOptions options) { RetryOptions retryOptions = options.getRetryOptions(); CallOptionsConfig callOptions = options.getCallOptionsConfig(); RetrySettings.Builder retryBuilder = retrySettings.toBuilder(); if (retryOptions.allowRetriesWithoutTimestamp()) { throw new UnsupportedOperationException("Retries without Timestamp does not support yet."); } Duration rpcTimeout = ofMillis(callOptions.isUseTimeout() ? callOptions.getShortRpcTimeoutMs() : RPC_DEADLINE_MS); retryBuilder .setInitialRetryDelay(ofMillis(retryOptions.getInitialBackoffMillis())) .setRetryDelayMultiplier(retryOptions.getBackoffMultiplier()) .setMaxRetryDelay(ofMillis(MAX_RETRY_TIMEOUT_MS)) .setInitialRpcTimeout(rpcTimeout) .setMaxRpcTimeout(rpcTimeout) .setMaxAttempts(0) .setTotalTimeout(ofMillis(retryOptions.getMaxElapsedBackoffMillis())); return retryBuilder.build(); }
Source:
<code><START> public Ordering(String field, SortItem.Ordering sortOrder, SortItem.NullOrdering nullOrder) <END> { this.field = field; this.sortOrder = sortOrder; this.nullOrder = nullOrder; }</code><technical_language>private? is a factory method</technical_language>

Target:
private Ordering(String field, SortItem.Ordering sortOrder, SortItem.NullOrdering nullOrder) { this.field = field; this.sortOrder = sortOrder; this.nullOrder = nullOrder; }
Source:
<code>public void deleteIssues(){ issues.findAllIssues(group.getRepository()).forEach(x -> { Stream<? extends IssueComment> comments = issueComments.getMostRecentIssueComments(Lists.<GroupRepository>asList(group.getRepository(), new GroupRepository[0]),10); comments.forEach(comment -> issueComments.delete(comment)); <START> issues.delete(x); <END> }); }</code><technical_language>I understand point :smile:, tests influence behaviour of main code base, is bad practise(I thought :wink: )</technical_language>

Target:
public void deleteIssues(){ List<Issue> allIssues = issues.findAllIssues(group.getRepository()); allIssues.stream() .map(issues::refresh) .forEach(issues::delete); }
Source:
<code>public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") <START> .withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><sessions><Session><" + <END> "session_id>" + sessionId + "</session_id><partner_id>123456</partner_id><create_dt>" + "Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(this.apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertFalse(session.getProperties().isP2p()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching("/session/create")) .withHeader("X-TB-PARTNER-AUTH", matching(this.apiKey+":"+this.apiSecret)) .withHeader("User-Agent", matching(".*Opentok-Java-SDK/"+ Version.VERSION+".*"))); }</code><technical_language>a const String for xml String reuse it</technical_language>

Target:
public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><sessions><Session><" + "session_id>" + sessionId + "</session_id><partner_id>123456</partner_id><create_dt>" + "Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(this.apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching("/session/create")) .withHeader("X-TB-PARTNER-AUTH", matching(this.apiKey+":"+this.apiSecret)) .withHeader("User-Agent", matching(".*Opentok-Java-SDK/"+ Version.VERSION+".*"))); }
Source:
<code>public static void main(String[] args) { try { Map<String, Object> argMap = parseArgs(args); Map<String, ModuleService> moduleServices = load(ModuleService.class); if (argMap.containsKey(ARG_HELP)) { System.out.println("core help"); <START> System.out.println("Modules: " + StringUtils.join(moduleServices.keySet(), ", ")); <END> return; } List<String> others = (List<String>) argMap.get("__other__"); String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists. To list existing modules use --help argument.", module) ); } Map<String, Object> moduleArgMap = moduleService.parseArguments(others); if(moduleArgMap.containsKey(ARG_HELP)) { System.out.println(module + " help"); return; } others = (List<String>)moduleArgMap.get("__other__"); if(others.size() > 1) { throw new IllegalArgumentException( String.format( "You've provided illegal arguments '%1$s' for module '%2$s' ", StringUtils.join(others, ", "), module ) ); } ExtensionsManager extensionsManager = new ExtensionsManager(); for(File f : CoreUtil.listFiles((String)argMap.get("extensions-dir"))) { extensionsManager.load(f); } for(ExtensionProxy proxy : extensionsManager.getLoadedExtensions()) { extensionsManager.initialize(proxy.getContext().<String>get(Base.ContextKeys.INSTANCE_NAME)); } ExtMap context = new ExtMap().mput(Base.GlobalContextKeys.EXTENSIONS, extensionsManager.getLoadedExtensions()); moduleService.setContext(context); moduleService.run(); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } catch (Throwable t) { t.printStackTrace(); } }</code><technical_language>please sort oh... return treemap, sort for presentation</technical_language>

Target:
public static void main(String[] args) { try { Map<String, Object> argMap = parseArgs(args); setupLogger(argMap); List<String> others = (List<String>) argMap.get("__other__"); Map<String, ModuleService> moduleServices = loadModules(ModuleService.class); if (argMap.containsKey(ARG_HELP) || others.isEmpty()) { List<String> modules = new ArrayList<>(moduleServices.keySet()); Collections.sort(modules); System.out.println("Modules: " + StringUtils.join(modules, ", ")); return; } String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists. To list existing modules use --help argument.", module) ); } if(moduleService.parseArguments(others)) { System.out.println(module + " help"); return; } loadExtensions(moduleService, (String) argMap.get("extensions-dir")); moduleService.run(); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); logger.error(ex.getMessage()); } catch (Throwable t) { System.out.println(t.getMessage()); logger.error(t.getMessage()); logger.debug(t.getMessage(), t); } }
Source:
<code>public static State convertToAcceptedState(State state, Item item) { if (state == null) { <START> return UnDefType.NULL; <END> } if (item != null && !isAccepted(item, state)) { for (Class<? extends State> acceptedType : item.getAcceptedDataTypes()) { State convertedState = state.as(acceptedType); if (convertedState != null) { LoggerFactory.getLogger(ItemUtil.class).debug("Converting '{}' to '{}' for item '{}'", state.getClass().getSimpleName(), state, convertedState.getClass().getSimpleName(), convertedState, item.getName()); return convertedState; } } } return state; }</code><technical_language>I null in here. IMHO fix root of first. Still, valid fail-safe here</technical_language>

Target:
public static State convertToAcceptedState(State state, Item item) { if (state == null) { LOGGER.error("A conversion of null was requested", new NullPointerException("state should not be null")); return UnDefType.NULL; } if (item != null && !isAccepted(item, state)) { for (Class<? extends State> acceptedType : item.getAcceptedDataTypes()) { State convertedState = state.as(acceptedType); if (convertedState != null) { LOGGER.debug("Converting '{}' to '{}' for item '{}'", state.getClass().getSimpleName(), state, convertedState.getClass().getSimpleName(), convertedState, item.getName()); return convertedState; } } } return state; }
Source:
<code>public WsAgentHealthStateDto check(Machine machine) throws NotFoundException, ServerException, ForbiddenException, BadRequestException, UnauthorizedException, ConflictException { final Map<String, ? extends Server> servers = machine.getRuntime().getServers(); Server wsAgent = null; for (Server server : servers.values()) { if (WSAGENT_REFERENCE.equals(server.getRef())) { <START> wsAgent = server; <END> } } final WsAgentHealthStateDto agentHealthStateDto = newDto(WsAgentHealthStateDto.class); if (wsAgent == null) { return agentHealthStateDto.withCode(NOT_FOUND.getStatusCode()) .withReason("Workspace Agent not available if Dev machine are not RUNNING"); } try { final HttpJsonRequest pingRequest = createPingRequest(machine); final HttpJsonResponse response = pingRequest.request(); agentHealthStateDto.withCode(response.getResponseCode()) .withReason(response.asString()); } catch (IOException e) { agentHealthStateDto.withCode(SERVICE_UNAVAILABLE.getStatusCode()) .withReason(e.getMessage()); } return agentHealthStateDto; }</code><technical_language>stop iterations</technical_language>

Target:
public WsAgentHealthStateDto check(Machine machine) throws ServerException { Server wsAgent = getWsAgent(machine); final WsAgentHealthStateDto agentHealthStateDto = newDto(WsAgentHealthStateDto.class); if (wsAgent == null) { return agentHealthStateDto.withCode(NOT_FOUND.getStatusCode()) .withReason("Workspace Agent not available"); } try { final HttpJsonRequest pingRequest = createPingRequest(machine); final HttpJsonResponse response = pingRequest.request(); return agentHealthStateDto.withCode(response.getResponseCode()); } catch (ApiException | IOException e) { return agentHealthStateDto.withCode(SERVICE_UNAVAILABLE.getStatusCode()) .withReason(e.getMessage()); } }
Source:
<code>void doRestore() { final Context context = getContext(); ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.UI_ACTION.toString(), context.getString(R.string.analytics_action_button_press), context.getString(R.string.analytics_label_button_press_restore_preference)); try { Backup.restore(context); ObaRegionsTask task = new ObaRegionsTask(context, new ObaRegionsTask.Callback() { @Override public void onRegionTaskFinished(boolean currentRegionChanged) { <START> Toast.makeText(context, <END> context.getString(R.string.preferences_db_restored), Toast.LENGTH_LONG).show(); } }, true, true); task.setProgressDialogMessage(context.getString(R.string.preferences_restore_loading)); task.execute(); } catch (IOException e) { Toast.makeText(context, context.getString(R.string.preferences_db_restore_error, e.getMessage()), Toast.LENGTH_LONG).show(); } }</code><technical_language>In Toast example [here](<LINK_0>, getApplicationContext() - I a option Activity context destroyed. Also, instead of context.getString(R.string.preferences_db_restored), I pass in resource ID: R.string.preferences_db_restored Sorry, I missed this in review</technical_language>

Target:
void doRestore() { final Context context = Application.get().getApplicationContext(); ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.UI_ACTION.toString(), context.getString(R.string.analytics_action_button_press), context.getString(R.string.analytics_label_button_press_restore_preference)); try { Backup.restore(context); Context activityContext = getContext(); if (activityContext != null) { ObaRegionsTask task = new ObaRegionsTask(activityContext, new ObaRegionsTask.Callback() { @Override public void onRegionTaskFinished(boolean currentRegionChanged) { Toast.makeText(context, R.string.preferences_db_restored, Toast.LENGTH_LONG).show(); } }, true, true); task.setProgressDialogMessage(context.getString(R.string.preferences_restore_loading)); task.execute(); } } catch (IOException e) { Toast.makeText(context, context.getString(R.string.preferences_db_restore_error, e.getMessage()), Toast.LENGTH_LONG).show(); } }
Source:
<code>public synchronized static void hangupCall(Call call, int reasonCode, String reason) { if (logger.isDebugEnabled()) { logger.debug("Hanging up :" + call, new Throwable()); } HangupCallThread hangupCallThread = new HangupCallThread(call, false); hangupCallThread.reasonCode = reasonCode; hangupCallThread.reason = reason; <START> if (!healthy && reasonCode > 400) <END> { new Thread(hangupCallThread).start(); } else { submit(hangupCallThread); } }</code><technical_language>reasonCode > 400 check? In case healthy==false, suspect submit() fail exception</technical_language>

Target:
public synchronized static void hangupCall(Call call, int reasonCode, String reason) { if (logger.isDebugEnabled()) { logger.debug("Hanging up :" + call, new Throwable()); } HangupCallThread hangupCallThread = new HangupCallThread(call, false); hangupCallThread.reasonCode = reasonCode; hangupCallThread.reason = reason; if (!healthy) { new Thread(hangupCallThread).start(); } else { submit(hangupCallThread); } }
Source:
<code>private static String unquote(String text, char quoteChar) { if (!isQuoted(text, quoteChar)) return text; String search = emptyQuoted(quoteChar); int nbMatch = 0; int start = -2; do { start = text.indexOf(search, start + 2); if (start != -1 && start != text.length() - 2) ++nbMatch; } while (start != -1); <START> <END> int newLength = text.length() - nbMatch - 2; char[] result = new char[newLength]; int newIdx = 0; boolean firstFound = false; for (int i = 1; i < text.length() - 1; i++) { char c = text.charAt(i); if (c == quoteChar) { if (firstFound) { firstFound = false; } else { firstFound = true; result[newIdx++] = c; } } else { result[newIdx++] = c; firstFound = false; } } return new String(result); }</code><technical_language>fast exit if quote is remove surrounding quotes</technical_language>

Target:
private static String unquote(String text, char quoteChar) { if (!isQuoted(text, quoteChar)) return text; if (text.length() == 2) return ""; String search = emptyQuoted(quoteChar); int nbMatch = 0; int start = -1; do { start = text.indexOf(search, start + 2); if (start != -1 && start != text.length() - 2) ++nbMatch; } while (start != -1); if (nbMatch == 0) return text.substring(1, text.length() - 1); int newLength = text.length() - nbMatch - 2; char[] result = new char[newLength]; int newIdx = 0; boolean firstFound = false; for (int i = 1; i < text.length() - 1; i++) { char c = text.charAt(i); if (c == quoteChar) { if (firstFound) { firstFound = false; } else { firstFound = true; result[newIdx++] = c; } } else { result[newIdx++] = c; firstFound = false; } } return new String(result); }
Source:
<code>public Response createPair(Iterator<FileItem> formData) throws BadRequestException, ServerException, ConflictException { String service = null; String name = null; String privateKey = null; String publicKey = null; while (formData.hasNext()) { FileItem item = formData.next(); String fieldName = item.getFieldName(); switch (fieldName) { case "service": service = item.getString(); break; case "name": name = item.getString(); break; case "privateKey": privateKey = item.getString(); break; case "publicKey": publicKey = item.getString(); <START> break; <END> } } requiredNotNull(service, "Service name required"); requiredNotNull(name, "Name required"); if (privateKey == null && publicKey == null) { throw new BadRequestException("Key content was not provided."); } sshManager.createPair(getCurrentUserId(), new SshPairImpl(service, name, publicKey, privateKey)); return Response.ok("", MediaType.TEXT_HTML).build(); }</code><technical_language>add default: findbugs throw warning</technical_language>

Target:
public Response createPair(Iterator<FileItem> formData) throws BadRequestException, ServerException, ConflictException { String service = null; String name = null; String privateKey = null; String publicKey = null; while (formData.hasNext()) { FileItem item = formData.next(); String fieldName = item.getFieldName(); switch (fieldName) { case "service": service = item.getString(); break; case "name": name = item.getString(); break; case "privateKey": privateKey = item.getString(); break; case "publicKey": publicKey = item.getString(); break; default: } } requiredNotNull(service, "Service name required"); requiredNotNull(name, "Name required"); if (privateKey == null && publicKey == null) { throw new BadRequestException("Key content was not provided."); } sshManager.createPair(getCurrentUserId(), new SshPairImpl(service, name, publicKey, privateKey)); return Response.ok("", MediaType.TEXT_HTML).build(); }
Source:
<code>private boolean navigateBackToPeopleListFragment() { if (getFragmentManager().getBackStackEntryCount() > 0) { getFragmentManager().popBackStack(); FragmentManager fragmentManager = getFragmentManager(); <START> PersonDetailFragment personDetailFragment = (PersonDetailFragment) fragmentManager <END> .findFragmentByTag(KEY_PERSON_DETAIL_FRAGMENT); boolean shouldResetToolbarElevation = (personDetailFragment != null); ActionBar actionBar = getSupportActionBar(); if (shouldResetToolbarElevation && actionBar != null) { actionBar.setElevation(getResources().getDimension(R.dimen.appbar_elevation)); } return true; } return false; }</code><technical_language>a number of places in this activity findFragmentByTag is locate list detail fragment. I cleaner methods for instead, this: private PeopleListFragment getListFragment() { return (PeopleListFragment) getFragmentManager().findFragmentByTag(KEY_PEOPLE_LIST_FRAGMENT); } private PersonDetailFragment getDetailFragment() { return (PersonDetailFragment) getFragmentManager().findFragmentByTag(KEY_PERSON_DETAIL_FRAGMENT); }</technical_language>

Target:
private boolean navigateBackToPeopleListFragment() { FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.people); } PersonDetailFragment personDetailFragment = getDetailFragment(); if (personDetailFragment != null && personDetailFragment.isAdded()) { resetToolbarElevation(); } return true; } return false; }
Source:
<code>public void testPort8443() { String clientConfig = ResourceHelpers.resourceFilePath("oldClientConfig"); String[] command = { "--help", "--config", clientConfig }; Client.main(command); <START> Assert.assertTrue("Should have warned about port 8443", systemOutRule.getLog().contains("deprecated port 8443")); <END> }</code><technical_language>Please a constant in Client.java referenced (lowers chance of instant breakage if change message slightly, developer a reference test)</technical_language>

Target:
public void testPort8443() { String clientConfig = ResourceHelpers.resourceFilePath("oldClientConfig"); String[] command = { "--help", "--config", clientConfig }; Client.main(command); Assert.assertTrue("Should have warned about port 8443", systemErrRule.getLog().contains(DEPRECATED_PORT_MESSAGE)); }
Source:
<code>private InstructorResultsQuestionTable buildQuestionTableWithoutResponseRows( FeedbackQuestionAttributes question, List<FeedbackResponseAttributes> responses, <START> String additionalInfoId) { <END> return buildQuestionTableAndResponseRows( question, responses, additionalInfoId, null, false); }</code><technical_language>buildQuestionTableAndResponseRows() buildQuestionTableWithoutResponseRows() called a in additionalInfoId? called place each, pass in "" for variable</technical_language>

Target:
private InstructorFeedbackResultsQuestionTable buildQuestionTableWithoutResponseRows( FeedbackQuestionAttributes question, List<FeedbackResponseAttributes> responses, String additionalInfoId) { return buildQuestionTableAndResponseRows(question, responses, additionalInfoId, null, false); }
Source:
<code>private QueryIterator variableSubject(Binding binding, Node s, Node score, StrMatch match, ExecutionContext execCxt) { Var sVar = Var.alloc(s) ; Var scoreVar = (score==null) ? null : Var.alloc(score) ; List<TextHit> r = query(match.getQueryString(), match.getLimit(), execCxt) ; Function<TextHit,Binding> converter = new TextHitConverter(binding, sVar, scoreVar); <START> Iterator<Binding> bIter = new Map1Iterator<TextHit, Binding>(converter, r.iterator()); <END> QueryIterator qIter = new QueryIterPlainWrapper(bIter, execCxt); return qIter ; }</code><technical_language>is a library of iterator utilities: Iterator<Binding> bIter = Iter.map(r.iterator(), converter) ;</technical_language>

Target:
private QueryIterator variableSubject(Binding binding, Node s, Node score, StrMatch match, ExecutionContext execCxt) { Var sVar = Var.alloc(s) ; Var scoreVar = (score==null) ? null : Var.alloc(score) ; List<TextHit> r = query(match.getQueryString(), match.getLimit(), execCxt) ; Function<TextHit,Binding> converter = new TextHitConverter(binding, sVar, scoreVar); Iterator<Binding> bIter = Iter.map(r.iterator(), converter); QueryIterator qIter = new QueryIterPlainWrapper(bIter, execCxt); return qIter ; }
Source:
<code>public synchronized void foundError(URL url, String reason) { headlessResult.addElement( new HeadlessResult(url.getFile() + ":" + reason, -1, HeadlessResult.ERROR)); <START> LOG.error(url.toString() + " - " + reason); <END> }</code><technical_language>suggest warn instead, this is necessarily issue/bug</technical_language>

Target:
public synchronized void foundError(URL url, String reason) { headlessResult.addElement( new HeadlessResult(url.getFile() + ":" + reason, -1, HeadlessResult.ERROR)); LOG.warn(url.toString() + " - " + reason); }
Source:
<code>private Collection<V> valuesForPagingPredicate(Predicate predicate) { PagingPredicateImpl pagingPredicate = unwrapPagingPredicate(predicate); pagingPredicate.setIterationType(IterationType.VALUE); PagingPredicateHolder pagingPredicateHolder = PagingPredicateHolder.of(pagingPredicate, getSerializationService()); ClientMessage request = MapValuesWithPagingPredicateCodec.encodeRequest(name, pagingPredicateHolder); ClientMessage response = invokeWithPredicate(request, predicate); MapValuesWithPagingPredicateCodec.ResponseParameters resultParameters = MapValuesWithPagingPredicateCodec .decodeResponse(response); SerializationService serializationService = getSerializationService(); if (resultParameters.response.isEmpty()) { return (Collection<V>) new ResultSet(); } int size = resultParameters.response.size(); <START> List<Map.Entry> entries = new ArrayList<>(size); <END> for (int i = 0; i < size; i++) { K key = serializationService.toObject(resultParameters.response.get(i)); entries.add(new AbstractMap.SimpleImmutableEntry(key, null)); } pagingPredicate.setAnchorList(resultParameters.anchorDataList.asAnchorList(serializationService)); return (Set<V>) new ResultSet(entries, IterationType.VALUE); }</code><technical_language>Is InflatableSet ? ResultSet creating SimpleImmutableEntries unnecessarily</technical_language>

Target:
private Collection<V> valuesForPagingPredicate(Predicate predicate) { PagingPredicateImpl pagingPredicate = unwrapPagingPredicate(predicate); pagingPredicate.setIterationType(IterationType.VALUE); PagingPredicateHolder pagingPredicateHolder = PagingPredicateHolder.of(predicate, getSerializationService()); ClientMessage request = MapValuesWithPagingPredicateCodec.encodeRequest(name, pagingPredicateHolder); ClientMessage response = invokeWithPredicate(request, predicate); MapValuesWithPagingPredicateCodec.ResponseParameters resultParameters = MapValuesWithPagingPredicateCodec .decodeResponse(response); SerializationService serializationService = getSerializationService(); pagingPredicate.setAnchorList(resultParameters.anchorDataList.asAnchorList(serializationService)); return (Collection<V>) new UnmodifiableLazyList(resultParameters.response, serializationService); }
Source:
<code>public void onOpenReply(String jobId, RCDeviceListener.RCConnectivityStatus connectivityStatus, RCClient.ErrorCodes status, String text) { RCLogger.i(TAG, "onOpenReply(): id: " + jobId + ", connectivityStatus: " + connectivityStatus + ", status: " + status + ", text: " + text); cachedConnectivityStatus = connectivityStatus; if (isServiceAttached) { listener.onInitialized(this, connectivityStatus, status.ordinal(), text); <START> registerForPush(false); <END> } else { RCLogger.w(TAG, "RCDeviceListener event suppressed since Restcomm Client Service not attached: onInitialized(): " + RCClient.errorText(status)); } if (status == RCClient.ErrorCodes.SUCCESS){ state = DeviceState.READY; } else { release(); return; } }</code><technical_language>registerForPush() if isServiceAttached? if user taps home button onOpenReply() is called</technical_language>

Target:
public void onOpenReply(String jobId, RCDeviceListener.RCConnectivityStatus connectivityStatus, RCClient.ErrorCodes status, String text) { RCLogger.i(TAG, "onOpenReply(): id: " + jobId + ", connectivityStatus: " + connectivityStatus + ", status: " + status + ", text: " + text); cachedConnectivityStatus = connectivityStatus; if (isServiceAttached) { listener.onInitialized(this, connectivityStatus, status.ordinal(), text); } else { RCLogger.w(TAG, "RCDeviceListener event suppressed since Restcomm Client Service not attached: onInitialized(): " + RCClient.errorText(status)); } registerForPush(false); if (status == RCClient.ErrorCodes.SUCCESS){ state = DeviceState.READY; } else { release(); } }