auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private static void handlePartialDownloadWithMultipleRanges(InputStream is, <END> List<ByteRange> byteRanges, HttpServletResponse response) throws IOException { ByteRangeInputStream bris = StreamUtils.findSource(ByteRangeInputStream.class, is); long length = StreamUtils.getLength(bris); boolean anyByteRangeNotSatisfiable = byteRanges.stream() .anyMatch(byteRange -> byteRange.getOffset() >= length); if (anyByteRangeNotSatisfiable) { setRangeNotSatisfiable(response, length); } else { final String rangesContentType = response.getContentType(); prepareResponseBuilderForPartialRequestWithMultipleRanges(response); copyPartialMultipleRangeToResponse(is, response, byteRanges, rangesContentType); } }</code><technical_language>setting response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(partialLength)); copyToResponse set response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(totalBytes));</technical_language>

Target:
private static void handlePartialDownloadWithMultipleRanges(InputStream is, List<ByteRange> byteRanges, HttpServletResponse response) throws IOException { ByteRangeInputStream bris = StreamUtils.findSource(ByteRangeInputStream.class, is); long length = bris != null ? StreamUtils.getLength(bris) : 0; boolean anyByteRangeNotSatisfiable = byteRanges.stream() .anyMatch(byteRange -> byteRange.getOffset() >= length); if (anyByteRangeNotSatisfiable) { setRangeNotSatisfiable(response, length); } else { final String rangesContentType = response.getContentType(); prepareResponseBuilderForPartialRequestWithMultipleRanges(response); copyPartialMultipleRangeToResponse(is, response, byteRanges, rangesContentType); } }
Source:
<code>public static StreamsAddressResponse getLogAddressSpace(RuntimeLayout runtimeLayout) { Set<String> segmentsHeadNodes = getChainHeadFromAllSegments(runtimeLayout.getLayout()); long[] globalTail = {Address.NON_EXIST}; final Map<UUID, StreamAddressSpace> streamsAddressSpace = new HashMap<>(); segmentsHeadNodes.stream() <START> .map(node -> runtimeLayout <END> .getLogUnitClient(node) .getLogAddressSpace()) .map(CFUtils::getUninterruptibly) .forEach(resp -> { globalTail[0] = Long.max(resp.getLogTail(), globalTail[0]); resp.getAddressMap().forEach((k, v) -> streamsAddressSpace .merge(k, v, StreamAddressSpace::merge)); }); log.debug("getLogAddressSpace: nodes selected log tail stream addresses {}", segmentsHeadNodes, globalTail[0], streamsAddressSpace); return new StreamsAddressResponse(globalTail[0], streamsAddressSpace); }</code><technical_language>AtomicLong is cleaner array</technical_language>

Target:
public static StreamsAddressResponse getLogAddressSpace(RuntimeLayout runtimeLayout) { Set<String> segmentsHeadNodes = getChainHeadFromAllSegments(runtimeLayout.getLayout()); AtomicLong globalTail = new AtomicLong(Address.NON_EXIST); final Map<UUID, StreamAddressSpace> streamsAddressSpace = new HashMap<>(); List<CompletableFuture<StreamsAddressResponse>> cfs = segmentsHeadNodes.stream() .map(node -> runtimeLayout.getLogUnitClient(node).getLogAddressSpace()) .collect(Collectors.toList()); cfs.stream() .map(CFUtils::getUninterruptibly) .forEach( resp -> { epochCheck(resp.getEpoch(), runtimeLayout.getLayout().getEpoch()); globalTail.set(Long.max(resp.getLogTail(), globalTail.get())); resp.getAddressMap() .forEach((k, v) -> streamsAddressSpace.merge(k, v, StreamAddressSpace::merge)); }); log.debug( "getLogAddressSpace: nodes selected log tail stream addresses {}", segmentsHeadNodes, globalTail.get(), streamsAddressSpace); return new StreamsAddressResponse(globalTail.get(), streamsAddressSpace); }
Source:
<code>public TopNResultBuilder addEntry(DimensionAndMetricValueExtractor dimensionAndMetricValueExtractor) { String dimensionValue = dimensionAndMetricValueExtractor.getStringDimensionValue(dimSpec.getOutputName()); if (shouldAdd(dimensionValue)) { pQueue.add( new DimValHolder.Builder().withDimName(dimensionValue) .withMetricValues(dimensionAndMetricValueExtractor.getBaseObject()) .build() ); <START> if (this.pQueue.size() > this.threshold) { <END> pQueue.poll(); } } return this; }</code><technical_language>this</technical_language>

Target:
public TopNResultBuilder addEntry(DimensionAndMetricValueExtractor dimensionAndMetricValueExtractor) { String dimensionValue = dimensionAndMetricValueExtractor.getStringDimensionValue(dimSpec.getOutputName()); if (shouldAdd(dimensionValue)) { pQueue.add( new DimValHolder.Builder().withDimName(dimensionValue) .withMetricValues(dimensionAndMetricValueExtractor.getBaseObject()) .build() ); if (pQueue.size() > threshold) { pQueue.poll(); } } return this; }
Source:
<code>private InputStream open() throws IOException, CoreException, IncorrectObjectTypeException { if (blobId == null) return new ByteArrayInputStream(new byte[0]); try { WorkingTreeOptions workingTreeOptions = db.getConfig().get(WorkingTreeOptions.KEY); ObjectLoader loader = db.open(blobId, Constants.OBJ_BLOB); final InputStream objectInputStream = LfsFactory.getInstance() .applySmudgeFilter(db, loader, null ) <START> .openStream(); <END> switch (workingTreeOptions.getAutoCRLF()) { case INPUT: case FALSE: return objectInputStream; case TRUE: default: return new AutoCRLFInputStream(objectInputStream, true); } } catch (MissingObjectException notFound) { throw new CoreException(Activator.error(NLS.bind( CoreText.BlobStorage_blobNotFound, blobId.name(), path), notFound)); } }</code><technical_language>I earlier patch set, special-casing this for LFS is right go. mentioned in <LINK_0> I do user need a control this happen a per-file basis; for instance a .gitattribute</technical_language>

