auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static PublicJobState mapState(JobState state) { if (state == null) { return null; } PublicJobState publicJobState; switch (state) { case FINISHED: publicJobState = PublicJobState.FINISHED; break; case CREATED: publicJobState = PublicJobState.CREATED; break; case QUEUED: case RUNNING: case SCHEDULED: case WAITING: publicJobState = PublicJobState.RUNNING; break; case ABORTED: case CANCELED: case FAILED: <START> case FAILED_WITH_RETRY: <END> default: publicJobState = PublicJobState.FAILED; break; } return publicJobState; }</code><technical_language>torn this one. I a temporary "FAILED" output useful, kind of "RUNNING" get picked breaks internally</technical_language>

Target:
public static PublicJobState mapState(JobState state) { if (state == null) { return null; } PublicJobState publicJobState; switch (state) { case FINISHED: publicJobState = PublicJobState.FINISHED; break; case CREATED: case QUEUED: publicJobState = PublicJobState.CREATED; break; case CANCELED: publicJobState = PublicJobState.CANCELED; break; case FAILED_WITH_RETRY: case RUNNING: case SCHEDULED: case WAITING: publicJobState = PublicJobState.RUNNING; break; case ABORTED: case FAILED: default: publicJobState = PublicJobState.FAILED; break; } return publicJobState; }
Source:
<code>public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newLinkedList(); Object item = entry.getDocument(); try { Datasift datasift = mapper.convertValue(item, Datasift.class); result.add(this.converter.convert(datasift)); } catch (Exception e) { <START> e.printStackTrace(); <END> } return result; }</code><technical_language>This output a Logger</technical_language>

