auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static boolean attemptToCreateKeyspace(CassandraKeyValueServiceConfig config) throws InvalidRequestException { for (InetSocketAddress host : config.servers()) { try { if (!keyspaceAlreadyExists(host, config)) { attemptToCreateKeyspaceOnHost(host, config); } return true; } catch (InvalidRequestException ire) { if (attemptedToCreateKeyspaceTwice(ire)) { return true; } else { throw ire; } } catch (Exception exception) { <START> log.warn("Couldn't use host to of keyspace." <END> + " It returned exception \"{}\" during the attempt." + " We will retry on other nodes, so this shouldn't be a problem unless all nodes failed." + " See the debug-level log for the stack trace.", SafeArg.of("host", CassandraLogHelper.host(host)), UnsafeArg.of("exceptionMessage", exception.toString())); log.debug("Specifically, creating the keyspace failed with the following stack trace", exception); } } return false; }</code><technical_language>more unintended ofs - yeah this is a problem renaming methods named common English words</technical_language>

Target:
private static boolean attemptToCreateKeyspace(CassandraKeyValueServiceConfig config) throws InvalidRequestException { for (InetSocketAddress host : config.servers()) { try { if (!keyspaceAlreadyExists(host, config)) { attemptToCreateKeyspaceOnHost(host, config); } return true; } catch (InvalidRequestException ire) { if (attemptedToCreateKeyspaceTwice(ire)) { return true; } else { throw ire; } } catch (Exception exception) { log.warn("Couldn't use host to create keyspace." + " It returned exception \"{}\" during the attempt." + " We will retry on other nodes, so this shouldn't be a problem unless all nodes failed." + " See the debug-level log for the stack trace.", SafeArg.of("host", CassandraLogHelper.host(host)), UnsafeArg.of("exceptionMessage", exception.toString())); log.debug("Specifically, creating the keyspace failed with the following stack trace", exception); } } return false; }
Source:
<code>public CharSequence getSym(int col) { <START> return reader.getSymbolMapReader(columnIndex).valueOf(recordIndex); <END> }</code><technical_language>missed a spot</technical_language>

Target:
public CharSequence getSym(int col) { return symbolMapReader.valueOf(recordIndex); }
Source:
<code>public void evaluate_shouldReturnAllPatientsCurrentlyActiveOnDrugs() throws Exception { cohortDefinition.setOnlyCurrentlyActive(true); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); <START> System.out.println("Currently on Drugs " + cohort.getMemberIds() + " " + cohortDefinition + "==="); <END> }</code><technical_language>a this? <LINK_0></technical_language>

