auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { workerThreads.compute(walGroupId, (key, value) -> { if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug( "{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), key); } return value; } else { if (LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), key); } ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning( walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, <START> (t,e) -> { <END> this.uncaughtException(t,e); while (true) { try { LOG.info("Refreshing replication sources now due " + "to previous error on reader thread."); this.manager.refreshSources(this.getPeerId()); break; } catch (IOException e1) { LOG.error("Replication sources refresh failed.", e1); sleepForRetries("Sleeping before try refreshing sources again", maxRetriesMultiplier); } } }); worker.setWALReader(walReader); worker.startup(this::uncaughtException); return worker; } }); }</code><technical_language>is for wal reader. I refreshSources retry is acceptable way. test abortOnError flag here? If is true, call uncaughtException, try refresh replication source</technical_language>

Target:
private void tryStartNewShipper(String walGroupId, PriorityBlockingQueue<Path> queue) { workerThreads.compute(walGroupId, (key, value) -> { if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug( "{} Someone has beat us to start a worker thread for wal group {}", logPeerId(), key); } return value; } else { if (LOG.isDebugEnabled()) { LOG.debug("{} Starting up worker for wal group {}", logPeerId(), key); } ReplicationSourceShipper worker = createNewShipper(walGroupId, queue); ReplicationSourceWALReader walReader = createNewWALReader(walGroupId, queue, worker.getStartPosition()); Threads.setDaemonThreadRunning( walReader, Thread.currentThread().getName() + ".replicationSource.wal-reader." + walGroupId + "," + queueId, (t,e) -> this.uncaughtException(t, e, this.manager, this.getPeerId())); worker.setWALReader(walReader); worker.startup((t,e) -> this.uncaughtException(t, e, this.manager, this.getPeerId())); return worker; } }); }
Source:
<code>public static void main(String[] args) { if (args.length < 5) { <START> System.out.println("Please specify your access key and call id and leg id and recording id example :" + <END> " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final String recordingId = args[3]; final String basePath = args[4]; final String filePath = messageBirdClient.downloadRecording(callId, legId, recordingId, basePath); if (filePath != null) { System.out.println("Record file is downloaded to "+filePath); } } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }</code><technical_language>System.out.println("...... path id (optional)......</technical_language>

Target:
public static void main(String[] args) { if (args.length < 4) { System.out.println("Please specify your access key and call id and leg id and recording id and base path(optional) example :" + " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 /users/{user}/test"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final String recordingId = args[3]; String basePath = null; if (args.length > 4) { basePath = args[4]; } final String filePath = messageBirdClient.downloadRecording(callId, legId, recordingId, basePath); if (filePath != null) { System.out.println("Record file is downloaded to "+filePath); } } catch (GeneralException | NotFoundException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
<code>private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { Set<@NonNull String> requiredEventsFields = <START> Collections.singleton( ITraceEventConstants.DURATION); <END> TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, requiredEventsFields); return Collections.singleton(entryReq); }</code><technical_language>this fit line</technical_language>

Target:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, Collections.singleton(ITraceEventConstants.DURATION)); return Collections.singleton(entryReq); }
Source:
<code>public ReadContext init(InitContext context) { Configuration configuration = context.getConfiguration(); String readerSchemaString = configuration.get(AVRO_READ_SCHEMA); boolean checkSchemaCompatibility = configuration.getBoolean(AVRO_SCHEMA_COMPATIBILITY_CHECK, false); if (readerSchemaString != null && checkSchemaCompatibility) { Schema.Parser parser = new Schema.Parser(); Schema readerSchema = parser.parse(readerSchemaString); return init(configuration, mergeKeyValueMetadata(context, readerSchema), context.getFileSchema()); } else { <START> return init(configuration, context.getMergedKeyValueMetaData(), context.getFileSchema()); <END> } }</code><technical_language>InitContext#getMergedKeyValueMetaData() is deprecated, avoid calling it. calling a private mergeKeyValueMetadata(context) method checks compatibility if checkSchemaCompatibility is true, falls behaviour in InitContext#getMergedKeyValueMetaData()</technical_language>

Target:
public ReadContext init(InitContext context) { MessageType fileSchema = context.getFileSchema(); MessageType schema = fileSchema; Map<String, String> metadata = getMergedKeyValueMetadata(context); Configuration configuration = context.getConfiguration(); String readerSchemaString = configuration.get(AVRO_READ_SCHEMA); if (readerSchemaString != null) { metadata.put(AVRO_READ_SCHEMA_METADATA_KEY, readerSchemaString); } String requestedProjectionString = configuration.get(AVRO_REQUESTED_PROJECTION); if (requestedProjectionString != null) { Schema avroRequestedProjection = new Schema.Parser().parse(requestedProjectionString); schema = new AvroSchemaConverter().convert(avroRequestedProjection); } String avroReadSchema = configuration.get(AVRO_READ_SCHEMA); if (avroReadSchema != null) { metadata = new LinkedHashMap<String, String>(); metadata.put(AVRO_READ_SCHEMA_METADATA_KEY, avroReadSchema); } return new ReadContext(getSchemaForRead(fileSchema, schema), metadata); }
Source:
<code>public static SWTBotRootMenu contextMenu(final Control control, final int x, final int y) throws WidgetNotFoundException { <START> ContextMenuHelper.notifyMenuDetect(control, control); <END> WaitForObjectCondition<Menu> waitForMenu = waitForNatTablePopupMenu(control, x, y); new SWTBot().waitUntil(waitForMenu); return new SWTBotRootMenu(waitForMenu.get(0)); }</code><technical_language>This send SWT.MenuDetect coordinates of center of NatTable control. I want send coordinates received argument. Note however, received coordinates relative control, coordinates in SWT.MenuDetect relative display</technical_language>

Target:
public static SWTBotRootMenu contextMenu(final Control control, final int x, final int y) throws WidgetNotFoundException { UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { control.notifyListeners(SWT.MouseDown, createMouseEvent(control, x, y, 3, SWT.NONE, 1)); } }); notifyMenuDetect(control, x, y); WaitForObjectCondition<Menu> waitForMenu = waitForNatTablePopupMenu(control, x, y); new SWTBot().waitUntil(waitForMenu); return new SWTBotRootMenu(waitForMenu.get(0)); }
Source:
<code>public void testAllChildrenNoMatchExpectFalse() { fFilter.setNot(false); <START> assertFalse(fFilter.matches(fEvent)); <END> }</code><technical_language>testNoChild... filter children</technical_language>

Target:
public void testAllChildrenNoMatchExpectFalse() { fFilter.setNot(false); ITmfFilterTreeNode child = fFilterNode.clone(); assertEquals("addChild()", 0, fFilterNode.addChild(child)); assertFalse(fFilter.matches(fEvent)); }
Source:
<code>public static boolean isMatch(AttributeDescriptor a, AttributeDescriptor b, boolean strict) { if (a == b) { return true; } if (b == null) { return false; } if (a == null) { return false; } if (a.equals(b)) { return true; } if (strict) { if (a.getLocalName().equals(b.getLocalName()) && a.getType().getBinding().equals(b.getType().getBinding())) { return true; } } else { <START> if (a.getLocalName().equals(b.getLocalName()) && a.getClass().equals(b.getClass())) { <END> return true; } } return false; }</code><technical_language>want compare descriptor classes, of compatibility looked a simple coding mistake (to me)... AttributeDescriptor is interface, implementations for effectively behave way. If for is a comparison accounts for name, limit it. (the case thinking here, is implementation classes of AttributeDescriptor, AttributeDescriptorImpl a hypothetical AttributeDescriptorImpl2 provided for reason, GeometryDescriptorImpl AttributeDescriptorImpl)</technical_language>

Target:
public static boolean isMatch(AttributeDescriptor a, AttributeDescriptor b, boolean strict) { if (a == b) { return true; } if (b == null) { return false; } if (a == null) { return false; } if (a.equals(b)) { return true; } if (strict) { if (a.getLocalName().equals(b.getLocalName()) && a.getType().getBinding().equals(b.getType().getBinding())) { return true; } } else { if (a.getLocalName().equals(b.getLocalName())) { return true; } } return false; }
Source:
<code>private void initializeLanguageDialog(PreferenceScreen screen) { ListPreference languageSelection = (ListPreference) screen.findPreference(LANGUAGE); if (languageSelection != null) { Map<String, List<String>> items = new TreeMap<>(); for (String localeCode : LanguageUtil.APP_LANGUAGES) { Locale loc = LanguageUtil.getLocale(localeCode); <START> items.put(loc.getDisplayName(loc).toLowerCase(), Arrays.asList(loc.getDisplayName(loc), loc.toString())); <END> } CharSequence[] languageDialogLabels = new CharSequence[items.size() + 1]; CharSequence[] languageDialogValues = new CharSequence[items.size() + 1]; languageDialogLabels[0] = getResources().getString(R.string.language_system); languageDialogValues[0] = ""; int i = 1; for (Map.Entry<String, List<String>> e : items.entrySet()) { languageDialogLabels[i] = e.getValue().get(0); languageDialogValues[i] = e.getValue().get(1); i++; } languageSelection.setEntries(languageDialogLabels); languageSelection.setEntryValues(languageDialogValues); } }</code><technical_language>Beware of Arrays.asList. returns implementation of List calling add crash. This is fine, for future reference</technical_language>

Target:
private void initializeLanguageDialog(PreferenceScreen screen) { ListPreference languageSelection = (ListPreference) screen.findPreference(LANGUAGE); if (languageSelection != null) { Map<String, String> items = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (String localeCode : LanguageUtil.APP_LANGUAGES) { Locale loc = LanguageUtil.getLocale(localeCode); items.put(loc.getDisplayName(loc), loc.toString()); } CharSequence[] languageDialogLabels = new CharSequence[items.size() + 1]; CharSequence[] languageDialogValues = new CharSequence[items.size() + 1]; languageDialogLabels[0] = getResources().getString(R.string.language_system); languageDialogValues[0] = ""; int i = 1; for (Map.Entry<String, String> e : items.entrySet()) { languageDialogLabels[i] = e.getKey(); languageDialogValues[i] = e.getValue(); i++; } languageSelection.setEntries(languageDialogLabels); languageSelection.setEntryValues(languageDialogValues); } }
Source:
<code>protected void compute() { try { final int parallelTaskCount = computeNumTasks(); if (sequences.size() < 4 || parallelTaskCount < 2) { <START> LOG.info( <END> "Input sequence count (%s) or available parallel merge task count (%s) too small to perform parallel" + " merge-combine, performing serially with a single merge-combine task", sequences.size(), parallelTaskCount ); QueuePusher<ResultBatch<T>> resultsPusher = new QueuePusher<>(out, hasTimeout, timeoutAt); List<BatchedResultsCursor<T>> sequenceCursors = new ArrayList<>(sequences.size()); for (Sequence<T> s : sequences) { sequenceCursors.add(new YielderBatchedResultsCursor<>(new SequenceBatcher<>(s, batchSize), orderingFn)); } PrepareMergeCombineInputsAction<T> blockForInputsAction = new PrepareMergeCombineInputsAction<>( sequenceCursors, resultsPusher, orderingFn, combineFn, yieldAfter, batchSize, cancellationGizmo ); getPool().execute(blockForInputsAction); } else { LOG.info("Spawning %s parallel merge-combine tasks for %s sequences", parallelTaskCount, sequences.size()); spawnParallelTasks(parallelTaskCount); } } catch (Exception ex) { cancellationGizmo.cancel(ex); out.offer(new ResultBatch<>()); } }</code><technical_language>I info level chatty for this log</technical_language>

Target:
protected void compute() { try { final int parallelTaskCount = computeNumTasks(); if (parallelTaskCount < 2) { LOG.debug( "Input sequence count (%s) or available parallel merge task count (%s) too small to perform parallel" + " merge-combine, performing serially with a single merge-combine task", sequences.size(), parallelTaskCount ); QueuePusher<ResultBatch<T>> resultsPusher = new QueuePusher<>(out, hasTimeout, timeoutAt); List<BatchedResultsCursor<T>> sequenceCursors = new ArrayList<>(sequences.size()); for (Sequence<T> s : sequences) { sequenceCursors.add(new YielderBatchedResultsCursor<>(new SequenceBatcher<>(s, batchSize), orderingFn)); } PrepareMergeCombineInputsAction<T> blockForInputsAction = new PrepareMergeCombineInputsAction<>( sequenceCursors, resultsPusher, orderingFn, combineFn, yieldAfter, batchSize, targetTimeNanos, cancellationGizmo ); getPool().execute(blockForInputsAction); } else { LOG.debug("Spawning %s parallel merge-combine tasks for %s sequences", parallelTaskCount, sequences.size()); spawnParallelTasks(parallelTaskCount); } } catch (Exception ex) { cancellationGizmo.cancel(ex); out.offer(ResultBatch.TERMINAL); } }
Source:
<code>protected void handleCreate(DebugEvent event) { if (isMissingRequiredThreadGroup(event)) { return; } <START> fLastCreatedThread = (IThread) event.getSource(); <END> super.handleCreate(event); fLastCreatedThread = null; }</code><technical_language>confirm this is called thread? I is (see org.eclipse.debug.core.DebugPlugin.EventDispatchJob) if debug plugin guarantees single-threaded event delivery simply coded moment</technical_language>

Target:
protected void handleCreate(DebugEvent event) { if (isMissingRequiredThreadGroup(event)) { return; } super.handleCreate(event); }
Source:
<code>public byte[] encode(final Identity identity) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(out); try { gzip.write(this.origin.encode(identity)); } finally { gzip.close(); <START> out.close(); <END> } return out.toByteArray(); }</code><technical_language>this is pointless, need close byte array output stream</technical_language>

Target:
public byte[] encode(final Identity identity) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GZIPOutputStream gzip = new GZIPOutputStream(out); try { gzip.write(this.origin.encode(identity)); } finally { gzip.close(); } return out.toByteArray(); }
Source:
<code>private Collection<CommandParameter> getDiagramTypesCreation() { final Collection<CommandParameter> result = new HashSet<CommandParameter>(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { DiagramDescription <START> sequenceDiagramDescription = <END> diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription(); sequenceDiagramDescription.setDefaultLayer(DescriptionFactory.eINSTANCE.createLayer()); final CommandParameter typeCommandParameter = new CommandParameter(null, DescriptionPackage.Literals.VIEWPOINT__OWNED_REPRESENTATIONS, sequenceDiagramDescription); result.add(typeCommandParameter); } return result; }</code><technical_language>This is necessarilry a sequence diagram (event if this is subtype currently available). specificDiagramDescription</technical_language>

Target:
private Collection<CommandParameter> getDiagramTypesCreation() { final Collection<CommandParameter> result = new HashSet<CommandParameter>(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { DiagramDescription specificDiagramDescription = diagramTypeDescriptor.getDiagramDescriptionProvider().createDiagramDescription(); if (specificDiagramDescription.getDefaultLayer() == null) { specificDiagramDescription.setDefaultLayer(DescriptionFactory.eINSTANCE.createLayer()); } final CommandParameter typeCommandParameter = new CommandParameter(null, DescriptionPackage.Literals.VIEWPOINT__OWNED_REPRESENTATIONS, specificDiagramDescription); result.add(typeCommandParameter); } return result; }
Source:
<code>protected void testAccessControl() throws Exception { dataBundle = getTypicalDataBundle(); <START> removeAndRestoreDataBundle(dataBundle); <END> InstructorAttributes moderatedInstructor = dataBundle.instructors.get("instructor1OfCourse1"); String courseId = moderatedInstructor.courseId; String feedbackSessionName = ""; String moderatedInstructorEmail = "instructor1@course1.tmt"; String[] submissionParams; feedbackSessionName = "First feedback session"; submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedInstructorEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifyCoursePrivilege(submissionParams); }</code><technical_language>Similarly here. super.prepareTestData() in overridden method suffice</technical_language>

Target:
protected void testAccessControl() throws Exception { InstructorAttributes moderatedInstructor = typicalBundle.instructors.get("helperOfCourse1"); String courseId = moderatedInstructor.courseId; String feedbackSessionName = "First feedback session"; String moderatedInstructorEmail = "helper@course1.tmt"; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName, Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, moderatedInstructorEmail }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams); }
Source:
<code>private void courtier(Game game, MoveContext context, Player currentPlayer) { if (currentPlayer.getHand().size() == 0) return; Card card = currentPlayer.controlPlayer.courtier_cardToReveal(context); if (card == null) { Util.playerError(currentPlayer, "Courtier errror, reveal random card."); card = Util.randomCard(currentPlayer.hand); } int numTypes = card.getNumberOfTypes(currentPlayer); if (numTypes > 0) { <START> CourtierOption[] options = currentPlayer.controlPlayer.courtier_chooseOptions(context, numTypes); <END> if (options == null || options.length != numTypes ) { Util.playerError(currentPlayer, "Courtier Erro, Ignoring"); } else { for (CourtierOption option : options) { switch (option) { case AddAction: context.actions++; break; case AddBuy: context.buys++; break; case AddCoins: context.addCoins(3, this.controlCard); break; case GainGold: currentPlayer.gainNewCard(Cards.gold, this.controlCard, context); break; } } } } }</code><technical_language>need pass in a list Array of CourtierOption player options valid</technical_language>

Target:
private void courtier(Game game, MoveContext context, Player currentPlayer) { if (currentPlayer.getHand().size() == 0) return; Card card = currentPlayer.controlPlayer.courtier_cardToReveal(context); if (card == null) { Util.playerError(currentPlayer, "Courtier errror, reveal random card."); card = Util.randomCard(currentPlayer.hand); } currentPlayer.reveal(card, this.controlCard, context); int numTypes = card.getNumberOfTypes(currentPlayer); if (numTypes > 0) { CourtierOption[] options = null; if (numTypes >= 4) { options = CourtierOption.values(); } else { options = currentPlayer.controlPlayer.courtier_chooseOptions(context, CourtierOption.values(), numTypes); } if (options == null || options.length != numTypes ) { Util.playerError(currentPlayer, "Courtier Erro, Ignoring"); } else { for (CourtierOption option : options) { switch (option) { case AddAction: context.actions++; break; case AddBuy: context.buys++; break; case AddCoins: context.addCoins(3, this.controlCard); break; case GainGold: currentPlayer.gainNewCard(Cards.gold, this.controlCard, context); break; } } } } }
Source:
<code>public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) { return; } restoreFeature = executorService.submit(new Runnable() { @Override public void run() { try { LOGGER.info("Starting restore on keyspace {}", keyspace); keyspaceStarted(); final BackupManager backupManager = new BackupManager(checkNotNull(jmxConnect), backupDir); backupManager.restore(keyspace, truncateTables); <START> <END> keyspaceFinished("SUCCESS", keyspace); } catch (final Exception e) { LOGGER.error("Failed to restore keyspace " + keyspace, e); keyspaceFinished("FAILURE", keyspace); } finally { startNextKeyspace(); } } }); LOGGER.info("Submitted restore for keyspace {}", keyspace); }</code><technical_language>constants for SUCCESS FAILURE in multiple places</technical_language>