Target:
public List<StreamsDatum> process(StreamsDatum entry) { List<StreamsDatum> result = Lists.newLinkedList(); Object item = entry.getDocument(); try { Datasift datasift = mapper.convertValue(item, Datasift.class); result.add(this.converter.convert(datasift)); } catch (Exception e) { LOGGER.error("Exception converting Datasift Interaction to "+this.outClass.getName()+ " : {}", e); } return result; }
Source:
<code>public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { verifyNativeCommandPresent(d.getAnnotation(Native.class)); verifyNativeCommandPresent(d.getTestClass().getAnnotation(Native.class)); base.evaluate(); } private void verifyNativeCommandPresent(Native n) throws IOException, InterruptedException { if (n==null) return; if (!(controller instanceof LocalController)) { throw new AssumptionViolatedException("Test skipped. Native should be used with a local controller, otherwise it cannot be fully trusted to work as expected."); } List<String> supportedCmds = Lists.newLinkedList(); String path = System.getenv("PATH"); if (path != null) { <START> String[] dirsInPath = SystemUtils.IS_OS_WINDOWS ? path.split(";") : path.split(":"); <END> for (String dirName : dirsInPath) { File dir = new File(dirName); if (dir.isDirectory()) { supportedCmds.addAll(Arrays.asList(dir.list())); } } } for (String cmd : n.value()) { if (!supportedCmds.contains(cmd)) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system."); } } } }; }</code><technical_language>File.pathSeparator mean</technical_language>

Target:
public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { verifyNativeCommandPresent(d.getAnnotation(Native.class)); verifyNativeCommandPresent(d.getTestClass().getAnnotation(Native.class)); base.evaluate(); } private void verifyNativeCommandPresent(Native n) throws IOException, InterruptedException { if (n==null) return; for (String cmd : n.value()) { if (SystemUtils.IS_OS_WINDOWS) { if (new CommandBuilder("where",cmd).system()!=0) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system"); } } else { if (new CommandBuilder("which",cmd).system()!=0) { throw new AssumptionViolatedException(cmd + " is needed for the test but doesn't exist in the system"); } } } } }; }
Source:
<code>public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications(5, TimeUnit.MINUTES); String appName = clientConfig.getReadClusterAppName(); if (applications != null && appName != null) { Application application = applications.getRegisteredApplications(appName); if (application != null) { List<InstanceInfo> validInstanceInfos = application.getInstances(); for (InstanceInfo instanceInfo : validInstanceInfos) { if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { result.add(ResolverUtils.instanceInfoToEndpoint(clientConfig, instanceInfo)); } } } } <START> logger.debug("Retrieved endpoint list {}", result); <END> return result; }</code><technical_language>For stale data return empty list, while contract is return previous value</technical_language>

Target:
public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications( transportConfig.getApplicationsResolverDataStalenessThresholdSeconds(), TimeUnit.SECONDS); String vipAddress = transportConfig.getReadClusterVip(); if (applications != null && vipAddress != null) { List<InstanceInfo> validInstanceInfos = applications.getInstancesByVirtualHostName(vipAddress); for (InstanceInfo instanceInfo : validInstanceInfos) { if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) { result.add(ResolverUtils.instanceInfoToEndpoint(clientConfig, instanceInfo)); } } } logger.debug("Retrieved endpoint list {}", result); return result; }
Source:
<code>private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { <START> try (AbfsPerfInfo tracker = new AbfsPerfInfo(client.getAbfsPerfTracker(), "writeCurrentBufferToService", "append")) { <END> tracker.registerResult(client.append(path, offset, bytes, 0, bytesLength).getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); tracker.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }</code><technical_language>This tirgger a checkstyle >80 chars. extract perf tracker. In addition, constants for strings</technical_language>

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
<code>public NestedPropertyMappingMethod build() { List<String> existingVariableNames = new ArrayList<String>(); for ( Parameter parameter : method.getSourceParameters() ) { existingVariableNames.add( parameter.getName() ); } final List<Type> thrownTypes = new ArrayList<Type>(); List<SafePropertyEntry> safePropertyEntries = new ArrayList<SafePropertyEntry>(); for ( PropertyEntry propertyEntry : propertyEntries ) { String safeName = Strings.getSaveVariableName( propertyEntry.getName(), existingVariableNames ); safePropertyEntries.add( new SafePropertyEntry( propertyEntry, safeName ) ); existingVariableNames.add( safeName ); List<Type> declaredExceptions = ctx.getTypeFactory().getThrownTypes( (ExecutableType) propertyEntry.getReadAccessor().getExecutable().asType() ); for (Type declaredException : declaredExceptions) { thrownTypes.add( declaredException ); } } NestedPropertyMappingMethod mappingMethod = new NestedPropertyMappingMethod( method, safePropertyEntries ); <START> for (Type thrownType : thrownTypes) { <END> if (!mappingMethod.getThrownTypes().contains( thrownType )) { mappingMethod.getThrownTypes().add( thrownType ); } } return mappingMethod; }</code><technical_language>Instead of this change public Builder method( Method sourceMethod ) public Builder method( ForgedMethod sourceMethod ) do method.addThrownTypes(declaredExceptions)</technical_language>

Target:
public NestedPropertyMappingMethod build() { List<String> existingVariableNames = new ArrayList<String>(); for ( Parameter parameter : method.getSourceParameters() ) { existingVariableNames.add( parameter.getName() ); } final List<Type> thrownTypes = new ArrayList<Type>(); List<SafePropertyEntry> safePropertyEntries = new ArrayList<SafePropertyEntry>(); for ( PropertyEntry propertyEntry : propertyEntries ) { String safeName = Strings.getSaveVariableName( propertyEntry.getName(), existingVariableNames ); safePropertyEntries.add( new SafePropertyEntry( propertyEntry, safeName ) ); existingVariableNames.add( safeName ); thrownTypes.addAll( ctx.getTypeFactory().getThrownTypes( propertyEntry.getReadAccessor() ) ); } method.addThrownTypes( thrownTypes ); return new NestedPropertyMappingMethod( method, safePropertyEntries ); }
Source:
<code>private void ping() throws IOException, InterruptedException { LOGGER.log(Level.FINE, "pinging {0}", channel.getName()); Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); long remaining = end - System.nanoTime(); do { LOGGER.log(Level.FINE, "waiting {0}s on {1}", new Object[] {TimeUnit.NANOSECONDS.toSeconds(remaining), channel.getName()}); try { f.get(Math.max(1,remaining),TimeUnit.NANOSECONDS); LOGGER.log(Level.FINE, "ping succeeded on {0}", channel.getName()); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; throw e; } catch (TimeoutException e) { } remaining = end - System.nanoTime(); } while(remaining>0); <START> throw new TimeoutException( "Ping started at " + start + <END> " hasn't completed by " + System.currentTimeMillis() ); }</code><technical_language>cleaner do a String.format</technical_language>

Target:
private void ping() throws IOException, InterruptedException { LOGGER.log(Level.FINE, "pinging {0}", channel.getName()); int timeouts = 0; while (true) { Future<?> f = channel.callAsync(new Ping()); long start = System.currentTimeMillis(); long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout); long remaining = end - System.nanoTime(); do { LOGGER.log( Level.FINE, "waiting {0}s on {1}", new Object[] {TimeUnit.NANOSECONDS.toSeconds(remaining), channel.getName()} ); try { f.get(Math.max(1,remaining),TimeUnit.NANOSECONDS); LOGGER.log(Level.FINE, "ping succeeded on {0}", channel.getName()); return; } catch (ExecutionException e) { if (e.getCause() instanceof RequestAbortedException) return; onDead(e); return; } catch (TimeoutException e) { } remaining = end - System.nanoTime(); } while(remaining>0); if (++timeouts >= maxTimeouts) { break; } Logger.log(Level.WARNING, "ping timeout {0}/{1} on {2}", new Object[] {timeouts, maxTimeouts, channel.getName()} ); } onDead(new TimeoutException( String.format("Ping started at %d hasn't completed by %d", start, System.currentTimeMillis()) )); }
Source:
<code>public void testCreationOfFakeCommentBlock() throws Exception { <START> final Method createFakeBlockComment = <END> Whitebox.getMethod(CommonUtils.class, "createFakeBlockComment", String.class); final DetailAST testCommentBlock = (DetailAST) createFakeBlockComment.invoke(null, "test_comment"); assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_BEGIN, testCommentBlock.getType()); assertEquals("Invalid text", " ", endCommentBlock.getText()); }</code><technical_language>method public is need in reflection</technical_language>