Target:
public void evaluate_shouldReturnAllPatientsCurrentlyActiveOnDrugs() throws Exception { cohortDefinition.setOnlyCurrentlyActive(true); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(21)); Assert.assertTrue(cohort.contains(22)); Assert.assertEquals(3, cohort.size()); }
Source:
<code>public void execute(Tuple input) { byte[] bytes = input.getBinaryByField("bytes"); try { IotasMessage iotasMessage = objectMapper.readValue(new String(bytes, StandardCharsets.UTF_8), IotasMessage.class); Parser parser = getParser(iotasMessage); Map<String, Object> parsed = parser.parse(iotasMessage.getData()); Values values = new Values(); for(String s: parsed.keySet()) { <START> System.out.print("\"" + s + "\","); <END> } System.out.println(); for (String str : outputFields) { values.add(parsed.get(str)); } collector.emit(input, values); collector.ack(input); } catch (Exception e) { collector.fail(input); collector.reportError(e); } }</code><technical_language>is parseFileds method do this in a single line. values.addAll(parser.parseFields(iotasMessage.getData())</technical_language>

Target:
public void execute(Tuple input) { byte[] bytes = input.getBinaryByField("bytes"); Parser parser = null; try { if (parserId == null) { IotasMessage iotasMessage = objectMapper.readValue(new String(bytes, StandardCharsets.UTF_8), IotasMessage.class); parser = getParser(iotasMessage); bytes = iotasMessage.getData(); } else { parser = getParser(parserId); } Map<String, Object> parsed = parser.parse(bytes); Values values = new Values(parsed); collector.emit(input, values); collector.ack(input); } catch (Exception e) { collector.fail(input); collector.reportError(e); } }
Source:
<code>private ArrayList<SingleRecyclerViewLocation> setUpLists() { locationList = new ArrayList<>(); LatLng[] coordinates = new LatLng[] { new LatLng(-34.6054099, -58.363654800000006), new LatLng(-34.6041508, -58.38555650000001), new LatLng(-34.6114412, -58.37808899999999), new LatLng(-34.6097604, -58.382064000000014), new LatLng(-34.596636, -58.373077999999964), new LatLng(-34.590548, -58.38256609999996), new LatLng(-34.5982127, -58.38110440000003) }; <START> for (int x = 0; x < 7; x++) { <END> SingleRecyclerViewLocation singleLocation = new SingleRecyclerViewLocation(); singleLocation.setName(String.format(getString(R.string.rv_card_name), x)); singleLocation.setBedInfo(String.format(getString(R.string.rv_card_bed_info), x)); singleLocation.setLocationCoordinates(coordinates[x]); locationList.add(singleLocation); mapboxMap.addMarker(new MarkerOptions() .position(coordinates[x]) .title(String.format(getString(R.string.rv_card_name), x)) .snippet(String.format(getString(R.string.rv_card_bed_info), x))); mapboxMap.setOnMarkerClickListener(this); } return locationList; }</code><technical_language>coordinates.length instead of 7</technical_language>

Target:
private ArrayList<SingleRecyclerViewLocation> setUpLists() { locationList = new ArrayList<>(); LatLng[] coordinates = new LatLng[] { new LatLng(-34.6054099, -58.363654800000006), new LatLng(-34.6041508, -58.38555650000001), new LatLng(-34.6114412, -58.37808899999999), new LatLng(-34.6097604, -58.382064000000014), new LatLng(-34.596636, -58.373077999999964), new LatLng(-34.590548, -58.38256609999996), new LatLng(-34.5982127, -58.38110440000003) }; for (int x = 0; x < coordinates.length; x++) { SingleRecyclerViewLocation singleLocation = new SingleRecyclerViewLocation(); singleLocation.setName(String.format(getString(R.string.rv_card_name), x)); singleLocation.setBedInfo(String.format(getString(R.string.rv_card_bed_info), x)); singleLocation.setLocationCoordinates(coordinates[x]); locationList.add(singleLocation); mapboxMap.addMarker(new MarkerOptions() .position(coordinates[x]) .title(String.format(getString(R.string.rv_card_name), x)) .snippet(String.format(getString(R.string.rv_card_bed_info), x))); mapboxMap.setOnMarkerClickListener(this); } return locationList; }
Source:
<code>public Exchange createDbzExchange(final SourceRecord record) { final Exchange exchange = super.createExchange(); final Message message = exchange.getIn(); message.setHeader(DebeziumConstants.FIELD_IDENTIFIER, record.topic()); message.setHeader(DebeziumConstants.FIELD_KEY, record.key()); message.setHeader(DebeziumConstants.FIELD_SOURCE, record.sourceOffset()); setOperationFieldInHeader(message, record.valueSchema(), record.value()); <START> message.setBody(record.value()); <END> return exchange; }</code><technical_language>a general question: IIUC, pass original type of change event (i.e. Struct obtained SourceRecord); wondering a good idea, exposes Kafka Connect specific types Camel route, desirable. said, Camel expert, I idea types messages typically represented. If is hash maps basically, do following: * create a Map fields of "after" Structfrom SourceRecords this message body * create a Map fields SourceRecords key propagate this message header (assuming maps there) * pass op, ts values source struct header properties * create a Map fields of "before" Structfrom SourceRecords pass this a message header way, message body a map new row column values (or null/empty map in case of a "d" event), *may* messages easier handle existing Camel sinks. Alternatively, create a nested structure "before"/"after" propagate other headers (that kind of mapping is currently consider for CloudEvents). another solution convert entire Debezium event envelope a JSON structure. Again, what'd work in terms of Camel's conventions/expectations, exposing Kafka Connect types ideal. a good idea do some integration testing / PoC of sorts selected consumers (at JDBC sink), get a feeling of useful</technical_language>

Target:
public Exchange createDbzExchange(final SourceRecord record) { final Exchange exchange = super.createExchange(); final Message message = exchange.getIn(); final Schema valueSchema = record.valueSchema(); final Object value = record.value(); final Map<String, Object> sourceMetadata = extractSourceMetadataValueFromValueStruct(valueSchema, value); final Object operation = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.OPERATION); final Object before = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.BEFORE); final Object after = extractAfterValueFromValueStruct(valueSchema, value); final Object timestamp = extractValueFromValueStruct(valueSchema, value, Envelope.FieldName.TIMESTAMP); message.setHeader(DebeziumConstants.HEADER_IDENTIFIER, record.topic()); message.setHeader(DebeziumConstants.HEADER_KEY, record.key()); message.setHeader(DebeziumConstants.HEADER_SOURCE_METADATA, sourceMetadata); message.setHeader(DebeziumConstants.HEADER_OPERATION, operation); message.setHeader(DebeziumConstants.HEADER_BEFORE, before); message.setHeader(DebeziumConstants.HEADER_TIMESTAMP, timestamp); message.setBody(after); return exchange; }
Source:
<code>private String formatPageName(String pageName) { if (pageName.startsWith("/")) { <START> return pageName.substring(1, pageName.length()).toLowerCase(Locale.ENGLISH); <END> } else { return pageName.toLowerCase(Locale.ENGLISH); } }</code><technical_language>Fortify complain comparing. stick default toLowerCase "local.english". need check comparing equalIgnoreCase local.english. Check checkConfiguredDisplay() method "constant".equalIgnoreCase("stringtocompare")</technical_language>

Target:
private String formatPageName(String pageName) { if (pageName.startsWith("/")) { return pageName.substring(1, pageName.length()).toLowerCase(); } else { return pageName.toLowerCase(); } }
Source:
<code>public synchronized String process(final Integer key, final String message) { LOG.log(Level.INFO, "{0}-th iteration, message : {1}", new Object[]{key, message}); if (!counterMap.containsKey(key)) { counterMap.put(key, new AtomicInteger(0)); } final AtomicInteger counter = counterMap.get(key); switch (message) { case SynchronizationTestWorker.BEFORE_BARRIER_MSG: if (counter.get() < 0) { killEvaluatorWithMessage("A BEFORE_BARRIER_MSG in " + key + "-th iteration has arrived after a AFTER_BARRIER_MSG for the iteration"); } else { counter.incrementAndGet(); } break; case SynchronizationTestWorker.AFTER_BARRIER_MSG: if (counter.get() > 0) { counter.set(-counter.get()); } <START> <END> counter.incrementAndGet(); break; default: killEvaluatorWithMessage("Illegal message : " + message); } return message; }</code><technical_language>Inconsistent line breaks</technical_language>

