auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void handleNewSession(final String sessionId) throws Exception { if (sessionId != null && !getSessionId().equals(sessionId)) { LOG.info("Session: is not handled because it is expired.", sessionId); return; } LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, <START> _instanceType, sessionId); <END> waitUntilConnected(); stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(false); } resetHandlers(false); _baseDataAccessor.reset(); if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } }</code><technical_language>If sessionId == null, log ugly. Please add a check avoid output "null"</technical_language>

Target:
public void handleNewSession(final String sessionId) throws Exception { waitUntilConnected(); LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, _instanceType, sessionId == null ? "None" : sessionId); stopTimerTasks(); if (_leaderElectionHandler != null) { _leaderElectionHandler.reset(false); } resetHandlers(false); _baseDataAccessor.reset(); if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); } _sessionStartTime = System.currentTimeMillis(); switch (_instanceType) { case PARTICIPANT: handleNewSessionAsParticipant(); break; case CONTROLLER: handleNewSessionAsController(); break; case CONTROLLER_PARTICIPANT: handleNewSessionAsParticipant(); handleNewSessionAsController(); break; case ADMINISTRATOR: case SPECTATOR: default: break; } startTimerTasks(); initHandlers(_handlers); if (_stateListener != null) { try { _stateListener.onConnected(this); } catch (Exception e) { LOG.warn("stateListener.onConnected callback fails", e); } } }
Source:
<code>public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition stateModel, boolean recreateIfExists) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("cluster " + clusterName + " is not setup yet"); } String stateModelDefPath = HelixUtil.getStateModelDefinitionPath(clusterName); String stateModelPath = stateModelDefPath + "/" + stateModelDef; if (_zkClient.exists(stateModelPath)) { if (recreateIfExists) { logger.warn("Operation.State Model directory exists:" + stateModelPath + ", remove and recreate."); _zkClient.deleteRecursive(stateModelPath); } else { logger.warn("Skip the operation.State Model directory exists:" + stateModelPath); <START> return; <END> } } HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.stateModelDef(stateModel.getId()), stateModel); }</code><technical_language>this changed longer throw exception? fail loudly in methods return void</technical_language>

Target:
public void addStateModelDef(String clusterName, String stateModelDef, StateModelDefinition stateModel, boolean recreateIfExists) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("cluster " + clusterName + " is not setup yet"); } String stateModelDefPath = HelixUtil.getStateModelDefinitionPath(clusterName); String stateModelPath = stateModelDefPath + "/" + stateModelDef; if (_zkClient.exists(stateModelPath)) { if (recreateIfExists) { logger.info("Operation.State Model directory exists:" + stateModelPath + ", remove and recreate."); _zkClient.deleteRecursive(stateModelPath); } else { logger.info("Skip the operation. State Model directory exists:" + stateModelPath); return; } } HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.stateModelDef(stateModel.getId()), stateModel); }
Source:
<code>public static OvernightRateSensitivity of( OvernightIndex index, Currency currency, LocalDate fixingDate, double sensitivity) { LocalDate endDate = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(fixingDate)); <START> return new OvernightRateSensitivity(index, currency, fixingDate, endDate, sensitivity); <END> }</code><technical_language>return of(index, currency, fixingDate, endDate, sensitivity);</technical_language>

Target:
public static OvernightRateSensitivity of( OvernightIndex index, Currency currency, LocalDate fixingDate, double sensitivity) { LocalDate endDate = index.calculateMaturityFromEffective(index.calculateEffectiveFromFixing(fixingDate)); return OvernightRateSensitivity.of(index, currency, fixingDate, endDate, sensitivity); }
Source:
<code>private void matched(Matcher matcher, HttpMessage msg, int id) { String tag = getConf(); if (tagHistoryType(msg.getHistoryRef().getHistoryType())) { if (matcher.groupCount() > 0) { StringBuffer result = new StringBuffer(); matcher.appendReplacement(result, tag); tag = result.substring(matcher.start()); <START> parent.addTag(id, tag); <END> } else { parent.addTag(id, tag); } } try { Stats.incCounter(SessionStructure.getHostName(msg), TAG_STATS_PREFIX + this.getConf()); } catch (URIException e) { } }</code><technical_language>This done outside/after if/then branches. replaced tag in stats</technical_language>

Target:
private void matched(Matcher matcher, HttpMessage msg, int id) { String tag = getConf(); if (tagHistoryType(msg.getHistoryRef().getHistoryType())) { if (matcher.groupCount() > 0) { tag = matcher.pattern().matcher(matcher.group()).replaceFirst(tag); } parent.addTag(id, tag); } try { Stats.incCounter(SessionStructure.getHostName(msg), TAG_STATS_PREFIX + this.getConf()); } catch (URIException e) { } }
Source:
<code>XmlManifest(RepoCommand command, InputStream inputStream, String filename, String baseUrl, String groups) { this.command = command; this.inputStream = inputStream; this.filename = filename; <START> this.baseUrl = baseUrl.replaceAll("/+$", ""); END> remotes = new HashMap<String, String>(); projects = new ArrayList<Project>(); plusGroups = new HashSet<String>(); minusGroups = new HashSet<String>(); if (groups == null || groups.length() == 0 || groups.equals("default")) { minusGroups.add("notdefault"); } else { for (String group : groups.split(",")) { if (group.startsWith("-")) minusGroups.add(group.substring(1)); else plusGroups.add(group); } } }</code><technical_language>This is pretty inefficient, do this in JGit is: while (baseUrl.charAt(baseUrl.length() - 1) == '/') baseUrl = baseUrl.substring(0, baseUrl.length() - 1);</technical_language>

