auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("<replace-with-your-text-analytics-key-here>") .endpoint("<replace-with-your-text-analytics-endpoint-here>") .buildClient(); String text = "hello world"; final DetectLanguageResult detectLanguageResult = client.detectLanguage(text, "US"); <START> final DetectedLanguage detectedDocumentLanguage = detectLanguageResult.getPrimaryLanguage(); <END> System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", detectedDocumentLanguage.getName(), detectedDocumentLanguage.getIso6391Name(), detectedDocumentLanguage.getScore()); final List<DetectedLanguage> detectedLanguages = detectLanguageResult.getDetectedLanguages(); for (DetectedLanguage detectedLanguage : detectedLanguages) { System.out.printf("Other detected languages: %s, ISO 6391 name: %s, score: %s.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }</code><technical_language>nit: call this variable detectedPrimaryLanguage</technical_language>

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("{subscription_key}") .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); String text = "hello world"; final DetectLanguageResult detectLanguageResult = client.detectLanguage(text, "US"); final DetectedLanguage detectedPrimaryLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", detectedPrimaryLanguage.getName(), detectedPrimaryLanguage.getIso6391Name(), detectedPrimaryLanguage.getScore()); for (DetectedLanguage detectedLanguage : detectLanguageResult.getDetectedLanguages()) { System.out.printf("Another detected language: %s, ISO 6391 name: %s, score: %s.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }
Source:
<code>protected BlobHardRef getRef(Object entity) { try { return (BlobHardRef) super.getValueFromField(this.accessPath.apply(entity)); } catch (Exception e) { throw Exceptions.handle() .to(OMA.LOG) .error(e) .withSystemErrorMessage( <START> "Unable to obtain StoredObjectRef object from entity ref field ('%s' in '%s'): %s (%s)", <END> getName(), descriptor.getType().getName()) .handle(); } }</code><technical_language>StoredObject, right</technical_language>

Target:
protected BlobHardRef getRef(Object entity) { try { return (BlobHardRef) super.getValueFromField(this.accessPath.apply(entity)); } catch (Exception e) { throw Exceptions.handle() .to(OMA.LOG) .error(e) .withSystemErrorMessage( "Unable to obtain a reference object from entity ref field ('%s' in '%s'): %s (%s)", getName(), descriptor.getType().getName()) .handle(); } }
Source:
<code>public final long numberOfBits(final Integer value) { <START> if (value + offset >= (1L << readNofBits)) <END> throw new IllegalArgumentException("Value to be written is bigger then allowed: value=" + value + ", max nof bits=" + readNofBits); return readNofBits; }</code><technical_language>This correct case. Do code sets offset noticed bug? needs additional constrain is + offset >= 0</technical_language>

Target:
public final long numberOfBits(final Integer value) { return bitsPerValue; }
Source:
<code>public void openPortForwardingAndAdvertise(EntityAndAttribute<Integer> privatePort, Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr, EntityAndAttribute<String> whereToAdvertiseEndpoint) { getPortForwarderAsync().openPortForwardingAndAdvertise(privatePort, optionalPublicPort, protocol, accessingCidr, <START> Optional.of(whereToAdvertiseEndpoint), Optional.<EntityAndAttribute<String>>absent()); <END> }</code><technical_language>leave this calling deprecated method getPortForwarderAsync(), Optional.absent() here. duplicating handling of deprecated case in async code</technical_language>

Target:
public void openPortForwardingAndAdvertise(EntityAndAttribute<Integer> privatePort, Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr, EntityAndAttribute<String> whereToAdvertiseEndpoint) { getPortForwarderAsync().openPortForwardingAndAdvertise(privatePort, optionalPublicPort, protocol, accessingCidr, whereToAdvertiseEndpoint); }
Source:
<code>private void loadData(final View view) { if ( courseData == null ) return; if (isTaskRunning) { logger.debug("skipping a call to loadData, task is already running"); getHeirarchyTask.setTaskProcessCallback(taskProcessCallback); return; } <START> getHeirarchyTask = new GetCourseOutlineTask(getActivity()) { <END> @Override public void onFinish(ICourse course) { if (course != null) { logger.debug("Start displaying on UI "+ DateUtil.getCurrentTimeStamp()); adapter.setData(course); if(adapter.getCount()==0){ view.findViewById(R.id.no_chapter_tv).setVisibility(View.VISIBLE); } } CourseManager.getSharedInstance().setCourseInView(course); if (adapter.getCount() == 0) { } logger.debug("Completed displaying data on UI "+ DateUtil.getCurrentTimeStamp()); isTaskRunning = false; } @Override public void onException(Exception ex) { if(adapter.getCount()==0) { } isTaskRunning = false; } }; getHeirarchyTask.setTaskProcessCallback(taskProcessCallback); logger.debug("Initializing Chapter Task"+ DateUtil.getCurrentTimeStamp()); isTaskRunning = true; getHeirarchyTask.execute(courseData.getCourse().getId()); }</code><technical_language>hierarchy is misspelled</technical_language>