Target:
public synchronized String process(final Integer key, final String message) { if (message.equals(SynchronizationTestWorker.FINAL_MSG)) { checkCounters(); return message; } LOG.log(Level.INFO, "{0}-th iteration, message : {1}", new Object[]{key, message}); if (!beforeMsgCounterMap.containsKey(key)) { beforeMsgCounterMap.put(key, 0); afterMsgCounterMap.put(key, 0); } switch (message) { case SynchronizationTestWorker.BEFORE_BARRIER_MSG: if (afterMsgCounterMap.get(key) > 0) { killEvaluatorWithMessage("A BEFORE_BARRIER_MSG in " + key + "-th iteration should not arrive after a AFTER_BARRIER_MSG for the iteration"); } else { beforeMsgCounterMap.put(key, beforeMsgCounterMap.get(key) + 1); } break; case SynchronizationTestWorker.AFTER_BARRIER_MSG: afterMsgCounterMap.put(key, afterMsgCounterMap.get(key) + 1); break; default: killEvaluatorWithMessage("Illegal message : " + message); } return message; }
Source:
<code>public List<String> getPushOptions() { <START> if (pushOptions == null) { <END> return null; } return Collections.unmodifiableList(pushOptions); }</code><technical_language>interesting cases here. If caller call setAllowPushOptions(true), advertise get push options pushOptions is null. detect this case checking allowPushOptions variable directly. caller responsible for setting true, if turn call getPushOptions(), confused. a good time throw IllegalStateException(). If caller call setAllowPushOptions client support push options, pushOptions is null. This is analogous C git hooks --- Git sets GIT_PUSH_OPTION_COUNT envvar 0 client supported push options set envvar client support push options. This method behave similarly @Nullable, do here. If I called setAllowPushOptions(true) called receive() yet, enabledCapabilities null. This is another case client is confused. a good time throw RequestNotYetReadException</technical_language>

Target:
public List<String> getPushOptions() { if (allowPushOptions) { if (enabledCapabilities == null) { throw new RequestNotYetReadException(); } return pushOptions == null ? null : Collections.unmodifiableList(pushOptions); } else { throw new IllegalStateException(); } }
Source:
<code>private final static void simpleJsonResponse(String jsonp, String message, HttpServletResponse rsp, int code) { ClientResponseImpl rimpl = new ClientResponseImpl( ClientResponse.UNEXPECTED_FAILURE, new VoltTable[0], message); String msg = rimpl.toJSONString(); if (jsonp != null) { msg = asJsonp(jsonp, msg); } rsp.setStatus(code); try { rsp.getWriter().print(msg); rsp.getWriter().flush(); } catch (IOException e) { <START> } <END> }</code><technical_language>swallow</technical_language>

Target:
private final static void simpleJsonResponse(String jsonp, String message, HttpServletResponse rsp, int code) { ClientResponseImpl rimpl = new ClientResponseImpl( ClientResponse.UNEXPECTED_FAILURE, new VoltTable[0], message); String msg = rimpl.toJSONString(); if (jsonp != null) { msg = asJsonp(jsonp, msg); } rsp.setStatus(code); try { rsp.getWriter().print(msg); rsp.getWriter().flush(); } catch (IOException ignoreThisAsBrowserMustHaveClosed) { } }
Source:
<code>private void updateSubscribers(final Branch.NameKey updatedBranch, final ObjectId mergedCommit, final String msg) { try { final List<Subscription> subscribers = schema.subscriptions().getSubscribers(updatedBranch).toList(); if (!subscribers.isEmpty()) { final StringBuilder msgbuf = new StringBuilder(); if (msg == null) { <START> updatedSubscribers = new ArrayList<String>(); <END> updatedSubscribers.add(updatedBranch.toString()); for (final Change chg : submitted) { final CodeReviewCommit c = commits.get(chg.getId()); if (c != null && (c.statusCode == CommitMergeStatus.CLEAN_MERGE || c.statusCode == CommitMergeStatus.CLEAN_PICK)) { msgbuf.append("\n"); msgbuf.append(c.getFullMessage()); } } } else { msgbuf.append(msg); } if (msgbuf.length() > 0) { for (final Subscription s : subscribers) { if (updatedSubscribers.contains(s.getSubscriber().toString())) { log.error("Possible circular subscription involving " + s.toString()); } else { Map<Branch.NameKey, ObjectId> modules = new HashMap<Branch.NameKey, ObjectId>(1); modules.put(updatedBranch, mergedCommit); updateGitlinks(s.getSubscriber(), modules, msgbuf.toString()); updatedSubscribers.add(s.getSubscriber().toString()); } } } } } catch (OrmException e) { log.error("Cannot read subscription records", e); } }</code><technical_language>I prefer a HashSet<Branch.NameKey></technical_language>

Target:
private void updateSubscribers(final Branch.NameKey updatedBranch, final ObjectId mergedCommit, final String msg) { try { final List<Subscription> subscribers = schema.subscriptions().getSubscribers(updatedBranch).toList(); if (!subscribers.isEmpty()) { final StringBuilder msgbuf = new StringBuilder(); if (msg == null) { updatedSubscribers = new HashSet<Branch.NameKey>(); updatedSubscribers.add(updatedBranch); for (final Change chg : submitted) { final CodeReviewCommit c = commits.get(chg.getId()); if (c != null && (c.statusCode == CommitMergeStatus.CLEAN_MERGE || c.statusCode == CommitMergeStatus.CLEAN_PICK)) { msgbuf.append("\n"); msgbuf.append(c.getFullMessage()); } } } else { msgbuf.append(msg); } if (msgbuf.length() > 0) { for (final Subscription s : subscribers) { if (updatedSubscribers.contains(s.getSubscriber())) { log.error("Possible circular subscription involving " + s.toString()); } else { Map<Branch.NameKey, ObjectId> modules = new HashMap<Branch.NameKey, ObjectId>(1); modules.put(updatedBranch, mergedCommit); updateGitlinks(s.getSubscriber(), modules, msgbuf.toString()); updatedSubscribers.add(s.getSubscriber()); } } } } } catch (OrmException e) { log.error("Cannot read subscription records", e); } }
Source:
<code>void mapActionItemsToSelection(ISelection selection) { setMoveItemsEnabled(false); if (selection == null || selection.isEmpty()) return; if (selection instanceof IStructuredSelection) { IStructuredSelection structured = (IStructuredSelection) selection; Object obj = structured.getFirstElement(); if (!(obj instanceof PlanElement)) return; PlanElement firstSelectedEntry = (PlanElement) obj; if (structured.size() > 1) { ElementAction type = firstSelectedEntry.getPlanElementAction(); <START> PlanElement entry = null; <END> for (Iterator iterator = structured.iterator(); iterator .hasNext();) { Object selectedObj = iterator.next(); if (!(selectedObj instanceof PlanElement)) continue; entry = (PlanElement) selectedObj; if (type != entry.getPlanElementAction()) { unselectAllActionItemsExecpt(null); break; } } enableMoveButtons(structured, firstSelectedEntry, entry); return; } enableMoveButtons(structured, firstSelectedEntry, firstSelectedEntry); unselectAllActionItemsExecpt(getItemFor(firstSelectedEntry .getPlanElementAction())); } }</code><technical_language>rename "lastSelectedEntry" (keeping "entry" name in for loop)</technical_language>

