auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean isSupported(AbstractFile file) { if (file == null) { return false; } if (file.getSize() == 0) { return false; } if (file.getNameExtension().toLowerCase().startsWith(LOG_FILE_EXTENSION)) { return false; } byte[] header = new byte[0x4000]; try { file.read(header, 0x0, Math.min(0x4000, file.getSize())); } catch (TskCoreException ex) { <START> logger.log(Level.WARNING, "Failed to read file content", ex); <END> } ByteBuffer buf = ByteBuffer.wrap(header); RegistryHive hive = new RegistryHiveBuffer(buf); try { hive.getHeader(); return true; } catch (RegistryParseException ex) { logger.log(Level.WARNING, "Failed to get hive header", ex); return false; } }</code><technical_language>I guess question, exit if exception while read data file? Is a point in continue pass incomplete/gibberish data other classes</technical_language>

Target:
public boolean isSupported(AbstractFile file) { if (file == null) { return false; } if (file.getSize() == 0) { return false; } if (file.getNameExtension().toLowerCase().startsWith(LOG_FILE_EXTENSION)) { return false; } byte[] header = new byte[0x4000]; try { file.read(header, 0x0, Math.min(0x4000, file.getSize())); } catch (TskCoreException ex) { logger.log(Level.WARNING, "Failed to read file content", ex); return false; } ByteBuffer buf = ByteBuffer.wrap(header); RegistryHive hive = new RegistryHiveBuffer(buf); try { hive.getHeader(); return true; } catch (RegistryParseException ex) { logger.log(Level.WARNING, "Failed to get hive header", ex); return false; } }
Source:
<code>private BigInteger byteArrayToBigInteger(final byte[] bitStringValue) { <START> BigInteger value = null; <END> for (final byte element : bitStringValue) { if (value != null) { value = value.shiftLeft(8); } else if (value == null) { value = BigInteger.valueOf(0); } value = value.add(BigInteger.valueOf(element & 0xFF)); } return value; }</code><technical_language>start "BigInteger = BigInteger.valueOf(0);", leave out null check for loop? If this is null returned for empty bitStringValue, first</technical_language>

Target:
private BigInteger byteArrayToBigInteger(final byte[] bitStringValue) { if (bitStringValue == null || bitStringValue.length == 0) { return null; } BigInteger value = BigInteger.valueOf(0); for (final byte element : bitStringValue) { value = value.shiftLeft(8); value = value.add(BigInteger.valueOf(element & 0xFF)); } return value; }
Source:
<code>public void executionSkipped(TestIdentifier testIdentifier, String reason) { <START> String source = getClassName(testIdentifier).orElse(parentDisplayName(testIdentifier)); <END> runListener.testSkipped(ignored(source, testIdentifier.getDisplayName(), reason)); }</code><technical_language>a _really_ expensive computation orElseGet</technical_language>

Target:
public void executionSkipped(TestIdentifier testIdentifier, String reason) { String source = getClassName(testIdentifier).orElseGet(() -> parentDisplayName(testIdentifier)); runListener.testSkipped(ignored(source, testIdentifier.getDisplayName(), reason)); }
Source:
<code>public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AppConfig.class); PersonRepository repository = context.getBean(PersonRepository.class); Person peter = new Person("Peter", "Sagan", 17); Person nasta = new Person("Nasta", "Kuzminova", 25); Person john = new Person("John", "lawrence", 35); Person terry = new Person("Terry", "Law", 36); repository.save(peter); repository.save(nasta); repository.save(john); repository.save(terry); LOGGER.info("Count Person records: {}", repository.count()); List<Person> persons = (List<Person>) repository.findAll(); for (Person person : persons) { LOGGER.info(person.toString()); } nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); <START> LOGGER.info("Find by id 2: {}", repository.findById(2L)); <END> repository.deleteById(2L); LOGGER.info("Count Person records: {}", repository.count()); Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); LOGGER.info("Find by John is {}", p.get()); persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); for (Person person : persons) { LOGGER.info(person.toString()); } context.close(); }</code><technical_language>Returns Optional.</technical_language>

Target:
public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AppConfig.class); PersonRepository repository = context.getBean(PersonRepository.class); Person peter = new Person("Peter", "Sagan", 17); Person nasta = new Person("Nasta", "Kuzminova", 25); Person john = new Person("John", "lawrence", 35); Person terry = new Person("Terry", "Law", 36); repository.save(peter); repository.save(nasta); repository.save(john); repository.save(terry); LOGGER.info("Count Person records: {}", repository.count()); List<Person> persons = (List<Person>) repository.findAll(); for (Person person : persons) { LOGGER.info(person.toString()); } nasta.setName("Barbora"); nasta.setSurname("Spotakova"); repository.save(nasta); LOGGER.info("Find by id 2: {}", repository.findById(2L).get()); repository.deleteById(2L); LOGGER.info("Count Person records: {}", repository.count()); Optional<Person> p = repository.findOne(new PersonSpecifications.NameEqualSpec("John")); LOGGER.info("Find by John is {}", p.get()); persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); LOGGER.info("Find Person with age between 20,40: "); for (Person person : persons) { LOGGER.info(person.toString()); } context.close(); }
Source:
<code>public String generateLoadBalancerEndpoint(Stack stack, LoadBalancerType type) { <START> List<String> s = Arrays.asList(stack.getName(), ENDPOINT_SUFFIX); <END> if (LoadBalancerType.PUBLIC.equals(type)) { s.add(PUBLIC_SUFFIX); } return String.join("-", s); }</code><technical_language>More descriptive variable name please. i feel do String s = stack.getname()+"-"+ENDPOING_SUFFIX; if public +="-"+PUBLIC_SUFFIX</technical_language>