Target:
XmlManifest(RepoCommand command, InputStream inputStream, String filename, String baseUrl, String groups) { this.command = command; this.inputStream = inputStream; this.filename = filename; int lastIndex = baseUrl.length() - 1; while (baseUrl.charAt(lastIndex) == '/') lastIndex--; this.baseUrl = baseUrl.substring(0, lastIndex + 1); remotes = new HashMap<String, String>(); projects = new ArrayList<Project>(); plusGroups = new HashSet<String>(); minusGroups = new HashSet<String>(); if (groups == null || groups.length() == 0 || groups.equals("default")) { minusGroups.add("notdefault"); } else { for (String group : groups.split(",")) { if (group.startsWith("-")) minusGroups.add(group.substring(1)); else plusGroups.add(group); } } }
Source:
<code><START> public ClusterFeature mapRow(ResultSet rs, int rowNum) <END> throws SQLException { ClusterFeature feature = new ClusterFeature(); feature.setVdsGroupId(getGuidDefaultEmpty(rs, "vds_group_id")); feature.setEnabled(rs.getBoolean("is_enabled")); feature.setFeature(rs.getString("feature")); return feature; }</code><technical_language>please merge lines</technical_language>

Target:
public ClusterFeature mapRow(ResultSet rs, int rowNum) throws SQLException { ClusterFeature feature = new ClusterFeature(); feature.setFeatureId(getGuidDefaultEmpty(rs, "feature_id")); feature.setFeature(rs.getString("feature")); feature.setDescription(rs.getString("description")); feature.setApplicationMode(ApplicationMode.from(rs.getInt("app_mode"))); feature.setVersion(rs.getString("version")); return feature; }
Source:
<code>public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorControlLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, <START> cursorControlLocation.x)); <END> long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }</code><technical_language>Technically, this in control's coordinates is in control's parent's coordinates. However, control is currently x=0 in parent..</technical_language>