Target:
public void testCreationOfFakeCommentBlock() { final DetailAST testCommentBlock = CommonUtils.createBlockCommentNode("test_comment"); assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_BEGIN, testCommentBlock.getType()); assertEquals("Invalid text", " ", endCommentBlock.getText()); }
Source:
<code>protected void relearnAdditionalParameters(final ExpectationStep eStep) { final Function<Double, Double> emissionLogLikelihood = width -> { double logLikelihood = 0.0; for (int position = 0; position < positions.size(); position++) { for (int state = 0; state < weights.length; state++) { final double eStepPosterior = eStep.pStateAtPosition(state, position); logLikelihood += eStepPosterior < NEGLIGIBLE_POSTERIOR_FOR_M_STEP ? 0 :eStepPosterior * CopyRatioHiddenMarkovModel.logEmissionProbability(data.get(position), hiddenStateValues[state], width); } } return logLikelihood; }; <START> logCoverageCauchyWidth = OptimizationUtils.quickArgmax(emissionLogLikelihood, 0, <END> MAX_REASONABLE_CAUCHY_WIDTH, logCoverageCauchyWidth); logger.info("New coverage standard deviation learned: " + logCoverageCauchyWidth); }</code><technical_language>same, extract max eval tolerance if necessary</technical_language>

Target:
protected void relearnAdditionalParameters(final ExpectationStep eStep) { final Function<Double, Double> emissionLogLikelihood = width -> { double logLikelihood = 0.0; for (int position = 0; position < positions.size(); position++) { for (int state = 0; state < weights.length; state++) { final double eStepPosterior = eStep.pStateAtPosition(state, position); logLikelihood += eStepPosterior < NEGLIGIBLE_POSTERIOR_FOR_M_STEP ? 0 :eStepPosterior * CopyRatioHiddenMarkovModel.logEmissionProbability(data.get(position), hiddenStateValues[state], width); } } return logLikelihood; }; logCoverageCauchyWidth = OptimizationUtils.argmax(emissionLogLikelihood, 0, MAX_REASONABLE_CAUCHY_WIDTH, logCoverageCauchyWidth, RELATIVE_TOLERANCE_FOR_OPTIMIZATION, ABSOLUTE_TOLERANCE_FOR_OPTIMIZATION, MAX_EVALUATIONS_FOR_OPTIMIZATION); logger.info("New coverage standard deviation learned: " + logCoverageCauchyWidth); }
Source:
<code>public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { <START> logger.debug("Error closing an autorecovered channel"); <END> } finally { hasListener.remove(recoverable); } }</code><technical_language>"Error closing" debug</technical_language>

Target:
public void handleRecoveryStarted(Recoverable recoverable) { if (logger.isDebugEnabled()) { logger.debug("Closing an autorecovered channel: " + recoverable); } try { ((Channel) recoverable).close(); } catch (IOException | TimeoutException e) { logger.error("Error closing an autorecovered channel", e); } finally { hasListener.remove(recoverable); } }
Source:
<code>private boolean canScanNode(StructuralNode node) { if (node == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null node"); } return false; } HistoryReference hRef = node.getHistoryReference(); if (hRef == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null history reference for node: " + node.getName()); } return false; } if (HistoryReference.TYPE_SCANNER == hRef.getHistoryType()) { if (log.isDebugEnabled()) { log.debug( "Ignoring \"scanner\" type href [id=" + hRef.getHistoryId() + ", URL=" + hRef.getURI() + "]"); } return false; } if (!nodeInScope(node.getName())) { if (log.isDebugEnabled()) { log.debug("Ignoring node not in scope: " + node.getName()); } return false; } <START> Set<FilterResult> filterResult = filterNode(node); <END> if (filterResult.size() > 0) { if (log.isDebugEnabled()) { log.debug("Ignoring filtered node: " + node.getName() + " Reasons for Ignoring: " + filterResult.toString()); } return false; } return true; }</code><technical_language>Other scans show a tab/table reason details of message, do here</technical_language>

Target:
private boolean canScanNode(StructuralNode node) { if (node == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null node"); } return false; } HistoryReference hRef = node.getHistoryReference(); if (hRef == null) { if (log.isDebugEnabled()) { log.debug("Ignoring null history reference for node: " + node.getName()); } return false; } if (HistoryReference.TYPE_SCANNER == hRef.getHistoryType()) { if (log.isDebugEnabled()) { log.debug( "Ignoring \"scanner\" type href [id=" + hRef.getHistoryId() + ", URL=" + hRef.getURI() + "]"); } return false; } if (!nodeInScope(node.getName())) { if (log.isDebugEnabled()) { log.debug("Ignoring node not in scope: " + node.getName()); } return false; } if (filterNode(node)) { return false; } return true; }
Source:
<code>public void zoomOut() { double maxRange = layoutPanel.getFirstChild().getPlotRepresentation().getMaxRange(); for (PlotContainer pc : layoutPanel.getAllChildren()) { SimplePlot plot = pc.getPlotRepresentation().getSimplePlot(); Zoom zoom = Zoom.create().setAmount(1.1); plot.zoomOut(zoom); pc.getPlotRepresentation().calculateScrollWidth(); } PlotRepresentation plotRepresentation = layoutPanel.getFirstChild().getPlotRepresentation(); double minVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMinimumValue(); double maxVisible = plotRepresentation.getSimplePlot().getAxes().getX().getMaximumValue(); if (maxVisible > maxRange && minVisible < 0) { return; } double percent; if (maxVisible >= maxRange) { percent = 1; } else if (minVisible <= 0) { percent = 0; } else { percent = minVisible / (maxRange - maxVisible + minVisible); } <START> plotRepresentation.panToPercent(percent); <END> }</code><technical_language>zoomIn zoomOut code differe in single line 'plot.zoom[Out](zoom)' please avoid code duplication</technical_language>