Target:
private void loadData(final View view) { if ( courseData == null ) return; if (isTaskRunning) { logger.debug("skipping a call to loadData, task is already running"); getHierarchyTask.setTaskProcessCallback(taskProcessCallback); return; } getHierarchyTask = new GetCourseOutlineTask(getActivity()) { @Override public void onFinish(ICourse course) { if (course != null) { logger.debug("Start displaying on UI "+ DateUtil.getCurrentTimeStamp()); adapter.setData(course); if(adapter.getCount()==0){ view.findViewById(R.id.no_chapter_tv).setVisibility(View.VISIBLE); } } CourseManager.getSharedInstance().setCourseInView(course); if (adapter.getCount() == 0) { } logger.debug("Completed displaying data on UI "+ DateUtil.getCurrentTimeStamp()); isTaskRunning = false; } @Override public void onException(Exception ex) { if(adapter.getCount()==0) { } isTaskRunning = false; } }; getHierarchyTask.setTaskProcessCallback(taskProcessCallback); logger.debug("Initializing Chapter Task" + DateUtil.getCurrentTimeStamp()); isTaskRunning = true; getHierarchyTask.execute(courseData.getCourse().getId()); }
Source:
<code>public static boolean waitForServerUp(String hp, long timeout, boolean secure) { long start = Time.currentElapsedTime(); while (true) { try { HostPort hpobj = parseHostPortList(hp).get(0); String result = send4LetterWord(hpobj.host, hpobj.port, "stat", secure); if (result.startsWith("Zookeeper version:") && !result.contains("READ-ONLY")) { return true; } } catch (ConnectException e) { LOG.info("server not up", hp); <START> } catch (IOException e) { <END> LOG.info("server not up", hp, e); } catch (SSLContextException e) { LOG.error("server not up", hp, e); } if (Time.currentElapsedTime() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { } } return false; }</code><technical_language>If printing stacktraces is useful annoying, Adding e.getMessage() type of exception happened is better</technical_language>

Target:
public static boolean waitForServerUp(String hp, long timeout, boolean secure) { long start = Time.currentElapsedTime(); while (true) { try { HostPort hpobj = parseHostPortList(hp).get(0); String result = send4LetterWord(hpobj.host, hpobj.port, "stat", secure); if (result.startsWith("Zookeeper version:") && !result.contains("READ-ONLY")) { return true; } } catch (ConnectException e) { LOG.info("server not up: {}", hp, e.toString()); } catch (IOException e) { LOG.info("server not up", hp, e); } catch (SSLContextException e) { LOG.error("server not up", hp, e); } if (Time.currentElapsedTime() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { } } return false; }
Source:
<code>public void revalidateSession(QuorumPacket qp, LearnerHandler learnerHandler) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(qp.getData()); DataInputStream dis = new DataInputStream(bis); long id = dis.readLong(); int to = dis.readInt(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeLong(id); boolean valid = zk.checkIfValidGlobalSession(id, to); if (valid) { try { zk.setOwner(id, learnerHandler); } catch (KeeperException.SessionExpiredException e) { LOG.error( <START> "Somehow session expired right after being renewed! (impossible)", <END> Long.toHexString(id), e); } } if (LOG.isTraceEnabled()) { ZooTrace.logTraceMessage( LOG, ZooTrace.SESSION_TRACE_MASK, "Session 0x" + Long.toHexString(id) + " is valid: " + valid); } dos.writeBoolean(valid); qp.setData(bos.toByteArray()); learnerHandler.queuePacket(qp); }</code><technical_language>Add "0x"</technical_language>

Target:
public void revalidateSession(QuorumPacket qp, LearnerHandler learnerHandler) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(qp.getData()); DataInputStream dis = new DataInputStream(bis); long id = dis.readLong(); int to = dis.readInt(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeLong(id); boolean valid = zk.checkIfValidGlobalSession(id, to); if (valid) { try { zk.setOwner(id, learnerHandler); } catch (KeeperException.SessionExpiredException e) { LOG.error( "Somehow session 0x{} expired right after being renewed! (impossible)", Long.toHexString(id), e); } } if (LOG.isTraceEnabled()) { ZooTrace.logTraceMessage( LOG, ZooTrace.SESSION_TRACE_MASK, "Session 0x" + Long.toHexString(id) + " is valid: " + valid); } dos.writeBoolean(valid); qp.setData(bos.toByteArray()); learnerHandler.queuePacket(qp); }
Source:
<code>public void writeContent(XMLExtendedStreamWriter writer, ModelMarshallingContext context) throws XMLStreamException { String defaultNamespace = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); ModelNode subsystems = context.getModelNode().get(SUBSYSTEM); boolean empty = !subsystems.has(mainSubsystemName); try { if (!empty) { ModelNode subsystem = subsystems.get(mainSubsystemName); XMLElementWriter<SubsystemMarshallingContext> subsystemWriter = context.getSubsystemWriter(mainSubsystemName); if (subsystemWriter != null) { subsystemWriter.writeContent(writer, new SubsystemMarshallingContext(subsystem, writer)); } } }catch (Throwable t){ Assert.fail("could not marshal subsystem xml: "+t.getMessage()+":\n"+ Arrays.toString(t.getStackTrace()).replaceAll(", ","\n")); } finally { writer.setDefaultNamespace(defaultNamespace); } if (empty){ writer.writeEmptyElement(Element.SUBSYSTEM.getLocalName()); <START> } <END> writer.writeEndDocument(); }</code><technical_language>in try block</technical_language>

Target:
public void writeContent(XMLExtendedStreamWriter writer, ModelMarshallingContext context) throws XMLStreamException { String defaultNamespace = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX); try { ModelNode subsystems = context.getModelNode().get(SUBSYSTEM); if (subsystems.has(mainSubsystemName)) { ModelNode subsystem = subsystems.get(mainSubsystemName); XMLElementWriter<SubsystemMarshallingContext> subsystemWriter = context.getSubsystemWriter(mainSubsystemName); if (subsystemWriter != null) { subsystemWriter.writeContent(writer, new SubsystemMarshallingContext(subsystem, writer)); } }else{ writer.writeEmptyElement(Element.SUBSYSTEM.getLocalName()); } }catch (Throwable t){ Assert.fail("could not marshal subsystem xml: "+t.getMessage()+":\n"+ Arrays.toString(t.getStackTrace()).replaceAll(", ","\n")); } finally { writer.setDefaultNamespace(defaultNamespace); } writer.writeEndDocument(); }
Source:
<code>public void add(GeoLocationParseResult<T> toAdd) { <START> this.successfullyParsed = (this.successfullyParsed == false) <END> ? false : toAdd.isSuccessfullyParsed(); this.items.addAll(toAdd.getItems()); }</code><technical_language>I believed Codacy flagged this. I this replaced this.successfullyParsed &&= toAdd.isSuccessfullyParsed()</technical_language>