Target:
public String generateLoadBalancerEndpoint(Stack stack, LoadBalancerType type) { StringBuilder name = new StringBuilder() .append(stack.getName()) .append('-') .append(ENDPOINT_SUFFIX); if (LoadBalancerType.PUBLIC.equals(type)) { name.append('-').append(PUBLIC_SUFFIX); } return name.toString(); }
Source:
<code>private boolean requirejsManagerInitIsCalled( String response, String useFullyQualifiedUrlParameter ) { final boolean containsScript = response.contains( "requirejs-manager/js/require-init.js?requirejs=false" ); final boolean containsFullyQualifiedUrlParameter = response.contains( <START> "&useFullyQualifiedUrl=" + ( useFullyQualifiedUrlParameter != null ? useFullyQualifiedUrlParameter : "" ) <END> ); return containsScript && containsFullyQualifiedUrlParameter == ( useFullyQualifiedUrlParameter != null ); }</code><technical_language>PentahoWebContextFilter.USE_FULL_URL_PARAM too</technical_language>

Target:
private boolean requirejsManagerInitIsCalled( String response, String useFullyQualifiedUrlParameter ) { final boolean containsScript = response.contains( "requirejs-manager/js/require-init.js?requirejs=false" ); final String parameterValue = useFullyQualifiedUrlParameter != null ? useFullyQualifiedUrlParameter : ""; final boolean containsFullyQualifiedUrlParameter = response.contains( "&" + PentahoWebContextFilter.USE_FULL_URL_PARAM + "=" + parameterValue ); return containsScript && containsFullyQualifiedUrlParameter == ( useFullyQualifiedUrlParameter != null ); }
Source:
<code>public static Duration adjustServerTimeout(Duration clientTimeout) { <START> return clientTimeout.minusMillis(200); <END> }</code><technical_language>this issue if clientTimeout is 200 milliseconds</technical_language>

Target:
static Duration adjustServerTimeout(Duration clientTimeout) { return clientTimeout.minusMillis(200); }
Source:
<code>public boolean transientHasPriority() { <START> return transientHasPriority; <END> }</code><technical_language>this. (applies missing this.)</technical_language>

Target:
public boolean transientHasPriority() { return this.transientHasPriority; }
Source:
<code>public void testFiresOnNestedCountAggregate() { tester.assertThat(new PruneCountAggregationOverScalar()) .on(p -> p.aggregation((a) -> a.addAggregation( p.symbol("count_1", BigintType.BIGINT), new AggregationNode.Aggregation( new FunctionCall(QualifiedName.of("count"), ImmutableList.of()), new Signature("count", AGGREGATE, parseTypeSignature(StandardTypes.BIGINT)), Optional.empty())) .source(p.aggregation((aggregationBuilder) -> aggregationBuilder .source(p.tableScan(ImmutableList.of(), ImmutableMap.of())) .groupingSets(ImmutableList.of(ImmutableList.of())))) .step(AggregationNode.Step.SINGLE) .groupingSets(ImmutableList.of(ImmutableList.of())) <START> .step(AggregationNode.Step.SINGLE) <END> )).matches(PlanMatchPattern.values(ImmutableMap.of("count_1", 0))); }</code><technical_language>add blank line</technical_language>

Target:
public void testFiresOnNestedCountAggregate() { tester.assertThat(new PruneCountAggregationOverScalar()) .on(p -> p.aggregation((a) -> a .addAggregation( p.symbol("count_1", BigintType.BIGINT), new FunctionCall(QualifiedName.of("count"), ImmutableList.of()), ImmutableList.of(BigintType.BIGINT)) .globalGrouping() .step(AggregationNode.Step.SINGLE) .source( p.aggregation((aggregationBuilder) -> aggregationBuilder .source(p.tableScan(ImmutableList.of(), ImmutableMap.of())) .globalGrouping() .step(AggregationNode.Step.SINGLE))))) .matches(values(ImmutableMap.of("count_1", 0))); }
Source:
<code>public boolean provides(IAdaptable adaptable) { if (adaptable != null) { View view = (View) adaptable.getAdapter(View.class); if (view != null) { Diagram diagram = view.getDiagram(); <START> return diagram != null && diagram.getElement() instanceof DDiagram; <END> } } return false; }</code><technical_language>EMF reflection instead of Java for kinds of tests. EMF counterparts more flexible (they work dynamic instances). DiagramPackage.Literals.DDIAGRAM.isInstance(diagram.getElement())</technical_language>