Target:
public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) { return; } restoreFeature = executorService.submit(new Runnable() { @Override public void run() { try { LOGGER.info("Starting restore on keyspace {}", keyspace); keyspaceStarted(); final BackupManager backupManager = new BackupManager(checkNotNull(jmxConnect), backupDir); backupManager.restore(keyspace); keyspaceFinished(SUCCESS, keyspace); } catch (final Exception e) { LOGGER.error("Failed to restore keyspace " + keyspace, e); keyspaceFinished(FAILURE, keyspace); } finally { startNextKeyspace(); } } }); LOGGER.info("Submitted restore for keyspace {}", keyspace); }
Source:
<code>private List<Tuple> tuplesResult(EntityKey[] keys, Object[] searchObjects, TupleContext tupleContext, DBCursor cursor) { List<Tuple> tuples = CollectionHelper.initializeSizedList( searchObjects.length, null ); for ( DBObject dbObject : cursor ) { for ( int i = 0; i < searchObjects.length; i++ ) { if ( dbObject.get( ID_FIELDNAME ).equals( searchObjects[i] ) ) { <START> tuples.set( i, createTuple( keys[i], tupleContext, dbObject ) ); <END> break; } } } return tuples; }</code><technical_language>Thinking it, consume cursor a map drive result set creating iterating requested keys result. In current approach n \* n/2 loop iterations average (it n \* n, already), n 1000 @emmanuelbernard. a temporary map, n + n (once iterating cursor, incoming keys), cost of map allocation. Of optimize prematurely, n \* n growth is scary. @Sanne, thoughts</technical_language>