Target:
public void zoomOut() { zoom(true); }
Source:
<code>private void failWithTimeout(long now, Throwable cause) { if (log.isDebugEnabled()) { <START> log.debug("{} timed out at after attempt(s)", this, now, retryContext.getTries() + 1, <END> new Exception(prettyPrintException(cause))); } handleFailure(new TimeoutException(this + " timed out at " + now + " after " + getRetryContext().getTries() + " attempt(s)", cause)); }</code><technical_language>this retryContext.tries() retryContext.tries() + 1</technical_language>

Target:
private void failWithTimeout(long now, Throwable cause) { if (log.isDebugEnabled()) { log.debug("{} timed out at after attempt(s)", this, now, callRetryContext.tries() + 1, new Exception(prettyPrintException(cause))); } handleFailure(new TimeoutException(this + " timed out at " + now + " after " + callRetryContext().tries() + " attempt(s)", cause)); }
Source:
<code>public static boolean authorizeUpdatePassword(Context context, String email) { try { EPerson eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(context, email); if (eperson != null && eperson.canLogIn()) { <START> return true; <END> } } catch (SQLException e) { log.error("Something went wrong trying to retrieve EPerson for email: " + email, e); } return false; }</code><technical_language>this call AuthenticateServiceFactory.getInstance().getAuthenticationService() .allowSetPassword(context, request, null); ? odd *anyone* update a password long EPerson exists login</technical_language>

Target:
public static boolean authorizeUpdatePassword(Context context, String email) { try { EPerson eperson = EPersonServiceFactory.getInstance().getEPersonService().findByEmail(context, email); if (eperson != null && eperson.canLogIn()) { HttpServletRequest request = new DSpace().getRequestService().getCurrentRequest() .getHttpServletRequest(); return AuthenticateServiceFactory.getInstance().getAuthenticationService() .allowSetPassword(context, request, null); } } catch (SQLException e) { log.error("Something went wrong trying to retrieve EPerson for email: " + email, e); } return false; }
Source:
<code>public void validate(PatientRecord patientRecord) throws ImportResourceException { if (patientRecord.getPatient() == null) { throw new ImportResourceException("Patient must be defined"); } if (patientRecord.getPatient().getPatientNumbers() == null) { throw new ImportResourceException("PatientNumbers must be defined"); } if (CollectionUtils.isEmpty(patientRecord.getPatient().getPatientNumbers().getPatientNumber())) { throw new ImportResourceException("PatientNumbers must have at least one Number"); } findIdentifier(patientRecord); if (patientRecord.getSurveys() != null && !CollectionUtils.isEmpty(patientRecord.getSurveys().getSurvey())) { for (uk.org.rixg.Survey survey : patientRecord.getSurveys().getSurvey()) { validateSurvey(survey); } } if (patientRecord.getDocuments() != null && !CollectionUtils.isEmpty(patientRecord.getDocuments().getDocument())) { if (StringUtils.isEmpty(patientRecord.getSendingFacility().toString())) { throw new ImportResourceException("SendingFacility must be defined (for Documents)"); } <START> if (groupRepository.findByCode(patientRecord.getSendingFacility().toString()) == null) { <END> throw new ImportResourceException("SendingFacility PatientView Group not found (for Documents)"); } for (Document document : patientRecord.getDocuments().getDocument()) { validateDocument(document); } } }</code><technical_language>Is this OK? toString() a null object give "null"</technical_language>

Target:
public void validate(PatientRecord patientRecord) throws ImportResourceException { if (patientRecord.getPatient() == null) { throw new ImportResourceException("Patient must be defined"); } if (patientRecord.getPatient().getPatientNumbers() == null) { throw new ImportResourceException("PatientNumbers must be defined"); } if (CollectionUtils.isEmpty(patientRecord.getPatient().getPatientNumbers().getPatientNumber())) { throw new ImportResourceException("PatientNumbers must have at least one Number"); } findIdentifier(patientRecord); if (patientRecord.getSurveys() != null && !CollectionUtils.isEmpty(patientRecord.getSurveys().getSurvey())) { for (uk.org.rixg.Survey survey : patientRecord.getSurveys().getSurvey()) { validateSurvey(survey); } } if (patientRecord.getDocuments() != null && !CollectionUtils.isEmpty(patientRecord.getDocuments().getDocument())) { if (patientRecord.getSendingFacility() == null || StringUtils.isEmpty(patientRecord.getSendingFacility().toString())) { throw new ImportResourceException("SendingFacility must be defined (for Documents)"); } if (groupRepository.findByCode(patientRecord.getSendingFacility().toString()) == null) { throw new ImportResourceException("SendingFacility PatientView Group not found (for Documents)"); } for (Document document : patientRecord.getDocuments().getDocument()) { validateDocument(document); } } }
Source:
<code>public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug(e.getMessage(), e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug(e.getMessage(), e); <START> result.use(Results.http()).sendError(SC_BAD_REQUEST, e.getMessage()); <END> } }</code><technical_language>for symmetry a InvalidInputHandler component this</technical_language>