Target:
public boolean provides(IAdaptable adaptable) { if (adaptable != null) { View view = (View) adaptable.getAdapter(View.class); if (view != null) { Diagram diagram = view.getDiagram(); return diagram != null && DiagramPackage.Literals.DDIAGRAM.isInstance(diagram.getElement()); } } return false; }
Source:
<code>void cacheConfig(boolean doCache) { Map<File, CachedConfig> cache = CACHED_CONFIG.get(); CachedConfig cfg = cache.get(getDirectory()); if (cfg == null) { if (!doCache) { return; } cfg = new CachedConfig(); cache.put(getDirectory(), cfg); } <START> if (!doCache && cfg.level > 0) { <END> if (--cfg.level == 0) { cache.remove(getDirectory()); } } else if (doCache) { cfg.level++; } }</code><technical_language>do adding logging for !doCache level==0? wrong usage of API unnoticed</technical_language>

Target:
void cacheConfig(boolean doCache) { Map<File, CachedConfig> cache = CACHED_CONFIG.get(); CachedConfig cfg = cache.get(getDirectory()); if (cfg == null) { if (!doCache) { return; } cfg = new CachedConfig(); cache.put(getDirectory(), cfg); } if (!doCache) { if (cfg.level > 0) { if (--cfg.level == 0) { cache.remove(getDirectory()); } } else { Activator.logWarning(MessageFormat.format( CoreText.CachingRepository_cacheLevelZero, getDirectory()), null); } } else if (doCache) { cfg.level++; } }
Source:
<code>void shouldReturnDelegateWhenFullyQualifiedNamePresent() { final Optional<IDelegate> result = <START> xmlGameElementMapper.newDelegate("games.strategy.triplea.delegate.battle.BattleDelegate"); <END> assertThat(result, isPresent()); assertThat(result.get(), is(instanceOf(BattleDelegate.class))); }</code><technical_language>This change is incorrect</technical_language>

Target:
void shouldReturnDelegateWhenFullyQualifiedNamePresent() { final Optional<IDelegate> result = xmlGameElementMapper.newDelegate("games.strategy.triplea.delegate.BattleDelegate"); assertThat(result, isPresent()); assertThat(result.get(), is(instanceOf(BattleDelegate.class))); }
Source:
<code>public void testNot() { assertOptimizedEquals("not true", "false"); assertOptimizedEquals("not false", "true"); assertOptimizedEquals("not null", "null"); assertOptimizedEquals("not 1=1", "false"); assertOptimizedEquals("not 1=BIGINT '1'", "false"); assertOptimizedEquals("not 1!=1", "true"); assertOptimizedEquals("not unbound_long=1", "not unbound_long=1"); assertOptimizedEquals("not unbound_long=(1+1)", "not unbound_long=2"); <START> assertOptimizedEquals("cast(json_parse(unbound_string) as map(varchar, varchar))", "cast(json_parse(unbound_string) as map(varchar, varchar))"); <END> assertOptimizedEquals("cast(json_parse(unbound_string) as array(varchar))", "cast(json_parse(unbound_string) as array(varchar))"); assertOptimizedEquals("cast(json_parse(unbound_string) as row(bigint, varchar))", "cast(json_parse(unbound_string) as row(bigint, varchar))"); }</code><technical_language>in testNot? -- perform optimization</technical_language>

Target:
public void testNot() { assertOptimizedEquals("not true", "false"); assertOptimizedEquals("not false", "true"); assertOptimizedEquals("not null", "null"); assertOptimizedEquals("not 1=1", "false"); assertOptimizedEquals("not 1=BIGINT '1'", "false"); assertOptimizedEquals("not 1!=1", "true"); assertOptimizedEquals("not unbound_long=1", "not unbound_long=1"); assertOptimizedEquals("not unbound_long=(1+1)", "not unbound_long=2"); }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (o == null || !(o instanceof TupleValue)) return false; DefaultTupleValue that = (DefaultTupleValue) o; if (this.protocolVersion() != that.protocolVersion()) return false; for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); DataType innerThatType = type.getComponentTypes().get(i); if (!innerThisType.equals(innerThatType)) { return false; } Object thisValue = this.codecRegistry() .codecFor(innerThatType) .decode(this.values[i], this.protocolVersion()); Object thatValue = that.codecRegistry() .codecFor(innerThatType) .decode(that.values[i], that.protocolVersion()); if (!((thisValue == thatValue) || (thisValue != null && thisValue.equals(thatValue)))) { return false; } } return true; }</code><technical_language>Nit: add braces, if is statement? part of Google style guide adhere to</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TupleValue)) { return false; } TupleValue that = (TupleValue) o; if (!this.protocolVersion().equals(that.protocolVersion())) { return false; } for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); DataType innerThatType = that.getType().getComponentTypes().get(i); if (!innerThisType.equals(innerThatType)) { return false; } Object thisValue = this.codecRegistry() .codecFor(innerThisType) .decode(this.getBytesUnsafe(i), this.protocolVersion()); Object thatValue = that.codecRegistry() .codecFor(innerThatType) .decode(that.getBytesUnsafe(i), that.protocolVersion()); if (!Objects.equals(thisValue, thatValue)) { return false; } } return true; }
Source:
<code>protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { ViewGroup answerView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.base_geo_widget_layout, null); answerDisplay = answerView.findViewById(R.id.geo_answer_text); <START> answerDisplay.setTextColor(new ThemeUtils(context).getColorOnSurface()); <END> answerDisplay.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); startGeoButton = answerView.findViewById(R.id.simple_button); readOnly = getFormEntryPrompt().isReadOnly(); if (readOnly) { startGeoButton.setVisibility(GONE); } else { startGeoButton.setText(getDefaultButtonLabel()); startGeoButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); startGeoButton.setOnClickListener(v -> onButtonClick()); } return answerView; }</code><technical_language>This defined in layout</technical_language>

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = GeoWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); View answerView = binding.getRoot(); binding.geoAnswerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); readOnly = prompt.isReadOnly(); if (readOnly) { binding.simpleButton.setVisibility(GONE); } else { binding.simpleButton.setText(getDefaultButtonLabel()); binding.simpleButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.simpleButton.setOnClickListener(v -> onButtonClick()); } return answerView; }
Source:
<code>public void setFocus(final IDMContext[] focus, RequestMonitor rm) { assert focus != null; IDMContext elem = focus[0]; IFrameDMContext frameCtx = null; IMIExecutionDMContext threadCtx = null; if (elem instanceof IFrameDMContext) { <START> frameCtx = (IFrameDMContext)elem; <END> threadCtx = getThreadFromFrame(frameCtx); } else if (elem instanceof IMIExecutionDMContext) { threadCtx = (IMIExecutionDMContext)elem; frameCtx = createFrameContext((IExecutionDMContext)elem, STACKFRAME_ID_DEFAULT); } else { assert false; return; } final IFrameDMContext finalFrameCtx = frameCtx; final IMIExecutionDMContext finalThreadCtx = threadCtx; setThreadFocus(threadCtx, new ImmediateRequestMonitor(rm) { @Override protected void handleCompleted() { setFrameFocus(finalFrameCtx, new ImmediateRequestMonitor(rm) { @Override public void handleCompleted() { fCurrentStackFrameCtx = finalFrameCtx; fCurrentThreadCtx = finalThreadCtx; rm.done(); } }); } } ); }</code><technical_language>simplify setting frame? frameDmc thread a parent, -stack-select-frame thread a --thread flag automatically</technical_language>