Target:
public void zoom(boolean zoomIn) { Point cursorDisplayLocation = getDisplay().getCursorLocation(); Point cursorControlLocation = toControl(cursorDisplayLocation); Point cursorParentLocation = getParent().toControl(cursorDisplayLocation); Rectangle controlBounds = getBounds(); if (!controlBounds.contains(cursorParentLocation.x, controlBounds.y)) { return; } int nameSpace = fTimeProvider.getNameSpace(); int timeSpace = fTimeProvider.getTimeSpace(); int xPos = Math.max(nameSpace, Math.min(nameSpace + timeSpace, cursorControlLocation.x)); long time0 = fTimeProvider.getTime0(); long time1 = fTimeProvider.getTime1(); long interval = time1 - time0; if (interval == 0) { interval = 1; } long newInterval; if (zoomIn) { newInterval = Math.max(Math.round(interval * ZOOM_IN_FACTOR), fTimeProvider.getMinTimeInterval()); } else { newInterval = (long) Math.ceil(interval * ZOOM_OUT_FACTOR); } long center = time0 + Math.round(((double) (xPos - nameSpace) / timeSpace * interval)); long newTime0 = center - Math.round((double) newInterval * (center - time0) / interval); newTime0 = Math.max(fTimeProvider.getMinTime(), Math.min(newTime0, fTimeProvider.getMaxTime() - newInterval)); long newTime1 = newTime0 + newInterval; fTimeProvider.setStartFinishTimeNotify(newTime0, newTime1); }
Source:
<code>private Node tryFoldKnownMethods(Node subtree) { checkArgument(subtree.isCall(), subtree); subtree = tryFoldArrayJoin(subtree); if (subtree.isCall()) { subtree = tryToFoldArrayConcat(subtree); checkState(subtree.isCall(), subtree); Node callTarget = checkNotNull(subtree.getFirstChild()); <START> if (NodeUtil.isGet(callTarget)) { <END> if (callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Array": return tryFoldKnownArrayMethods(subtree, callTarget); case "Math": if (isASTNormalized()) { return tryFoldKnownMathMethods(subtree, callTarget); } break; default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }</code><technical_language>I follow this isASTNormalized() check is incompatible new optimization. I thought waiting for AST normalized work "Array" "Math". it</technical_language>

Target:
private Node tryFoldKnownMethods(Node subtree) { checkArgument(subtree.isCall(), subtree); subtree = tryFoldArrayJoin(subtree); if (subtree.isCall()) { subtree = tryToFoldArrayConcat(subtree); checkState(subtree.isCall(), subtree); Node callTarget = checkNotNull(subtree.getFirstChild()); if (NodeUtil.isGet(callTarget)) { if (isASTNormalized() && callTarget.getFirstChild().isQualifiedName()) { switch (callTarget.getFirstChild().getQualifiedName()) { case "Array": return tryFoldKnownArrayMethods(subtree, callTarget); case "Math": return tryFoldKnownMathMethods(subtree, callTarget); default: } } subtree = tryFoldKnownStringMethods(subtree, callTarget); } else if (callTarget.isName()) { subtree = tryFoldKnownNumericMethods(subtree, callTarget); } } return subtree; }
Source:
<code>public Review(List<ReviewFile> files, boolean revievTestFiles) { if (revievTestFiles) { this.files = files; } else { this.files = FluentIterable.from(files) .filter(new Predicate<ReviewFile>() { @Override public boolean apply(ReviewFile file) { return !file.isTestFile(); } }).toList(); <START> } <END> }</code><technical_language>I this body, I prefere extracted a method called constructor</technical_language>

Target:
public Review(List<ReviewFile> files, boolean revievTestFiles) { if (revievTestFiles) { this.files = files; } else { this.files = filterOutTestFiles(files); } }
Source:
<code>public PageWriter(DataSink dataSink, DataSize pageFileStripeMaxSize) { this.dataSink = requireNonNull(dataSink, "pageDataSink is null"); this.maxBufferedBytes = requireNonNull(pageFileStripeMaxSize, "pageFileStripeMaxSize is null").toBytes(); bufferedPages = new ArrayList<>(); <START> stripeOffsets = new ArrayList<>(ImmutableList.of(0L)); <END> }</code><technical_language>if stripes? feels this initialized empty</technical_language>

Target:
public PageWriter(DataSink dataSink, DataSize pageFileStripeMaxSize) { this.dataSink = requireNonNull(dataSink, "pageDataSink is null"); this.maxBufferedBytes = requireNonNull(pageFileStripeMaxSize, "pageFileStripeMaxSize is null").toBytes(); bufferedPages = new ArrayList<>(); stripeOffsets = new ArrayList<>(); }
Source:
<code>public void unvoidPatientProgram_shouldTestUnvoidPatientProgram() { PatientProgram patientProgram = pws.getPatientProgram(1); PatientProgram patientProgram1 = pws.voidPatientProgram(patientProgram, "expired"); Date voidDate = patientProgram.getDateVoided(); patientProgram1 = pws.unvoidPatientProgram(patientProgram); assertEquals(patientProgram1.getVoided(), false); for (PatientState state : patientProgram.getStates()) { if (voidDate != null && voidDate.equals(state.getDateVoided())) { assertEquals(state.getVoided(), false); assertNull(state.getVoidedBy()); assertNull(state.getDateVoided()); <START> assertNull(state.getVoidReason()); <END> } } }</code><technical_language>voidDate is human understandable. a english name for void? this date is relevant</technical_language>

Target:
public void unvoidPatientProgram_shouldTestUnvoidPatientProgram() { PatientProgram existingPatientProgram = pws.getPatientProgram(1); PatientProgram existingPatientProgramVoided = pws.voidPatientProgram(existingPatientProgram, "expired"); Date patientProgramDateVoided = existingPatientProgramVoided.getDateVoided(); existingPatientProgramVoided = pws.unvoidPatientProgram(existingPatientProgram); assertEquals(existingPatientProgramVoided.getVoided(), false); for (PatientState state : existingPatientProgram.getStates()) { assertEquals(state.getVoided(), false); if (patientProgramDateVoided != null && patientProgramDateVoided.equals(state.getDateVoided())) { assertNull(state.getVoidedBy()); assertNull(state.getDateVoided()); assertNull(state.getVoidReason()); } } }
Source:
<code>public void toggleStarred(String key, String value) { TaskAttribute taskAttribute = fTaskData.getRoot(); <START> taskAttribute.getAttribute(key).setValue(value); <END> setAttribute(key, value); }</code><technical_language>attribute null here</technical_language>

Target:
public void toggleStarred(String key, String value) { if (key != null && value != null) { TaskAttribute taskAttribute = fTaskData.getRoot(); taskAttribute.getAttribute(key).setValue(value); setAttribute(key, value); } }
Source:
<code>public CliShellEnvironmentVariableHandler() { <START> specs.put(SHELL_DEBUG, new String[] {"true", "false"}, "false"); <END> }</code><technical_language>specs immutable initialized in constructor</technical_language>

Target:
public CliShellEnvironmentVariableHandler() { }
Source:
<code>private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); List<Step> steps = getStepDao().getStepsByExternalId(taskId); if (steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } for (Step step: steps) { if (step.getEndTime() != null) { continue; } <START> String message = getTaskMessage(cluster,step.getStepType(),task); <END> if(message.contains("Total size moved")) { int start = message.lastIndexOf(' ') + 1; int end = message.length() - 1; String sSize = message.substring(start, end); Long size = Long.parseLong(sSize); sSize = SizeConverter.toString(size); StringBuilder tmp = new StringBuilder(message); tmp = tmp.replace(start, end, sSize); message = new String(tmp.toString()); } step.setDescription(message); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } return runningTasks; }</code><technical_language>do this massaging in method getTaskMessage</technical_language>

Target:
private Map<Guid, GlusterAsyncTask> updateTasksInCluster(final VDSGroup cluster) { if (!supportsGlusterAsyncTasksFeature(cluster)) { return null; } Map<Guid, GlusterAsyncTask> runningTasks = getProvider().getTaskListForCluster(cluster.getId()); if (runningTasks == null) { return null; } for (Entry<Guid, GlusterAsyncTask> entry : runningTasks.entrySet()) { Guid taskId = entry.getKey(); final GlusterAsyncTask task = entry.getValue(); List<Step> steps = getStepDao().getStepsByExternalId(taskId); if (steps.isEmpty()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { try { createJobToMonitor(cluster,task); } catch (VdcBLLException e) { log.error("Error creating job for task from CLI", e); } return null; } }); } for (Step step: steps) { if (step.getEndTime() != null) { continue; } step.setDescription(getTaskMessage(cluster,step.getStepType(),task)); if (hasTaskCompleted(task)) { step.markStepEnded(task.getStatus()); endStepJob(step); releaseVolumeLock(task.getTaskId()); } else { getJobRepository().updateStep(step); } } } return runningTasks; }
Source:
<code>private Map<Class<? extends Annotation>, List<ClientListenerInvocation>> findMethods(Object listener) { Map<Class<? extends Annotation>, List<ClientListenerInvocation>> listenerMethodMap = new HashMap<Class<? extends Annotation>, List<ClientListenerInvocation>>(4, 0.99f); for (Method m : listener.getClass().getMethods()) { for (Map.Entry<Class<? extends Annotation>, Class<?>[]> entry : allowedListeners.entrySet()) { Class<? extends Annotation> annotationType = entry.getKey(); Class<?>[] eventTypes = entry.getValue(); if (m.isAnnotationPresent(annotationType)) { testListenerMethodValidity(m, eventTypes, annotationType.getName()); <START> m.setAccessible(true); <END> ClientListenerInvocation invocation = new ClientListenerInvocation(listener, m); List<ClientListenerInvocation> invocables = listenerMethodMap.get(annotationType); if (invocables == null) { invocables = new ArrayList<ClientListenerInvocation>(); listenerMethodMap.put(annotationType, invocables); } invocables.add(invocation); } } } return listenerMethodMap; }</code><technical_language>wrapped in SecurityAction</technical_language>

