auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ConversationSendResponse sendMessage(ConversationSendRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s", this.conversationsBaseUrl, CONVERSATION_SEND_PATH); return messageBirdService.sendPayLoad(url, request, ConversationSendResponse.class); <START> } <END></code><technical_language>update this.conversationsBaseUrl CONVERSATIONS_BASE_URL line 951</technical_language>

Target:
public ConversationSendResponse sendMessage(ConversationSendRequest request) throws UnauthorizedException, GeneralException { String url = String.format("%s%s", CONVERSATIONS_BASE_URL, CONVERSATION_SEND_PATH); return messageBirdService.sendPayLoad(url, request, ConversationSendResponse.class); }
Source:
<code>private static HyperLogLogPlus decodeBytes(DataInput oi, int version) throws IOException { int p = Varint.readUnsignedVarInt(oi); int sp = Varint.readUnsignedVarInt(oi); int formatType = Varint.readUnsignedVarInt(oi); if (formatType == 0) { int storageType = 1; <START> if (version < -2) <END> storageType = Varint.readUnsignedVarInt(oi); int size = Varint.readUnsignedVarInt(oi); byte[] longArrayBytes = new byte[size]; oi.readFully(longArrayBytes); HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, new RegisterSet(1 << p, Bits.getBits(longArrayBytes), RegisterSetStorage.Type.fromInt(storageType))); hyperLogLogPlus.format = Format.NORMAL; return hyperLogLogPlus; } else { int[] rehydratedSparseSet = new int[Varint.readUnsignedVarInt(oi)]; int prevDeltaRead = 0; for (int i = 0; i < rehydratedSparseSet.length; i++) { int nextVal = Varint.readUnsignedVarInt(oi) + prevDeltaRead; rehydratedSparseSet[i] = nextVal; prevDeltaRead = nextVal; } HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, rehydratedSparseSet); hyperLogLogPlus.format = Format.SPARSE; return hyperLogLogPlus; } }</code><technical_language>braces</technical_language>

Target:
private static HyperLogLogPlus decodeBytes(DataInput oi, int version) throws IOException { int p = Varint.readUnsignedVarInt(oi); int sp = Varint.readUnsignedVarInt(oi); int formatType = Varint.readUnsignedVarInt(oi); if (formatType == 0) { boolean useDirect = false; if (version < -2) { useDirect = oi.readBoolean(); } int size = Varint.readUnsignedVarInt(oi); byte[] longArrayBytes = new byte[size]; oi.readFully(longArrayBytes); HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, new RegisterSet(1 << p, Bits.getBits(longArrayBytes), useDirect)); hyperLogLogPlus.format = Format.NORMAL; return hyperLogLogPlus; } else { int[] rehydratedSparseSet = new int[Varint.readUnsignedVarInt(oi)]; int prevDeltaRead = 0; for (int i = 0; i < rehydratedSparseSet.length; i++) { int nextVal = Varint.readUnsignedVarInt(oi) + prevDeltaRead; rehydratedSparseSet[i] = nextVal; prevDeltaRead = nextVal; } HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(p, sp, rehydratedSparseSet); hyperLogLogPlus.format = Format.SPARSE; return hyperLogLogPlus; } }
Source:
<code>public int getSlaveConnectTimeout() { <START> return slaveConnectTimeout; <END> }</code><technical_language>upgrading slaveConnectTimeout in object, get set 0 IIRC need handle in readResolve set default, return default if is 0</technical_language>

Target:
public int getSlaveConnectTimeout() { if (slaveConnectTimeout == 0) return DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT; return slaveConnectTimeout; }
Source:
<code>public ArrayList<SectionItemInterface> getRecentDownloadedVideosList() { ArrayList<SectionItemInterface> recentVideolist = new ArrayList<>(); ArrayList<EnrolledCoursesResponse> courseList = null; String username = getUsername(); if (username != null) { courseList = (ArrayList) api.getUserEnrolledCourses(username, true); } <START> if (courseList != null || courseList.size() == 0) { <END> for (final EnrolledCoursesResponse course : courseList) { List<VideoModel> videos = db.getSortedDownloadsByDownloadedDateForCourseId( course.getCourse().getId(), null); if (videos != null && videos.size() > 0) { recentVideolist.add(course); for (VideoModel videoModel : videos) { recentVideolist.add((SectionItemInterface) videoModel); } } } } return recentVideolist; }</code><technical_language>un-necessary null check</technical_language>

Target:
public ArrayList<SectionItemInterface> getRecentDownloadedVideosList() { ArrayList<SectionItemInterface> recentVideolist = new ArrayList<>(); ArrayList<EnrolledCoursesResponse> courseList = null; String username = getUsername(); if (username != null) { courseList = (ArrayList) api.getUserEnrolledCourses(username, true); } if (courseList != null && !courseList.isEmpty()) { for (final EnrolledCoursesResponse course : courseList) { List<VideoModel> videos = db.getSortedDownloadsByDownloadedDateForCourseId( course.getCourse().getId(), null); if (videos != null && videos.size() > 0) { recentVideolist.add(course); for (VideoModel videoModel : videos) { recentVideolist.add((SectionItemInterface) videoModel); } } } } return recentVideolist; }
Source:
<code>public String getContinuationToken() { <START> return this.nextLink; <END> }</code><technical_language>in other places. Change continuationToken</technical_language>