Target:
public void add(GeoLocationParseResult<T> toAdd) { this.successfullyParsed = this.successfullyParsed && toAdd.isSuccessfullyParsed(); this.items.addAll(toAdd.getItems()); }
Source:
<code>public PathResult(AnalysisWorkerTask task, TransitLayer transitLayer) { if (task instanceof TravelTimeSurfaceTask) { nDestinations = 1; } else { nDestinations = task.nTargetsPerOrigin(); if (nDestinations > 5000) throw new UnsupportedOperationException("Path results are limited to 5000 " + "destinations"); } <START> this.nIterations = task.getTimeWindowLengthMinutes() * task.getMonteCarloDrawsPerMinute(); <END> itinerariesForPathTemplates = new Multimap[nDestinations]; this.transitLayer = transitLayer; }</code><technical_language>For reasons discussed in #661 this number of iterations wrong if half-headway</technical_language>

Target:
public PathResult(AnalysisWorkerTask task, TransitLayer transitLayer) { if (task instanceof TravelTimeSurfaceTask) { nDestinations = 1; } else { nDestinations = task.nTargetsPerOrigin(); if (nDestinations > 5000) throw new UnsupportedOperationException("Path results are limited to 5000 " + "destinations"); } this.nIterations = task.getTotalIterations(transitLayer.hasFrequencies); itinerariesForPathTemplates = new Multimap[nDestinations]; this.transitLayer = transitLayer; }
Source:
<code>public static MPMetrics getInstance(Context context, String token) { MPMetrics instance = mInstanceMap.get(token); if (instance == null) { instance = new MPMetrics(context.getApplicationContext(), token); mInstanceMap.put(token, instance); } <START> instance.mPushPref.edit().putString("mp_token", token).commit(); <END> return instance; }</code><technical_language>I SharedPreferences shared tokens, if is multiple tokens, this overwrite token. writing device ids wrong project. Please check this</technical_language>

Target:
public static MPMetrics getInstance(Context context, String token) { MPMetrics instance = mInstanceMap.get(token); if (instance == null) { instance = new MPMetrics(context.getApplicationContext(), token); mInstanceMap.put(token, instance); } return instance; }
Source:
<code>private String sendRequest(String url) throws IOException { BufferedReader in = null; StringBuilder b = new StringBuilder(); try{ URLConnection urlConnection = new URL(url).openConnection(); in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.forName("utf-8"))); String inputLine = in.readLine(); while (inputLine != null) { b.append(inputLine).append("\n"); inputLine = in.readLine(); } <START> }finally { <END> if(in != null){ try{ in.close(); }catch (IOException e){ log.error("Error occurred while closing BufferedReader"); } } } return b.toString(); }</code><technical_language>space betweeen } finally</technical_language>

Target:
private String sendRequest(String url) throws IOException { BufferedReader in = null; StringBuilder b = new StringBuilder(); try{ URLConnection urlConnection = new URL(url).openConnection(); in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.forName("utf-8"))); String inputLine = in.readLine(); while (inputLine != null) { b.append(inputLine).append("\n"); inputLine = in.readLine(); } } finally { IdentityIOStreamUtils.closeReader(in); } return b.toString(); }
Source:
<code>public void addQueues(Queue... queues) { <START> addQueues(Arrays.asList(queues) <END> .stream() .map(Queue::getName) .collect(Collectors.toList())); super.addQueues(queues); }</code><technical_language>a method called Arrays.stream(array...)</technical_language>

Target:
public void addQueues(Queue... queues) { try { addQueues(Arrays.stream(queues) .map(Queue::getName)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + Arrays.asList(queues), e.getCause()); } super.addQueues(queues); }
Source:
<code>public void trackUserSubmitRating(String versionName, int rating) { final FirebaseEvent event = new FirebaseEvent(Events.APP_REVIEWS_SUBMIT_RATING, Values.APP_REVIEWS_SUBMIT_RATING); event.putString(Keys.APP_VERSION, versionName); <START> event.putLong(Keys.RATING, rating); <END> logFirebaseEvent(event.getName(), event.getBundle()); }</code><technical_language>a putInt function in FirebaseEvent class instead of putLong</technical_language>

Target:
public void trackUserSubmitRating(String versionName, int rating) { final FirebaseEvent event = new FirebaseEvent(Events.APP_REVIEWS_SUBMIT_RATING, Values.APP_REVIEWS_SUBMIT_RATING); event.putString(Keys.CATEGORY, Values.APP_REVIEWS_CATEGORY); event.putString(Keys.APP_VERSION, versionName); event.putInt(Keys.RATING, rating); logFirebaseEvent(event.getName(), event.getBundle()); }
Source:
<code>protected CloudBigtableScanConfiguration( ValueProvider<String> projectId, ValueProvider<String> instanceId, ValueProvider<String> tableId, ValueProvider<ReadRowsRequest> request, Map<String, ValueProvider<String>> additionalConfiguration) { super(projectId, instanceId, tableId, additionalConfiguration); this.request = NestedValueProvider.of( <START> request, <END> new SerializableFunction<ReadRowsRequest, ReadRowsRequest>() { @Override public ReadRowsRequest apply(ReadRowsRequest request) { if (!request.getTableName().isEmpty()) { return request; } BigtableInstanceName bigtableInstanceName = new BigtableInstanceName(getProjectId(), getInstanceId()); String fullTableName = bigtableInstanceName.toTableNameStr(getTableId()); return request.toBuilder().setTableName(fullTableName).build(); } }); }</code><technical_language>ValueProvider interface isAccessible method. implement interface & in isAccessible return logical of components' isAccessible</technical_language>