Target:
private Map<Class<? extends Annotation>, List<ClientListenerInvocation>> findMethods(Object listener) { Map<Class<? extends Annotation>, List<ClientListenerInvocation>> listenerMethodMap = new HashMap<Class<? extends Annotation>, List<ClientListenerInvocation>>(4, 0.99f); for (Method m : listener.getClass().getMethods()) { for (Map.Entry<Class<? extends Annotation>, Class<?>[]> entry : allowedListeners.entrySet()) { Class<? extends Annotation> annotationType = entry.getKey(); Class<?>[] eventTypes = entry.getValue(); if (m.isAnnotationPresent(annotationType)) { testListenerMethodValidity(m, eventTypes, annotationType.getName()); SecurityActions.setAccessible(m); ClientListenerInvocation invocation = new ClientListenerInvocation(listener, m); List<ClientListenerInvocation> invocables = listenerMethodMap.get(annotationType); if (invocables == null) { invocables = new ArrayList<ClientListenerInvocation>(); listenerMethodMap.put(annotationType, invocables); } invocables.add(invocation); } } } return listenerMethodMap; }
Source:
<code>public void createControl(Composite parent) { super.createControl(parent); Composite optionPane = (Composite) this.getControl(); optionPane.setLayout(new GridLayout()); optionPane.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true)); final SelectionListener linkedListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setLinked(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; fLink = new Button(optionPane, SWT.RADIO); <START> fLink.setText("Link traces (Recommended)"); END> fLink.setSelection(true); fLink.setLayoutData(new GridData()); fLink.addSelectionListener(linkedListener); fCopy = new Button(optionPane, SWT.RADIO); fCopy.setText("Copy traces"); fCopy.setLayoutData(new GridData()); fCopy.addSelectionListener(linkedListener); fOverwrite = new Button(optionPane, SWT.CHECK); fOverwrite.setText("Overwrite existing traces (recommended)"); fOverwrite.setLayoutData(new GridData()); fOverwrite.setSelection(true); fOverwrite.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { getBatchWizard().setOverwrite(((Button) e.widget).getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); createDestinationGroup(optionPane); getBatchWizard().setResourcePath(getContainerFullPath()); }</code><technical_language>externalized strings</technical_language>

Target:
public void createControl(Composite parent) { super.createControl(parent); init(); }
Source:
<code>public static FStringsGrammar createGrammar(String s) { <START> while (s.contains("\\N{")) { <END> int pos = s.indexOf("\\N{") + 3; int posLength = s.substring(0, pos).length(); s = s.replace(s.charAt(pos), '_'); String s_ = s.substring(pos); pos = s_.indexOf("}"); s = s.replace(s.charAt(pos + posLength), '_'); } FastCharStream in = new FastCharStream(s.toCharArray()); FStringsGrammar fStringsGrammar = new FStringsGrammar(in); return fStringsGrammar; }</code><technical_language>do as: int i; while((i=s.indexOf("\\N{")) != -1) { avoid iterate more (one for contains another for indexOf). Still, some issues in code... code check if s_.indexOf("}"); returns -1 (so, if have\\N{ closing issues) s = s.replace(s.charAt(pos), '_'); done replace occurrences of {, is want (so, if input multiple \\N code replaced {var}, find var (please create test cases for situations)). Also, I need create temporary strings, a single loop do want... code a bit (note: I run it, so, please update code if is wrong / tests fail -- provide idea for code). char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == '\\' && i + 2 < c.length && c[i + 1] == 'N' && c[i + 2] == '{') { c[i + 2] = '_'; i += 2; for (; i < c.length; i++) { if (c[i] == '}') { c[i] = '_'; break; } } } } test in conditions corner cases, \N \N{ \N{\N{}</technical_language>

Target:
public static FStringsGrammar createGrammar(String s) { char[] c = s.toCharArray(); for (int i = 0, z = 0; i < c.length; i++) { if (c[i] == '\\' && i + 2 < c.length && c[i + 1] == 'N' && c[i + 2] == '{') { c[i + 2] = '_'; i += 2; z = i + 1; for (; z < c.length; z++) { if (c[z] == '}') { c[z] = '_'; break; } } } } FastCharStream in = new FastCharStream(c); FStringsGrammar fStringsGrammar = new FStringsGrammar(in); return fStringsGrammar; }
Source:
<code>public Object call() throws Exception { if (request == null) { return null; } try { LOG.info("starting plan change "); LogicalPlan lp = plan.cloneLogicalPlan(); PlanModifier pm = new PlanModifier(lp); pm.applyDagChangeSet(request); lp.validate(); LOG.info("validated logical plan, now making actual change"); pm = new PlanModifier(plan); pm.applyDagChangeSet(request); LOG.info("plan change done"); return null; } finally { <START> plan.clearPendingChangeRequest(); <END> } }</code><technical_language>is this needed</technical_language>

Target:
public Object call() throws Exception { if (request == null) { return null; } try { LOG.info("Starting logical plan change "); LogicalPlan lp = (LogicalPlan)SerializationUtils.clone(plan.getLogicalPlan()); PlanModifier pm = new PlanModifier(lp); pm.applyDagChangeSet(request); lp.validate(); LOG.info("Validated logical plan, now making actual change"); pm = new PlanModifier(plan); pm.applyDagChangeSet(request); LOG.info("plan change done"); return null; } finally { plan.setPendingDagChangeRequest(null); } }
Source:
<code>private static <T extends SpecificRecord>JavaRDD<T> parseResultToAvro(JavaRDD<? extends Result> source, OafEntityToAvroConverter<Result, T> entityConverter) { <START> return source.map(x -> entityConverter.convert(x)).filter(x -> x != null); <END> }</code><technical_language>IDE hints replace source.map(x -> entityConverter.convert(x)).filter(x -> x != null) source.map(entityConverter::convert).filter(Objects::nonNull)</technical_language>

Target:
private static <T extends SpecificRecord>JavaRDD<T> parseResultToAvro(JavaRDD<? extends Result> source, OafEntityToAvroConverter<Result, T> entityConverter) { return source.map(entityConverter::convert).filter(Objects::nonNull); }
Source:
<code>void setResourceInformationUnSafe(Object resource, String resourceName, long amount) { if (!isYarnResourceTypesAvailable) { <START> LOG.info("Will not request extended resource because the underlying YARN does not support it.", resourceName); <END> return; } try { resourceSetResourceInformationMethod.invoke( resource, resourceName, resourceInformationNewInstanceMethod.invoke(null, resourceName, amount)); } catch (Exception e) { LOG.error("Error in setting the external resource {}, will not request it to YARN. {}", resourceName, e); } }</code><technical_language>suggestion LOG.info("Will request extended resource YARN version support it.", resourceName);</technical_language>

Target:
void setResourceInformationUnSafe(Object resource, String resourceName, long amount) { if (!isYarnResourceTypesAvailable) { LOG.info("Will not request extended resource because the used YARN version does not support it.", resourceName); return; } try { resourceSetResourceInformationMethod.invoke( resource, resourceName, resourceInformationNewInstanceMethod.invoke(null, resourceName, amount)); } catch (Exception e) { LOG.warn("Error in setting the external resource {}. Will not request this resource from YARN.", resourceName, e); } }
Source:
<code>public String getLabel(VDomainModelReference reference) { final String path = getEcorePath(); <START> if (path == null) { } <END> final String firstPath = path.split("/")[1]; final String editPath = firstPath + ".edit/plugin.properties"; final IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(editPath); if (member.exists()) { final File file = member.getLocation().toFile(); final Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); } catch (final FileNotFoundException ex) { ex.printStackTrace(); } catch (final IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (final IOException ex) { ex.printStackTrace(); } } } final EStructuralFeature feature = getEStructuralFeature(reference); if (feature == null) { return null; } final EClass eClass = feature.getEContainingClass(); final String key = String.format(DISPLAY_NAME, eClass.getName(), feature.getName()); final String result = p.getProperty(key); if (result == null) { return feature.getName(); } return result; } final EStructuralFeature feature = getEStructuralFeature(reference); return feature.getName(); }</code><technical_language>This if-block strange. Is missing something</technical_language>

Target:
public String getLabel(VDomainModelReference reference) { final String path = getEcorePath(); if (path == null) { try { final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<EMFFormsLabelProvider> serviceReference = bundleContext .getServiceReference(EMFFormsLabelProvider.class); final EMFFormsLabelProvider labelProvider = bundleContext.getService(serviceReference); final IObservableValue observableValue = labelProvider.getDisplayName(reference); final String result = (String) observableValue.getValue(); observableValue.dispose(); bundleContext.ungetService(serviceReference); return result; } catch (final NoLabelFoundException ex) { ex.printStackTrace(); } } final String firstPath = path.split("/")[1]; final String editPath = firstPath + ".edit/plugin.properties"; final IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(editPath); if (member.exists()) { final File file = member.getLocation().toFile(); final Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); } catch (final FileNotFoundException ex) { ex.printStackTrace(); } catch (final IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (final IOException ex) { ex.printStackTrace(); } } } final EStructuralFeature feature = getEStructuralFeature(reference); if (feature == null) { return null; } final EClass eClass = feature.getEContainingClass(); final String key = String.format(DISPLAY_NAME, eClass.getName(), feature.getName()); final String result = p.getProperty(key); if (result == null) { return feature.getName(); } return result; } final EStructuralFeature feature = getEStructuralFeature(reference); return feature.getName(); }
Source:
<code>private static String resolveKafkaService() { <START> final StringBuilder sb = new StringBuilder() <END> .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)); return sb.toString(); }</code><technical_language>need assign a variable</technical_language>