Target:
public String getContinuationToken() { return this.continuationToken; }
Source:
<code>public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { <START> LOGGER.warn("Root path is blank. ", path, absolutePath.toAbsolutePath()); <END> } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }</code><technical_language>Passing arguments a log format string variable in it. message is inaccurate passing in root path. do similar above. calling out _ddf.home_ specifically, change this debug: LOGGER.debug("Root path is blank. Resolving relative path to: {}", path, absolutePath.toAbsolutePath());</technical_language>

Target:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, absolutePath.toAbsolutePath()); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }
Source:
<code>protected String getKeyForInstructor(String courseId, String instructorEmail) { <START> return StringHelper.encrypt(getInstructor(courseId, instructorEmail).getKey()); <END> }</code><technical_language>this stage, dependency StringHelper.encrypt this method dependency encryption key set in application. need either: - Set another encryption method is configured test.properties E2E tests. (not preferred) - Modify API layer keys returned encrypted. I of belief this is case for non-admin user-facing endpoints</technical_language>

Target:
protected String getKeyForInstructor(String courseId, String instructorEmail) { return getInstructor(courseId, instructorEmail).getKey(); }
Source:
<code>public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm) { if (globalConfiguration.authorization().enabled()) { if (Security.isPrivileged()) { Security.checkPermission(perm.getSecurityPermission()); } else { Subject subject = Security.getSubject(); try { if (subject != null) { int subjectMask = computeSubjectRoleMask(subject, configuration); if ((subjectMask & perm.getMask()) != perm.getMask()) { checkSecurityManagerPermission(perm); } else { <START> if (audit != null) { <END> audit.audit(subject, context, name, perm, AuditResponse.ALLOW); } } } else { checkSecurityManagerPermission(perm); } } catch (SecurityException e) { if (audit != null) { audit.audit(subject, context, name, perm, AuditResponse.DENY); } throw log.unauthorizedAccess(String.valueOf(subject), perm.toString()); } } } }</code><technical_language>a NullAuditLogger implementation? branching field access is enemy, in terms of readability/robustness performance ;-)</technical_language>

Target:
public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm) { if (globalConfiguration.authorization().enabled()) { if (Security.isPrivileged()) { Security.checkPermission(perm.getSecurityPermission()); } else { Subject subject = Security.getSubject(); try { if (subject != null) { int subjectMask = computeSubjectRoleMask(subject, configuration); if ((subjectMask & perm.getMask()) != perm.getMask()) { checkSecurityManagerPermission(perm); } else { audit.audit(subject, context, name, perm, AuditResponse.ALLOW); } } else { checkSecurityManagerPermission(perm); } } catch (SecurityException e) { audit.audit(subject, context, name, perm, AuditResponse.DENY); throw log.unauthorizedAccess(String.valueOf(subject), perm.toString()); } } } }
Source:
<code>public void onConfigurationChange(Configuration conf) { float originSlop = slop; float originOverallSlop = overallSlop; super.setConf(conf); LOG.info("Update configuration of SimpleLoadBalancer, previous slop is " + originSlop + ", current slop is " + slop + "previous overallSlop is" + <START> originOverallSlop + ", current overallSlop is " + overallSlop); <END> }</code><technical_language>nit: parameterized log syntax? LOG.info( "Update configuration of SimpleLoadBalancer, previous slop is {}, current slop is previous overallSlop is {}, current overallSlop is {}", originSlop, slop, originOverallSlop, overallSlop);</technical_language>

Target:
public void onConfigurationChange(Configuration conf) { float originSlop = slop; float originOverallSlop = overallSlop; super.setConf(conf); LOG.info("Update configuration of SimpleLoadBalancer, previous slop is {}," + " current slop is {}, previous overallSlop is {}, current overallSlop is {}", originSlop, slop, originOverallSlop, overallSlop); }
Source:
<code>public synchronized void serviceStart() throws Exception { try { if (!getConfig().getBoolean( JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_FIXED_PORTS)) { String hostname = MiniYARNCluster.getHostname(); getConfig().set(JHAdminConfig.MR_HISTORY_ADDRESS, hostname + ":0"); MRWebAppUtil.setJHSWebappURLWithoutScheme(getConfig(), hostname + ":0"); getConfig().set(JHAdminConfig.JHS_ADMIN_ADDRESS, hostname + ":0"); } historyServer = new JobHistoryServer(); historyServer.init(getConfig()); new Thread() { public void run() { historyServer.start(); jhsStarted = true; }; <START> }.start(); <END> final int launchTimeout = getConfig().getInt( JHAdminConfig.MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS); GenericTestUtils.waitFor(() -> jhsStarted, 1500, launchTimeout); if (historyServer.getServiceState() != STATE.STARTED) { throw new IOException("HistoryServer failed to start"); } super.serviceStart(); } catch (Throwable t) { throw new YarnRuntimeException(t); } }</code><technical_language>this historyServer thread initialized new configuration is enabled? nice avoid allocating resources if need them</technical_language>

Target:
public synchronized void serviceStart() throws Exception { try { if (!getConfig().getBoolean( JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, JHAdminConfig.DEFAULT_MR_HISTORY_MINICLUSTER_FIXED_PORTS)) { String hostname = MiniYARNCluster.getHostname(); getConfig().set(JHAdminConfig.MR_HISTORY_ADDRESS, hostname + ":0"); MRWebAppUtil.setJHSWebappURLWithoutScheme(getConfig(), hostname + ":0"); getConfig().set(JHAdminConfig.JHS_ADMIN_ADDRESS, hostname + ":0"); } historyServer = new JobHistoryServer(); historyServer.init(getConfig()); new Thread() { public void run() { historyServer.start(); }; }.start(); final int launchTimeout = getConfig().getInt( MR_HISTORY_MINICLUSTER_LAUNCH_TIMEOUT_MS, 60_000); GenericTestUtils.waitFor( () -> historyServer.getServiceState() == STATE.STARTED || historyServer.getServiceState() == STATE.STOPPED, 100, launchTimeout); if (historyServer.getServiceState() != STATE.STARTED) { throw new IOException("HistoryServer failed to start"); } super.serviceStart(); } catch (Throwable t) { throw new YarnRuntimeException(t); } }
Source:
<code>private String normalizeQName(QName qName) { return qName.toString().substring(1) <START> .replace("}", "__") <END> .replace("/", "") .replace(':', '_'); }</code><technical_language>wow, char is a {? :-)</technical_language>