Target:
public void setFocus(final IDMContext[] focus, RequestMonitor rm) { assert focus != null; IDMContext elem = focus[0]; if (elem instanceof IFrameDMContext) { final IFrameDMContext finalFrameCtx = (IFrameDMContext)elem; setFrameFocus(finalFrameCtx, new ImmediateRequestMonitor(rm) { @Override public void handleCompleted() { fCurrentGDBFocus = finalFrameCtx; rm.done(); } }); } else if (elem instanceof IMIExecutionDMContext) { final IMIExecutionDMContext finalThreadCtx = (IMIExecutionDMContext)elem; setThreadFocus(finalThreadCtx, new ImmediateRequestMonitor(rm) { @Override protected void handleCompleted() { fCurrentGDBFocus = finalThreadCtx; rm.done(); } }); } else { assert false; rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "Invalid context to set focus to", null)); return; } }
Source:
<code>public Member sponsorMember(PerunSession session, Vo vo, User sponsored, User sponsor) throws MemberNotExistsException, InternalErrorException, AlreadyMemberException { Member sponsoredMember; try { sponsoredMember = getMemberByUser(session, vo, sponsored); if(!sponsoredMember.isSponsored()) { <START> throw new IllegalArgumentException("member "+sponsoredMember.getId()+" is not marked as sponsored"); <END> } getMembersManagerImpl().addSponsor(session, sponsoredMember,sponsor); getPerunBl().getAuditer().log(session, "{} added sponsor {}", sponsoredMember, sponsor); } catch (MemberNotExistsException ex) { sponsoredMember = getMembersManagerImpl().createSponsoredMember(session, vo, sponsored, sponsor); getPerunBl().getAuditer().log(session, "{} created, sponsored by {}", sponsoredMember, sponsor); } return sponsoredMember; }</code><technical_language>of methods (not GUI) account unchecked exceptions. create a checked one</technical_language>

Target:
public Member sponsorMember(PerunSession session, Vo vo, User sponsored, User sponsor) throws MemberNotExistsException, InternalErrorException, AlreadyMemberException, MemberNotSponsoredException { Member sponsoredMember; try { sponsoredMember = getMemberByUser(session, vo, sponsored); if(!sponsoredMember.isSponsored()) { throw new MemberNotSponsoredException("member "+sponsoredMember.getId()+" is not marked as sponsored"); } getMembersManagerImpl().addSponsor(session, sponsoredMember,sponsor); getPerunBl().getAuditer().log(session, "{} added sponsor {}", sponsoredMember, sponsor); } catch (MemberNotExistsException ex) { sponsoredMember = getMembersManagerImpl().createSponsoredMember(session, vo, sponsored, sponsor); getPerunBl().getAuditer().log(session, "{} created, sponsored by {}", sponsoredMember, sponsor); } return sponsoredMember; }
Source:
<code>public static ReactiveSocket createClient() { try { String target = "tcp://localhost:4567/rs"; URI uri = new URI(target); Publisher<ReactiveSocket> socketPublisher = buildConnection(uri); <START> SocketWrapper client = new SocketWrapper(); <END> CountDownLatch hold = new CountDownLatch(1); socketPublisher.subscribe(new Subscriber<ReactiveSocket>() { @Override public void onSubscribe(Subscription s) { s.request(1); } @Override public void onNext(ReactiveSocket reactiveSocket) { client.setSocket(reactiveSocket); hold.countDown(); } @Override public void onError(Throwable t) { System.out.println("error when getting reactive socket"); } @Override public void onComplete() { } }); hold.await(); return client.getSocket(); } catch (Exception e) { System.out.println("Something went wrong"); } return null; }</code><technical_language>replace by: Unsafe.blockingSingleWait(socketPublisher, 5, TimeUnit.SECONDS);</technical_language>