Target:
private static String resolveKafkaService() { return new StringBuilder() .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)).toString(); }
Source:
<code>private void restoreOrInit(PageStoreOptions options) { <START> Preconditions.checkState(mState.get() == READ_ONLY); <END> if (!restore(options)) { try { mPageStore.close(); try (LockResource r = new LockResource(mMetaLock.writeLock())) { mMetaStore.reset(); } PageStore.initialize(options); mPageStore = PageStore.create(options); } catch (Exception e) { LOG.error("Failed to clean up PageStore", e); return; } } mState.set(READ_WRITE); Metrics.STATE.inc(); }</code><technical_language>concern is if multiple threads restoreOrInit</technical_language>

Target:
private void restoreOrInit(PageStoreOptions options) { synchronized (LocalCacheManager.class) { Preconditions.checkState(mState.get() == READ_ONLY); if (!restore(options)) { try (LockResource r = new LockResource(mMetaLock.writeLock())) { mMetaStore.reset(); } try { mPageStore.close(); mPageStore = PageStore.create(options); } catch (Exception e) { LOG.error("Failed to create a new PageStore. Cache is NOT_IN_USE: ", e); mState.set(NOT_IN_USE); Metrics.STATE.dec(); return; } } LOG.info("Cache is in READ_WRITE."); mState.set(READ_WRITE); Metrics.STATE.inc(); } }
Source:
<code>void shutdown() { <START> executor.shutdown(); shutdown = true; <END> }</code><technical_language>right, I missed thanks</technical_language>