Target:
private String normalizeQName(QName qName) { return qName.toString() .replace("}", "") .replace("}", "__") .replace("/", "") .replace(':', '_'); }
Source:
<code><START> public static double stXMax(@SqlType(GEOMETRY_TYPE_NAME) Slice input) <END> { Envelope envelope = deserializeEnvelope(input); if (envelope == null) { return 0.0; } return envelope.getXMax(); }</code><technical_language>please squash commits - fix commit message. Optimize Min Max geospatial functions is generic, instead please describe changed resulted performance of min max geospatial functions</technical_language>

Target:
public static Double stXMax(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { Envelope envelope = deserializeEnvelope(input); if (envelope == null) { return null; } return envelope.getXMax(); }
Source:
<code>public static void updateDocumentBy(Document doc, Patient patient) { doc.setPatientId(patient.getPatientIdentifierIso()); doc.setSourcePatientId(patient.getPatientIdentifierIso()); Personname personname = HelperUtil.lastItem(patient.getPersonnames()); if (personname != null) { doc.setPid5(MessageFormat.format("{0}^{1}^^^", personname.getLastName(), personname.getFirstName())); } Timestamp dateOfBirth = patient.getDateOfBirth(); <START> { <END> doc.setPid7(new SimpleDateFormat("yyyyMMdd").format(dateOfBirth)); } doc.setPid8(patient.getGender()); Address address = HelperUtil.lastItem(patient.getAddresses()); if (address != null) { doc.setPid11(MessageFormat.format("{0}^^{1}^{2}^{3}^", address.getStreet1(), address.getCity(), address.getState(), address.getPostal())); } if (HelperUtil.isId(patient.getPatientId())) { doc.setPatientRecordId(patient.getPatientId()); } }</code><technical_language>missing - if (dateOfBirth != null)</technical_language>

Target:
public static void updateDocumentBy(Document doc, Patient patient) { doc.setPatientId(patient.getPatientIdentifierIso()); doc.setSourcePatientId(patient.getPatientIdentifierIso()); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Personname personname = HelperUtil.lastItem(patient.getPersonnames()); if (personname != null) { doc.setPid5(MessageFormat.format("{0}^{1}^^^", personname.getLastName(), personname.getFirstName())); } Timestamp dateOfBirth = patient.getDateOfBirth(); if (dateOfBirth != null) { doc.setPid7(sdf.format(dateOfBirth)); } doc.setPid8(patient.getGender()); Address address = HelperUtil.lastItem(patient.getAddresses()); if (address != null) { doc.setPid11(MessageFormat.format("{0}^^{1}^{2}^{3}^", address.getStreet1(), address.getCity(), address.getState(), address.getPostal())); } if (HelperUtil.isId(patient.getPatientId())) { doc.setPatientRecordId(patient.getPatientId()); } }
Source:
<code>public void run() { started = true; if(!prepared) { logger.error("The StageRunner was not prepared prior to being started. Aborting!"); return; } <START> if(stageGroup.getSize() < 1) { <END> logger.info("Stage group "+stageGroup.getName() + " has no stages, and can not be started."); return; } do { logger.info("Starting stage group " + stageGroup.getName() + ". Times started so far: " + timesStarted); timesStarted++; boolean cleanShutdown = runGroup(); if (cleanShutdown) { return; } if (!hasQueried()) { logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes."); return; } } while (timesToRetry == -1 || timesToRetry >= timesStarted); logger.error("Stage group " + stageGroup.getName() + " has failed and cannot be restarted. "); }</code><technical_language>Is this performed often? another method is needed? java if (stageGroup.isEmpty())</technical_language>

Target:
public void run() { started = true; if (!prepared) { logger.error("The StageRunner was not prepared prior to being started. Aborting!"); return; } if (stageGroup.isEmpty()) { logger.info("Stage group " + stageGroup.getName() + " has no stages, and can not be started."); return; } do { logger.info("Starting stage group " + stageGroup.getName() + ". Times started so far: " + timesStarted); timesStarted++; boolean cleanShutdown = runGroup(); if (cleanShutdown) { return; } if (!hasQueried()) { logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes."); return; } } while (timesToRetry == -1 || timesToRetry >= timesStarted); logger.error("Stage group " + stageGroup.getName() + " has failed and cannot be restarted. "); }
Source:
<code>public void handlesPersistentConnection() throws Exception { final int port = 8080; final String uri = String.format("http://localhost:%d", port); final int count = 1; final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkBasic(take), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); final HttpURLConnection conn = HttpURLConnection.class.cast( new URL(uri).openConnection() ); final String connection = "Connection"; final String keepAlive = "Keep-Alive"; conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Host", "localhost"); conn.addRequestProperty(connection, keepAlive); MatcherAssert.assertThat( conn.getHeaderFields(), Matchers.hasKey(connection) ); MatcherAssert.assertThat( conn.getHeaderFields().get(connection), Matchers.hasItem(keepAlive) ); completed.countDown(); completed.await(1L, TimeUnit.MILLISECONDS); <START> MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); <END> }</code><technical_language>@mstzn36 check here? I completed.getCount() equals 0</technical_language>

Target:
public void handlesPersistentConnection() throws Exception { final int port = 8080; final String uri = String.format("http://localhost:%d", port); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new TkEmpty().act(req); } }; final Thread app = new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkBasic(take), port ).start( Exit.NEVER ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ); app.start(); Thread.sleep(BkBasicTest.WAIT_APP); final HttpURLConnection httpURLConnection = HttpURLConnection .class.cast( new URL(uri).openConnection() ); final String connection = "Connection"; final String keepAlive = "Keep-Alive"; httpURLConnection.setRequestMethod("GET"); httpURLConnection.setUseCaches(false); httpURLConnection.setInstanceFollowRedirects(false); httpURLConnection.addRequestProperty("Host", "localhost"); httpURLConnection.addRequestProperty(connection, keepAlive); MatcherAssert.assertThat( httpURLConnection.getHeaderFields().get(connection), Matchers.hasItem(keepAlive) ); app.interrupt(); }
Source:
<code><START> public int initializeAppResources(CommCareApp app) { <END> try { currentApp = app; if (currentApp.initializeApplication()) { return STATE_READY; } else { return STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); return STATE_CORRUPTED; } }</code><technical_language>added a bunch of methods in overloaded versions of initializeAppResources. Please move initializeAppResources definitions next other, code easier read</technical_language>

Target:
public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; if (currentApp.initializeApplication()) { resourceState = STATE_READY; } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); }
Source:
<code>public void canFetchLogsForQuery() { writeToLogs(1, 100); int lastVerified = 27; List<HistoryQuery> historyQueries = ImmutableList.of(HistoryQuery.of(NAMESPACE_AND_USE_CASE, lastVerified, lastVerified + 500)); List<LogsForNamespaceAndUseCase> paxosHistory = HistoryLoaderAndTransformer.getLogsForHistoryQueries(history, historyQueries); <START> sanityCheckLoadedHistory(paxosHistory, 100 - lastVerified + 1); <END> }</code><technical_language>Speaking of sanity checks, is this: (100 - lastVerified) + 1 100 - (lastVerified + 1)? I assume latter, determines this - bracket it</technical_language>

Target:
public void canFetchLogsForQuery() { writeToLogs(1, 100); int lastVerified = 27; List<HistoryQuery> historyQueries = ImmutableList.of(HistoryQueries.unboundedHistoryQuerySinceSeq(lastVerified)); List<LogsForNamespaceAndUseCase> paxosHistory = HistoryLoaderAndTransformer.getLogsForHistoryQueries(history, historyQueries); sanityCheckLoadedHistory(paxosHistory, 100 - lastVerified + 1); }
Source:
<code>public void initialise() { final ScrollableArea scrollArea = find("scrollArea", ScrollableArea.class); scrollArea.moveToBottom(); commandLine = find("commandLine", UIText.class); getManager().setFocus(commandLine); commandLine.subscribe(widget -> { String text = commandLine.getText(); if (!text.isEmpty()) { String command = "say"; List<String> params = Collections.singletonList(text); console.execute(new Name(command), params, localPlayer.getClientEntity()); commandLine.setText(""); scrollArea.moveToBottom(); MiniChatOverlay overlay = nuiManager.addOverlay("engine:minichatOverlay", MiniChatOverlay.class); overlay.setVisible(true); nuiManager.closeScreen(this); } }); final UILabel history = find("messageHistory", UILabel.class); history.bindText(new ReadOnlyBinding<String>() { @Override public String get() { StringBuilder messageList = new StringBuilder(); for (Iterator<Message> it = console.getMessages(CoreMessageType.CHAT, CoreMessageType.NOTIFICATION).iterator(); it.hasNext();) { messageList.append(it.next().getMessage()); if (it.hasNext()) { messageList.append(Console.NEW_LINE); <START> } <END> } return messageList.toString(); } }); }</code><technical_language>about: Iterable<Message> messageIterable = console.getMessages(CoreMessageType.CHAT, CoreMessageType.NOTIFICATION); Stream<Message> messageStream = StreamSupport.stream(messageIterable.spliterator(), false); return messageStream.map(Message::getMessage).collect(Collectors.joining(Console.NEW_LINE));</technical_language>

Target:
public void initialise() { final ScrollableArea scrollArea = find("scrollArea", ScrollableArea.class); scrollArea.moveToBottom(); commandLine = find("commandLine", UIText.class); getManager().setFocus(commandLine); commandLine.subscribe(widget -> { String text = commandLine.getText(); if (!text.isEmpty()) { String command = "say"; List<String> params = Collections.singletonList(text); console.execute(new Name(command), params, localPlayer.getClientEntity()); commandLine.setText(""); scrollArea.moveToBottom(); MiniChatOverlay overlay = nuiManager.addOverlay("engine:minichatOverlay", MiniChatOverlay.class); overlay.setVisible(true); nuiManager.closeScreen(this); } }); final UILabel history = find("messageHistory", UILabel.class); history.bindText(new ReadOnlyBinding<String>() { @Override public String get() { Iterable<Message> messageIterable = console.getMessages(CoreMessageType.CHAT, CoreMessageType.NOTIFICATION); Stream<Message> messageStream = StreamSupport.stream(messageIterable.spliterator(), false); return messageStream.map(Message::getMessage).collect(Collectors.joining(Console.NEW_LINE)); } }); }
Source:
<code>public void testLiveEventListGet_withOptions() throws Exception { Client client = getLiveClient(); Request<ScopedList<Event>> request = new Event.ListRequestBuilder() .options(new ScopedList.Options() .limit(5) .order(Ordering.ReverseChronological)) .build(); <START> <END> ScopedList<Event> events = client.sendRequest(request, new TypeReference<ScopedList<Event>>() { }); assertEquals(5, events.getLimit()); assertEquals(5, events.getData().size()); assertEquals(Ordering.ReverseChronological, events.getOrder()); assertEquals(114, events.getTotal()); Event event = events.getData().get(0); assertNotNull(event); }</code><technical_language>remove a newline</technical_language>

Target:
public void testLiveEventListGet_withOptions() throws Exception { Request<ScopedList<Event>> request = new Event.ListRequestBuilder() .options(new ScopedList.Options() .limit(5) .order(Ordering.ReverseChronological)) .build(); ScopedList<Event> events = client.sendRequest(request, new TypeReference<ScopedList<Event>>() { }); assertEquals(5, events.getLimit()); assertEquals(5, events.getData().size()); assertEquals(Ordering.ReverseChronological, events.getOrder()); assertTrue(events.getTotal() > 0); Event event = events.getData().get(0); assertNotNull(event); }
Source:
<code>public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws AxisFault { API api = getAPIFromSynapseConfig(request); if (api == null) { handleException(request.getRequestURI()); } else { String responseString; try { Yaml yamlDefinition = new Yaml(); String defFromRegistry = retrieveFromRegistry(api, request); if (defFromRegistry != null) { JsonParser jsonParser = new JsonParser(); responseString = yamlDefinition.dumpAsMap(GSONUtils.gsonJsonObjectToMap(jsonParser.parse(defFromRegistry))); } else { AxisConfiguration axisConfiguration = DataHolder.getInstance().getAxisConfigurationContext().getAxisConfiguration(); <START> ServerConfig serverConfig = new CarbonServerConfig(axisConfiguration); <END> responseString = yamlDefinition.dumpAsMap(new GenericApiObjectDefinition(api, serverConfig).getDefinitionMap()); } } catch (RegistryException e) { throw new AxisFault("Error occurred while retrieving swagger definition from registry", e); } updateResponse(response, responseString, SwaggerConstants.CONTENT_TYPE_YAML); } }</code><technical_language>Lets get a singleton instance if possible</technical_language>

Target:
public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws AxisFault { API api = getAPIFromSynapseConfig(request); if (api == null) { handleException(request.getRequestURI()); } else { String responseString; try { Yaml yamlDefinition = new Yaml(); String defFromRegistry = retrieveFromRegistry(api, request); if (defFromRegistry != null) { JsonParser jsonParser = new JsonParser(); responseString = yamlDefinition.dumpAsMap(GSONUtils.gsonJsonObjectToMap(jsonParser.parse(defFromRegistry))); } else { ServerConfig serverConfig = new CarbonServerConfig(); responseString = yamlDefinition.dumpAsMap(new GenericApiObjectDefinition(api, serverConfig).getDefinitionMap()); } } catch (RegistryException e) { throw new AxisFault("Error occurred while retrieving swagger definition from registry", e); } updateResponse(response, responseString, SwaggerConstants.CONTENT_TYPE_YAML); } }
Source:
<code>private static Event compact(Event event) { final EventContext context = event.getContext(); final EventContext.Builder resultContext = context.toBuilder() .clearEnrichment(); final EventContext originEventContext = context.getEventContext(); <START> if (!isDefault(originEventContext)) { <END> resultContext.setEventContext(originEventContext.toBuilder() .clearOrigin() .clearEnrichment()); } final RejectionContext originRejectionContext = context.getRejectionContext(); if (!isDefault(originRejectionContext)) { resultContext.setRejectionContext(originRejectionContext.toBuilder() .clearEnrichment()); } return event.toBuilder() .setContext(resultContext) .build(); }</code><technical_language>Please case detection API Protobuf</technical_language>

Target:
private static Event compact(Event event) { final EventContext context = event.getContext(); final EventContext.Builder resultContext = context.toBuilder() .clearEnrichment(); final EventContext.OriginCase originCase = resultContext.getOriginCase(); switch (originCase) { case EVENT_CONTEXT: resultContext.setEventContext(context.getEventContext() .toBuilder() .clearOrigin() .clearEnrichment()); break; case REJECTION_CONTEXT: resultContext.setRejectionContext(context.getRejectionContext() .toBuilder() .clearEnrichment()); break; case COMMAND_CONTEXT: break; case ORIGIN_NOT_SET: break; default: throw newIllegalStateException("Unsupported origin case encountered: %s", originCase); } return event.toBuilder() .setContext(resultContext) .build(); }
Source:
<code><START> public boolean isEquilateral() { <END> throw new UnsupportedOperationException("Delete this statement and write your own implementation."); }</code><technical_language>A minor point (sorry picky) need public here. practice restrictive access modifiers need this package private (which, know, is default it). Especially constructor class package private, sense for methods :)</technical_language>

Target:
boolean isEquilateral() { throw new UnsupportedOperationException("Delete this statement and write your own implementation."); }
Source:
<code>private static Double toNumeric_inclusiveOfDatestrings(Object o) { Double d = toNumeric(o); if (Double.isNaN(d.doubleValue())) { o = unpack(o); if (o instanceof String) { Date dateFromString = DateUtils.parseDate((String)o); if (dateFromString != null) { <START> return new Double(DateUtils.daysSinceEpoch(dateFromString)); <END> } } } return d; }</code><technical_language>For cohesiveness, process a string turns a date, a date turns a double code paths normally? IE: if(NaN) { try toNumeric(toDate(val)) catch() } if complexity (your unpack() call is a good example), complexity is compartmentalized</technical_language>

Target:
private static Double toNumeric_inclusiveOfDatestrings(Object o) { Double d = toNumeric(o); if (Double.isNaN(d.doubleValue())) { o = unpack(o); if (o instanceof String) { Date dateFromString = DateUtils.parseDate((String)o); if (dateFromString != null) { return toNumeric(dateFromString); } } } return d; }
Source:
<code>public List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Group group) throws InternalErrorException { try { <START> return jdbc.query("select " + getAttributeMappingSelectQuery("mem") + " from attr_names " + <END> "left join member_group_attr_values mem on id=mem.attr_id and mem.group_id=? and member_id=? " + "where namespace in (?,?,?) " + "and attr_names.id in (select distinct service_required_attrs.attr_id from service_required_attrs " + "join resource_services on service_required_attrs.service_id=resource_services.service_id and resource_services.resource_id=?)", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), AttributesManager.NS_MEMBER_GROUP_ATTR_DEF, AttributesManager.NS_MEMBER_GROUP_ATTR_OPT, AttributesManager.NS_MEMBER_GROUP_ATTR_VIRT, resourceToGetServicesFrom.getId()); } catch(EmptyResultDataAccessException ex) { return new ArrayList<Attribute>(); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>problem name above</technical_language>

Target:
public List<Attribute> getRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Group group) throws InternalErrorException { try { return jdbc.query("select " + getAttributeMappingSelectQuery("mem_gr") + " from attr_names " + "left join member_group_attr_values mem_gr on id=mem_gr.attr_id and mem_gr.group_id=? and member_id=? " + "where namespace in (?,?,?) " + "and attr_names.id in (select distinct service_required_attrs.attr_id from service_required_attrs " + "join resource_services on service_required_attrs.service_id=resource_services.service_id and resource_services.resource_id=?)", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), AttributesManager.NS_MEMBER_GROUP_ATTR_DEF, AttributesManager.NS_MEMBER_GROUP_ATTR_OPT, AttributesManager.NS_MEMBER_GROUP_ATTR_VIRT, resourceToGetServicesFrom.getId()); } catch(EmptyResultDataAccessException ex) { return new ArrayList<Attribute>(); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>private HostControllerBootstrap boot(String[] args, final String authCode) { try { final long startTime = Module.getStartTime(); final HostControllerEnvironmentWrapper hostControllerEnvironmentWrapper = determineEnvironment(args, startTime); if (hostControllerEnvironmentWrapper.getHostControllerEnvironment() == null) { usage(); if (hostControllerEnvironmentWrapper.getHostControllerEnvironmentStatus() == HostControllerEnvironmentWrapper.HostControllerEnvironmentStatus.ERROR) { abort(); <START> } <END> return null; } else { try { final HostControllerBootstrap hc = new HostControllerBootstrap(hostControllerEnvironmentWrapper.getHostControllerEnvironment(), authCode); hc.bootstrap(); return hc; } catch(Throwable t) { abort(t); return null; } } } catch (Throwable t) { abort(t); return null; } }</code><technical_language>need 'else' clause end calling SystemExiter.logAndExit(), ExitLogger a no-op. create a constant in SystemExiter class</technical_language>

Target:
private HostControllerBootstrap boot(String[] args, final String authCode) { try { final long startTime = Module.getStartTime(); final HostControllerEnvironmentWrapper hostControllerEnvironmentWrapper = determineEnvironment(args, startTime); if (hostControllerEnvironmentWrapper.getHostControllerEnvironment() == null) { usage(); if (hostControllerEnvironmentWrapper.getHostControllerEnvironmentStatus() == HostControllerEnvironmentWrapper.HostControllerEnvironmentStatus.ERROR) { abort(); } else { SystemExiter.safeAbort(); } return null; } else { try { final HostControllerBootstrap hc = new HostControllerBootstrap(hostControllerEnvironmentWrapper.getHostControllerEnvironment(), authCode); hc.bootstrap(); return hc; } catch(Throwable t) { abort(t); return null; } } } catch (Throwable t) { abort(t); return null; } }
Source:
<code>public MethodInvariantContext(MethodTree methodTree) { this.methodTree = methodTree; TypeTree returnType = methodTree.returnType(); this.returnStatementTrees = extractReturnStatements(methodTree); methodToCheck = !isConstructorOrVoid(returnType) && returnStatementTrees.size() > 1; <START> returnImmutableType = methodToCheck && (returnType.symbolType().isPrimitive() || returnType.symbolType().is("java.lang.String")); <END> }</code><technical_language>need for this</technical_language>

Target:
MethodInvariantContext(MethodTree methodTree) { this.methodTree = methodTree; TypeTree returnType = methodTree.returnType(); this.returnStatementTrees = extractReturnStatements(methodTree); methodToCheck = !isConstructorOrVoid(methodTree, returnType) && returnStatementTrees.size() > 1; returnImmutableType = methodToCheck && (returnType.symbolType().isPrimitive() || returnType.symbolType().is("java.lang.String")); }
Source:
<code>protected static Predicate<Image> createPredicateMatchingRepoTags(final String imageIdOrName) { return new Predicate<Image>() { @Override public boolean apply(Image input) { <START> final String imageNameWithHostPrefix = "docker.io/" + imageIdOrName; <END> for (String tag : input.repoTags()) { if (tag.equals(imageIdOrName) || tag.equals(imageIdOrName + ":latest") || tag.equals(imageNameWithHostPrefix) || tag.equals(imageNameWithHostPrefix + ":latest")) { return true; } } return false; } }; }</code><technical_language>Move "docker.io" a constant referenced tests too? IIRC previous versions of Docker prefixed official images library/. I agree this is change, I is worth prefix isolated in a single constant</technical_language>

Target:
protected static Predicate<Image> createPredicateMatchingRepoTags(final String imageIdOrName) { final Pattern imgPattern = Pattern .compile(PATTERN_IMAGE_PREFIX + Pattern.quote(imageIdOrName) + PATTERN_IMAGE_SUFFIX); return new Predicate<Image>() { @Override public boolean apply(Image input) { for (String tag : input.repoTags()) { if (imgPattern.matcher(tag).matches()) { return true; } } return false; } }; }
Source:
<code>public void validateInstalatorData(VM vm, String token) throws InvalidInstallProductRequestException { if (!vm.canWorkWithInstallatorServer()) { String message = "The VM does not include the node hostname required to Install " + "software"; throw new InvalidInstallProductRequestException(message); } try { this.isNodeRegistered(vm.getHostname(), token); <START> } catch (CanNotCallChefException e) { <END> String errorMesg = "Node " + vm.getHostname() + " is not registered in ChefServer"; log.info(errorMesg); throw new InvalidInstallProductRequestException(errorMesg); } }</code><technical_language>cannotcallpuppetexception</technical_language>

Target:
public void validateInstalatorData(VM vm, String token) throws InvalidInstallProductRequestException { if (!vm.canWorkWithInstallatorServer()) { String message = "The VM does not include the node hostname required to Install " + "software"; throw new InvalidInstallProductRequestException(message); } try { this.isNodeRegistered(vm.getHostname(), token); } catch (CanNotCallPuppetException e) { String errorMesg = "Node " + vm.getHostname() + " is not registered in the puppet master " + e.getMessage(); log.info(errorMesg); throw new InvalidInstallProductRequestException(errorMesg); } }
Source:
<code>public void initialise() { UIText address = find("address", UIText.class); <START> getManager().setFocus(address); <END> WidgetUtil.trySubscribe(this, "join", new ActivateEventListener() { @Override public void onActivated(UIWidget button) { getManager().popScreen(); UIText address = find("address", UIText.class); JoinStatus status = networkSystem.join(address.getText(), TerasologyConstants.DEFAULT_PORT); if (status.getStatus() != JoinStatus.Status.FAILED) { engine.changeState(new StateLoading(status)); } else { getManager().pushScreen("engine:errorMessagePopup", ErrorMessagePopup.class) .setError("Failed to Join", "Could not connect to server - " + status.getErrorMessage()); } } }); WidgetUtil.trySubscribe(this, "cancel", new ActivateEventListener() { @Override public void onActivated(UIWidget button) { getManager().popScreen(); } }); }</code><technical_language>do this onOpen in initialise</technical_language>

Target:
public void initialise() { WidgetUtil.trySubscribe(this, "join", new ActivateEventListener() { @Override public void onActivated(UIWidget button) { getManager().popScreen(); UIText address = find("address", UIText.class); JoinStatus status = networkSystem.join(address.getText(), TerasologyConstants.DEFAULT_PORT); if (status.getStatus() != JoinStatus.Status.FAILED) { engine.changeState(new StateLoading(status)); } else { getManager().pushScreen("engine:errorMessagePopup", ErrorMessagePopup.class) .setError("Failed to Join", "Could not connect to server - " + status.getErrorMessage()); } } }); WidgetUtil.trySubscribe(this, "cancel", new ActivateEventListener() { @Override public void onActivated(UIWidget button) { getManager().popScreen(); } }); }
Source:
<code>public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) { return null; } Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Map<Object, Object> data = new HashMap<>(); if (labels.containsKey(SystemLabels.LABEL_AGENT_CREATE) && labels.get(SystemLabels.LABEL_AGENT_CREATE).equals("true")) { List<String> dataVolumes = new ArrayList<>(DataAccessor.fieldStringList(instance, InstanceConstants.FIELD_DATA_VOLUMES)); if (!dataVolumes.contains(AgentConstants.AGENT_INSTANCE_BIND_MOUNT)) { dataVolumes.add(AgentConstants.AGENT_INSTANCE_BIND_MOUNT); } data.put(InstanceConstants.FIELD_DATA_VOLUMES, dataVolumes); } setName(instance, labels, data); setNetworkMode(instance, labels, data); setDns(instance, labels, data); setLogConfig(instance, data); if (!data.isEmpty()) { return new HandlerResult(data); } String uuid = DataAccessor.fieldString(instance, InstanceConstants.FIELD_IMAGE_UUID); <START> if (uuid == null || uuid.isEmpty() || uuid.trim().isEmpty()) { <END> return null; } String fullImageName = DockerImage.parse(uuid).getFullName(); DockerImage dockerImage = DockerImage.parse(uuid); if (dockerImage == null) { return null; } String server = dockerImage.getServer(); if (!fullImageName.startsWith(server)) { String defaultRegistry = DEFAULT_REGISTRY.get(); fullImageName = defaultRegistry + "/" + fullImageName; } data.put(InstanceConstants.FIELD_IMAGE_UUID, fullImageName); return null; }</code><technical_language>change for null isEmpty StringUtils.isEmpty method</technical_language>