Target:
void mapActionItemsToSelection(ISelection selection) { setMoveItemsEnabled(false); if (selection == null || selection.isEmpty()) return; if (selection instanceof IStructuredSelection) { IStructuredSelection structured = (IStructuredSelection) selection; Object obj = structured.getFirstElement(); if (!(obj instanceof PlanElement)) return; PlanElement firstSelectedEntry = (PlanElement) obj; PlanElement lastSelectedEntry = firstSelectedEntry; if (structured.size() > 1) { ElementAction type = firstSelectedEntry.getPlanElementAction(); for (Iterator iterator = structured.iterator(); iterator .hasNext();) { Object selectedObj = iterator.next(); if (!(selectedObj instanceof PlanElement)) continue; PlanElement entry = lastSelectedEntry = (PlanElement) selectedObj; if (type != entry.getPlanElementAction()) { unselectAllActionItemsExecpt(null); } } } else { unselectAllActionItemsExecpt(getItemFor(firstSelectedEntry .getPlanElementAction())); } enableMoveButtons(firstSelectedEntry, lastSelectedEntry); } }
Source:
<code><START> private String getReservedId() { <END> final IPentahoSession session = PentahoSessionHolder.getSession(); final IJobIdGenerator iJobIdGenerator = PentahoSystem.get( IJobIdGenerator.class ); final String failover = UUID.randomUUID().toString(); final String precomputedId = getRequestParameters().getStringParameter( RESERVED_ID, failover ); UUID uuid = null; try { uuid = UUID.fromString( precomputedId ); } catch ( final IllegalArgumentException e ) { logger.warn( "Wrong uuid came from client side: ", e ); } if ( session != null && iJobIdGenerator != null && iJobIdGenerator.acquire( session, uuid ) ) { return precomputedId; } return failover; }</code><technical_language>This easily a UUID returning function</technical_language>

Target:
private UUID getReservedId() throws IllegalStateException { final IJobIdGenerator iJobIdGenerator = PentahoSystem.get( IJobIdGenerator.class ); final UUID failover = UUID.randomUUID(); final String precomputedId = getRequestParameters().getStringParameter( RESERVED_ID, failover.toString() ); final UUID uuid; try { uuid = UUID.fromString( precomputedId ); } catch ( final IllegalArgumentException e ) { logger.warn( "Wrong uuid came from client side: ", e ); return failover; } if ( iJobIdGenerator != null && iJobIdGenerator.acquire( userSession, uuid ) ) { return uuid; } return failover; }
Source:
<code>private Schedule scheduleAround(Broadcast broadcast, Set<Publisher> publishers) { Duration shortBroadcastFlexibility = Duration.standardMinutes(2); Duration broadcastPeriod = new Duration( broadcast.getTransmissionTime(), broadcast.getTransmissionEndTime() ); DateTime start = broadcast.getTransmissionTime().minus(flexibility); DateTime end = broadcast.getTransmissionEndTime().plus(flexibility); <START> if (broadcastPeriod.compareTo(new Duration(600000)) < 0) { <END> start = broadcast.getTransmissionTime().minus(shortBroadcastFlexibility); end = broadcast.getTransmissionEndTime().plus(shortBroadcastFlexibility); } Maybe<Channel> channel = channelResolver.fromUri(broadcast.getBroadcastOn()); if (channel.hasValue()) { return resolver.unmergedSchedule( start, end, ImmutableSet.of(channel.requireValue()), publishers ); } return null; }</code><technical_language>Duration.standardMinutes(10)</technical_language>

Target:
private Schedule scheduleAround(Broadcast broadcast, Set<Publisher> publishers) { Duration shortBroadcastFlexibility = Duration.standardMinutes(2); Duration broadcastPeriod = new Duration( broadcast.getTransmissionTime(), broadcast.getTransmissionEndTime() ); DateTime start = broadcast.getTransmissionTime().minus(flexibility); DateTime end = broadcast.getTransmissionEndTime().plus(flexibility); if (broadcastPeriod.compareTo(SHORT_CONTENT_REDUCED_TIME_FLEXIBILITY) < 0) { start = broadcast.getTransmissionTime().minus(shortBroadcastFlexibility); end = broadcast.getTransmissionEndTime().plus(shortBroadcastFlexibility); } Maybe<Channel> channel = channelResolver.fromUri(broadcast.getBroadcastOn()); if (channel.hasValue()) { return resolver.unmergedSchedule( start, end, ImmutableSet.of(channel.requireValue()), publishers ); } return null; }
Source:
<code>public void acceptsCorrectContentTypeRequest() throws IOException { final Take consumes = new TkConsumes( new TkFixed(new RsJSON(new RsEmpty())), "application/json" ); final Response response = consumes.act( new RqFake( Arrays.asList( "GET /?TkConsumes", "Content-Type: application/json" ), "" ) ); MatcherAssert.assertThat( new RsPrint(response).print(), <START> Matchers.equalTo( <END> Joiner.on("\r\n").join( "HTTP/1.1 200 OK", "Content-Type: application/json", "", "" ) ) ); }</code><technical_language>Matcher.startWith avoid joining 2 empty strings</technical_language>