Target:
private List<Tuple> tuplesResult(EntityKey[] keys, Object[] searchObjects, TupleContext tupleContext, DBCursor cursor) { Tuple[] tuples = new Tuple[searchObjects.length]; for ( DBObject dbObject : cursor ) { for ( int i = 0; i < searchObjects.length; i++ ) { if ( dbObject.get( ID_FIELDNAME ).equals( searchObjects[i] ) ) { tuples[i] = createTuple( keys[i], tupleContext, dbObject ); break; } } } return Arrays.asList( tuples ); }
Source:
<code>private void writeObject(ObjectOutputStream oos) throws IOException { if (buf == null) { buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); } <START> oos.defaultWriteObject(); <END> }</code><technical_language>Instead of defaultWriteObject, handle yourself: oos.writeInt(hash); T object = this.object; byte[] buf = this.buf; if (object == null) { oos.writeInt(buf.length); oos.write(buf); } else { oos.writeInt(codec.sizeof(object)); CodedOutputStream cos = CodedOutputStream.newInstance(out); codec.encode(object, cos); cos.flush(); }</technical_language>

Target:
private void writeObject(ObjectOutputStream oos) throws IOException { if (buf == null) { buf = new byte[codec.sizeof(object)]; codec.encode(object, buf); } oos.writeInt(hash); if (object == null) { oos.writeInt(buf.length); oos.write(buf); } else { oos.writeInt(codec.sizeof(object)); CodedOutputStream cos = CodedOutputStream.newInstance(oos); codec.encode(object, cos); cos.flush(); } }
Source:
<code>public void reportsRequestResultWhenStopFails() throws Exception { final Repo repo = new MkGithub().randomRepo(); final Issue issue = repo.issues().create("Bug", "stop it please"); final Talk talk = ReportsTest.example(repo, issue); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); MatcherAssert.assertThat( "Comment contains warning about stop request", repo.issues().get(1).comments().get(1).toString().contains( ReportsTest.PHRASES.getString("Reports.stop-fails").replace( "%s", <START> "" <END> ) ) ); }</code><technical_language>@xupyprmv do repace %s empty string here</technical_language>