Target:
public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug(e.getMessage(), e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug(e.getMessage(), e); invalidInputHandler.deny(e); } }
Source:
<code>generateX509Certificate( X500Name subject, AsymmetricCipherKeyPair keyPair) { String signatureAlgorithm = ConfigUtils.getString( LibJitsi.getConfigurationService(), PROP_SIGNATURE_ALGORITHM, "SHA1withRSA"); if (logger.isDebugEnabled()) logger.debug("Signature algorithm: " + signatureAlgorithm); try { long now = System.currentTimeMillis(); Date notBefore = new Date(now - ONE_DAY); <START> Date notAfter = new Date(now + CERT_VALIDITY_TIME); <END> X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject, BigInteger.valueOf(now), notBefore, notAfter, subject, SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo( keyPair.getPublic())); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find(signatureAlgorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keyPair.getPrivate()); return builder.build(signer).toASN1Structure(); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } else { logger.error( "Failed to generate self-signed X.509 certificate", t); if (t instanceof RuntimeException) throw (RuntimeException) t; else throw new RuntimeException(t); } } }</code><technical_language>CERT_VALIDITY_TIME + ONE_DAY</technical_language>

Target:
generateX509Certificate( X500Name subject, AsymmetricCipherKeyPair keyPair) { String signatureAlgorithm = ConfigUtils.getString( LibJitsi.getConfigurationService(), PROP_SIGNATURE_ALGORITHM, "SHA1withRSA"); if (logger.isDebugEnabled()) logger.debug("Signature algorithm: " + signatureAlgorithm); try { long now = System.currentTimeMillis(); Date notBefore = new Date(now - ONE_DAY); Date notAfter = new Date(now + ONE_DAY * 6 + CERT_CACHE_EXPIRE_TIME); X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject, BigInteger.valueOf(now), notBefore, notAfter, subject, SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo( keyPair.getPublic())); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find(signatureAlgorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(keyPair.getPrivate()); return builder.build(signer).toASN1Structure(); } catch (Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } else { logger.error( "Failed to generate self-signed X.509 certificate", t); if (t instanceof RuntimeException) throw (RuntimeException) t; else throw new RuntimeException(t); } } }
Source:
<code>public boolean hasRadiologyOrderClaimedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.like("radiologyOrder", radiologyOrder)).add( Restrictions.like("radiologyReportStatus", RadiologyReportStatus.CLAIMED)).list(); <START> if (radiologyReports.size() == 1) { <END> return true; } else { return false; } }</code><technical_language>please ternary this</technical_language>

Target:
public boolean hasRadiologyOrderClaimedRadiologyReport(RadiologyOrder radiologyOrder) { List<RadiologyReport> radiologyReports = sessionFactory.getCurrentSession().createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)).add( Restrictions.eq("reportStatus", RadiologyReportStatus.CLAIMED)).list(); return radiologyReports.size() == 1 ? true : false; }
Source:
<code>private Direction getParamDirection(int columnType, boolean isFunction) { Direction dir = null; if (isFunction) { switch (columnType) { case DatabaseMetaData.functionColumnIn: dir = Direction.INPUT; break; <START> case DatabaseMetaData.functionReturn: <END> dir = Direction.RETURN_VALUE; break; } } else { switch (columnType) { case DatabaseMetaData.procedureColumnIn: dir = Direction.INPUT; break; case DatabaseMetaData.procedureColumnInOut: dir = Direction.INPUT_OUTPUT; break; case DatabaseMetaData.procedureColumnOut: dir = Direction.OUTPUT; break; } } if (dir == null) { throw new UnsupportedOperationException( "Type " + columnType + " is not a supported type for " + (isFunction ? "function" : "procedure") + " parameters"); } return dir; }</code><technical_language>a function output parameter</technical_language>

Target:
private Direction getParamDirection(int columnType, boolean isFunction) { if (isFunction) { switch (columnType) { case DatabaseMetaData.functionColumnIn: return Direction.INPUT; case DatabaseMetaData.functionReturn: return Direction.RETURN_VALUE; } } else { switch (columnType) { case DatabaseMetaData.procedureColumnIn: return Direction.INPUT; case DatabaseMetaData.procedureColumnInOut: return Direction.INPUT_OUTPUT; case DatabaseMetaData.procedureColumnOut: return Direction.OUTPUT; } } throw new UnsupportedOperationException("Type " + columnType + " is not a supported type for " + (isFunction ? "function" : "procedure") + " parameters"); }
Source:
<code><START> public static final <T> StoreQueryParams<T> fromNameAndType(final String storeName, final QueryableStoreType<T> queryableStoreType) { <END> return new<T> StoreQueryParams<T>(storeName, queryableStoreType); }</code><technical_language>nit: line long. final required -- a static method overwritten</technical_language>

Target:
public static <T> StoreQueryParams<T> fromNameAndType(final String storeName, final QueryableStoreType<T> queryableStoreType) { return new StoreQueryParams<T>(storeName, queryableStoreType); }
Source:
<code><START> public static String getLeaseKey(ShardInfo shardInfo) { <END> return shardInfo.streamName().isPresent() ? MultiStreamLease.getLeaseKey(shardInfo.streamName().get(), shardInfo.shardId()) : shardInfo.shardId(); }</code><technical_language>ShardInfo needs LeaseKey MutltiStreamLease? abstract this information some common helper methods</technical_language>