Target:
public void acceptsCorrectContentTypeRequest() throws IOException { final Take consumes = new TkConsumes( new TkFixed(new RsJSON(new RsEmpty())), "application/json" ); final Response response = consumes.act( new RqFake( Arrays.asList( "GET /?TkConsumes", "Content-Type: application/json" ), "" ) ); MatcherAssert.assertThat( new RsPrint(response).print(), Matchers.startsWith( Joiner.on("\r\n").join( "HTTP/1.1 200 OK", "Content-Type: application/json" ) ) ); }
Source:
<code>private InputStream locateStream(String path) throws FileNotFoundException { if (path.startsWith("classpath:")) { <START> if (path.startsWith("classpath:")) { <END> path = path.replaceFirst("classpath:", ""); } InputStream resultStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); if (resultStream == null) { resultStream = getClass().getResourceAsStream(path); } if (resultStream == null) { throw new IllegalArgumentException("Classpath resource " + path + " not found for MicroProfile Rest Client SSL configuration"); } return resultStream; } else { if (path.startsWith("file:")) { path = path.replaceFirst("file:", ""); } File certificateFile = new File(path); if (!certificateFile.isFile()) { throw new IllegalArgumentException("Certificate file: " + path + " not found for MicroProfile Rest Client SSL configuration"); } return new FileInputStream(certificateFile); } }</code><technical_language>Duplicated check? ;-)</technical_language>

Target:
private InputStream locateStream(String path) throws FileNotFoundException { if (path.startsWith("classpath:")) { path = path.replaceFirst("classpath:", ""); InputStream resultStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); if (resultStream == null) { resultStream = getClass().getResourceAsStream(path); } if (resultStream == null) { throw new IllegalArgumentException("Classpath resource " + path + " not found for MicroProfile Rest Client SSL configuration"); } return resultStream; } else { if (path.startsWith("file:")) { path = path.replaceFirst("file:", ""); } File certificateFile = new File(path); if (!certificateFile.isFile()) { throw new IllegalArgumentException("Certificate file: " + path + " not found for MicroProfile Rest Client SSL configuration"); } return new FileInputStream(certificateFile); } }
Source:
<code>public final void initDS() { log.debug("Creating Datasource for " + this.getName()); boolean lazyload = false; String lzString = (String) this.get(DB_LAZY_INIT_MODE_KEY); if (lzString != null) { lazyload = Boolean.parseBoolean(lzString); } if (!lazyload) { Object handles = this.get(DATASOURCE_HANDLES_KEY); Object datasources = this.get(DATASOURCES_KEY); <START> if(handles != null && datasources != null){ <END> log.debug("register DB handles and Datasources"); registerMultipleDatsourceHandles(); registerDatasources(); } Datasource ds = getDatasource(); if (ds != null) { CRDatabaseFactory.releaseDatasource(ds); } } for (int i = 1; i <= getRequestProcessorSize(); i++) { CRConfigUtil requestProcessorConfig = getRequestProcessorConfig(i); requestProcessorConfig.initDS(); } }</code><technical_language>Format! separate handling of handles datasources</technical_language>

Target:
public final void initDS() { log.debug("Creating Datasource for " + this.getName()); boolean lazyload = false; String lzString = (String) this.get(DB_LAZY_INIT_MODE_KEY); if (lzString != null) { lazyload = Boolean.parseBoolean(lzString); } if (!lazyload) { registerDatsourceHandles(); registerDatasources(); Datasource ds = getDatasource(); if (ds != null) { CRDatabaseFactory.releaseDatasource(ds); } } for (int i = 1; i <= getRequestProcessorSize(); i++) { CRConfigUtil requestProcessorConfig = getRequestProcessorConfig(i); requestProcessorConfig.initDS(); } }
Source:
<code>public static ScenarioModifierManifest Deserialize(String fileName) { ScenarioModifierManifest resultingList = null; try { JAXBContext context = JAXBContext.newInstance(ScenarioModifierManifest.class); Unmarshaller um = context.createUnmarshaller(); File xmlFile = new File(fileName); if(!xmlFile.exists()) { MekHQ.getLogger().warning(ScenarioModifierManifest.class, "Deserialize", String.format("Specified file %s does not exist", fileName)); return null; } <START> JAXBElement<ScenarioModifierManifest> templateElement = um.unmarshal(new StreamSource(xmlFile), ScenarioModifierManifest.class); <END> resultingList = templateElement.getValue(); } catch(Exception e) { MekHQ.getLogger().error(ScenarioModifierManifest.class, "Deserialize", "Error Deserializing Scenario Modifier List", e); } return resultingList; }</code><technical_language>createSafeXmlSource</technical_language>

Target:
public static ScenarioModifierManifest Deserialize(String fileName) { ScenarioModifierManifest resultingList = null; try { JAXBContext context = JAXBContext.newInstance(ScenarioModifierManifest.class); Unmarshaller um = context.createUnmarshaller(); File xmlFile = new File(fileName); if(!xmlFile.exists()) { MekHQ.getLogger().warning(ScenarioModifierManifest.class, "Deserialize", String.format("Specified file %s does not exist", fileName)); return null; } Source inputSource = MekHqXmlUtil.createSafeXmlSource(new FileInputStream(xmlFile)); JAXBElement<ScenarioModifierManifest> templateElement = um.unmarshal(inputSource, ScenarioModifierManifest.class); resultingList = templateElement.getValue(); } catch(Exception e) { MekHQ.getLogger().error(ScenarioModifierManifest.class, "Deserialize", "Error Deserializing Scenario Modifier List", e); } return resultingList; }
Source:
<code>void updateProgress () { if (progressState == SWT.INDETERMINATE) return; if (progressState == SWT.DEFAULT) return; <START> parent.mTaskbarList3.SetProgressValue(shell.hAccel, progress, <END> PROGRESS_MAX); }</code><technical_language>Is this a bug</technical_language>