Target:
public void reportsRequestResultWhenStopFails() throws Exception { final String user = "john"; final String stop = "stop it please"; final Repo repo = new MkGithub(user).randomRepo(); final Talk talk = ReportsTest.example( repo, repo.issues().create("Bug", stop) ); final Agent agent = new Reports(repo.github()); agent.execute(talk); MatcherAssert.assertThat( talk.read(), XhtmlMatchers.hasXPath(XPATH) ); MatcherAssert.assertThat( "Comment contains warning about stop request", repo.issues().get(1).comments().get(1).json().getString( "body" ).equals( String.format( "> %s\n\n@%s %s %s", stop, user, ReportsTest.PHRASES.getString("Reports.stop-fails"), Logger.format( ReportsTest.PHRASES.getString("Reports.success"), "<LINK_0>", DURATION ) ) ) ); }
Source:
<code>private boolean isVmRunningInDatabaseOnMonitoredHost() { if (vdsManager.getVdsId().equals(dbVm.getRunOnVds())) { return true; } logVmDetectedOnUnexpectedHost(); <START> if (dbVm.getStatus().equals(VMStatus.MigratingFrom)) { <END> auditVmMigrationAbort(); } return false; }</code><technical_language>this is place for this code - if VM reached state destination host (in DB VM is set running source host status MigrationFrom)</technical_language>