Target:
public static String getLeaseKey(ShardInfo shardInfo) { return shardInfo.streamIdentifierSerOpt().isPresent() ? MultiStreamLease.getLeaseKey(shardInfo.streamIdentifierSerOpt().get(), shardInfo.shardId()) : shardInfo.shardId(); }
Source:
<code>public VM update(VM incoming) { if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if(!clusterId.toString().equals(get().getCluster().getId())){ performAction(VdcActionType.ChangeVMCluster, new ChangeVMClusterParameters(clusterId, guid)); } } if (incoming.isSetPlacementPolicy() && incoming.getPlacementPolicy().isSetHost() && incoming.getPlacementPolicy().getHost().isSetName() && !incoming.getPlacementPolicy().getHost().isSetId()) { incoming.getPlacementPolicy().getHost().setId(getHostId(incoming.getPlacementPolicy().getHost().getName())); } VM retVal = performUpdate(incoming, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class), VdcActionType.UpdateVm, new UpdateParametersProvider()); setPayload(retVal); <START> return retVal; <END> }</code><technical_language>Move call setPayload() in populate() (takes care of get() flow well)</technical_language>

Target:
public VM update(VM incoming) { if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if(!clusterId.toString().equals(get().getCluster().getId())){ performAction(VdcActionType.ChangeVMCluster, new ChangeVMClusterParameters(clusterId, guid)); } } if (incoming.isSetPlacementPolicy() && incoming.getPlacementPolicy().isSetHost() && incoming.getPlacementPolicy().getHost().isSetName() && !incoming.getPlacementPolicy().getHost().isSetId()) { incoming.getPlacementPolicy().getHost().setId(getHostId(incoming.getPlacementPolicy().getHost().getName())); } VM retVal = performUpdate(incoming, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class), VdcActionType.UpdateVm, new UpdateParametersProvider()); return retVal; }
Source:
<code><START> public String getPathRelativeToSourceRoot(File file, int stripCount) throws IOException, FileNotFoundException { <END> String canonicalPath = file.getCanonicalPath(); String sourceRoot = getSourceRootPath(); if(sourceRoot == null){ throw new FileNotFoundException("Source Root Not Found"); } if (canonicalPath.startsWith(sourceRoot)) { return canonicalPath.substring(sourceRoot.length() + stripCount); } for (String allowedSymlink : getAllowedSymlinks()) { String allowedTarget = new File(allowedSymlink).getCanonicalPath(); if (canonicalPath.startsWith(allowedTarget)) { return canonicalPath.substring(allowedTarget.length() + stripCount); } } throw new FileNotFoundException("Failed to resolve [" + canonicalPath + "] relative to source root [" + sourceRoot + "]"); }</code><technical_language>FileNotFoundException is a subclass of IOException</technical_language>

Target:
public String getPathRelativeToSourceRoot(File file, int stripCount) throws IOException { String canonicalPath = file.getCanonicalPath(); String sourceRoot = getSourceRootPath(); if(sourceRoot == null){ throw new FileNotFoundException("Source Root Not Found"); } if (canonicalPath.startsWith(sourceRoot)) { return canonicalPath.substring(sourceRoot.length() + stripCount); } for (String allowedSymlink : getAllowedSymlinks()) { String allowedTarget = new File(allowedSymlink).getCanonicalPath(); if (canonicalPath.startsWith(allowedTarget)) { return canonicalPath.substring(allowedTarget.length() + stripCount); } } throw new FileNotFoundException("Failed to resolve [" + canonicalPath + "] relative to source root [" + sourceRoot + "]"); }
Source:
<code>public void execute(JobExecutionContext context) throws JobExecutionException { String noteId = context.getJobDetail().getJobDataMap().getString("noteId"); Note note = notebook.getNote(noteId); if (note.isRunningOrPending()) { logger.info("execution of the cron job is skipped because there is a running or pending " + "paragraph (note id: {})", noteId); <START> return; <END> } note.runAll(); boolean releaseResource = false; String cronExecutingUser = null; try { Map<String, Object> config = note.getConfig(); if (config != null) { if (config.containsKey("releaseresource")) { releaseResource = (boolean) config.get("releaseresource"); } cronExecutingUser = (String) config.get("cronExecutingUser"); } } catch (ClassCastException e) { logger.error(e.getMessage(), e); } if (releaseResource) { for (InterpreterSetting setting : notebook.getInterpreterSettingManager() .getInterpreterSettings(note.getId())) { try { notebook.getInterpreterSettingManager().restart(setting.getId(), noteId, cronExecutingUser != null ? cronExecutingUser : "anonymous"); } catch (InterpreterException e) { logger.error("Fail to restart interpreter: " + setting.getId(), e); } } } }</code><technical_language>if is running notebook manually scheduler kicks off, block scheduler</technical_language>

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { String noteId = context.getJobDetail().getJobDataMap().getString("noteId"); Note note = notebook.getNote(noteId); if (note.isRunningOrPending()) { logger.warn("execution of the cron job is skipped because there is a running or pending " + "paragraph (note id: {})", noteId); return; } note.runAll(); boolean releaseResource = false; String cronExecutingUser = null; try { Map<String, Object> config = note.getConfig(); if (config != null) { if (config.containsKey("releaseresource")) { releaseResource = (boolean) config.get("releaseresource"); } cronExecutingUser = (String) config.get("cronExecutingUser"); } } catch (ClassCastException e) { logger.error(e.getMessage(), e); } if (releaseResource) { for (InterpreterSetting setting : notebook.getInterpreterSettingManager() .getInterpreterSettings(note.getId())) { try { notebook.getInterpreterSettingManager().restart(setting.getId(), noteId, cronExecutingUser != null ? cronExecutingUser : "anonymous"); } catch (InterpreterException e) { logger.error("Fail to restart interpreter: " + setting.getId(), e); } } } }
Source:
<code>private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); builder.append(actionType); builder.append(", Parameters: "); <START> builder.append(params); <END> } }</code><technical_language>missing "log.debug(builder.toString());"</technical_language>