Target:
public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) { return null; } Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Map<Object, Object> data = new HashMap<>(); if (labels.containsKey(SystemLabels.LABEL_AGENT_CREATE) && labels.get(SystemLabels.LABEL_AGENT_CREATE).equals("true")) { List<String> dataVolumes = new ArrayList<>(DataAccessor.fieldStringList(instance, InstanceConstants.FIELD_DATA_VOLUMES)); if (!dataVolumes.contains(AgentConstants.AGENT_INSTANCE_BIND_MOUNT)) { dataVolumes.add(AgentConstants.AGENT_INSTANCE_BIND_MOUNT); } data.put(InstanceConstants.FIELD_DATA_VOLUMES, dataVolumes); } setName(instance, labels, data); setNetworkMode(instance, labels, data); setDns(instance, labels, data); setLogConfig(instance, data); if (!data.isEmpty()) { return new HandlerResult(data); } return null; }
Source:
<code>public List<MetricFamilySamples> collect() { ArrayList<MetricFamilySamples> mfSamples = new ArrayList<MetricFamilySamples>(); for (SortedMap.Entry<String, Gauge> entry : registry.getGauges().entrySet()) { <START> mfSamples.addAll(fromGauge(entry.getKey(), entry.getValue())); <END> } for (SortedMap.Entry<String, Counter> entry : registry.getCounters().entrySet()) { mfSamples.addAll(fromCounter(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Histogram> entry : registry.getHistograms().entrySet()) { mfSamples.addAll(fromHistogram(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Timer> entry : registry.getTimers().entrySet()) { mfSamples.addAll(fromTimer(entry.getKey(), entry.getValue())); } for (SortedMap.Entry<String, Meter> entry : registry.getMeters().entrySet()) { mfSamples.addAll(fromMeter(entry.getKey(), entry.getValue())); } return mfSamples; }</code><technical_language>names tend periods, need sanitize valid metric names in Prometheus</technical_language>

Target:
public List<MetricFamilySamples> collect() { ArrayList<MetricFamilySamples> mfSamples = new ArrayList<MetricFamilySamples>(); for (SortedMap.Entry<String, Gauge> entry : registry.getGauges().entrySet()) { mfSamples.addAll(fromGauge(sanitizeMetricName(entry.getKey()), entry.getValue())); } for (SortedMap.Entry<String, Counter> entry : registry.getCounters().entrySet()) { mfSamples.addAll(fromCounter(sanitizeMetricName(entry.getKey()), entry.getValue())); } for (SortedMap.Entry<String, Histogram> entry : registry.getHistograms().entrySet()) { mfSamples.addAll(fromHistogram(sanitizeMetricName(entry.getKey()), entry.getValue())); } for (SortedMap.Entry<String, Timer> entry : registry.getTimers().entrySet()) { mfSamples.addAll(fromTimer(sanitizeMetricName(entry.getKey()), entry.getValue())); } for (SortedMap.Entry<String, Meter> entry : registry.getMeters().entrySet()) { mfSamples.addAll(fromMeter(sanitizeMetricName(entry.getKey()), entry.getValue())); } return mfSamples; }
Source:
<code>public boolean hasChildren(Object element) { <START> return ((MyModel) element).children.size() > 0; <END> }</code><technical_language>isEmpty() check collection is empty not</technical_language>

Target:
public boolean hasChildren(Object element) { return !((MyModel) element).children.isEmpty(); }
Source:
<code>public BarData doInBackground(Void... params) { cardDao = dbOpenHelper.getCardDao(); Integer DAYS = 30; List<String> xVals = new ArrayList<String>(INITIAL_CAPACITY); List<BarEntry> yVals = new ArrayList<BarEntry>(INITIAL_CAPACITY); <START> Integer MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; <END> Date now = new Date(); for (int i = -INITIAL_CAPACITY; i < 1; i++) { Date endDate = new Date(now.getTime() + i * MILLISECONDS_PER_DAY); Date startDate = new Date(endDate.getTime() - MILLISECONDS_PER_DAY); xVals.add("" + i); yVals.add(new BarEntry((float)cardDao.getNewLearnedCardCount(null, startDate, endDate), INITIAL_CAPACITY + i)); } BarDataSet dataSet = new BarDataSet(yVals, getString(R.string.number_of_new_cards_learned_in_a_day_text)); BarData data = new BarData(xVals, dataSet); data.setValueTextColor(Color.WHITE); return data; }</code><technical_language>This private static field in class</technical_language>

Target:
public BarData doInBackground(Void... params) { cardDao = dbOpenHelper.getCardDao(); List<String> xVals = new ArrayList<String>(INITIAL_CAPACITY); List<BarEntry> yVals = new ArrayList<BarEntry>(INITIAL_CAPACITY); Date now = new Date(); for (int i = -INITIAL_CAPACITY; i < 1; i++) { Date endDate = new Date(now.getTime() + i * MILLISECONDS_PER_DAY); Date startDate = new Date(endDate.getTime() - MILLISECONDS_PER_DAY); xVals.add("" + i); yVals.add(new BarEntry((float)cardDao.getNewLearnedCardCount(null, startDate, endDate), INITIAL_CAPACITY + i)); } BarDataSet dataSet = new BarDataSet(yVals, getString(R.string.number_of_new_cards_learned_in_a_day_text)); BarData data = new BarData(xVals, dataSet); data.setValueTextColor(Color.WHITE); return data; }