Target:
private InputStream open() throws IOException, CoreException, IncorrectObjectTypeException { if (blobId == null) return new ByteArrayInputStream(new byte[0]); try { WorkingTreeOptions workingTreeOptions = db.getConfig().get(WorkingTreeOptions.KEY); final InputStream objectInputStream = db.open(blobId, Constants.OBJ_BLOB).openStream(); switch (workingTreeOptions.getAutoCRLF()) { case INPUT: case FALSE: return objectInputStream; case TRUE: default: return new AutoCRLFInputStream(objectInputStream, true); } } catch (MissingObjectException notFound) { throw new CoreException(Activator.error(NLS.bind( CoreText.BlobStorage_blobNotFound, blobId.name(), path), notFound)); } }
Source:
<code>static void initializeAcl(final String zooKeeperConnectionString, final String zooKeeperClusterId, final String masterUser, final String masterPassword, final String agentUser, final String agentPassword) throws KeeperException { final ACLProvider aclProvider = heliosAclProvider( masterUser, digest(masterUser, masterPassword), agentUser, digest(agentUser, agentPassword)); final List<AuthInfo> authorization = Lists.newArrayList(new AuthInfo( "digest", String.format("%s:%s", masterUser, masterPassword).getBytes())); final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = new CuratorClientFactoryImpl().newClient( zooKeeperConnectionString, (int) TimeUnit.SECONDS.toMillis(60), (int) TimeUnit.SECONDS.toMillis(15), zooKeeperRetryPolicy, aclProvider, authorization); final ZooKeeperClient client = new DefaultZooKeeperClient(curator, zooKeeperClusterId); client.start(); <START> client.initializeAclRecursive("/", aclProvider); <END> }</code><technical_language>close client is done? try (ZooKeeperClient client = new DefaultZooKeeperClient(curator, zooKeeperClusterId)) { client.start(); client.initializeAclRecursive("/", aclProvider); }</technical_language>