Target:
private boolean isVmRunningInDatabaseOnMonitoredHost() { if (vdsManager.getVdsId().equals(dbVm.getRunOnVds())) { return true; } logVmDetectedOnUnexpectedHost(); return false; }
Source:
<code>protected PoolingDriver instance() throws OseeCoreException { try { Class.forName(CONNECTION_POOL_DRIVER); <START> } catch (Exception ex) { <END> throw new OseeDataStoreException(ex, "Error loading connectino pool driver [%s]", CONNECTION_POOL_DRIVER); } PoolingDriver driver; try { driver = (PoolingDriver) DriverManager.getDriver(CONNECTION_POOL_ID); } catch (SQLException ex) { throw new OseeDataStoreException(ex, "Error finding connection pool driver with id [%s]", CONNECTION_POOL_ID); } return driver; }</code><technical_language>typo in log message for word connection</technical_language>

Target:
protected PoolingDriver instance() throws OseeCoreException { try { Class.forName(CONNECTION_POOL_DRIVER); } catch (Exception ex) { throw new OseeDataStoreException(ex, "Error loading connection pool driver [%s]", CONNECTION_POOL_DRIVER); } PoolingDriver driver; try { driver = (PoolingDriver) DriverManager.getDriver(CONNECTION_POOL_ID); } catch (SQLException ex) { throw new OseeDataStoreException(ex, "Error finding connection pool driver with id [%s]", CONNECTION_POOL_ID); } return driver; }
Source:
<code>public void testGenerateInitAmazonS3WithOptionalQueryParams() throws IOException, ParseException, TemplateModelException { final Map<String,Object> testMap = new HashMap<>(); final Request testRequest = RequestConverter.toRequest(new Ds3Request( "com.spectralogic.s3.server.handler.reqhandler.amazons3.CreateObjectRequestHandler", HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.REQUIRED, null, null, null, null, false, null, ImmutableList.of( new Ds3Param("Job", "java.util.UUID", true), new Ds3Param("Offset", "long", false)), ImmutableList.of()), <START> new Ds3DocSpecImpl( <END> ImmutableMap.of(), ImmutableMap.of())); testMap.put("requestEntry", testRequest); final CCodeGenerator codeGenerator = new CCodeGenerator(); final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); codeGenerator.processTemplate(testMap, "request-templates/InitRequest.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_request* ds3_init_create_object(const char* bucket_name, const char* object_name, const uint64_t length) {" + "\n" + " struct _ds3_request* request = _common_request_init(HTTP_PUT, _build_path(\"/\", bucket_name, object_name));" + "\n" + " request->length = length;" + "\n" + "\n" + " return (ds3_request*) request;" + "\n" + "}\n"; assertEquals(expectedOutput, output); }</code><technical_language>Ds3DocSpecEmptyImpl for empty doc spec instead of initializing empty maps</technical_language>