Target:
void updateProgress () { if (progressState == SWT.INDETERMINATE) return; if (progressState == SWT.DEFAULT) return; parent.mTaskbarList3.SetProgressValue(shell.handle, progress, PROGRESS_MAX); }
Source:
<code>public static String loadJSONHTML(URL src) throws IOException { URLConnection con = ProxyConfiguration.open(src); int responseCode = HttpURLConnection.HTTP_OK; if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).setInstanceFollowRedirects(true); responseCode = ((HttpURLConnection) con).getResponseCode(); } if (HttpURLConnection.HTTP_OK != responseCode && HttpURLConnection.HTTP_MOVED_TEMP != responseCode && HttpURLConnection.HTTP_MOVED_PERM != responseCode && HttpURLConnection.HTTP_SEE_OTHER != responseCode) { throw new IOException("Could not find JSON in " + src); } else if (HttpURLConnection.HTTP_OK != responseCode) { <START> String redirection = ((HttpURLConnection) con).getHeaderField("Location"); <END> con = ProxyConfiguration.open(new URL(redirection)); responseCode = ((HttpURLConnection) con).getResponseCode(); } if (HttpURLConnection.HTTP_OK != responseCode) { throw new IOException("Could not find JSON in " + src); } try (InputStream is = con.getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); String preamble = "window.parent.postMessage(JSON.stringify("; int start = jsonp.indexOf(preamble); int end = jsonp.lastIndexOf("),'*');"); if (start >= 0 && end > start) { return jsonp.substring(start + preamble.length(), end).trim(); } else { throw new IOException("Could not find JSON in " + src); } } }</code><technical_language>Unchecked cast</technical_language>

Target:
public static String loadJSONHTML(URL src) throws IOException { URLConnection con; try { con = ProxyConfiguration.openURLAllowingCrossProtocolRedirects(src); } catch (IOException e) { throw new IOException("Could not find JSON in " + src, e); } try (InputStream is = con.getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); String preamble = "window.parent.postMessage(JSON.stringify("; int start = jsonp.indexOf(preamble); int end = jsonp.lastIndexOf("),'*');"); if (start >= 0 && end > start) { return jsonp.substring(start + preamble.length(), end).trim(); } else { throw new IOException("Could not find JSON in " + src); } } }
Source:
<code>private void assertGetResult(VM result) { assertNotNull(result); <START> assertTrue("Vm db generation wasn't loaded as expected", result.getDbGeneration() == 1); <END> assertEquals(result, existingVm); }</code><technical_language>Wait, this is worse previous version. happened assertEquals()</technical_language>

Target:
private void assertGetResult(VM result) { assertNotNull(result); assertEquals("Vm db generation wasn't loaded as expected", 1, result.getDbGeneration()); assertEquals(result, existingVm); }
Source:
<code>public void testDeleteSupplementaryFiles() { <START> setup(); <END> ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); try { assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFiles(trace); assertTrue(isDirectoryEmpty(suppFilesPath)); } catch (IOException e) { fail(e.getMessage()); } }</code><technical_language>call this</technical_language>

Target:
public void testDeleteSupplementaryFiles() { fTrace = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.TRACE2); ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); try { assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFiles(trace); assertTrue(isDirectoryEmpty(suppFilesPath)); } catch (IOException e) { fail(e.getMessage()); } }
Source:
<code>private String getSecurityManagerBySecurityLevel(String securityLevel) { if (GRINDER_SECURITY_LEVEL_LIGHT.equalsIgnoreCase(securityLevel)) { <START> return "NGrinderLightSecurityManager"; <END> } else { return "NGrinderSecurityManager"; } }</code><technical_language>org.ngrinder.sm.NGrinderLightSecurityManager</technical_language>

Target:
private String getSecurityManagerBySecurityLevel(String securityLevel) { if (GRINDER_SECURITY_LEVEL_LIGHT.equalsIgnoreCase(securityLevel)) { return "org.ngrinder.sm.NGrinderLightSecurityManager"; } else { return "org.ngrinder.sm.NGrinderSecurityManager"; } }
Source:
<code>private IResource[] toResourceArray(Collection<String> paths) { Set<IResource> resources = new HashSet<>(); final Repository <START> repository2 = <END> repository; for (String path : paths) { IFile file = null; if (repository2 != null && path != null) { file = ResourceUtil.getFileForLocation(repository2, path, false); } if (file != null) { resources.add(file.getProject()); } } if (resources.size() == 0 && repository2 != null) { resources .addAll(Arrays .asList(ProjectUtil.getProjects(repository2))); } return resources.toArray(new IResource[0]); }</code><technical_language>This variable unnecessary</technical_language>

Target:
private IResource[] toResourceArray(Collection<String> paths) { Set<IResource> resources = new HashSet<>(); for (String path : paths) { IFile file = null; if (path != null) { file = ResourceUtil.getFileForLocation(repository, path, false); } if (file != null) { resources.add(file.getProject()); } } if (resources.size() == 0) { resources .addAll(Arrays .asList(ProjectUtil.getProjects(repository))); } return resources.toArray(new IResource[0]); }
Source:
<code>protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.listBranches(projectName, new GerritCallback<List<Branch>>() { public void onSuccess(final List<Branch> result) { <START> Util.PROJECT_SVC.projectDetail(projectName, <END> new GerritCallback<ProjectDetail>() { public void onSuccess(final ProjectDetail projectDetail) { com.google.gerrit.client.account.Util.ACCOUNT_SEC.myGroups(new GerritCallback<List<AccountGroup>>() { public void onSuccess(List<AccountGroup> myGroups) { boolean userHasOwnRight = Util.hasOwnRight(projectDetail, myGroups); enableForm(true); branches.display(result, userHasOwnRight); addPanel.setVisible(userHasOwnRight); delBranch.setVisible(userHasOwnRight); } }); } }); } }); }</code><technical_language>Please generate 3 RPCs sequentially this. slows UI presenting information. Instead do is create a ListBranchResult data type return branch data listBranches. add a "canCreate" boolean if user is permitted create a branch, if so, set addPanel visible. Branch deletion is a per-branch right, need add a "canDelete" flag Branch, decide if delete checkbox available. server perform of this checking RefControl, need Util.hasOwnRight client UI side</technical_language>