Target:
static void initializeAcl(final String zooKeeperConnectionString, final String zooKeeperClusterId, final String masterUser, final String masterPassword, final String agentUser, final String agentPassword) throws KeeperException { final ACLProvider aclProvider = heliosAclProvider( masterUser, digest(masterUser, masterPassword), agentUser, digest(agentUser, agentPassword)); final List<AuthInfo> authorization = Lists.newArrayList(new AuthInfo( "digest", String.format("%s:%s", masterUser, masterPassword).getBytes())); final RetryPolicy zooKeeperRetryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework curator = new CuratorClientFactoryImpl().newClient( zooKeeperConnectionString, (int) TimeUnit.SECONDS.toMillis(60), (int) TimeUnit.SECONDS.toMillis(15), zooKeeperRetryPolicy, aclProvider, authorization); final ZooKeeperClient client = new DefaultZooKeeperClient(curator, zooKeeperClusterId); try { client.start(); initializeAclRecursive(client, "/", aclProvider); } finally { client.close(); } }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); HttpServletRequest req = (HttpServletRequest)request; <START> if (Collections.list(req.getHeaders("Prefer")).contains("persistent-auth")) { <END> HttpSession session = req.getSession(); try { int ttlValue = Integer.parseInt(req.getHeader("Session-TTL")) * SECONDS_IN_MINUTE; if (ttlValue >= MINIMAL_SESSION_TTL) { session = req.getSession(true); session.setMaxInactiveInterval(ttlValue); } } catch (NumberFormatException ex) { log.error("Session-TTL header was not passed. Not setting TTL value"); } } else if (FiltersHelper.isAuthenticated(req)) { InitialContext ctx = new InitialContext(); try { FiltersHelper.getBackend(ctx).runAction( VdcActionType.LogoutBySession, new VdcActionParametersBase( (String) req.getSession() .getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY) ) ); req.getSession().invalidate(); } finally { ctx.close(); } } } catch (Exception ex) { log.error(String.format("Error in REST-API session management. Message is: %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } } }</code><technical_language>FiltersHelper.Constants.HEADER_PREFER here</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest)request; HttpSession session = req.getSession(); boolean persistentAuth = Collections.list(req.getHeaders(FiltersHelper.Constants.HEADER_PREFER)).contains("persistent-auth"); if (persistentAuth) { try { int ttlValue = Integer.parseInt(req.getHeader("Session-TTL")) * SECONDS_IN_MINUTE; if (ttlValue >= MINIMAL_SESSION_TTL) { session.setMaxInactiveInterval(ttlValue); } session.setAttribute( SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY ) ); } catch (NumberFormatException ex) { log.error("Session-TTL header was not passed. Not setting TTL value"); } } chain.doFilter(request, response); if (!persistentAuth && FiltersHelper.isAuthenticated(req)) { InitialContext ctx = new InitialContext(); try { FiltersHelper.getBackend(ctx).runAction( VdcActionType.LogoutBySession, new VdcActionParametersBase( (String) req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY) ) ); req.getSession().invalidate(); } finally { ctx.close(); } } } catch (Exception ex) { log.error("Error in REST-API session management. ", ex); } }
Source:
<code>public List<VelocitySourceWriter> generateWriters(AnnotationExtractionRequest request) throws IOException { AnnotationExtractionResponse response = annotationExtractionService.extract(request); <START> return writerGenerator.generateWriters(request.getElement(), response); <END> }</code><technical_language>This is another of lines debugger cry. do this please? java List<VelocitySourceWriter> writerList = writerGenerator.generateWriters(request.getElement(),response); return writerList;</technical_language>

Target:
public List<VelocitySourceWriter> generateWriters(AnnotationExtractionRequest request) throws IOException { AnnotationExtractionResponse response = annotationExtractionService.extract(request); List<VelocitySourceWriter> writerList = writerGenerator.generateWriters(request.getElement(),response); return writerList; }
Source:
<code>boolean hasPermission(@NonNull final PackageInfo app, @NonNull final String permission) { if (app.requestedPermissions == null || app.requestedPermissionsFlags == null) { return false; } final int index = ArrayUtils.indexOf(app.requestedPermissions, permission); if (index < 0 || index <START> > app.requestedPermissionsFlags.length) <END> return false; return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0; }</code><technical_language>this >= instead of > ? if app.requestedPermissions.length == 4, index == 3, app.requesterPermissionsFlags.length == 3, code crash</technical_language>

Target:
boolean hasPermission(@NonNull final PackageInfo app, @NonNull final String permission) { if (app.requestedPermissions == null || app.requestedPermissionsFlags == null) { return false; } final int index = ArrayUtils.indexOf(app.requestedPermissions, permission); if (index < 0 || index >= app.requestedPermissionsFlags.length) return false; return (app.requestedPermissionsFlags[index] & REQUESTED_PERMISSION_GRANTED) != 0; }
Source:
<code>public SWTBotTreeItem expand() { waitForEnabled(); if (isExpanded()) { log.warn(MessageFormat.format("Tree item {0} is already expanded. Won''t expand it again.", this)); return this; } <START> asyncExec(new VoidResult() { <END> @Override public void run() { widget.setExpanded(true); } }); postExpandNotify(); return this; }</code><technical_language>a syncExec, I matters (the runnable surely execute postExpandNotify runnable, notify() a syncExec() end)</technical_language>

Target:
public SWTBotTreeItem expand() { waitForEnabled(); if (isExpanded()) { log.warn(MessageFormat.format("Tree item {0} is already expanded. Won''t expand it again.", this)); return this; } preExpandNotify(); syncExec(new VoidResult() { @Override public void run() { widget.setExpanded(true); } }); postExpandNotify(); return this; }
Source:
<code>private static void checkTree(final String filename, final DetailAST root) { DetailAST curNode = root; while (curNode != null) { <START> checkNode(curNode, curNode.getParent(), curNode.getPreviousSibling(), filename, root); <END> DetailAST toVisit = curNode.getFirstChild(); while (curNode != null && toVisit == null) { toVisit = curNode.getNextSibling(); if (toVisit == null) { curNode = curNode.getParent(); } } curNode = toVisit; } }</code><technical_language>Information method done DetailAST methods. point of this test is verify exact methods functioning properly. Example: Parameter prev is set curNode.getPreviousSibling() method, is verified assertEquals(badPrevMsg, prev, node.getPreviousSibling());. is is testing method itself. If change getPreviousSibling() return invalid value, test pass. Original test track of parent previous itself. This is why</technical_language>

Target:
private static void checkTree(final String filename, final DetailAST root) { DetailAST curNode = root; DetailAST parent = null; DetailAST prev = null; while (curNode != null) { checkNode(curNode, parent, prev, filename, root); DetailAST toVisit = curNode.getFirstChild(); if (toVisit != null) { parent = curNode; curNode = toVisit; prev = null; } else { while (curNode != null && toVisit == null) { toVisit = curNode.getNextSibling(); if (toVisit != null) { prev = curNode; curNode = toVisit; } else { curNode = curNode.getParent(); if (curNode != null) { parent = curNode.getParent(); } } } } } }
Source:
<code>private void validateSchema(final EventType eventType) throws InvalidEventTypeException { if (eventType.getSchema() != null) { try { final JSONObject schemaAsJson = new JSONObject(eventType.getSchema().getSchema()); if (hasReservedField(eventType, schemaAsJson, "metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); <START> } else { <END> SchemaLoader.load(schemaAsJson); } } catch (JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } } }</code><technical_language>needless else ;)</technical_language>

Target:
private void validateSchema(final EventType eventType) throws InvalidEventTypeException { if (eventType.getSchema() != null) { try { final JSONObject schemaAsJson = new JSONObject(eventType.getSchema().getSchema()); if (hasReservedField(eventType, schemaAsJson, "metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } SchemaLoader.load(schemaAsJson); } catch (JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } } }
Source:
<code>public AbstractApplicationSentListingMessage(String rawMessage) throws Exception { super(rawMessage); pages = new ArrayList<>(); populatePages(); populateApplicationIdentifierKey(); <START> if (LOG.isLoggable(Level.FINE)) <END> LOG.fine("got: " + this); }</code><technical_language>Please wrap this simple if {}</technical_language>

Target:
public AbstractApplicationSentListingMessage(String rawMessage) throws Exception { super(rawMessage); pages = new ArrayList<>(); populatePages(); populateApplicationIdentifierKey(); if (log.isLoggable(Level.FINE)) { log.fine("ApplicationSentListingMessage received: " + this); } }
Source:
<code>private static boolean checkSmartCardCompatibility(PGPSecretKey key, OperationLog log, int indent) { PGPPublicKey publicKey = key.getPublicKey(); int algorithm = publicKey.getAlgorithm(); if (algorithm != PublicKeyAlgorithmTags.RSA_ENCRYPT && algorithm != PublicKeyAlgorithmTags.RSA_SIGN && algorithm != PublicKeyAlgorithmTags.RSA_GENERAL) { log.add(OperationResult.LogType.MSG_K2C_ERROR_BAD_ALGO, indent + 1); <START> return true; <END> } int keySize = publicKey.getBitStrength(); if (keySize != 2048) { log.add(OperationResult.LogType.MSG_K2C_ERROR_BAD_SIZE, indent + 1); return false; } if (isDivertToCard(key) || isDummy(key)) { log.add(OperationResult.LogType.MSG_K2C_ERROR_BAD_STRIPPED, indent + 1); return false; } return true; }</code><technical_language>true</technical_language>

Target:
private static boolean checkSmartCardCompatibility(PGPSecretKey key, OperationLog log, int indent) { PGPPublicKey publicKey = key.getPublicKey(); int algorithm = publicKey.getAlgorithm(); if (algorithm != PublicKeyAlgorithmTags.RSA_ENCRYPT && algorithm != PublicKeyAlgorithmTags.RSA_SIGN && algorithm != PublicKeyAlgorithmTags.RSA_GENERAL) { log.add(LogType.MSG_MF_ERROR_BAD_NFC_ALGO, indent + 1); return false; } int keySize = publicKey.getBitStrength(); if (keySize != 2048) { log.add(LogType.MSG_MF_ERROR_BAD_NFC_SIZE, indent + 1); return false; } if (isDivertToCard(key) || isDummy(key)) { log.add(LogType.MSG_MF_ERROR_BAD_NFC_STRIPPED, indent + 1); return false; } return true; }
Source:
<code><START> private Date getPatientBirthdateAdjustedIfEstimated(Patient patient) { <END> Date birthday = patient.getBirthdate(); if (patient.getBirthdateEstimated()) { Calendar cal = Calendar.getInstance(); cal.setTime(birthday); cal.add(Calendar.YEAR, new Double(Math.ceil(patient.getAge() * ESTIMATED_BIRTHDATE_ERROR_MARGIN)).intValue()); birthday = cal.getTime(); } return birthday; }</code><technical_language>please move this private method method improve readability, simply scan code top bottom. validateVisitStartedBeforePatientBirthdate -> getPatientBirthdateAdjustedIfEstimated</technical_language>

Target:
private Date getPatientBirthdateAdjustedIfEstimated(Patient patient) { Date birthday = patient.getBirthdate(); if (patient.getBirthdateEstimated()) { Calendar cal = Calendar.getInstance(); cal.setTime(birthday); cal.add(Calendar.YEAR, calculateGracePeriodInYears(patient.getAge())); birthday = cal.getTime(); } return birthday; }
Source:
<code>public void bundleChanged(BundleEvent bundleEvent) { final String symbolicName = bundleEvent.getBundle().getSymbolicName(); if (bundleEvent.getType() == BundleEvent.STARTED) { LOGGER.debug("Bundle started", symbolicName); platformStatus.addOSGiStartedBundle(symbolicName); checkOsgiBundle(bundleEvent.getBundle()); } else if (bundleEvent.getType() == BundleEvent.STOPPED) { <START> LOGGER.trace("Bundle stopped", symbolicName); <END> platformStatus.removeOSGiStartedBundle(symbolicName); } }</code><technical_language>handle this event well? handling errors</technical_language>

Target:
public void bundleChanged(BundleEvent bundleEvent) { final String symbolicName = bundleEvent.getBundle().getSymbolicName(); if (bundleEvent.getType() == BundleEvent.STARTED) { LOGGER.debug("Bundle started", symbolicName); platformStatus.addOSGiStartedBundle(symbolicName); checkBundleOsgiStarted(bundleEvent.getBundle()); } else if (bundleEvent.getType() == BundleEvent.STOPPED) { LOGGER.trace("Bundle stopped", symbolicName); platformStatus.removeOSGiStartedBundle(symbolicName); checkBundleOsgiStarted(bundleEvent.getBundle()); checkBundleBlueprintStarted(bundleEvent.getBundle()); } }
Source:
<code>private void validateTargetedSequencing(LibraryDesignCode libraryDesignCode, Collection<LibraryDilution> libraryDilutions, List<ValidationError> errors) throws IOException { libraryDesignCode = libraryDesignCodeService.get(libraryDesignCode.getId()); if (libraryDesignCode.isTargetedSequencingRequired()) { List<String> badDilutions = libraryDilutions.stream().filter(dilution -> dilution.getTargetedSequencing() == null) .map(LibraryDilution::getName).collect(Collectors.toList()); if (!badDilutions.isEmpty()) { <START> errors.add(new ValidationError("libraryDesignCodeId", <END> String.format("Library design code %s requires targeted sequencing, but the following dilutions have none: %s", libraryDesignCode.getCode(), String.join(", ", badDilutions)))); } } }</code><technical_language>Property "libraryDesignCode" "libraryDesignCodeId"</technical_language>

Target:
private void validateTargetedSequencing(LibraryDesignCode libraryDesignCode, Collection<LibraryDilution> libraryDilutions, List<ValidationError> errors) throws IOException { if (libraryDilutions == null || libraryDilutions.isEmpty()) { return; } libraryDesignCode = libraryDesignCodeService.get(libraryDesignCode.getId()); if (libraryDesignCode.isTargetedSequencingRequired()) { List<String> badDilutions = libraryDilutions.stream().filter(dilution -> dilution.getTargetedSequencing() == null) .map(LibraryDilution::getName).collect(Collectors.toList()); if (!badDilutions.isEmpty()) { errors.add(new ValidationError("libraryDesignCode", String.format("Targeted sequencing must be assigned to the affected dilutions (%s) to use this library design code: %s", String.join(", ", badDilutions), libraryDesignCode.getCode()))); } } }
Source:
<code>private ExecutionResult(List<HystrixEventType> events, int executionTime, Exception e) { this.events = events; this.executionTime = executionTime; if (executionTime >= 0 ) { <START> this.commandRunStartTime = System.currentTimeMillis() - this.executionTime; <END> } else { this.commandRunStartTime = -1; } this.exception = e; }</code><technical_language>Consider System.nanoTime() for execution timing</technical_language>

Target:
private ExecutionResult(List<HystrixEventType> events, int executionTime, Exception e) { this.events = events; this.executionTime = executionTime; if (executionTime >= 0 ) { this.commandRunStartTimeNano = System.nanoTime() - this.executionTime*1000*1000; } else { this.commandRunStartTimeNano = -1; } this.exception = e; }
Source:
<code><START> public void removeProjectile(Projectile projectile) { <END> if (projectile.getShooter() instanceof Player) { Player player = (Player) projectile.getShooter(); if (projectiles.containsKey(player)) { projectiles.get(player).remove(projectile); } } }</code><technical_language>add method. _shouldn't_ necessary check if player is in map, is a possibility of bugs server result in projectiles dying appeared in a ProjectileLaunchEvent, safe sorry. java Set<Projectile> launched = projectiles.get(player); if (launched != null) { launched.remove(projectile); }</technical_language>

Target:
public void removeProjectile(Projectile projectile) { if (projectile.getShooter() instanceof Player) { Player player = (Player) projectile.getShooter(); Set<Projectile> launched = projectiles.get(player); if(launched == null) return; launched.remove(projectile); } }
Source:
<code>public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { return new JsonResult("No student with given email in given course.", HttpStatus.SC_NOT_FOUND); } InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, logic.getCourse(courseId), student.section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean hasSection = false; try { hasSection = logic.hasIndicatedSections(courseId); } catch (EntityDoesNotExistException e) { return new JsonResult("No course with given id.", HttpStatus.SC_NOT_FOUND); } StudentProfileAttributes studentProfile = logic.getStudentProfile(student.googleId); student.googleId = null; student.key = null; <START> studentProfile.googleId = null; <END> studentProfile.modifiedDate = null; StudentInfo output = new StudentInfo(student, studentProfile, hasSection); return new JsonResult(output); }</code><technical_language>testing, I NPE studentProfile is null. This needs a non-null check. needs a test prevent happening again</technical_language>

Target:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { return new JsonResult("No student with given email in given course.", HttpStatus.SC_NOT_FOUND); } InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, userInfo.id); gateKeeper.verifyAccessible(instructor, logic.getCourse(courseId), student.section, Const.ParamsNames.INSTRUCTOR_PERMISSION_VIEW_STUDENT_IN_SECTIONS); boolean hasSection = false; try { hasSection = logic.hasIndicatedSections(courseId); } catch (EntityDoesNotExistException e) { return new JsonResult("No course with given id.", HttpStatus.SC_NOT_FOUND); } StudentProfileAttributes studentProfile = logic.getStudentProfile(student.googleId); student.googleId = null; student.key = null; if (studentProfile != null) { studentProfile.googleId = null; studentProfile.modifiedDate = null; } StudentInfo output = new StudentInfo(student, studentProfile, hasSection); return new JsonResult(output); }
Source:
<code>protected ISourceContainer[] createSourceContainers() throws CoreException { List<ISourceContainer> result = new LinkedList<ISourceContainer>(); ILaunchConfiguration config = getLaunchConfiguration(); try { Project project = LaunchUtils.getBndProject(config); if (project != null) { Collection<Container> runbundles = project.getRunbundles(); for (Container runbundle : runbundles) { if (runbundle.getType() == TYPE.PROJECT) { String targetProjName = runbundle.getProject().getName(); IProject targetProj = ResourcesPlugin.getWorkspace().getRoot().getProject(targetProjName); if (targetProj != null) { IJavaProject targetJavaProj = JavaCore.create(targetProj); result.add(new JavaProjectSourceContainer(targetJavaProj)); } } else if (runbundle.getType() == TYPE.REPO) { <START> ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(runbundle.getFile().toString(), false); <END> result.add(container); } } } } catch (Exception e) { logger.logError("Error querying bnd dependency source containers.", e); } return result.toArray(new ISourceContainer[0]); }</code><technical_language>I if IPath bundlePath IFile bundleFile is null means a workspace archive ArchiveSourceContainer before. if in workspace fallback ExternalArchiveContainer</technical_language>

Target:
protected ISourceContainer[] createSourceContainers() throws CoreException { List<ISourceContainer> result = new LinkedList<ISourceContainer>(); ILaunchConfiguration config = getLaunchConfiguration(); try { Project project = LaunchUtils.getBndProject(config); if (project != null) { Collection<Container> runbundles = project.getRunbundles(); for (Container runbundle : runbundles) { if (runbundle.getType() == TYPE.PROJECT) { String targetProjName = runbundle.getProject().getName(); IProject targetProj = ResourcesPlugin.getWorkspace().getRoot().getProject(targetProjName); if (targetProj != null) { IJavaProject targetJavaProj = JavaCore.create(targetProj); result.add(new JavaProjectSourceContainer(targetJavaProj)); } } else if (runbundle.getType() == TYPE.REPO) { IPath bundlePath = Central.toPath(runbundle.getFile()); IFile bundleFile = null; if (bundlePath != null) { bundleFile = ResourcesPlugin.getWorkspace().getRoot().getFile(bundlePath); } if (bundleFile != null) { ArchiveSourceContainer tempArchiveCont = new ArchiveSourceContainer(bundleFile, false); result.add(tempArchiveCont); } else { ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(runbundle.getFile().toString(), false); result.add(container); } } } } } catch (Exception e) { logger.logError("Error querying bnd dependency source containers.", e); } return result.toArray(new ISourceContainer[0]); }
Source:
<code>public void goToDroneLocation() { super.goToDroneLocation(); <START> Drone drone = ((DroidPlannerApp) getActivity().getApplication()).getDrone(); <END> if(!drone.getGps().isPositionValid()) return; final int pressCount = mAppPrefs.prefs.getInt(PREF_DRONE_LOCATION_FIRST_PRESS, DEFAULT_DRONE_LOCATION_FIRST_PRESS); if (pressCount < MAX_TOASTS_FOR_LOCATION_PRESS) { Toast.makeText(context, R.string.drone_autopan_long_press, Toast.LENGTH_LONG) .show(); mAppPrefs.prefs.edit().putInt(PREF_DRONE_LOCATION_FIRST_PRESS, pressCount + 1).apply(); } }</code><technical_language>@metalnow FlightMapFragment's parent a protected Drone instance, instead(i.e: this.drone)</technical_language>

Target:
public void goToDroneLocation() { super.goToDroneLocation(); if(!this.drone.getGps().isPositionValid()) return; final int pressCount = mAppPrefs.prefs.getInt(PREF_DRONE_LOCATION_FIRST_PRESS, DEFAULT_DRONE_LOCATION_FIRST_PRESS); if (pressCount < MAX_TOASTS_FOR_LOCATION_PRESS) { Toast.makeText(context, R.string.drone_autopan_long_press, Toast.LENGTH_LONG) .show(); mAppPrefs.prefs.edit().putInt(PREF_DRONE_LOCATION_FIRST_PRESS, pressCount + 1).apply(); } }
Source:
<code>public static String getJsonStringforMap(Map<String, String> map) { <START> if (map == null) { <END> map = new HashMap(); } JSONObject pathPartMap = new JSONObject(map); return pathPartMap.toString(); }</code><technical_language>Nit: is a good practice reassign input parameters I change this following: Map<String, String> mapToUse = (map == null) ? emptyMap() : map; JSONObject pathPartMap = new JSONObject(mapToUse);</technical_language>

Target:
public static String getJsonStringforMap(Map<String, String> map) { Map<String, String> mapToUse = (map == null) ? Collections.emptyMap() : map; JSONObject pathPartMap = new JSONObject(mapToUse); return pathPartMap.toString(); }
Source:
<code>public static ErraiService getService() { <START> return service != null ? service : initProxy; <END> }</code><technical_language>this change, sense return reference stopped service, part of API supported re-initializing ErraiService. if allow that, checking isInitialized() here, instead of service != null</technical_language>

Target:
public static ErraiService getService() { return isActive() ? service : proxy; }
Source:
<code>protected Object doWork() { Utils.regularReadableUserFile(ponFile); try (final HDF5File ponReader = new HDF5File(ponFile)) { final PoN pon = new HDF5PoN(ponReader); if (pon.getVersion() < HDF5PoNCreator.CURRENT_PON_VERSION) { logger.warn("The version of the specified PoN (" + pon.getVersion() + ") is older than the latest version " + "(" + HDF5PoNCreator.CURRENT_PON_VERSION + ")."); } <START> final TargetCollection<Target> exonCollection = readTargetCollection(targetFile); <END> final ReadCountCollection readCountCollection = readInputReadCounts(readCountsFile, exonCollection); final TangentNormalizationResult tangentNormalizationResult = TangentNormalizer.tangentNormalizePcov(pon, readCountCollection); outputTangentNormalizationResult(tangentNormalizationResult); return "SUCCESS"; } }</code><technical_language>rename exonCollection more appropriate, targetCollection</technical_language>

Target:
protected Object doWork() { Utils.regularReadableUserFile(ponFile); try (final HDF5File ponReader = new HDF5File(ponFile)) { final PoN pon = new HDF5PoN(ponReader); if (pon.getVersion() < HDF5PoNCreator.CURRENT_PON_VERSION) { logger.warn("The version of the specified PoN (" + pon.getVersion() + ") is older than the latest version " + "(" + HDF5PoNCreator.CURRENT_PON_VERSION + ")."); } final TargetCollection<Target> targetCollection = readTargetCollection(targetFile); final ReadCountCollection readCountCollection = readInputReadCounts(readCountsFile, targetCollection); final TangentNormalizationResult tangentNormalizationResult = TangentNormalizer.tangentNormalizePcov(pon, readCountCollection); outputTangentNormalizationResult(tangentNormalizationResult); return "SUCCESS"; } }
Source:
<code>public FilterBuilder withAlternates(String alternate) { if (alternate != null) { <START> filters.add(new VariantRepositoryAlternateFilter(new ArrayList<>(Arrays.asList(alternate)))); <END> } return this; }</code><technical_language>suggestion filters.add(new VariantRepositoryAlternateFilter(Collections.singletonList(alternate)));</technical_language>

Target:
public FilterBuilder withAlternates(String alternate) { if (alternate != null) { filters.add(new VariantRepositoryAlternateFilter(Collections.singletonList(alternate))); } return this; }
Source:
<code>void afterNamesPerGroupChanged() { namesPerGroupInput = namesPerGroup.getText().toString().trim(); <START> boolean isInputValid = isInputValid(); <END> if (namesPerGroup.isFocused() && isInputValid && autocomplete.isChecked()) { numGroups.setText(getMatchingNumber(namesPerGroupInput)); } dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isInputValid); maybeShowUnevenGroupsWarning(); }</code><technical_language>compute this autocomplete potentially happens? if 1 input is empty, this evaluate false, autocomplete fill in other input (making valid). this calculated autocomplete change, positive button turned off</technical_language>

Target:
void afterNamesPerGroupChanged() { String namesPerGroupInput = namesPerGroup.getText().toString().trim(); boolean isInputValid = isInputValid(namesPerGroupInput); if (namesPerGroup.isFocused() && isInputValid && autocomplete.isChecked()) { numGroups.setText(getMatchingNumber(namesPerGroupInput)); } dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isInputValid); maybeShowUnevenGroupsWarning(); }
Source:
<code>public void testIllegalState() { String originalId = "064c292e02db027c22g"; Span span = new Span(); span.setAnnotations(Arrays.asList()); span.setId(originalId); span.setAnnotations(annotations()); String uniqueID = SpanUniqueIdGenerator.toUnique(span); span.setId(uniqueID); try { <START> SpanUniqueIdGenerator.toUnique(span); <END> Assert.fail(); } catch (IllegalStateException ex) { } }</code><technical_language>In @Test, @Test(expected=IllegalStateException.class) _not_ do try/catch method. This is cleaner more :)</technical_language>

Target:
public void testIllegalState() { String originalId = "064c292e02db027c22g"; Span span = new Span(); span.setAnnotations(Arrays.asList()); span.setId(originalId); span.setAnnotations(annotations()); String uniqueID = SpanUniqueIdGenerator.toUnique(span); span.setId(uniqueID); SpanUniqueIdGenerator.toUnique(span); }
Source:
<code><START> public static SingleThreadEventLoop.IoHandlerFactory newFactory(final int maxEvents, <END> final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new SingleThreadEventLoop.IoHandlerFactory() { @Override public SingleThreadEventLoop.IoHandler newHandler() { return new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } }; }</code><technical_language>here, possibly unnecessarily final</technical_language>

Target:
public static IoHandlerFactory newFactory(final int maxEvents, final SelectStrategyFactory selectStrategyFactory) { ObjectUtil.checkPositiveOrZero(maxEvents, "maxEvents"); ObjectUtil.checkNotNull(selectStrategyFactory, "selectStrategyFactory"); return new IoHandlerFactory() { @Override public IoHandler newHandler() { return new EpollHandler(maxEvents, selectStrategyFactory.newSelectStrategy()); } }; }
Source:
<code>public static void main(final String[] args) throws Exception { String queryClassname = args[0]; String startWorkersScript = args[1]; System.out.println("Begin start master"); Server server = startMaster(); System.out.println("End start master"); System.out.println("Begin start workers"); startWorkers(startWorkersScript); System.out.println("End start workers"); MyriaConfiguration config = MyriaConfiguration.loadWithDefaultValues(FilenameUtils.concat(masterHome, MyriaConstants.DEPLOYMENT_CONF_FILE)); int[] allWorkers = new int[config.getWorkerIds().size()]; int idx = 0; <START> for (String id : config.getWorkerIds()) { <END> allWorkers[idx++] = Integer.parseInt(id); } QueryPlanGenerator qpg = (QueryPlanGenerator) (Class.forName(queryClassname).newInstance()); final Map<Integer, RootOperator[]> workerPlans = qpg.getWorkerPlan(allWorkers); final LinkedBlockingQueue<TupleBatch> resultStore = new LinkedBlockingQueue<TupleBatch>(); final RootOperator masterPlan = qpg.getMasterPlan(allWorkers, resultStore); long start = System.nanoTime(); QueryFuture qf = server.submitQueryPlan(masterPlan, workerPlans); TupleBatch tb = null; int numResult = 0; while (!qf.isDone() || !resultStore.isEmpty()) { tb = resultStore.poll(100, TimeUnit.MILLISECONDS); System.out.print(tb); numResult += tb.numTuples(); } System.out.println("Time spent: " + DateTimeUtils.nanoElapseToHumanReadable(System.nanoTime() - start)); System.out.println("Total " + numResult + " tuples."); qf.get(); server.shutdown(); }</code><technical_language>getWorkerIds() return a list of ints</technical_language>

Target:
public static void main(final String[] args) throws Exception { String queryClassname = args[0]; String startWorkersScript = args[1]; System.out.println("Begin start master"); Server server = startMaster(); System.out.println("End start master"); System.out.println("Begin start workers"); startWorkers(startWorkersScript); System.out.println("End start workers"); MyriaConfiguration config = MyriaConfiguration.loadWithDefaultValues(FilenameUtils.concat(workingDir, MyriaConstants.DEPLOYMENT_CONF_FILE)); int[] allWorkers = Ints.toArray(config.getWorkerIds()); QueryPlanGenerator qpg = (QueryPlanGenerator) (Class.forName(queryClassname).newInstance()); final Map<Integer, RootOperator[]> workerPlans = qpg.getWorkerPlan(allWorkers); final LinkedBlockingQueue<TupleBatch> resultStore = new LinkedBlockingQueue<TupleBatch>(); final RootOperator masterPlan = qpg.getMasterPlan(allWorkers, resultStore); long start = System.nanoTime(); QueryFuture qf = server.submitQueryPlan(masterPlan, workerPlans); TupleBatch tb = null; int numResult = 0; while (!qf.isDone() || !resultStore.isEmpty()) { tb = resultStore.poll(100, TimeUnit.MILLISECONDS); System.out.print(tb); numResult += tb.numTuples(); } System.out.println("Time spent: " + DateTimeUtils.nanoElapseToHumanReadable(System.nanoTime() - start)); System.out.println("Total " + numResult + " tuples."); qf.get(); server.shutdown(); }
Source:
<code>public static Guid SelectStorageDomain(VmTemplate vmTemplate) { Guid selectedDomainId = Guid.Empty; if (vmTemplate != null && vmTemplate.getDiskMap().size() > 0) { int size = -1; DiskImage disk = DbFacade.getInstance().getDiskImageDAO().getSnapshotById( LinqUtils.firstOrNull(vmTemplate.getDiskMap().values(), new All<DiskImageTemplate>()) <START> .getId()); <END> List<Guid> domainsList = (List<Guid>) Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.GetImageDomainsList, new GetImageDomainsListVDSCommandParameters(vmTemplate.getstorage_pool_id().getValue(), disk.getimage_group_id().getValue())).getReturnValue(); for (Guid domainId : domainsList) { storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(domainId, vmTemplate.getstorage_pool_id()); if (domain != null && domain.getstorage_domain_type() != StorageDomainType.ImportExport && domain.getstatus() == StorageDomainStatus.Active && StorageDomainSpaceChecker.isBelowThresholds(domain)) { if (domain.getavailable_disk_size() != null && domain.getavailable_disk_size() > size) { selectedDomainId = domainId; size = domain.getavailable_disk_size(); } } } } return selectedDomainId; }</code><technical_language>i guess call this template disk, this code assume disks domain</technical_language>

Target:
public static Guid SelectStorageDomain(VmTemplate vmTemplate) { Guid selectedDomainId = Guid.Empty; if (vmTemplate != null && vmTemplate.getDiskMap().size() > 0) { int size = -1; DiskImage disk = DbFacade.getInstance().getDiskImageDAO().getSnapshotById( LinqUtils.firstOrNull(vmTemplate.getDiskMap().values(), new All<DiskImage>()) .getId()); List<Guid> domainsList = (List<Guid>) Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.GetImageDomainsList, new GetImageDomainsListVDSCommandParameters(vmTemplate.getstorage_pool_id().getValue(), disk.getimage_group_id().getValue())).getReturnValue(); for (Guid domainId : domainsList) { storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(domainId, vmTemplate.getstorage_pool_id()); if (domain != null && domain.getstorage_domain_type() != StorageDomainType.ImportExport && domain.getstatus() == StorageDomainStatus.Active && StorageDomainSpaceChecker.isBelowThresholds(domain)) { if (domain.getavailable_disk_size() != null && domain.getavailable_disk_size() > size) { selectedDomainId = domainId; size = domain.getavailable_disk_size(); } } } } return selectedDomainId; }
Source:
<code>protected final void withTopologyService(String host, int port, Consumer<TopologyService> consumer) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), OP_TIMEOUT, <START> OP_TIMEOUT, <END> null)) { consumer.accept(diagnosticService.getProxy(TopologyService.class)); } }</code><technical_language>overridable getOperationTimeout() method instead</technical_language>

Target:
protected final void withTopologyService(String host, int port, Consumer<TopologyService> consumer) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null)) { consumer.accept(diagnosticService.getProxy(TopologyService.class)); } }
Source:
<code>public static <T> Call<T> response(T successValue) { <START> return response(Response.fakeSuccess(successValue)); <END> }</code><technical_language>Do need word fake here? imagining other cases useful</technical_language>