Target:
void shutdown() { shutdown = true; executor.shutdown(); }
Source:
<code>public void testReadWriteJimfs(String extension, boolean gzipped) throws IOException { final Path jmfsRoot = inMemoryFileSystem.getRootDirectories().iterator().next(); final Path tmp = Files.createTempFile(jmfsRoot, "test", extension); final String expected = "lorem ipswitch, nantucket, bucket"; <START> try( final Writer out = IOUtil.openFileForBufferedWriting(tmp)){ <END> out.write(expected); } try( final InputStream in = new BufferedInputStream(Files.newInputStream(tmp))){ Assert.assertEquals(IOUtil.isGZIPInputStream(in), gzipped); } try( final BufferedReader in = IOUtil.openFileForBufferedReading(tmp)){ final String actual = in.readLine(); Assert.assertEquals(actual, expected); } }</code><technical_language>suggestion try (Writer out = IOUtil.openFileForBufferedWriting(tmp)){</technical_language>

Target:
public void testReadWriteJimfs(String extension, boolean gzipped) throws IOException { final Path jmfsRoot = inMemoryFileSystem.getRootDirectories().iterator().next(); final Path tmp = Files.createTempFile(jmfsRoot, "test", extension); final String expected = "lorem ipswitch, nantucket, bucket"; try (Writer out = IOUtil.openFileForBufferedWriting(tmp)){ out.write(expected); } try (InputStream in = new BufferedInputStream(Files.newInputStream(tmp))){ Assert.assertEquals(IOUtil.isGZIPInputStream(in), gzipped); } try (BufferedReader in = IOUtil.openFileForBufferedReading(tmp)){ final String actual = in.readLine(); Assert.assertEquals(actual, expected); } }
Source:
<code>private boolean maybeCompleted(long time){ <START> if (time >= actionTime && type == TransactionTypeNormal) { <END> return true; } else { return false; } }</code><technical_language>return time >= actionTime && type == TransactionTypeNormal;</technical_language>

Target:
private boolean maybeCompleted(long time){ return shouldAction(time) && type == TransactionTypeNormal; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { NamedElement element = refactoring.getContextObject(); if (element != null) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); List<Issue> issues = validator.validate(element.eResource(), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl); Stream<Issue> errors = issues.stream().filter(issue -> issue.getSeverity() == Severity.ERROR); String message = ""; if (errors.count() > 0) { <START> message = "File contains errors!!\n\n"; <END> } message += "Please enter new name: "; InputDialog dialog = new InputDialog(window.getShell(), "Rename.." , message, element.getName(), new NameUniquenessValidator(element)); if (dialog.open() == Window.OK) { String newName = dialog.getValue(); if (newName != null) { ((RenameRefactoring)refactoring).setNewName(newName); refactoring.execute(); } } } return null; }</code><technical_language>a status bar indicating file contains errors renaming unsuccessful. Add a warning icon. / reuse parts of TitleAreaDialog <LINK_0></technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { NamedElement element = refactoring.getContextObject(); if (element != null) { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); List<Issue> issues = validator.validate(element.eResource(), CheckMode.NORMAL_AND_FAST, CancelIndicator.NullImpl); Stream<Issue> errors = issues.stream().filter(issue -> issue.getSeverity() == Severity.ERROR); RenameDialog dialog = new RenameDialog(window.getShell(), "Rename..", "Please enter new name: ", element.getName(), new NameUniquenessValidator(element), errors.count() > 0); if (dialog.open() == Window.OK) { String newName = dialog.getNewName(); if (newName != null) { ((RenameRefactoring) refactoring).setNewName(newName); refactoring.execute(); } } } return null; }
Source:
<code>public void constructorForJsonModelRunBindsParametersCorrectly() throws Exception { JsonModelDisease expectedDisease = new JsonModelDisease(); GeoJsonDiseaseOccurrenceFeatureCollection expectedOccurrences = new GeoJsonDiseaseOccurrenceFeatureCollection(); <START> Map<Integer, Integer> expectedExtents = new HashMap<>(); <END> JsonModelRun result = new JsonModelRun( expectedDisease, expectedOccurrences, expectedExtents); assertThat(result.getDisease()).isEqualTo(expectedDisease); assertThat(result.getOccurrences()).isEqualTo(expectedOccurrences); assertThat(result.getExtents()).isEqualTo(expectedExtents); }</code><technical_language>expectedExtentWeightings</technical_language>