Target:
protected void onLoad() { enableForm(false); super.onLoad(); Util.PROJECT_SVC.listBranches(projectName, new GerritCallback<ListBranchesResult>() { public void onSuccess(final ListBranchesResult result) { enableForm(true); display(result.getBranches()); addPanel.setVisible(result.getCanAdd()); } }); }
Source:
<code>private Pair<Long, Long> populateTestRealmAndCompactOnLaunch(CompactOnLaunchCallback compactOnLaunch) { final String REALM_NAME = "test.realm"; RealmConfiguration realmConfig = configFactory.createConfiguration(REALM_NAME); Realm realm = Realm.getInstance(realmConfig); populateTestRealm(realm, 100); realm.beginTransaction(); realm.deleteAll(); realm.commitTransaction(); realm.close(); long before = new File(realmConfig.getPath()).length(); RealmConfiguration.Builder builder = configFactory.createConfigurationBuilder(); <START> File folder = configFactory.getRoot(); <END> builder.directory(folder); builder.name(REALM_NAME); builder.compactOnLaunch(compactOnLaunch); realmConfig = builder.build(); realm = Realm.getInstance(realmConfig); realm.close(); long after = new File(realmConfig.getPath()).length(); return new Pair(before, after); }</code><technical_language>Please pattern do elsewhere. Also, this is set in configFactory, RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .name(REALM_NAME) .compactOnLaunch(compactOnLaunch) .build();</technical_language>

Target:
private Pair<Long, Long> populateTestRealmAndCompactOnLaunch(CompactOnLaunchCallback compactOnLaunch) { return populateTestRealmAndCompactOnLaunch(compactOnLaunch, 100); }
Source:
<code>public String toString() { <START> StringBuffer sb = new StringBuffer( super.toString() ); <END> sb.append( "(GAVCE=" ); sb.append( getGroupId() ); sb.append( ":" ); sb.append( getArtifactId() ); sb.append( ":" ); sb.append( getVersion() ); sb.append( ":c=" ); sb.append( getClassifier() ); sb.append( ":e=" ); sb.append( getExtension() ); sb.append( ", for " ); sb.append( RepositoryStringUtils.getHumanizedNameString( getMavenRepository() ) ); sb.append( ") " ); return sb.toString(); }</code><technical_language>StringBuilder</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder( super.toString() ); sb.append( "(GAVCE=" ); sb.append( getGroupId() ); sb.append( ":" ); sb.append( getArtifactId() ); sb.append( ":" ); sb.append( getVersion() ); sb.append( ":c=" ); sb.append( getClassifier() ); sb.append( ":e=" ); sb.append( getExtension() ); sb.append( ", for " ); sb.append( RepositoryStringUtils.getHumanizedNameString( getMavenRepository() ) ); sb.append( ") " ); return sb.toString(); }
Source:
<code><START> public boolean isPeerReplicaLeaderForPartition(String partitionName, ReplicaId replicaId) { <END> rwLock.readLock().lock(); try { return peerLeaderReplicasByPartition.containsKey(partitionName) && peerLeaderReplicasByPartition.get( partitionName).contains(replicaId); } finally { rwLock.readLock().unlock(); } }</code><technical_language>this method used</technical_language>

Target:
public boolean isPeerReplicaLeaderForPartition(String partitionName, ReplicaId replicaId) { rwLock.readLock().lock(); try { return peerLeaderReplicasByPartition.getOrDefault(partitionName, Collections.emptySet()).contains(replicaId); } finally { rwLock.readLock().unlock(); } }
Source:
<code>protected SSLContext createSSLContext(Map<String, Object> configuration, String keystoreProvider, String keystorePath, String keystorePassword, String truststoreProvider, String truststorePath, String truststorePassword, String crlPath, String trustManagerFactoryPlugin, boolean trustAll) throws Exception { <START> if (LOGGER.isDebugEnabled()) { <END> final StringBuilder builder = new StringBuilder(); configuration.forEach((k, v) -> builder.append("\r\n").append(k).append("=").append(v)); LOGGER.debugf("Creating SSL context with configuration %s", builder.toString()); } boolean useDefaultSslContext = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_DEFAULT_SSL_CONTEXT_PROP_NAME, TransportConstants.DEFAULT_USE_DEFAULT_SSL_CONTEXT, configuration); if (useDefaultSslContext) { return SSLContext.getDefault(); } return new SSLSupport() .setKeystoreProvider(keystoreProvider) .setKeystorePath(keystorePath) .setKeystorePassword(keystorePassword) .setTruststoreProvider(truststoreProvider) .setTruststorePath(truststorePath) .setTruststorePassword(truststorePassword) .setTrustAll(trustAll) .setCrlPath(crlPath) .setTrustManagerFactoryPlugin(trustManagerFactoryPlugin) .createContext(); }</code><technical_language>squash commits. this commit compile declare LOGGER, next remove this LOGGER. a matter of fact, I call log else, OCD side</technical_language>