Target:
public static ReactiveSocket createClient() { ConnectionSetupPayload setupPayload = ConnectionSetupPayload.create("", ""); if ("tcp".equals(uri.getScheme())) { Function<SocketAddress, TcpClient<ByteBuf, ByteBuf>> clientFactory = socketAddress -> TcpClient.newClient(socketAddress); if (debug) clientFactory = socketAddress -> TcpClient.newClient(socketAddress).enableWireLogging("rs", LogLevel.ERROR); return toObservable( TcpReactiveSocketConnector.create(setupPayload, Throwable::printStackTrace, clientFactory) .connect(new InetSocketAddress(uri.getHost(), uri.getPort()))).toSingle() .toBlocking() .value(); } else { throw new UnsupportedOperationException("uri unsupported: " + uri); } }
Source:
<code>public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); <START> } catch (CandybeanException e) { <END> return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }</code><technical_language>multi-catch here</technical_language>

Target:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }
Source:
<code>public boolean isAvailable() { boolean isAvailable = false; if (!lastAvailable || (lastAvailableDate.before( new Date(System.currentTimeMillis() - availabilityPollInterval)))) { Response response = null; try { response = getClientFactory().getWebClient().head(); } catch (Exception e) { LOGGER.debug("Web Client was unable to connect to endpoint.", e); } if (response != null && !(response.getStatus() >= HttpStatus.SC_NOT_FOUND || response.getStatus() == HttpStatus.SC_BAD_REQUEST || response.getStatus() == HttpStatus.SC_PAYMENT_REQUIRED)) { isAvailable = true; lastAvailableDate = new Date(); } } else { isAvailable = lastAvailable; } updateMonitors(isAvailable); <START> lastAvailable = isAvailable; <END> return isAvailable; }</code><technical_language>I concurrency issues lastAvailable lastAvailableDate accessed modified simultaneous threads</technical_language>

Target:
public synchronized boolean isAvailable() { boolean isAvailable = false; if (!lastAvailable || (lastAvailableDate.before( new Date(System.currentTimeMillis() - availabilityPollInterval)))) { Response response = null; try { response = getClientFactory().getWebClient().head(); } catch (Exception e) { LOGGER.debug("Web Client was unable to connect to endpoint.", e); } if (response != null && !(response.getStatus() >= HttpStatus.SC_NOT_FOUND || response.getStatus() == HttpStatus.SC_BAD_REQUEST || response.getStatus() == HttpStatus.SC_PAYMENT_REQUIRED)) { isAvailable = true; lastAvailableDate = new Date(); } } else { isAvailable = lastAvailable; } updateMonitors(isAvailable); lastAvailable = isAvailable; return isAvailable; }
Source:
<code><START> void markDependencySuccess(final DependencyInstanceContext context) { <END> this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to success", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (Status.isDone(depInst.getStatus())) { logger.warn(String.format("OnSuccess of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } processStatusUpdate(depInst, Status.SUCCEEDED); if (depInst.getTriggerInstance().getStatus() == Status.SUCCEEDED) { logger.info(String.format("trigger instance with execId %s succeeded", depInst.getTriggerInstance().getId())); this.triggerProcessor.processSucceed(depInst.getTriggerInstance()); this.runningTriggers.remove(depInst.getTriggerInstance()); } } else { logger.debug(String.format("unable to find trigger instance with context %s when marking " + "it success", context)); } }); }</code><technical_language>mark this public,</technical_language>

Target:
public void markDependencySuccess(final DependencyInstanceContext context) { this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to success", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (Status.isDone(depInst.getStatus())) { logger.warn(String.format("OnSuccess of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } processStatusUpdate(depInst, Status.SUCCEEDED); if (depInst.getTriggerInstance().getStatus() == Status.SUCCEEDED) { logger.info(String.format("trigger instance with execId %s succeeded", depInst.getTriggerInstance().getId())); this.triggerProcessor.processSucceed(depInst.getTriggerInstance()); this.runningTriggers.remove(depInst.getTriggerInstance()); } } else { logger.debug(String.format("unable to find trigger instance with context %s when marking " + "it success", context)); } }); }
Source:
<code>public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { FPlayer playerdata = plugin.pl.getPlayer(playerSender); playerdata.setCommandSpy(!playerdata.cmdspyEnabled()); if (playerdata.cmdspyEnabled() == true) { plugin.al.setCommandSpyActive(true, playerSender); <START> } else <END> { plugin.al.setCommandSpyActive(false, playerSender); } msg("CommandSpy " + (playerdata.cmdspyEnabled() ? "enabled." : "disabled.")); return true; }</code><technical_language>else next line</technical_language>

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { Admin admin = getAdmin(playerSender); FPlayer playerdata = plugin.pl.getPlayer(playerSender); playerdata.setCommandSpy(!playerdata.cmdspyEnabled()); if (playerdata.cmdspyEnabled()) { admin.setCommandSpy(true); } else { admin.setCommandSpy(false); } msg("CommandSpy " + (playerdata.cmdspyEnabled() ? "enabled." : "disabled.")); return true; }
Source:
<code>public void force_shutdown_after_timeout() throws InterruptedException { final ExecutorService service = Executors.newSingleThreadExecutor(); service.submit(this::sleep); final long beginShutdownTime = System.currentTimeMillis(); this.executorServiceUtils.gracefulShutdown(service, Duration.ofMillis(1)); final long endShutdownTime = System.currentTimeMillis(); assertThat(service.isShutdown()).isTrue(); final long shutdownDuration = endShutdownTime - beginShutdownTime; <START> assertThat(shutdownDuration).isLessThan(100); <END> }</code><technical_language>milliseconds? 100 would've sleep time stabilize some flaky unit tests Travis builds suffer random slowdowns. 1 enough sometimes. If me, remove this assertion if set guaranteed high enough, 10 seconds</technical_language>