Target:
private void debugAction(VdcActionType actionType, VdcActionParametersBase params) { if(log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(50); builder.append("Action type: "); builder.append(actionType); builder.append(", Parameters: "); builder.append(params); log.debug(builder.toString()); } }
Source:
<code>protected void collectColumns() throws IOException { TermFactory factory = TermFactory.instance(); int index = 0; String[] header = reader.readNext(); if (header == null || header.length == 0) throw new IndexBuilderException("No header in CSV file"); <START> this.termLocations = new HashMap<>(header.length); <END> this.terms = new ArrayList<>(header.length); for (String heading: header) { heading = heading.trim(); Term term = factory.findTerm(heading); if (term == null) term = ALATerm.valueOf(heading); if (term != null) this.termLocations.put(term, index); this.terms.add(term); index++; } }</code><technical_language>LinkedHashMap is basically in terms of performance helps debugging of constant iteration order behaviour</technical_language>

Target:
protected void collectColumns() throws IOException { TermFactory factory = TermFactory.instance(); int index = 0; String[] header = reader.readNext(); if (header == null || header.length == 0) throw new IndexBuilderException("No header in CSV file"); this.termLocations = new LinkedHashMap<>(header.length); this.terms = new ArrayList<>(header.length); for (String heading: header) { heading = heading.trim(); Term term = factory.findTerm(heading); if (term == null) term = ALATerm.valueOf(heading); if (term != null) this.termLocations.put(term, index); else logger.warn("Unable to map " + heading + " onto a term"); this.terms.add(term); index++; } }
Source:
<code><START> public final U assertValueAt(int index, T value) { <END> int s = values.size(); if (s == 0) { throw fail("No values"); } if (index >= values.size()) { throw fail("Invalid index: " + index); } T v = values.get(index); if (!ObjectHelper.equals(value, v)) { throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); } return (U)this; }</code><technical_language>@Experimental</technical_language>

Target:
public final U assertValueAt(int index, T value) { int s = values.size(); if (s == 0) { throw fail("No values"); } if (index >= s) { throw fail("Invalid index: " + index); } T v = values.get(index); if (!ObjectHelper.equals(value, v)) { throw fail("Expected: " + valueAndClass(value) + ", Actual: " + valueAndClass(v)); } return (U)this; }
Source:
<code>public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, LockingStrategyException { TypeTranslator typeTranslator = lockable.getFactory().getServiceRegistry().getService( TypeTranslator.class ); GridType idGridType = typeTranslator.getType( lockable.getIdentifierType() ); EntityKey key = EntityKeyBuilder.fromData( ( (OgmEntityPersister) lockable ).getRootEntityKeyMetadata(), idGridType, id, session ); IgniteCache<Object, BinaryObject> cache = provider.getEntityCache( key.getMetadata() ); if ( cache == null ) { <START> throw new IgniteHibernateException( "Cache " + key.getMetadata().getTable() + " is not found" ); <END> } Lock lock = cache.lock( provider.createKeyObject( key ) ); try { lock.tryLock( timeout, TimeUnit.MILLISECONDS ); } catch (InterruptedException e) { throw new IgniteLockingStrategyException( object, e.getMessage(), e ); } }</code><technical_language>this somethignlike: log.cacheNotFound( key.getMetadata().getTable )</technical_language>

Target:
public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, LockingStrategyException { TypeTranslator typeTranslator = lockable.getFactory().getServiceRegistry().getService( TypeTranslator.class ); GridType idGridType = typeTranslator.getType( lockable.getIdentifierType() ); EntityKey key = EntityKeyBuilder.fromData( ( (OgmEntityPersister) lockable ).getRootEntityKeyMetadata(), idGridType, id, session ); IgniteCache<Object, BinaryObject> cache = provider.getEntityCache( key.getMetadata() ); Lock lock = cache.lock( provider.createKeyObject( key ) ); try { lock.tryLock( timeout, TimeUnit.MILLISECONDS ); } catch (InterruptedException e) { throw new IgniteLockingStrategyException( object, e.getMessage(), e ); } }
Source:
<code>protected void buildOpenMergeRequests(final GitLabPushTrigger trigger, final Integer projectId, String projectRef) { try { <START> GitLabConnectionProperty property = project.getProperty(GitLabConnectionProperty.class); <END> if (property != null && property.getClient() != null) { GitlabAPI client = property.getClient(); for (final GitlabMergeRequest mergeRequest : client.getOpenMergeRequests(projectId)) { String sourceBranch = mergeRequest.getSourceBranch(); String targetBranch = mergeRequest.getTargetBranch(); if (projectRef.endsWith(sourceBranch) || (trigger.getTriggerOpenMergeRequestOnPush().equals("both") && projectRef.endsWith(targetBranch))) { if (trigger.getCiSkip() && mergeRequest.getDescription().contains("[ci-skip]")) { LOGGER.log(Level.INFO, "Skipping MR " + mergeRequest.getTitle() + " due to ci-skip."); continue; } final LastCommit lastCommit = createLastCommit(projectId, client.getBranch(createProject(projectId), sourceBranch)); ACL.impersonate(ACL.SYSTEM, new Runnable() { public void run() { trigger.onPost(createMergeRequest(projectId, mergeRequest, lastCommit)); } }); } } } } catch (Exception e) { LOGGER.warning("failed to communicate with gitlab server to determine is this is an update for a merge request: " + e.getMessage()); e.printStackTrace(); } }</code><technical_language>Ok, fixed here</technical_language>