Target:
protected CloudBigtableScanConfiguration( ValueProvider<String> projectId, ValueProvider<String> instanceId, ValueProvider<String> tableId, ValueProvider<ReadRowsRequest> request, Map<String, ValueProvider<String>> additionalConfiguration) { super(projectId, instanceId, tableId, additionalConfiguration); this.request = new RequestValueProvider(projectId, instanceId, tableId, request); }
Source:
<code>private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) throws ServletParseException { String senderPath = sender.path().name(); callMap.remove(senderPath); CallInfo callInfo = callDetailsMap.remove(senderPath); if (callInfo != null && callInfo.invite() != null) { if (logger.isDebugEnabled()) { logger.debug("onStopObserving Before: callLocationMap: "+ callLocationMap.toString()); } callLocationMap.remove(callInfo.invite().getAddressHeader(ContactHeader.NAME).getURI().toString()); if (logger.isDebugEnabled()) { <START> logger.debug("onStopObserving After: callLocationMap: "+ callLocationMap.toString()); <END> } } if (callInfo.direction().equalsIgnoreCase("inbound")) { if (logger.isDebugEnabled()) { logger.debug("Removed inbound call from: "+callInfo.from()+" to: "+callInfo.to()); } incomingCallDetailsMap.remove(senderPath); } else { if (logger.isDebugEnabled()) { logger.debug("Removed outbound call from: "+callInfo.from()+" to: "+callInfo.to()); } outgoingCallDetailsMap.remove(senderPath); } callStateMap.remove(senderPath); }</code><technical_language>removed</technical_language>

Target:
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) throws ServletParseException { String senderPath = sender.path().name(); callMap.remove(senderPath); CallInfo callInfo = callDetailsMap.remove(senderPath); if (callInfo != null && callInfo.invite() != null) { callLocationMap.remove(callInfo.invite().getAddressHeader(ContactHeader.NAME).getURI().toString()); } if (callInfo.direction().equalsIgnoreCase("inbound")) { if (logger.isDebugEnabled()) { logger.debug("Removed inbound call from: "+callInfo.from()+" to: "+callInfo.to()); } incomingCallDetailsMap.remove(senderPath); } else { if (logger.isDebugEnabled()) { logger.debug("Removed outbound call from: "+callInfo.from()+" to: "+callInfo.to()); } outgoingCallDetailsMap.remove(senderPath); } callStateMap.remove(senderPath); }
Source:
<code>private AbstractChannelHandlerContext findContextOutbound(int mask) { AbstractChannelHandlerContext ctx = this; EventExecutor currentExecutor = executor(); do { ctx = ctx.prev; } while (!ChannelHandlerMask.isOutbound(ctx.executionMask) <START> || (ctx.executionMask & mask) == 0 && ctx.executor() == currentExecutor); <END> return ctx; }</code><technical_language>this is correct (and above) a ClassCastException if ChannelHandlerContext wrap ChannelOutboundHandler</technical_language>

Target:
private AbstractChannelHandlerContext findContextOutbound(int mask) { AbstractChannelHandlerContext ctx = this; EventExecutor currentExecutor = executor(); do { ctx = ctx.prev; } while (skipContext(ctx, currentExecutor, mask, MASK_ONLY_OUTBOUND)); return ctx; }
Source:
<code>private void matchBibFile(Path file, String line) { Matcher bibliographyMatch = BIBLIOGRAPHY_PATTERN.matcher(line); while (bibliographyMatch.find()) { Arrays.stream(bibliographyMatch.group(BIBLIOGRAPHY_GROUP).split(",")) .map(bibString -> file.toAbsolutePath().getParent().resolve(bibString.endsWith(BIB_EXT) ? bibString : String.format("%s%s", bibString, BIB_EXT))) .filter(bibFile -> bibFile.toFile().exists()) <START> .forEach(bibFile -> texParserResult.addBibFile(file, bibFile)); <END> } }</code><technical_language>also, a traditonal for loop is</technical_language>

Target:
private void matchBibFile(Path file, String line) { Matcher bibliographyMatch = BIBLIOGRAPHY_PATTERN.matcher(line); while (bibliographyMatch.find()) { for (String bibString : bibliographyMatch.group(BIBLIOGRAPHY_GROUP).split(",")) { bibString = bibString.trim(); Path bibFile = file.getParent().resolve( bibString.endsWith(BIB_EXT) ? bibString : String.format("%s%s", bibString, BIB_EXT)); if (bibFile.toFile().exists()) { texParserResult.addBibFile(file, bibFile); } } } }
Source:
<code>private void addEntry(T value) { <START> final HorizontalPanel entry = new HorizontalPanel(); <END> entry.addStyleName(style.entryStyle()); contentPanel.add(entry); final V widget = createWidget(value); Pair<T, V> item = new Pair<T, V>(value, widget); items.add(item); entry.add(widget); PushButton button = createButton(item); entry.add(button); final boolean ghost = isGhost(value); toggleGhost(value, widget, ghost); widget.addValueChangeHandler(new ValueChangeHandler<T>() { private boolean wasGhost = ghost; @Override public void onValueChange(ValueChangeEvent<T> event) { T value = event.getValue(); boolean becomingGhost = isGhost(value); if (becomingGhost != wasGhost) { ((PushButton) entry.getWidget(entry.getWidgetCount() - 1)).setEnabled(!becomingGhost); toggleGhost(value, widget, becomingGhost); wasGhost = becomingGhost; } } }); onAdd(value, widget); }</code><technical_language>Please try avoid Horizontal/Vertical panels if is a bit possible. rendered tables is hard style content divs (FlowPanels) try avoid them</technical_language>