Target:
public void force_shutdown_after_timeout() throws InterruptedException { final ExecutorService service = Executors.newSingleThreadExecutor(); service.submit(this::sleep); final long beginShutdownTime = System.currentTimeMillis(); this.executorServiceUtils.gracefulShutdown(service, Duration.ofMillis(1)); final long endShutdownTime = System.currentTimeMillis(); assertThat(service.isShutdown()).isTrue(); assertThat(this.isTestThreadInterrupted).isTrue(); final long shutdownDuration = endShutdownTime - beginShutdownTime; assertThat(shutdownDuration).isLessThan(1000); }
Source:
<code>private void parseApiKey(String key, String value) throws ConfigurationException { if (value == null) { logger.warn("Weather apikey setting '{}' has no value. Check openhab.cfg.", key); return; } String provider = PropertyResolver.last(key); ProviderName providerName = getProviderName(provider); ProviderConfig pConfig = providerConfigs.get(providerName); if (pConfig == null) { pConfig = new ProviderConfig(); pConfig.setProviderName(providerName); providerConfigs.put(providerName, pConfig); } String keyId = PropertyResolver.first(key); if (StringUtils.equalsIgnoreCase(keyId, "apikey")) { pConfig.setApiKey(value); } else if (StringUtils.equalsIgnoreCase(keyId, "apikey2")) { pConfig.setApiKey2(value); } else { <START> logger.debug("Unknown configuration key '{}'. Check openhab.cfg.", key); <END> } }</code><technical_language>debug warn</technical_language>

Target:
private void parseApiKey(String key, String value) throws ConfigurationException { if (value == null) { logger.warn("Weather apikey setting '{}' has no value. Check openhab.cfg.", key); return; } String provider = PropertyResolver.last(key); ProviderName providerName = getProviderName(provider); ProviderConfig pConfig = providerConfigs.get(providerName); if (pConfig == null) { pConfig = new ProviderConfig(); pConfig.setProviderName(providerName); providerConfigs.put(providerName, pConfig); } String keyId = PropertyResolver.first(key); if (StringUtils.equalsIgnoreCase(keyId, "apikey")) { pConfig.setApiKey(value); } else if (StringUtils.equalsIgnoreCase(keyId, "apikey2")) { pConfig.setApiKey2(value); } else { logger.warn("Unknown configuration key '{}'. Check openhab.cfg.", key); } }
Source:
<code>public final void handleMessage(Message<?> message) { Assert.notNull(message, "Message must not be null"); Assert.notNull(message.getPayload(), "Message payload must not be null"); if (this.logger.isDebugEnabled()) { this.logger.debug(this + " received message: " + message); } long start = 0; try { if (message != null && this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } if (this.countsEnabled) { <START> this.handlerMetrics.beforeHandle(message); <END> } this.handleMessageInternal(message); this.handlerMetrics.afterHandle(start, true); } catch (Exception e) { this.handlerMetrics.afterHandle(start, false); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageHandlingException(message, "error occurred in message handler [" + this + "]", e); } }</code><technical_language>start adjusted System.currentTimeMillis() here. in SimpleMessageHandlerMetrics this.duration.append(System.currentTimeMillis() - 0); is big :smile:</technical_language>

Target:
public final void handleMessage(Message<?> message) { Assert.notNull(message, "Message must not be null"); Assert.notNull(message.getPayload(), "Message payload must not be null"); if (this.logger.isDebugEnabled()) { this.logger.debug(this + " received message: " + message); } long start = 0; try { if (message != null && this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } if (this.countsEnabled) { start = this.handlerMetrics.beforeHandle(message); } this.handleMessageInternal(message); this.handlerMetrics.afterHandle(start, true); } catch (Exception e) { this.handlerMetrics.afterHandle(start, false); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageHandlingException(message, "error occurred in message handler [" + this + "]", e); } }
Source:
<code><START> private void createCommandHandler(String handlerClassName) throws ExecutorException { <END> commandHandlers.add((CommandHandler) createInstance(handlerClassName)); }</code><technical_language>Throwing a ExecutorException appropriate</technical_language>