Target:
public void testGenerateInitAmazonS3WithOptionalQueryParams() throws IOException, ParseException, TemplateModelException { final Map<String,Object> testMap = new HashMap<>(); final Request testRequest = RequestConverter.toRequest(new Ds3Request( "com.spectralogic.s3.server.handler.reqhandler.amazons3.CreateObjectRequestHandler", HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.REQUIRED, null, null, null, null, false, null, ImmutableList.of( new Ds3Param("Job", "java.util.UUID", true), new Ds3Param("Offset", "long", false)), ImmutableList.of()), new Ds3DocSpecEmptyImpl()); testMap.put("requestEntry", testRequest); final CCodeGenerator codeGenerator = new CCodeGenerator(); final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); codeGenerator.processTemplate(testMap, "request-templates/InitRequest.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_request* ds3_init_create_object(const char* bucket_name, const char* object_name, const uint64_t length) {" + "\n" + " struct _ds3_request* request = _common_request_init(HTTP_PUT, _build_path(\"/\", bucket_name, object_name));" + "\n" + " request->length = length;" + "\n" + "\n" + " return (ds3_request*) request;" + "\n" + "}\n"; assertEquals(expectedOutput, output); }
Source:
<code>public void handleEvent(IResumedDMEvent event) { VisualizerModel model = fVisualizer.getModel(); if (model == null) { return; } IDMContext context = event.getDMContext(); if (context != null && isSessionAllStop(context.getSessionId()) ) { List<VisualizerThread> tList = model.getThreads(); for(VisualizerThread t : tList) { t.setState(VisualizerExecutionState.RUNNING); t.setLocationInfo((String) null); } fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); return; } if (context instanceof IContainerDMContext) { } else if (context instanceof IMIExecutionDMContext) { int tid; VisualizerThread thread = null; try { tid = Integer.parseInt(((IMIExecutionDMContext) context).getThreadId()); thread = model.getThread(tid); <START> } catch (NumberFormatException e) { <END> return; } if (thread != null) { assert thread.getState() == VisualizerExecutionState.SUSPENDED || thread.getState() == VisualizerExecutionState.CRASHED; thread.setState(VisualizerExecutionState.RUNNING); thread.setLocationInfo((String) null); fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); } } }</code><technical_language>Add assert eventually catch case a tid string is passed translate int? ex: tid = "1.1". This trigger need adapt code new PIDs</technical_language>

Target:
public void handleEvent(IResumedDMEvent event) { VisualizerModel model = fVisualizer.getModel(); if (model == null) { return; } IDMContext context = event.getDMContext(); if (context != null && isSessionAllStop(context.getSessionId()) ) { List<VisualizerThread> tList = model.getThreads(); for(VisualizerThread t : tList) { t.setState(VisualizerExecutionState.RUNNING); t.setLocationInfo((String) null); } fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); return; } if (context instanceof IContainerDMContext) { } else if (context instanceof IMIExecutionDMContext) { int tid; VisualizerThread thread = null; String strThreadId = ((IMIExecutionDMContext) context).getThreadId(); try { tid = Integer.parseInt(strThreadId); thread = model.getThread(tid); } catch (NumberFormatException e) { assert false : THE_THREAD_ID_DOES_NOT_CONVERT_TO_AN_INTEGER + strThreadId; return; } if (thread != null) { assert thread.getState() == VisualizerExecutionState.SUSPENDED || thread.getState() == VisualizerExecutionState.CRASHED; thread.setState(VisualizerExecutionState.RUNNING); thread.setLocationInfo((String) null); fVisualizer.getMulticoreVisualizerCanvas().requestUpdate(); } } }
Source:
<code>public static String urlConstructor(String... urlChunks) { <START> String url = canvasURL + CANVAS_API_VERSION; <END> for (String chunk : urlChunks) { url += chunk; } return url; }</code><technical_language>Stringbuffer more memory efficient. is lots of URL construction worth efficient avoid garbage collections</technical_language>

Target:
public static String urlConstructor(String... urlChunks) { StringBuffer url =new StringBuffer(); url.append(canvasURL); url.append(CANVAS_API_VERSION); for (String chunk : urlChunks) { url.append(chunk); } return url.toString(); }
Source:
<code>public void multipleTags() throws Exception { if (!getVersion(dockerClient).isGreaterOrEqual(RemoteApiVersion.VERSION_1_21)) { throw new SkipException("API version should be >= 1.21"); } File baseDir = fileFromBuildTestResource("labels"); String imageId = dockerClient.buildImageCmd(baseDir).withNoCache(true) <START> .withTag("docker-java-test:tag1").withTag("docker-java-test:tag2") <END> .exec(new BuildImageResultCallback()) .awaitImageId(); InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); assertThat(inspectImageResponse.getRepoTags().size(), equalTo(2)); assertThat(inspectImageResponse.getRepoTags().contains("docker-java-test:tag1"), equalTo(true)); assertThat(inspectImageResponse.getRepoTags().contains("docker-java-test:tag2"), equalTo(true)); }</code><technical_language>imho obvious. If user wants tag call .withTag if multiple .withTags(Set<String>) getTag() add getTags() prefer getTags fallback getTag()</technical_language>

Target:
public void multipleTags() throws Exception { if (!getVersion(dockerClient).isGreaterOrEqual(RemoteApiVersion.VERSION_1_21)) { throw new SkipException("API version should be >= 1.21"); } File baseDir = fileFromBuildTestResource("labels"); String imageId = dockerClient.buildImageCmd(baseDir).withNoCache(true) .withTag("fallback-when-withTags-not-called") .withTags(new HashSet<>(Arrays.asList("docker-java-test:tag1", "docker-java-test:tag2"))) .exec(new BuildImageResultCallback()) .awaitImageId(); InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); assertThat(inspectImageResponse.getRepoTags().size(), equalTo(2)); assertThat(inspectImageResponse.getRepoTags(), containsInAnyOrder("docker-java-test:tag1", "docker-java-test:tag2")); }
Source:
<code>public void start() { <START> if (!ctx.game.loggedIn()){ <END> ctx.controller.stop(); return; } System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }</code><technical_language>need worry player is logged in; script's start() method invoked player is in game</technical_language>