Target:
private void addEntry(T value) { final V widget = createWidget(value); Pair<T, V> item = new Pair<T, V>(value, widget); items.add(item); PushButton button = createButton(item); final boolean ghost = isGhost(value); toggleGhost(value, widget, ghost); widget.addValueChangeHandler(new ValueChangeHandler<T>() { private boolean wasGhost = ghost; @Override public void onValueChange(ValueChangeEvent<T> event) { T value = event.getValue(); boolean becomingGhost = isGhost(value); if (becomingGhost != wasGhost) { ((AddRemoveRowPanel) widget.getParent()).setButtonEnabled(!becomingGhost); toggleGhost(value, widget, becomingGhost); wasGhost = becomingGhost; } } }); AddRemoveRowPanel entry = new AddRemoveRowPanel(widget, button); contentPanel.add(entry); onAdd(value, widget); }
Source:
<code>public void debugClearMessagesLocally(final List<LocalMessage> messages) { <START> if (!K9.DEBUG) { <END> throw new AssertionError("method must only be used in debug build!"); } putBackground("debugClearLocalMessages", null, new Runnable() { @Override public void run() { for (LocalMessage message : messages) { try { message.debugClearLocalData(); } catch (MessagingException e) { throw new AssertionError("clearing local message content failed!", e); } } } }); }</code><technical_language>K9.DEBUG is constant tied "debug logging" setting. Please BuildConfig.DEBUG</technical_language>