Target:
private void createCommandHandler(String handlerClassName) throws CommandHandlerException { try { commandHandlers.add((CommandHandler) createInstance(handlerClassName)); } catch (ClassCastException e) { String errMsg = String.format("Error trying to cast Object of class %s to CommandHandler", handlerClassName); LOG.error(errMsg); throw new CommandHandlerException(errMsg, e); } catch (Exception e) { LOG.error(e.getMessage()); throw new CommandHandlerException(e); } }
Source:
<code>public Scheduler(Schedulable singleThreadEntryValve, SiddhiAppContext siddhiAppContext) { this.threadBarrier = siddhiAppContext.getThreadBarrier(); this.siddhiAppContext = siddhiAppContext; this.singleThreadEntryValve = singleThreadEntryValve; this.scheduledExecutorService = siddhiAppContext.getScheduledExecutorService(); this.eventCaller = new EventCaller(); mutex = new Semaphore(1); <START> (siddhiAppContext.getTimestampGenerator()) <END> .addTimeChangeListener(new TimestampGenerator.TimeChangeListener() { @Override public void onTimeChange(long currentTimestamp) { Long lastTime = toNotifyQueue.peek(); if (lastTime != null && lastTime <= currentTimestamp) { sendTimerEvents(); } } }); }</code><technical_language>()</technical_language>

Target:
public Scheduler(Schedulable singleThreadEntryValve, SiddhiAppContext siddhiAppContext) { this.threadBarrier = siddhiAppContext.getThreadBarrier(); this.siddhiAppContext = siddhiAppContext; this.singleThreadEntryValve = singleThreadEntryValve; this.scheduledExecutorService = siddhiAppContext.getScheduledExecutorService(); this.eventCaller = new EventCaller(); mutex = new Semaphore(1); siddhiAppContext.getTimestampGenerator() .addTimeChangeListener(new TimestampGenerator.TimeChangeListener() { @Override public void onTimeChange(long currentTimestamp) { Long lastTime = toNotifyQueue.peek(); if (lastTime != null && lastTime <= currentTimestamp) { sendTimerEvents(); } } }); }
Source:
<code>protected void checkRemainingProperties(Set<String> missingProperties, List<String> availableProperties, String path, Class<?> clazz) { Properties properties = System.getProperties(); List<String> cleanNames = missingProperties.stream() .filter(propertyName -> !isPolymorphicType(clazz) || !polymorphicTypes.stream().anyMatch(type -> Objects.equals(type.getTypePath(), propertyName))) .map(propertyName -> toPath(path, propertyName)) .filter(propertyName -> !properties.containsKey(propertyName)) <START> .filter(propertyName -> new HashSet<>(properties.entrySet()).stream().noneMatch(entry -> entry.getKey().toString().startsWith(propertyName + "."))) <END> .sorted() .collect(Collectors.toList()); if (!cleanNames.isEmpty()) { throw new ConfigurationException("Unknown properties present in configuration: " + Joiner.on(", ").join(cleanNames) + "\n" + "Available properties:\n- " + Joiner.on("\n- ").join(availableProperties)); } }</code><technical_language>properties is accessed in filter call above, sense making a new Properties above? eg.. java Properties localProperties = new Properties(); localProperties.putAll(System.getProperties());</technical_language>

Target:
protected void checkRemainingProperties(Set<String> missingProperties, List<String> availableProperties, String path, Class<?> clazz) { Properties properties = new Properties(); properties.putAll(System.getProperties()); List<String> cleanNames = missingProperties.stream() .filter(propertyName -> !isPolymorphicType(clazz) || !polymorphicTypes.stream().anyMatch(type -> Objects.equals(type.getTypePath(), propertyName))) .map(propertyName -> toPath(path, propertyName)) .filter(propertyName -> !properties.containsKey(propertyName)) .filter(propertyName -> properties.entrySet().stream().noneMatch(entry -> entry.getKey().toString().startsWith(propertyName + "."))) .sorted() .collect(Collectors.toList()); if (!cleanNames.isEmpty()) { throw new ConfigurationException("Unknown properties present in configuration: " + Joiner.on(", ").join(cleanNames) + "\n" + "Available properties:\n- " + Joiner.on("\n- ").join(availableProperties)); } }
Source:
<code>protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
<code>public static void getMRandYarn(MetadataExtractor extractor, String marker){ <START> Iterable<Map<String, Object>> yarnOperationEntities = extractor.extractMetadata(marker, <END> "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", null).getEntities(); getFirstResult(yarnOperationEntities); List<String> sourceTypes = Lists.newArrayList("MAPREDUCE", "YARN"); List<String> types = Lists.newArrayList("OPERATION EXECUTION"); String entityQuery = ClientUtils.buildQuery(sourceTypes, types); Iterable<Map<String, Object>> yarnOperationEntities2 = extractor.extractMetadata(marker, entityQuery, "").getEntities(); getFirstResult(yarnOperationEntities2); Iterable<Map<String, Object>> yarnOperationRelations = extractor.extractMetadata(marker, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", "type:DATA_FLOW " + "AND endpoint1SourceType:HDFS OR endpoint2SourceType:HDFS").getRelations(); getFirstResult(yarnOperationRelations); }</code><technical_language>80 characters line please (<LINK_0></technical_language>

Target:
public static String getMRandYarn(MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> yarnOpEntities = extractor.extractMetadata( marker, null, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", null).getEntities(); getFirstResult(yarnOpEntities); List<String> sourceTypes = Lists.newArrayList("MAPREDUCE", "YARN"); List<String> types = Lists.newArrayList("OPERATION EXECUTION"); String entityQuery = ClientUtils.buildQuery(sourceTypes, types); Iterable<Map<String, Object>> yarnOpEntities2 = extractor.extractMetadata( marker, null, entityQuery, "").getEntities(); getFirstResult(yarnOpEntities2); MetadataResultSet yarnOp = extractor.extractMetadata( marker, null, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", "type:DATA_FLOW AND endpoint1SourceType:HDFS OR endpoint2SourceType:HDFS"); Iterable<Map<String, Object>> yarnOpRelations = yarnOp.getRelations(); getFirstResult(yarnOpRelations); return yarnOp.getMarker(); }
Source:
<code>public void hsbHueAlwaysGreaterThanZeroAndLessThan360() { final State lightState = new State(); <START> lightState.colormode = ColorMode.CT.toString(); <END> for (int hue = 0; hue <= 65535; ++hue) { lightState.hue = hue; assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() >= 0); assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() < 360); } }</code><technical_language>want ColorMode.HS.toString() in this case - is default do need set it</technical_language>