Target:
public void start() { System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }
Source:
<code>public String apply(@Nullable Object value) { <START> if (Objects.isNull(value)) { <END> return null; } if (asMillis && value instanceof String) { final Long theLong = GuavaUtils.tryParseLong((String) value); return theLong == null ? apply(new DateTime(value).getMillis()) : apply(theLong.longValue()); } else { return apply(new DateTime(value).getMillis()); } }</code><technical_language>above, suggested simply == null</technical_language>

Target:
public String apply(@Nullable Object value) { if (value == null) { return null; } if (asMillis && value instanceof String) { final Long theLong = GuavaUtils.tryParseLong((String) value); return theLong == null ? apply(new DateTime(value).getMillis()) : apply(theLong.longValue()); } else { return apply(new DateTime(value).getMillis()); } }
Source:
<code>void entityClass() { <START> boundedContext.register(ProjectAggregate.class); <END> }</code><technical_language>Looks, assertion call is missing</technical_language>

Target:
void entityClass() { boundedContext.register(ProjectAggregate.class); assertRegisteredRepositoryOf(ProjectAggregate.class); }
Source:
<code>public void testAccept() throws Exception { RejectionPolicy rejectionPolicy = new ServerTimeRejectionPolicyFactory().create( new Period("PT10M") ); Assert.assertTrue(rejectionPolicy.accept(new DateTime().getMillis())); <START> Assert.assertFalse(rejectionPolicy.accept(new DateTime("2000").getMillis())); <END> }</code><technical_language>sufficient (and more better) pull this out a DateTime = new DateTime(); DateTime = now.minus(Minutes.something(10)).minus(Milliseconds.ONE); test</technical_language>

Target:
public void testAccept() throws Exception { Period period = new Period("PT10M"); RejectionPolicy rejectionPolicy = new ServerTimeRejectionPolicyFactory().create(period); DateTime now = new DateTime(); DateTime past = now.minus(period).minus(1); Assert.assertTrue(rejectionPolicy.accept(now.getMillis())); Assert.assertFalse(rejectionPolicy.accept(past.getMillis())); }
Source:
<code>protected void wpLogin() { logoutIfNecessary(); new LoginFlow().loginSiteAddress( E2E_WP_COM_USER_SITE_ADDRESS, E2E_WP_COM_USER_USERNAME, <START> E2E_WP_COM_USER_PASSWORD); <END> }</code><technical_language>Curious login logic changed also</technical_language>

Target:
protected void wpLogin() { logoutIfNecessary(); new LoginFlow().loginEmailPassword(); }
Source:
<code>private void copyVmPermissions() { <START> if (getVmId() == null || !getParameters().isCopyVmPermissions()) { <END> return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> vmPermissions = dao.getAllForEntity(getVmId(), getCurrentUser().getUserId(), false); List<permissions> templatePermissions = new ArrayList<permissions>(); for (permissions vmPermission : vmPermissions) { templatePermissions.add(new permissions(getCurrentUser().getUserId(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate)); } if (templatePermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(templatePermissions.toArray(new permissions[templatePermissions.size()])); } }</code><technical_language>isVmInDb instead of null check</technical_language>

Target:
private void copyVmPermissions() { if (isVmInDb || !getParameters().isCopyVmPermissions()) { return; } PermissionDAO dao = getDbFacade().getPermissionDao(); List<permissions> vmPermissions = dao.getAllForEntity(getVmId(), getCurrentUser().getUserId(), false); List<permissions> templatePermissions = new ArrayList<permissions>(); for (permissions vmPermission : vmPermissions) { templatePermissions.add(new permissions(getCurrentUser().getUserId(), vmPermission.getrole_id(), getParameters().getVmTemplateId(), VdcObjectType.VmTemplate)); } if (templatePermissions.size() > 0) { MultiLevelAdministrationHandler.addPermission(templatePermissions.toArray(new permissions[templatePermissions.size()])); } }
Source:
<code>private String getDefaultPrimitiveValue(TypeName type) { String valueString = null; try { Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString())); if(primitiveClass != null) { Object defaultValue = Defaults.defaultValue(primitiveClass); if(defaultValue != null) { valueString = defaultValue.toString(); if (!Strings.isNullOrEmpty(valueString)) { switch (type.toString()) { case "double": valueString = valueString + "d"; break; case "float": valueString = valueString + "f"; break; case "long": valueString = valueString + "L"; } } } } <START> } catch (Exception e) { <END> } return valueString; }</code><technical_language>is this a wide exception type</technical_language>