Target:
public void debugClearMessagesLocally(final List<LocalMessage> messages) { if (!BuildConfig.DEBUG) { throw new AssertionError("method must only be used in debug build!"); } putBackground("debugClearLocalMessages", null, new Runnable() { @Override public void run() { for (LocalMessage message : messages) { try { message.debugClearLocalData(); } catch (MessagingException e) { throw new AssertionError("clearing local message content failed!", e); } } } }); }
Source:
<code>public void createCache(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { Configuration existing = cacheManager.getCacheConfiguration(name); if (existing == null) { cacheManager.defineConfiguration(name, configuration); log.debugf("Defined cache '%s' on '%s' using %s", name, cacheManager.getAddress(), configuration); } else if (!existing.equals(configuration)) { throw log.incompatibleClusterConfiguration(name, configuration, existing); } else { log.debugf("%s already has a cache %s with configuration %s", cacheManager.getAddress(), name, configuration); } if (flags.contains(CacheContainerAdmin.AdminFlag.PERSISTENT)) { <START> persistentCaches.add(name); <END> storeAll(); } cacheManager.getCache(name); }</code><technical_language>store invoked add() is successful</technical_language>

Target:
public void createCache(String name, Configuration configuration, EnumSet<CacheContainerAdmin.AdminFlag> flags) { Configuration existing = cacheManager.getCacheConfiguration(name); if (existing == null) { cacheManager.defineConfiguration(name, configuration); log.debugf("Defined cache '%s' on '%s' using %s", name, cacheManager.getAddress(), configuration); } else if (!existing.matches(configuration)) { throw log.incompatibleClusterConfiguration(name, configuration, existing); } else { log.debugf("%s already has a cache %s with configuration %s", cacheManager.getAddress(), name, configuration); } if (flags.contains(CacheContainerAdmin.AdminFlag.PERMANENT)) { persistentCaches.add(name); storeAll(); } cacheManager.getCache(name); }
Source:
<code>public String generateUuid() { String uuid = UUID.randomUUID().toString(); <START> if (useHyphens) { <END> uuid = uuid.replaceAll("-", ""); } return uuid; }</code><technical_language>I this !useHyphens</technical_language>

Target:
public String generateUuid() { String uuid = UUID.randomUUID().toString(); if (!useHyphens) { uuid = uuid.replaceAll("-", ""); } return uuid; }
Source:
<code>private InvalidSyntaxError mkException(Parser recognizer, RecognitionException cause) { int line = -1; int column = -1; String msg = null; String sourcePreview = null; Token currentToken = recognizer.getCurrentToken(); if (currentToken != null) { line = currentToken.getLine(); column = currentToken.getCharPositionInLine(); sourcePreview = mkPreview(line); msg = "Offending token is '" + currentToken.getText() + "'"; } <START> return new InvalidSyntaxError(singletonList(new SourceLocation(line, column, sourceName)), msg, sourcePreview, cause); <END> }</code><technical_language>resulting message end a -1,-1 location if currentToken result in a null value</technical_language>

Target:
private InvalidSyntaxException mkException(Parser recognizer, RecognitionException cause) { String sourcePreview = null; String offendingToken = null; SourceLocation sourceLocation = null; Token currentToken = recognizer.getCurrentToken(); if (currentToken != null) { int line = currentToken.getLine(); int column = currentToken.getCharPositionInLine(); offendingToken = currentToken.getText(); sourcePreview = mkPreview(line); sourceLocation = new SourceLocation(line, column, sourceName); } return new InvalidSyntaxException(sourceLocation, null, sourcePreview, offendingToken, cause); }
Source:
<code>private static void dumpHadoopCounters(PigStats pigStats) { try { <START> if (props.getBoolean("pig.dump.hadoopCounter", false)) { <END> if (pigStats != null) { JobGraph jGraph = pigStats.getJobGraph(); Iterator<JobStats> iter = jGraph.iterator(); while (iter.hasNext()) { JobStats jobStats = iter.next(); System.out.println("\n === Counters for job: " + jobStats.getJobId() + " ==="); Counters counters = jobStats.getHadoopCounters(); if (counters != null) { for (Counters.Group group : counters) { System.out.println(" Counter Group: " + group.getDisplayName() + " (" + group.getName() + ")"); System.out.println(" number of counters in this group: " + group.size()); for (Counters.Counter counter : group) { System.out.println(" - " + counter.getDisplayName() + ": " + counter.getCounter()); } } } else { System.out.println("There are no counters"); } } } else { System.out.println("pigStats is null, can't dump Hadoop counters"); } } } catch (Exception e) { System.out.println("Unexpected error: " + e.getMessage()); e.printStackTrace(System.out); } }</code><technical_language>"pig.dump.hadoopCounter" a const</technical_language>

Target:
private static void dumpHadoopCounters(PigStats pigStats) { try { if (props.getBoolean(PIG_DUMP_HADOOP_COUNTER_PROPERTY, false)) { if (pigStats != null) { JobGraph jGraph = pigStats.getJobGraph(); Iterator<JobStats> iter = jGraph.iterator(); while (iter.hasNext()) { JobStats jobStats = iter.next(); System.out.println("\n === Counters for job: " + jobStats.getJobId() + " ==="); Counters counters = jobStats.getHadoopCounters(); if (counters != null) { for (Counters.Group group : counters) { System.out.println(" Counter Group: " + group.getDisplayName() + " (" + group.getName() + ")"); System.out.println(" number of counters in this group: " + group.size()); for (Counters.Counter counter : group) { System.out.println(" - " + counter.getDisplayName() + ": " + counter.getCounter()); } } } else { System.out.println("There are no counters"); } } } else { System.out.println("pigStats is null, can't dump Hadoop counters"); } } } catch (Exception e) { System.out.println("Unexpected error: " + e.getMessage()); e.printStackTrace(System.out); } }
Source:
<code>public static Optional<Server> getServer(io.swagger.oas.annotations.servers.Server server) { if (server == null) { return Optional.empty(); } Server serverObject = new Server(); serverObject.setUrl(server.url()); serverObject.setDescription(server.description()); io.swagger.oas.annotations.servers.ServerVariable[] serverVariables = server.variables(); ServerVariables serverVariablesObject = new ServerVariables(); for (io.swagger.oas.annotations.servers.ServerVariable serverVariable : serverVariables) { ServerVariable serverVariableObject = new ServerVariable(); serverVariableObject.setDescription(serverVariable.description()); <START> serverVariablesObject.addServerVariable(serverVariable.name(), serverVariableObject); <END> } serverObject.setVariables(serverVariablesObject); return Optional.of(serverObject); }</code><technical_language>In general, adding a map, please ensure key is empty string StringUtils.isNotBlank(...) avoid stuff this: json "servers" : [ { "url" : "", "description" : "", "variables" : { "" : { "description" : "" } } } ]</technical_language>

Target:
public static Optional<Server> getServer(io.swagger.oas.annotations.servers.Server server) { if (server == null) { return Optional.empty(); } Server serverObject = new Server(); if (StringUtils.isNotBlank(server.url())) { serverObject.setUrl(server.url()); } if (StringUtils.isNotBlank(server.description())) { serverObject.setDescription(server.description()); } io.swagger.oas.annotations.servers.ServerVariable[] serverVariables = server.variables(); ServerVariables serverVariablesObject = new ServerVariables(); for (io.swagger.oas.annotations.servers.ServerVariable serverVariable : serverVariables) { ServerVariable serverVariableObject = new ServerVariable(); if (StringUtils.isNotBlank(serverVariable.description())) { serverVariableObject.setDescription(serverVariable.description()); } serverVariablesObject.addServerVariable(serverVariable.name(), serverVariableObject); } serverObject.setVariables(serverVariablesObject); return Optional.of(serverObject); }
Source:
<code>public int visit(IASTDeclSpecifier declSpec) { if (declSpec.isConst()) { String rawSignature = declSpec.getRawSignature(); if (!expectConstRight && !rawSignature.startsWith(Keywords.CONST)) { declSpecifiersWithMisalignedConst.add(declSpec); } else if <START> (expectConstRight && !rawSignature.endsWith(Keywords.CONST)) <END> { declSpecifiersWithMisalignedConst.add(declSpec); } } return PROCESS_CONTINUE; }</code><technical_language>I tell, ISO-14882 allows cv-qualifiers right side. This check mark int const volatile foo{}; for rewriting. catch case, rewrite nonetheless</technical_language>

Target:
public int visit(IASTDeclSpecifier declSpec) { if (declSpec.isConst()) { String rawSignature = declSpec.getRawSignature(); rawSignature = rawSignature.replace(Keywords.VOLATILE, "").trim(); if (!expectConstRight && !startsWithConst(rawSignature)) { declSpecifiersWithMisalignedConst.add(declSpec); } else if (expectConstRight && !endsWithConst(rawSignature)) { declSpecifiersWithMisalignedConst.add(declSpec); } } return PROCESS_CONTINUE; }
Source:
<code>private String[] getRoles(Set<Principal> principals) { <START> List<String> roles = new ArrayList<>(); <END> for (Principal principal : principals) { roles.add(principal.getName()); } return roles.toArray(new String[roles.size()]); }</code><technical_language>prevent reallocation of underlaying array, give a size hint if (principals.size())</technical_language>

Target:
private String[] getRoles(Set<Principal> principals) { String[] roles = new String[principals.size()]; int i = 0; for (Principal principal : principals) { roles[i++] = principal.getName(); } return roles; }
Source:
<code>private void growup() { <START> if (values.length == capacity()) { <END> throw new IllegalStateException("This matrix can't grow up."); } int c = rows * columns < 0 ? Integer.MAX_VALUE : rows * columns; int capacity = Math.min(c, (cardinality * 3) / 2 + 1); double $values[] = new double[capacity]; int $columnIndices[] = new int[capacity]; System.arraycopy(values, 0, $values, 0, cardinality); System.arraycopy(columnIndices, 0, $columnIndices, 0, cardinality); values = $values; columnIndices = $columnIndices; }</code><technical_language>Looks, need test for CCSMatrix</technical_language>

Target:
private void growup() { if (values.length == capacity()) { throw new IllegalStateException("This matrix can't grow up."); } int min = rows * columns; min = min < 0 ? Integer.MAX_VALUE : min; int capacity = Math.min(min, (cardinality * 3) / 2 + 1); double $values[] = new double[capacity]; int $columnIndices[] = new int[capacity]; System.arraycopy(values, 0, $values, 0, cardinality); System.arraycopy(columnIndices, 0, $columnIndices, 0, cardinality); values = $values; columnIndices = $columnIndices; }
Source:
<code>private Pair<Number, Number> tryConvergeVolatileOSMetrics(String attribute, Function<OSMetrics, Number> func) { try { Number cdsValue = 0; Number osMetricValue = -1; for (int i = 0; i < 5; i++) { CompositeDataSupport cds = (CompositeDataSupport) getPlatformMBeanServer() .invoke(mbeanObjectName, "showOSMetrics", null, null); cdsValue = (Number) cds.get(attribute); osMetricValue = func.apply(getMXBeanProxy().showOSMetrics()); if (cdsValue.equals(osMetricValue)) { break; } System.gc(); <START> System.runFinalization(); <END> } return Pair.of(cdsValue, osMetricValue); } catch (Exception ex) { return null; } }</code><technical_language>change test more patient expected value? Do values currently updated</technical_language>

Target:
private void tryConvergeVolatileOSMetrics(String attribute, Function<OSMetrics, Number> func) { GeodeAwaitility.await(attribute).atMost(SAMPLE_RATE * 5, TimeUnit.MILLISECONDS) .untilAsserted(() -> { CompositeDataSupport cds = (CompositeDataSupport) getPlatformMBeanServer() .invoke(mbeanObjectName, "showOSMetrics", null, null); Number cdsValue = (Number) cds.get(attribute); Number osMetricValue = func.apply(getMXBeanProxy().showOSMetrics()); assertThat(cdsValue).isEqualTo(osMetricValue); }); }
Source:
<code>protected Locale getLocaleFromRequest(final HttpServletRequest request) { String localeString = getLocaleStringFromReferer(request); <START> if (null == localeString) { <END> localeString = getLocaleStringFromPath(request.getPathInfo()); } Locale locale = LocaleUtils.getLocaleFromString(localeString, true); return locale; }</code><technical_language>Please "something <operator> null" convention</technical_language>

Target:
protected Locale getLocaleFromRequest(final HttpServletRequest request) { String localeString = getLocaleStringFromReferer(request); if (localeString == null) { localeString = getLocaleStringFromPath(request.getPathInfo()); } Locale locale = LocaleUtils.getLocaleFromString(localeString, true); return locale; }
Source:
<code>public static File getOpennlpDataDir() { <START> return new File(System.getProperty("OPENNLP_DATA_DIR")); <END> }</code><technical_language>This is a nice of fail. If data dir is set throws a NullPointerException. I propose catch case throw exception a proper description</technical_language>

Target:
public static File getOpennlpDataDir() throws FileNotFoundException { final String dataDirectory = System.getProperty("OPENNLP_DATA_DIR"); if (StringUtil.isEmpty(dataDirectory)) { throw new IllegalArgumentException("The OPENNLP_DATA_DIR is not set."); } final File file = new File(System.getProperty("OPENNLP_DATA_DIR")); if (!file.exists()) { throw new FileNotFoundException("The OPENNLP_DATA_DIR path of " + dataDirectory + " was not found."); } return file; }
Source:
<code>private void drawRevenue() { int minY = Integer.MAX_VALUE, maxY = 0; Date lastDate = null; for (Rank rank : ranks) { int gap = 0; if (rank.revenue.intValue() < minY) { minY = rank.revenue.intValue(); } if (rank.revenue.intValue() > maxY) { maxY = rank.revenue.intValue(); } if (lastDate != null && (gap = CalendarUtil.getDaysBetween(lastDate, rank.date)) > 1) { for (int i = 0; i < gap; i++) { CalendarUtil.addDaysToDate(lastDate, 1); curve.addPoint(lastDate.getTime(), Integer.MAX_VALUE); } } else { lastDate = CalendarUtil.copyDate(rank.date); <START> curve.addPoint(rank.date.getTime(), (showModelPredictions) ? rank.revenue.floatValue() : 0); <END> } } setYAxisRange(minY, maxY); }</code><technical_language>need for brackets here, if want put close bracket 0</technical_language>

Target:
private void drawRevenue() { int minY = Integer.MAX_VALUE, maxY = 0; Date lastDate = null; for (Rank rank : ranks) { int gap = 0; if (rank.revenue.intValue() < minY) { minY = rank.revenue.intValue(); } if (rank.revenue.intValue() > maxY) { maxY = rank.revenue.intValue(); } if (lastDate != null && (gap = CalendarUtil.getDaysBetween(lastDate, rank.date)) > 1) { for (int i = 0; i < gap; i++) { CalendarUtil.addDaysToDate(lastDate, 1); curve.addPoint(lastDate.getTime(), Integer.MAX_VALUE); } } else { lastDate = CalendarUtil.copyDate(rank.date); curve.addPoint(rank.date.getTime(), (showModelPredictions ? rank.revenue.floatValue() : 0)); } } setYAxisRange(minY, maxY); }
Source:
<code>public void activate() { <START> logger.debug("activate() is called!"); <END> }</code><technical_language>please remove decrease log level TRACE</technical_language>

Target:
public void activate() { logger.trace("activate() is called!"); }
Source:
<code>public void testSerializeUserListMessage() throws IOException { List<String> usernames = userList.getUsernames(); Hashtable<String, String> users = userList.getUsers(); UserListMessage oldMessage = new UserListMessage(); oldMessage.setUserList(userList); UserListMessage newMessage = super.testSerializeMessage(oldMessage); for(int i = 0; i < userList.getUsers().size(); i++) { System.out.println(i); assertEquals(usernames.get(i), newMessage.getUserList().getUsernames().get(i)); assertEquals(users.get(usernames.get(i)), <START> newMessage.getUserList().getUsers().get(newMessage.getUserList().getUsernames().get(i))); <END> } }</code><technical_language>This is a LOT of chaining..</technical_language>

Target:
public void testSerializeUserListMessage() throws IOException { UserList userList = new UserList(); populateTestUserList(userList); List<String> usernames = userList.getUsernames(); UserListMessage preSerializationUserListMessage = new UserListMessage(); preSerializationUserListMessage.setUserList(userList); UserListMessage postSerializationUserListMessage = super.testSerializeMessage(preSerializationUserListMessage); for(int i = 0; i < usernames.size(); i++) { assertEquals(usernames.get(i), postSerializationUserListMessage.getUserList().getUsernames().get(i)); } }
Source:
<code><START> protected void authenticatePacketHMAC(RawPacket pkt, int rocIn) <END> { mac.update(pkt.getBuffer(), pkt.getOffset(), pkt.getLength()); rbStore[0] = (byte) (rocIn >> 24); rbStore[1] = (byte) (rocIn >> 16); rbStore[2] = (byte) (rocIn >> 8); rbStore[3] = (byte) rocIn; mac.update(rbStore, 0, rbStore.length); mac.doFinal(tagStore, 0); }</code><technical_language>is this related subject of this PR and/or OveruseEstimator? @champtar, I please ask PRs a single, standalone subject? If need work dependent subjects, create PRs state in of depends other paste a link it</technical_language>

Target:
synchronized protected void authenticatePacketHMAC(RawPacket pkt, int rocIn) { mac.update(pkt.getBuffer(), pkt.getOffset(), pkt.getLength()); rbStore[0] = (byte) (rocIn >> 24); rbStore[1] = (byte) (rocIn >> 16); rbStore[2] = (byte) (rocIn >> 8); rbStore[3] = (byte) rocIn; mac.update(rbStore, 0, rbStore.length); mac.doFinal(tagStore, 0); }
Source:
<code>static public boolean sendXMPP( @ParamDoc(name="to") String to, @ParamDoc(name="message") String message) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, null); try { while(message.length()>=2000) { newChat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { System.out.println("Error Delivering block"); } catch (NotConnectedException e) { <START> System.out.println("Error Delivering block"); <END> } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; }</code><technical_language>i pattern please remove System.out log.warn instead? great if enhance error message (by e.getErrorMessage())</technical_language>

Target:
static public boolean sendXMPP( @ParamDoc(name="to") String to, @ParamDoc(name="message") String message) { boolean success = false; try { XMPPConnection conn = XMPPConnect.getConnection(); ChatManager chatmanager = ChatManager.getInstanceFor(conn); Chat newChat = chatmanager.createChat(to, null); try { while(message.length()>=2000) { newChat.sendMessage(message.substring(0, 2000)); message = message.substring(2000); } newChat.sendMessage(message); logger.debug("Sent message '{}' to '{}'.", message, to); success = true; } catch (XMPPException e) { logger.warn("Error Delivering block", e); } catch (NotConnectedException e) { logger.warn("Error Delivering block", e); } } catch (NotInitializedException e) { logger.warn("Could not send XMPP message as connection is not correctly initialized!"); } return success; }
Source:
<code>public BenchmarkSuiteInfo( @ColumnName("suite") String suite, @ColumnName("query_set") String querySet, @ColumnName("phases") List<PhaseSpecification> phases, @ColumnName("session_properties") Map<String, String> sessionProperties) { this.suite = requireNonNull(suite, "suite is null"); <START> this.querySet = requireNonNull(querySet, "query_set is null"); <END> this.phases = requireNonNull(phases, "phases is null"); this.sessionProperties = ImmutableMap.copyOf(sessionProperties); }</code><technical_language>querySet is null</technical_language>

Target:
public BenchmarkSuiteInfo( @ColumnName("suite") String suite, @ColumnName("query_set") String querySet, @ColumnName("phases") List<PhaseSpecification> phases, @ColumnName("session_properties") Map<String, String> sessionProperties) { this.suite = requireNonNull(suite, "suite is null"); this.querySet = requireNonNull(querySet, "querySet is null"); this.phases = requireNonNull(phases, "phases is null"); this.sessionProperties = ImmutableMap.copyOf(sessionProperties); }
Source:
<code>private void append(CharSequence csq) { try { out.append(csq); <START> } catch (IOException e) { <END> throw new AssertionError(e); } }</code><technical_language>JavaFile.writeTo methods throw AssertionErrors instead of IOExceptions? Sounds bad</technical_language>

Target:
private void append(CharSequence csq) { try { out.append(csq); } catch (IOException e) { throw new EmitRuntimeException(e); } }
Source:
<code>private List<Class<? extends Annotation>> findGinjectorAnnotations() throws UnableToCompleteException { List<Class<? extends Annotation>> annotations = new ArrayList<Class<? extends Annotation>>(); List<String> values = findConfigurationProperty(GIN_GINJECTOR_ANNOTATION).getValues(); <START> if (values.size() > 0) { <END> for (String value : values) { String annotationClassName = value.trim(); if (!annotationClassName.isEmpty()) { try { annotations.add(Class.forName(annotationClassName).asSubclass(Annotation.class)); } catch (ClassNotFoundException e) { getTreeLogger().log(TreeLogger.ERROR, "Cannot find the class '" + annotationClassName + "' used in '" + GIN_GINJECTOR_ANNOTATION + "' property."); throw new UnableToCompleteException(); } catch (ClassCastException e) { getTreeLogger().log(TreeLogger.ERROR, "Class '" + annotationClassName + "' used in '" + GIN_GINJECTOR_ANNOTATION + "' property is not an Annotation."); throw new UnableToCompleteException(); } } } } return annotations; }</code><technical_language>condition redundant</technical_language>

Target:
private List<Class<? extends Annotation>> findGinjectorAnnotations() throws UnableToCompleteException { List<Class<? extends Annotation>> annotations = new ArrayList<Class<? extends Annotation>>(); List<String> values = findConfigurationProperty(GIN_GINJECTOR_ANNOTATION).getValues(); for (String value : values) { String annotationClassName = value.trim(); if (!annotationClassName.isEmpty()) { try { annotations.add(Class.forName(annotationClassName).asSubclass(Annotation.class)); } catch (ClassNotFoundException e) { getTreeLogger().log(TreeLogger.ERROR, "Cannot find the class '" + annotationClassName + "' used in '" + GIN_GINJECTOR_ANNOTATION + "' property."); throw new UnableToCompleteException(); } catch (ClassCastException e) { getTreeLogger().log(TreeLogger.ERROR, "Class '" + annotationClassName + "' used in '" + GIN_GINJECTOR_ANNOTATION + "' property is not an Annotation."); throw new UnableToCompleteException(); } } } return annotations; }