Target:
protected void buildOpenMergeRequests(final GitLabPushTrigger trigger, final Integer projectId, String projectRef) { try { GitLabConnectionProperty property = project.getProperty(GitLabConnectionProperty.class); if (property != null && property.getClient() != null) { GitlabAPI client = property.getClient(); for (final GitlabMergeRequest mergeRequest : client.getOpenMergeRequests(projectId)) { String sourceBranch = mergeRequest.getSourceBranch(); String targetBranch = mergeRequest.getTargetBranch(); if (projectRef.endsWith(sourceBranch) || (trigger.getTriggerOpenMergeRequestOnPush().equals("both") && projectRef.endsWith(targetBranch))) { if (trigger.getCiSkip() && mergeRequest.getDescription().contains("[ci-skip]")) { LOGGER.log(Level.INFO, "Skipping MR " + mergeRequest.getTitle() + " due to ci-skip."); continue; } final LastCommit lastCommit = createLastCommit(projectId, client.getBranch(createProject(projectId), sourceBranch)); ACL.impersonate(ACL.SYSTEM, new Runnable() { public void run() { trigger.onPost(createMergeRequest(projectId, mergeRequest, lastCommit)); } }); } } } } catch (Exception e) { LOGGER.warning("Failed to communicate with gitlab server to determine if this is an update for a merge request: " + e.getMessage()); e.printStackTrace(); } }
Source:
<code>private static String encodeParameters(final Map<String, List<String>> params) { List<String> parameters = new ArrayList<>(); for (final Map.Entry<String, List<String>> entry : params.entrySet()) { try { String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); for (final String value : entry.getValue()) { if (value == null) { continue; } String encodedValue; <START> if (value.startsWith("+")) { <END> encodedValue = value; } else { encodedValue = URLEncoder.encode(value, "UTF-8"); } parameters.add(encodedName + "=" + encodedValue); } } catch (final UnsupportedEncodingException e) { throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); } } return joinIgnoreNull("&", parameters); }</code><technical_language>This is proper solution other characters this solve for. Proper changes needed in com.twilio.http.Request.buildURL()</technical_language>

Target:
private static String encodeParameters(final Map<String, List<String>> params) { List<String> parameters = new ArrayList<>(); for (final Map.Entry<String, List<String>> entry : params.entrySet()) { try { String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); for (final String value : entry.getValue()) { if (value == null) { continue; } String encodedValue = URLEncoder.encode(value, "UTF-8"); parameters.add(encodedName + "=" + encodedValue); } } catch (final UnsupportedEncodingException e) { throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); } } return joinIgnoreNull("&", parameters); }
Source:
<code>private void discoverSupervisorTaskPartitions() { for (StorageLocation location : shuffleDataLocations) { final Path localtionPath = location.getPath().toPath().toAbsolutePath(); final MutableInt numDiscovered = new MutableInt(0); final File[] dirsPerSupervisorTask = location.getPath().listFiles(); if (dirsPerSupervisorTask != null) { for (File supervisorTaskDir : dirsPerSupervisorTask) { final String supervisorTaskId = supervisorTaskDir.getName(); supervisorTaskCheckTimes.computeIfAbsent( supervisorTaskId, k -> { for (File eachFile : FileUtils.listFiles(supervisorTaskDir, null, true)) { <START> final String relativeSegmentPath = localtionPath <END> .relativize(eachFile.toPath().toAbsolutePath()) .toString(); final File reservedFile = location.reserve( relativeSegmentPath, eachFile.getName(), eachFile.length() ); if (reservedFile == null) { log.warn("Can't add a discovered partition[%s]", eachFile.getAbsolutePath()); } } numDiscovered.increment(); return DateTimes.nowUtc().plus(intermediaryPartitionTimeout); } ); } } log.info("Discovered partitions for [%s] new supervisor tasks", numDiscovered.getValue()); } }</code><technical_language>typo: localtionPath -> locationPath</technical_language>

Target:
private void discoverSupervisorTaskPartitions() { for (StorageLocation location : shuffleDataLocations) { final Path locationPath = location.getPath().toPath().toAbsolutePath(); final MutableInt numDiscovered = new MutableInt(0); final File[] dirsPerSupervisorTask = location.getPath().listFiles(); if (dirsPerSupervisorTask != null) { for (File supervisorTaskDir : dirsPerSupervisorTask) { final String supervisorTaskId = supervisorTaskDir.getName(); supervisorTaskCheckTimes.computeIfAbsent( supervisorTaskId, k -> { for (File eachFile : FileUtils.listFiles(supervisorTaskDir, null, true)) { final String relativeSegmentPath = locationPath .relativize(eachFile.toPath().toAbsolutePath()) .toString(); final File reservedFile = location.reserve( relativeSegmentPath, eachFile.getName(), eachFile.length() ); if (reservedFile == null) { LOG.warn("Can't add a discovered partition[%s]", eachFile.getAbsolutePath()); } } numDiscovered.increment(); return DateTimes.nowUtc().plus(intermediaryPartitionTimeout); } ); } } LOG.info( "Discovered partitions for [%s] new supervisor tasks under location[%s]", numDiscovered.getValue(), location.getPath() ); } }