Target:
public void constructorForJsonModelRunBindsParametersCorrectly() throws Exception { JsonModelDisease expectedDisease = new JsonModelDisease(); GeoJsonDiseaseOccurrenceFeatureCollection expectedOccurrences = new GeoJsonDiseaseOccurrenceFeatureCollection(); Map<Integer, Integer> expectedExtentWeightings = new HashMap<>(); JsonModelRun result = new JsonModelRun( expectedDisease, expectedOccurrences, expectedExtentWeightings); assertThat(result.getDisease()).isEqualTo(expectedDisease); assertThat(result.getOccurrences()).isEqualTo(expectedOccurrences); assertThat(result.getExtentWeightings()).isEqualTo(expectedExtentWeightings); }
Source:
<code><START> public <T extends OmiseList, S extends Model, R extends Request<S>> T sendRequest(R request, TypeReference<T> typeReference) throws IOException, OmiseException { <END> if (requester == null) return null; return requester.sendRequest(request, typeReference); }</code><technical_language>@Namiii type parameter of request class specifies returned right? do this? java public <T extends OmiseList, R extends Request<T>> T sendRequest( R request, TypeReference<T> typeReference )</technical_language>

Target:
public <T extends OmiseList, R extends Request<T>> T sendRequest(R request, TypeReference<T> typeReference) throws IOException, OmiseException { if (requester == null) return null; return requester.sendRequest(request, typeReference); }
Source:
<code><START> public static boolean filterSameDescriptor(IDataChartDescriptor<?, ?> desc, @Nullable IDataChartDescriptor<?, ?> filter) { <END> if (filter != null) { if (desc.getClass() != filter.getClass()) { return false; } } return true; }</code><technical_language>need "public" here, is public in interface. "static" is important though</technical_language>

Target:
static boolean filterSameDescriptor(IDataChartDescriptor<?, ?> desc, @Nullable IDataChartDescriptor<?, ?> filter) { if (filter != null) { if (desc.getClass() != filter.getClass()) { return false; } } return true; }
Source:
<code>public void dropPartitionFromStorageByFilter(LensSessionHandle sessionid, String cubeTableName, String storageName, String filter) throws LensException { try { acquire(sessionid); String tableName = MetastoreUtil.getStorageTableName(cubeTableName, Storage.getPrefix(storageName)); List<Partition> partitions = getClient(sessionid).getPartitionsByFilter( tableName, filter); for (Partition part : partitions) { Map<String, Date> timeSpec = new HashMap<String, Date>(); Map<String, String> nonTimeSpec = new HashMap<String, String>(); UpdatePeriod updatePeriod = populatePartSpec(part, timeSpec, nonTimeSpec); getClient(sessionid).dropPartition(cubeTableName, storageName, timeSpec, nonTimeSpec, updatePeriod); } LOG.info("Dropped partition for cube table: " + cubeTableName + " storage: " + storageName + " by filter:" + filter); } catch (HiveException exc) { if (exc.getCause() instanceof NoSuchObjectException) { <START> return; <END> } throw new LensException(exc); } finally { release(sessionid); } }</code><technical_language>Shouldnt return. continue in for loop. add another try-catch for-loop</technical_language>

Target:
public void dropPartitionFromStorageByFilter(LensSessionHandle sessionid, String cubeTableName, String storageName, String filter) throws LensException { try { acquire(sessionid); String tableName = MetastoreUtil.getStorageTableName(cubeTableName, Storage.getPrefix(storageName)); List<Partition> partitions = getClient(sessionid).getPartitionsByFilter( tableName, filter); for (Partition part : partitions) { try { Map<String, Date> timeSpec = new HashMap<String, Date>(); Map<String, String> nonTimeSpec = new HashMap<String, String>(); UpdatePeriod updatePeriod = populatePartSpec(part, timeSpec, nonTimeSpec); getClient(sessionid).dropPartition(cubeTableName, storageName, timeSpec, nonTimeSpec, updatePeriod); } catch (HiveException e) { if (e.getCause() instanceof NoSuchObjectException) { continue; } else { throw new LensException(e); } } } LOG.info("Dropped partition for cube table: " + cubeTableName + " storage: " + storageName + " by filter:" + filter); } catch (HiveException exc) { throw new LensException(exc); } finally { release(sessionid); } }
Source:
<code>private void updatePassword(String password) { EditPostRepository editPostRepository = getEditPostRepository(); if (editPostRepository == null) return; String trimmedPassword = password.trim(); Boolean isNewPasswordBlank = trimmedPassword.isEmpty(); String previousPassword = editPostRepository.getPassword(); <START> Boolean isPreviousPasswordBlank = previousPassword.isEmpty() || previousPassword.trim().isEmpty(); <END> if (isNewPasswordBlank && isPreviousPasswordBlank) return; String newPassword = isNewPasswordBlank ? trimmedPassword : password; editPostRepository.updateAsync(postModel -> { postModel.setPassword(newPassword); return true; }, (postModel, result) -> { if (result == UpdatePostResult.Updated.INSTANCE) { mPasswordTextView.setText(newPassword); } return null; }); }</code><technical_language>@adityabhaskar this give result making isEmpty() redundant? thoughts. Thanks suggestion Boolean isPreviousPasswordBlank = previousPassword.trim().isEmpty();</technical_language>