Target:
public static <T> Call<T> response(T successValue) { return response(Response.success(successValue)); }
Source:
<code>static void deleteTableUsageSnapshotsForNamespace(Connection connection, String namespace) throws IOException { Scan s = new Scan(); <START> s.setRowPrefixFilter(Bytes.toBytes("t." + namespace)); <END> s.addColumn(QUOTA_FAMILY_USAGE,QUOTA_QUALIFIER_POLICY); s.addColumn(QUOTA_FAMILY_INFO,QUOTA_QUALIFIER_SETTINGS); try (Table quotaTable = connection.getTable(QUOTA_TABLE_NAME); ResultScanner rs = quotaTable.getScanner(s)) { for (Result r : rs) { byte[] data = r.getValue(QUOTA_FAMILY_INFO, QUOTA_QUALIFIER_SETTINGS); if (data == null) { Delete delete = new Delete(r.getRow()); delete.addColumns(QUOTA_FAMILY_USAGE,QUOTA_QUALIFIER_POLICY); quotaTable.delete(delete); } } } }</code><technical_language>need namespace delimiter end of prefix filter, over-match e.g. deleting usage for namespace 'foo' end matching deleting for namespace 'foobar'. Making 't.foo:' good enough</technical_language>

Target:
static void deleteTableUsageSnapshotsForNamespace(Connection connection, String namespace) throws IOException { Scan s = new Scan(); s.setRowPrefixFilter(Bytes.add(QUOTA_TABLE_ROW_KEY_PREFIX, Bytes.toBytes(namespace + TableName.NAMESPACE_DELIM))); s.addColumn(QUOTA_FAMILY_USAGE,QUOTA_QUALIFIER_POLICY); s.addColumn(QUOTA_FAMILY_INFO,QUOTA_QUALIFIER_SETTINGS); try (Table quotaTable = connection.getTable(QUOTA_TABLE_NAME); ResultScanner rs = quotaTable.getScanner(s)) { for (Result r : rs) { byte[] data = r.getValue(QUOTA_FAMILY_INFO, QUOTA_QUALIFIER_SETTINGS); if (data == null) { Delete delete = new Delete(r.getRow()); delete.addColumns(QUOTA_FAMILY_USAGE,QUOTA_QUALIFIER_POLICY); quotaTable.delete(delete); } } } }
Source:
<code>private JobPriority getJobPriority(CommandLine cmdLine) { String jobPriorityOption = cmdLine.getOptionValue(JOB_PRIORITY_OPTION.getOpt()); if (jobPriorityOption == null) { return JobPriority.DEFAULT; } switch (jobPriorityOption) { case "0" : return JobPriority.VERY_HIGH; case "1" : return JobPriority.HIGH; case "2" : return JobPriority.NORMAL; case "3" : return JobPriority.LOW; case "4" : return JobPriority.VERY_LOW; <START> case "5" : return JobPriority.DEFAULT; <END> default: return JobPriority.UNDEFINED_PRIORITY; } }</code><technical_language>is JobPriority.DEFAULT level? this default case</technical_language>

Target:
private JobPriority getJobPriority(CommandLine cmdLine) { String jobPriorityOption = cmdLine.getOptionValue(JOB_PRIORITY_OPTION.getOpt()); if (jobPriorityOption == null) { return JobPriority.NORMAL; } switch (jobPriorityOption) { case "0" : return JobPriority.VERY_HIGH; case "1" : return JobPriority.HIGH; case "2" : return JobPriority.NORMAL; case "3" : return JobPriority.LOW; case "4" : return JobPriority.VERY_LOW; default: return JobPriority.NORMAL; } }
Source:
<code>protected Locale getLocale() { <START> return Locale.US; <END> }</code><technical_language>This / Locale.ROOT yeah</technical_language>

Target:
protected Locale getLocale() { return Locale.ROOT; }