Target:
protected SSLContext createSSLContext(Map<String, Object> configuration, String keystoreProvider, String keystorePath, String keystorePassword, String truststoreProvider, String truststorePath, String truststorePassword, String crlPath, String trustManagerFactoryPlugin, boolean trustAll) throws Exception { if (log.isDebugEnabled()) { final StringBuilder builder = new StringBuilder(); configuration.forEach((k, v) -> builder.append("\r\n").append(k).append("=").append(v)); log.debugf("Creating SSL context with configuration %s", builder.toString()); } boolean useDefaultSslContext = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_DEFAULT_SSL_CONTEXT_PROP_NAME, TransportConstants.DEFAULT_USE_DEFAULT_SSL_CONTEXT, configuration); if (useDefaultSslContext) { return SSLContext.getDefault(); } return new SSLSupport() .setKeystoreProvider(keystoreProvider) .setKeystorePath(keystorePath) .setKeystorePassword(keystorePassword) .setTruststoreProvider(truststoreProvider) .setTruststorePath(truststorePath) .setTruststorePassword(truststorePassword) .setTrustAll(trustAll) .setCrlPath(crlPath) .setTrustManagerFactoryPlugin(trustManagerFactoryPlugin) .createContext(); }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; <START> result = prime * result + ((repository == null) ? 0 : repository.hashCode()); <END> return result; }</code><technical_language>This return repository.hashCode()</technical_language>

Target:
public int hashCode() { return repository.hashCode(); }
Source:
<code><START> private void updateMapHelper(Map<String, Long> map, String key, Long value) { <END> Long existingValue = map.get(key); if (existingValue == null) { existingValue = value; } else { existingValue += value; } map.put(key, existingValue); }</code><technical_language>updateValidSizePerContainerId</technical_language>

Target:
private void updateMapHelper(Map<String, Long> map, String key, Long value) { Long newValue = map.containsKey(key) ? map.get(key) + value : value; map.put(key, newValue); }
Source:
<code>public String getResourceDir() { <START> return "resource" + File.separator + getClass().getSimpleName(); <END> }</code><technical_language>reference "resource" Util.getResourceDir()</technical_language>

Target:
public String getResourceDir() { return Util.getResourceDir() + File.separator + getClass().getSimpleName(); }
Source:
<code>public int purgeQueue(final String queueName) { return this.rabbitTemplate.execute(channel -> { PurgeOk queuePurged = channel.queuePurge(queueName); if (this.logger.isDebugEnabled()) { <START> logger.debug("Purged queue: " + queueName + ", " + queuePurged); <END> } return queuePurged.getMessageCount(); }); }</code><technical_language>Travis this: > Task :spring-rabbit:checkstyleMain [ant:checkstyle] [ERROR] /home/travis/build/spring-projects/spring-amqp/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/core/RabbitAdmin.java:340:33: Reference instance variable 'logger' needs "this.". [RequireThis] chances fix merge? Thanks</technical_language>

Target:
public int purgeQueue(final String queueName) { return this.rabbitTemplate.execute(channel -> { PurgeOk queuePurged = channel.queuePurge(queueName); if (this.logger.isDebugEnabled()) { this.logger.debug("Purged queue: " + queueName + ", " + queuePurged); } return queuePurged.getMessageCount(); }); }
Source:
<code>private void logTraceResults(long duration, Set<TableReference> tableRefs, ByteBuffer recvTrace, boolean failed) { if (failed || duration > tracingPrefs.getMinimumDurationToTraceMillis()) { <START> log.warn("Traced a call to that {}took ms. It will appear in system_traces with UUID={}", <END> tableRefs.stream().map(TableReference::getQualifiedName).collect(Collectors.joining(", ")), failed ? "failed and " : "", duration, CassandraKeyValueServices.convertCassandraByteBufferUuidToString(recvTrace)); } }</code><technical_language>This info message</technical_language>

Target:
private void logTraceResults(long duration, Set<TableReference> tableRefs, ByteBuffer recvTrace, boolean failed) { if (failed || duration > tracingPrefs.getMinimumDurationToTraceMillis()) { log.info("Traced a call to that {}took ms. It will appear in system_traces with UUID={}", tableRefs.stream().map(TableReference::getQualifiedName).collect(Collectors.joining(", ")), failed ? "failed and " : "", duration, CassandraKeyValueServices.convertCassandraByteBufferUuidToString(recvTrace)); } }
Source:
<code>public boolean offer(E e) { Objects.requireNonNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { if (this.queue.size() == this.maxSize) { final E discard = this.queue.remove(); <START> LOG.debug("Queue if full. Discarding oldest element: {}", discard); <END> } this.queue.add(e); this.notEmpty.signal(); } finally { lock.unlock(); } return true; }</code><technical_language>nice if a metric counting number of discarded items</technical_language>

Target:
public boolean offer(E e) { Objects.requireNonNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { if (this.queue.size() == this.maxSize) { final E discard = this.queue.remove(); this.droppedCount++; LOG.debug("Queue is full. Discarding oldest element [count={}]: {}", this.droppedCount, discard); } this.queue.add(e); this.notEmpty.signal(); } finally { lock.unlock(); } return true; }
Source:
<code>public void create(Username currentUser, SecurityAuthConfig securityAuthConfig, LocalizedOperationResult result) { <START> SecurityAuthConfigCreateCommand command = new SecurityAuthConfigCreateCommand(goConfigService, securityAuthConfig, authorizationExtension, currentUser, result); <END> validatePluginProperties(command, securityAuthConfig); update(currentUser, securityAuthConfig, result, command); }</code><technical_language>Move this validation PluginProfileService</technical_language>

Target:
public void create(Username currentUser, SecurityAuthConfig securityAuthConfig, LocalizedOperationResult result) { SecurityAuthConfigCreateCommand command = new SecurityAuthConfigCreateCommand(goConfigService, securityAuthConfig, authorizationExtension, currentUser, result); update(currentUser, securityAuthConfig, result, command); }