Target:
private void updatePassword(String password) { EditPostRepository editPostRepository = getEditPostRepository(); if (editPostRepository == null) return; String trimmedPassword = password.trim(); Boolean isNewPasswordBlank = trimmedPassword.isEmpty(); String previousPassword = editPostRepository.getPassword(); Boolean isPreviousPasswordBlank = previousPassword.trim().isEmpty(); if (isNewPasswordBlank && isPreviousPasswordBlank) return; String newPassword = isNewPasswordBlank ? trimmedPassword : password; editPostRepository.updateAsync(postModel -> { postModel.setPassword(newPassword); return true; }, (postModel, result) -> { if (result == UpdatePostResult.Updated.INSTANCE) { mPasswordTextView.setText(newPassword); } return null; }); }
Source:
<code>public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { <START> if (!ta.isFinished() && task.commitAttempt == null) { <END> earliestUnfinishedAttempt = ta; task.nodesWithRunningAttempts.add(ta.getNodeId()); } else { if (TaskAttemptState.SUCCEEDED.equals(ta.getState())) { LOG.info("Ignore speculation scheduling for task since it has succeeded with attempt {}.", task.getTaskId(), ta.getID()); return; } } } if (earliestUnfinishedAttempt == null) { LOG.info("Ignore speculation scheduling since there is no running attempt on task {}.", task.getTaskId()); return; } task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }</code><technical_language>Thanks for this patch @Chyler. This correct behavior, LOG.info give wrong reason. this improved log cases separately</technical_language>

Target:
public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { if (!ta.isFinished()) { earliestUnfinishedAttempt = ta; task.nodesWithRunningAttempts.add(ta.getNodeId()); } else { if (TaskAttemptState.SUCCEEDED.equals(ta.getState())) { LOG.info("Ignore speculation scheduling for task since it has succeeded with attempt {}.", task.getTaskId(), ta.getID()); return; } } } if (earliestUnfinishedAttempt == null) { LOG.info("Ignore speculation scheduling since there is no running attempt on task {}.", task.getTaskId()); return; } if (task.commitAttempt != null) { LOG.info("Ignore speculation scheduling for task since commit has started with commitAttempt {}.", task.getTaskId(), task.commitAttempt); return; } task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }
Source:
<code>private void handleFailedMigrations(MultiStatus status) throws CoreException { if (!status.isOK()) { MultiStatus errorStatus = new MultiStatus(ITasksCoreConstants.ID_PLUGIN, IStatus.ERROR, NLS.bind(Messages.RefactorTaskIdsOperation_FailedTaskCount, status.getChildren().length), null); errorStatus.merge(status); <START> throw new CoreException(errorStatus); <END> } }</code><technical_language>log this throwing it</technical_language>

Target:
private void handleFailedMigrations(MultiStatus status) throws CoreException { if (!status.isOK()) { MultiStatus errorStatus = new MultiStatus(ITasksCoreConstants.ID_PLUGIN, IStatus.ERROR, NLS.bind(Messages.RefactorTaskIdsOperation_FailedTaskCount, status.getChildren().length), null); errorStatus.merge(status); StatusHandler.log(errorStatus); throw new CoreException(errorStatus); } }
Source:
<code>public void doRunQuickFix() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; isApplicableMap.put(marker, quickFix.isApplicable(marker)); <START> quickFix.run(marker); <END> dispatch(0); } PlatformUI.getWorkbench().saveAllEditors(false); } }); }</code><technical_language>I run quick fix if applicable. (If existing tests fail, a bug.)</technical_language>

Target:
public void doRunQuickFix() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; isApplicableMap.put(marker, quickFix.isApplicable(marker)); if (quickFix.isApplicable(marker)) { quickFix.run(marker); dispatch(0); } } PlatformUI.getWorkbench().saveAllEditors(false); } }); }
Source:
<code>static <K, V> void setAll(Map<K, V> target, Map<K, V> newValues) { <START> target.clear(); <END> target.putAll(newValues); }</code><technical_language>This implementation is optimal leads unnecessary removing adding of values. is java target.keySet().retainAll(newValues.keySet()); target.putAll(newValues);</technical_language>

Target:
static <K, V> void setAll(Map<K, V> target, Map<K, V> newValues) { target.keySet().retainAll(newValues.keySet()); target.putAll(newValues); }
Source:
<code>default long getPriority() { <START> return 1; <END> }</code><technical_language>0, default one. other requirement choose positive range (to executed sooner) negative range (to executed later) in comparison default implementation</technical_language>

Target:
default long getPriority() { return 0; }