Target:
private String getDefaultPrimitiveValue(TypeName type) { String valueString = null; try { Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString())); if (primitiveClass != null) { Object defaultValue = Defaults.defaultValue(primitiveClass); if (defaultValue != null) { valueString = defaultValue.toString(); if (!Strings.isNullOrEmpty(valueString)) { switch (type.toString()) { case "double": valueString = valueString + "d"; break; case "float": valueString = valueString + "f"; break; case "long": valueString = valueString + "L"; break; } } } } } catch (ClassNotFoundException ignored) { } return valueString; }
Source:
<code>private Map<String, String> getExistingAzureUserMapping(RolesResourceApi rolesResourceApi, String clusterName, String rangerUserSyncRoleName) throws ApiException { ApiConfigList roleConfigList = rolesResourceApi.readRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "summary"); ApiConfig azureUserMappingConfig = roleConfigList.getItems().stream() .filter(apiConfig -> apiConfig.getName().equals(AZURE_USER_MAPPING)) .findFirst() <START> .get(); <END> String azureUserMappingStr = azureUserMappingConfig.getValue(); return userMappingStrToMap(azureUserMappingStr); }</code><technical_language>if found? is one</technical_language>

Target:
private Map<String, String> getExistingAzureUserMapping(RolesResourceApi rolesResourceApi, String clusterName, String rangerUserSyncRoleName) throws ApiException { ApiConfigList roleConfigList = rolesResourceApi.readRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "summary"); Optional<ApiConfig> azureUserMappingConfig = roleConfigList.getItems().stream() .filter(apiConfig -> apiConfig.getName().equals(AZURE_USER_MAPPING)) .findFirst(); Map<String, String> userMappingMap; if (azureUserMappingConfig.isPresent()) { String azureUserMappingStr = azureUserMappingConfig.get().getValue(); userMappingMap = userMappingStrToMap(azureUserMappingStr); } else { LOGGER.info("No azure cloud mapping config set."); userMappingMap = new HashMap<>(); } return userMappingMap; }
Source:
<code>public void exit() { <START> super.exit(); <END> removeMessages(BREDR_STOP_TIMEOUT); }</code><technical_language>this called end of child class' exit() method</technical_language>

Target:
public void exit() { removeMessages(BREDR_STOP_TIMEOUT); super.exit(); }
Source:
<code>public Argument build(Class<?> expectedType, T value, StatementContext ctx) { ArgBuilder<T> p = (ArgBuilder<T>) BUILDERS.get(expectedType); if (value != null && expectedType == Object.class) { ArgBuilder<T> v = (ArgBuilder<T>) BUILDERS.get(value.getClass()); if (v != null) { return v.build(value); } if (value.getClass().isEnum()) { return STR_BUILDER.build((((Enum<?>)value).name())); } } if (p != null) { return p.build(value); } if (expectedType.isEnum()) { return STR_BUILDER.build(value.toString()); } <START> return OBJ_BUILDER.build(value); <END> }</code><technical_language>This method some redundant logic expectedType == Object.class. a this class in [#235](<LINK_0> for a simpler flow</technical_language>

Target:
public Argument build(Class<?> expectedType, T value, StatementContext ctx) { Class<?> buildType = value != null && expectedType == Object.class ? value.getClass() : expectedType; ArgBuilder<T> v = (ArgBuilder<T>) BUILDERS.get(buildType); if (v != null) { return v.build(value); } if (value != null && value.getClass().isEnum()) { return STR_BUILDER.build((((Enum<?>)value).name())); } return OBJ_BUILDER.build(value); }
Source:
<code>private void checkNonAnnotatedVariantsRead(int expectedNonAnnotatedVariants, String study) throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_VARIANTS_NAME, Arrays.asList( VariantData.getVariantWithAnnotation(), VariantData.getVariantWithoutAnnotation(), VariantData.getVariantWithoutAnnotationOtherStudy())); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); NonAnnotatedVariantsMongoReader mongoItemReader = new NonAnnotatedVariantsMongoReader( mongoOperations, COLLECTION_VARIANTS_NAME, study); mongoItemReader.open(executionContext); int itemCount = 0; VariantWrapper variantWrapper; while ((variantWrapper = mongoItemReader.read()) != null) { itemCount++; assertFalse(variantWrapper.getChr().isEmpty()); <START> assertFalse(variantWrapper.getStart() == 0); <END> Field privateVariantField = VariantWrapper.class.getDeclaredField("variant"); privateVariantField.setAccessible(true); VariantAnnotation annotation = ((Variant) privateVariantField.get(variantWrapper)).getAnnotation(); assertNull(annotation.getConsequenceTypes()); } assertEquals(expectedNonAnnotatedVariants, itemCount); mongoItemReader.close(); }</code><technical_language>assertNotEquals</technical_language>

Target:
private void checkNonAnnotatedVariantsRead(int expectedNonAnnotatedVariants, String study) throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); String databaseName = mongoRule.createDBAndInsertDocuments(COLLECTION_VARIANTS_NAME, Arrays.asList( VariantData.getVariantWithAnnotation(), VariantData.getVariantWithoutAnnotation(), VariantData.getVariantWithoutAnnotationOtherStudy())); MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(databaseName, mongoConnection, mongoMappingContext); NonAnnotatedVariantsMongoReader mongoItemReader = new NonAnnotatedVariantsMongoReader( mongoOperations, COLLECTION_VARIANTS_NAME, study); mongoItemReader.open(executionContext); int itemCount = 0; VariantWrapper variantWrapper; while ((variantWrapper = mongoItemReader.read()) != null) { itemCount++; assertFalse(variantWrapper.getChr().isEmpty()); assertNotEquals(0, variantWrapper.getStart()); Field privateVariantField = VariantWrapper.class.getDeclaredField("variant"); privateVariantField.setAccessible(true); VariantAnnotation annotation = ((Variant) privateVariantField.get(variantWrapper)).getAnnotation(); assertNull(annotation.getConsequenceTypes()); } assertEquals(expectedNonAnnotatedVariants, itemCount); mongoItemReader.close(); }