Target:
public void hsbHueAlwaysGreaterThanZeroAndLessThan360() { final State lightState = new State(); for (int hue = 0; hue <= 65535; ++hue) { lightState.hue = hue; assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() >= 0); assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() < 360); } }
Source:
<code>public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException{ Variable v = symbolTable.get(identifier); if(v == null){ if(parentScope == null){ throw new VariableNotDefinedException(identifier); } <START> return parentScope.getVariable(identifier); <END> }else{ return v; } }</code><technical_language>Throw this in else clause</technical_language>

Target:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException { Variable v = symbolTable.get(identifier); if (v == null) { if (parentScope == null) { throw new VariableNotDefinedException(identifier); } else { return parentScope.getVariable(identifier); } } else { return v; } }
Source:
<code>public void queryDepartures() throws Exception { <START> final QueryDeparturesResult result = queryDepartures("NA190", false); <END> print(result); }</code><technical_language>Is a valid station ID? Judging results of nearby stations, station IDs prefixed OAW:SP:</technical_language>

Target:
public void queryDepartures() throws Exception { final QueryDeparturesResult result = queryDepartures("OAW:SP:CH240", false); print(result); }
Source:
<code>public Response install(Action action) { <START> VDS vds = getEntity(); <END> UpdateVdsActionParameters params = new UpdateVdsActionParameters(vds.getStaticData(), action.getRootPassword(), true); if (action.isSetSsh()) { if (action.getSsh().isSetUser()) { if (action.getSsh().getUser().isSetPassword()) { params.setRootPassword(action.getSsh().getUser().getPassword()); } } if (action.getSsh().isSetPort()) { params.getvds().setSshPort(action.getSsh().getPort().intValue()); } if (action.getSsh().isSetFingerprint()) { params.getvds().setSshKeyFingerprint(action.getSsh().getFingerprint()); } if (action.getSsh().isSetAuthenticationMethod()) { AuthenticationMethod m = getMapper(String.class, AuthenticationMethod.class). map(action.getSsh().getAuthenticationMethod(), null); if (m != null) { params.setAuthMethod( getMapper(AuthenticationMethod.class, org.ovirt.engine.core.common.action.VdsOperationActionParameters.AuthenticationMethod.class).map(m, null)); } } } if (vds.getVdsType()==VDSType.oVirtNode) { params.setIsReinstallOrUpgrade(true); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } } else { validateParameters(action, "rootPassword"); } return doAction(VdcActionType.UpdateVds, params, action); }</code><technical_language>call validateEnums missing</technical_language>

Target:
public Response install(Action action) { VDS vds = getEntity(); validateEnums(Action.class, action); UpdateVdsActionParameters params = new UpdateVdsActionParameters(vds.getStaticData(), action.getRootPassword(), true); params = (UpdateVdsActionParameters) getMapper (Action.class, VdsOperationActionParameters.class).map(action, (VdsOperationActionParameters) params); if (vds.getVdsType()==VDSType.oVirtNode) { params.setIsReinstallOrUpgrade(true); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } } else { validateParameters(action, "rootPassword"); } return doAction(VdcActionType.UpdateVds, params, action); }
Source:
<code>public NamespaceHandler(HttpHandler containerHandler) { log.info("Creating NamespaceHandler"); this.containerHandler = containerHandler; try { this.token = getToken(); log.info("Received token from " + TOKEN_FILE_LOCATION); } catch (Exception e){ <START> log.info("Error retrieving token from file " + TOKEN_FILE_LOCATION); <END> throw new RuntimeException(e); } namespaceListener = new NamespaceListener(token); NamespaceOverrideMapper nom = new NamespaceOverrideMapper(token); log.info("Received namespace overrides: " + nom.overrides); this.projectOverwrites = nom.overrides; }</code><technical_language>log.error</technical_language>

Target:
public NamespaceHandler(HttpHandler containerHandler) { log.info("Creating NamespaceHandler"); this.containerHandler = containerHandler; try { this.token = getToken(); log.info("Received token from " + TOKEN_FILE_LOCATION); } catch (Exception e){ log.error("Error retrieving token from file " + TOKEN_FILE_LOCATION); throw new RuntimeException(e); } namespaceListener = new NamespaceListener(token); NamespaceOverrideMapper nom = new NamespaceOverrideMapper(token); log.info("Received namespace overrides: " + nom.overrides); this.projectOverwrites = nom.overrides; }