auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response startJob(@QueryParam("jobid") Optional<String> jobIds, @QueryParam("select") @DefaultValue("-1") int select, @QueryParam("id") Optional<String> id, @QueryParam("task") @DefaultValue("-1") int task, @QueryParam("priority") @DefaultValue("0") int priority, @QueryParam("user") String user, @QueryParam("token") String token, @QueryParam("sudo") String sudo) { List<String> success = new ArrayList<>(); List<String> error = new ArrayList<>(); List<String> disabled = new ArrayList<>(); List<String> unauthorized = new ArrayList<>(); try { if (jobIds.isPresent()) { Iterable<String> joblist = COMMA_SPLITTER.split(jobIds.get()); for (String aJob : joblist) { IJob job = spawn.getJob(aJob); if (job == null) { error.add(aJob); } else if(!job.isEnabled()) { disabled.add(aJob); } else if (!spawn.getPermissionsManager().isExecutable(user, token, sudo, job)) { unauthorized.add(aJob); } else { startJobHelper(aJob, select, priority); success.add(aJob); } } } else if (id.isPresent()) { String jobId = id.get(); <START> IJob job = spawn.getJob(jobId); <END> if (job == null) { error.add(jobId); } else if(!job.isEnabled()) { disabled.add(jobId); } else if (!spawn.getPermissionsManager().isExecutable(user, token, sudo, job)) { unauthorized.add(jobId); } else { startJobHelper(jobId, select, priority); success.add(jobId); } } else { return Response.status(Response.Status.BAD_REQUEST).entity("job id not specified").build(); } String json = CodecJSON.encodeString(ImmutableMap.of( "success", success, "error", error, "disabled", disabled, "unauthorized", unauthorized)); return Response.ok(json).build(); } catch (Exception ex) { return buildServerError(ex); } }</code><technical_language>This block of code of validating kicking a job is identical code above. refactored a method in places</technical_language>

Target:
public Response startJob(@QueryParam("jobid") Optional<String> jobIds, @QueryParam("select") @DefaultValue("-1") int select, @QueryParam("id") Optional<String> id, @QueryParam("task") @DefaultValue("-1") int task, @QueryParam("priority") @DefaultValue("0") int priority, @QueryParam("user") String user, @QueryParam("token") String token, @QueryParam("sudo") String sudo) { Map<String, List<String>> checkJobMap = new HashMap<>(); checkJobMap.put("success", new ArrayList<>()); checkJobMap.put("error", new ArrayList<>()); checkJobMap.put("disable", new ArrayList<>()); checkJobMap.put("unauthorized", new ArrayList<>()); try { if (jobIds.isPresent()) { Iterable<String> joblist = COMMA_SPLITTER.split(jobIds.get()); for (String jobId : joblist) { checkJob(jobId, select, priority, user, token, sudo, checkJobMap); } } else if (id.isPresent()) { String jobId = id.get(); checkJob(jobId, select, priority, user, token, sudo, checkJobMap); } else { return Response.status(Response.Status.BAD_REQUEST).entity("job id not specified").build(); } String json = CodecJSON.encodeString(checkJobMap); return Response.ok(json).build(); } catch (Exception ex) { return buildServerError(ex); } }
Source:
<code><START> public void disableAccelerometer() { <END> BluetoothLeGattCharacteristic enableChar; if (this.cc2650) { byte[] config = { 0x00, 0x00 }; try { enableChar = this.gattServices.get(MOVEMENT).findCharacteristic(TiSensorTagGatt.UUID_MOV_SENSOR_ENABLE); writeOnCharacteristic(config, enableChar); } catch (KuraException e) { logger.error(MOV_ERROR_MESSAGE, e); } } else { byte[] config = { 0x00 }; try { enableChar = this.gattServices.get(ACCELEROMETER) .findCharacteristic(TiSensorTagGatt.UUID_ACC_SENSOR_ENABLE); enableChar.writeValue(config); } catch (KuraException e) { logger.error("Accelerometer enable failed", e); } } }</code><technical_language>Similar</technical_language>

Target:
public boolean disableAccelerometer() { boolean result = false; BluetoothLeGattCharacteristic enableChar; if (this.cc2650) { byte[] config = { 0x00, 0x00 }; try { enableChar = this.gattServices.get(MOVEMENT).findCharacteristic(TiSensorTagGatt.UUID_MOV_SENSOR_ENABLE); writeOnCharacteristic(config, enableChar); result = true; } catch (KuraException e) { logger.error(MOV_ERROR_MESSAGE, e); } } else { byte[] config = { 0x00 }; try { enableChar = this.gattServices.get(ACCELEROMETER) .findCharacteristic(TiSensorTagGatt.UUID_ACC_SENSOR_ENABLE); enableChar.writeValue(config); result = true; } catch (KuraException e) { logger.error("Accelerometer enable failed", e); } } return result; }
Source:
<code>private void applyChanges(Run target, Run source) throws IOException { target.setAlias(source.getAlias()); target.setAccession(source.getAccession()); target.setDescription(source.getDescription()); target.setPairedEnd(source.getPairedEnd()); target.setFilePath(source.getFilePath()); target.setHealth(source.getHealth()); target.setStartDate(source.getStartDate()); target.setCompletionDate(source.getCompletionDate()); target.setMetrics(source.getMetrics()); List<SequencerPartitionContainer> saveContainers = new ArrayList<>(); for (SequencerPartitionContainer container : source.getSequencerPartitionContainers()) { SequencerPartitionContainer managedContainer = containerService.get(container.getId()); containerService.applyChanges(container, managedContainer); saveContainers.add(managedContainer); } makeContainerChangesChangeLog(target, saveContainers); target.setSequencerPartitionContainers(saveContainers); target.setSequencingParameters(source.getSequencingParameters()); target.setSequencerReference(source.getSequencerReference()); if (isIlluminaRun(target)) applyIlluminaChanges((IlluminaRun) target, (IlluminaRun) source); if (isPacBioRun(target)) applyPacBioChanges((PacBioRun) target, (PacBioRun) source); if (isLS454Run(target)) applyLS454Changes((LS454Run) target, (LS454Run) source); <START> if (isSolidRun(target)) applySolidChanges((SolidRun) target, (SolidRun) source); <END> }</code><technical_language>This 'else ifs' Remove target.setPairedEnd set specific subclasses</technical_language>

Target:
private void applyChanges(Run target, Run source) throws IOException { target.setAlias(source.getAlias()); target.setAccession(source.getAccession()); target.setDescription(source.getDescription()); target.setFilePath(source.getFilePath()); target.setHealth(source.getHealth()); target.setStartDate(source.getStartDate()); target.setCompletionDate(source.getCompletionDate()); target.setMetrics(source.getMetrics()); List<SequencerPartitionContainer> saveContainers = new ArrayList<>(); for (SequencerPartitionContainer container : source.getSequencerPartitionContainers()) { SequencerPartitionContainer managedContainer = containerService.get(container.getId()); containerService.applyChanges(container, managedContainer); saveContainers.add(managedContainer); } makeContainerChangesChangeLog(target, saveContainers); target.setSequencerPartitionContainers(saveContainers); target.setSequencingParameters(source.getSequencingParameters()); target.setSequencerReference(source.getSequencerReference()); if (isIlluminaRun(target)) { applyIlluminaChanges((IlluminaRun) target, (IlluminaRun) source); } else if (isPacBioRun(target)) { applyPacBioChanges((PacBioRun) target, (PacBioRun) source); } else if (isLS454Run(target)) { applyLS454Changes((LS454Run) target, (LS454Run) source); } else if (isSolidRun(target)) { applySolidChanges((SolidRun) target, (SolidRun) source); } }
Source:
<code>void process(final MappedClass mc, final Validation validation) { if (validation != null) { String collectionName = mc.getCollectionName(); CommandResult result = getDB() .command(new BasicDBObject("collMod", collectionName) .append("validator", parse(validation.value())) .append("validationLevel", validation.level().getValue()) .append("validationAction", validation.action().getValue()) ); if (!result.ok()) { if (result.getInt("code") == 26) { try { ValidationOptions options = new ValidationOptions() .validator(parse(validation.value())) .validationLevel(validation.level()) .validationAction(validation.action()); getDatabase().createCollection(collectionName, new CreateCollectionOptions().validationOptions(options)); <START> } catch (JsonParseException e) { <END> LOG.warning(format("Could not parse validator for '%s:' %s", collectionName, e.getMessage())); } } else { LOG.warning(format("Could not add document validation on '%s:' %s", collectionName, result.getErrorMessage())); } } } }</code><technical_language>This is inconsistent collMod case above, JsonParseException is caught. I catch a real error user deal with</technical_language>

Target:
void process(final MappedClass mc, final Validation validation) { if (validation != null) { String collectionName = mc.getCollectionName(); CommandResult result = getDB() .command(new BasicDBObject("collMod", collectionName) .append("validator", parse(validation.value())) .append("validationLevel", validation.level().getValue()) .append("validationAction", validation.action().getValue()) ); if (!result.ok()) { if (result.getInt("code") == 26) { ValidationOptions options = new ValidationOptions() .validator(parse(validation.value())) .validationLevel(validation.level()) .validationAction(validation.action()); getDatabase().createCollection(collectionName, new CreateCollectionOptions().validationOptions(options)); } else { result.throwOnError(); } } } }
Source:
<code>public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { <START> if (other.getName().equals(this.getName()) && this.getClass().getName().equals(other.getClass().getName())) { <END> return getCombiningFactory(); } else { throw new AggregatorFactoryNotMergeableException( "can't merge [%s : %s] and [%s : %s]", this.getName(), this.getClass().getName(), other.getName(), other.getClass().getName() ); } }</code><technical_language>Class objects compared ==</technical_language>

Target:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { throw new UnsupportedOperationException(String.format("[%s] does not implement getMergingFactory(..)", this.getClass().getName())); }
Source:
<code>public Map<String, String> createNewUser(final String userName) throws AuthenticationException, DatabaseAccessException { final ObjectId userId = new ObjectId(); final String userPassword = AbstractServerWebSocketHandler.Encoder.nextID().toString(); String hashPassword; try { hashPassword = HashManager.createHash(userPassword); } catch (NoSuchAlgorithmException e) { <START> LOG.error("Algorithm could not be found", e); <END> throw new AuthenticationException(e); } final DBCollection userCollection = database.getCollection(DatabaseStringConstants.USER_COLLECTION); final BasicDBObject query = new BasicDBObject(DatabaseStringConstants.USER_NAME, userName); final DBObject cursor = userCollection.findOne(query); if (cursor == null) { userCollection.insert(new BasicDBObject(DatabaseStringConstants.SELF_ID, userId) .append(DatabaseStringConstants.USER_NAME, userName) .append(DatabaseStringConstants.PASSWORD, hashPassword)); } else { throw new DatabaseAccessException("User [" + userName + "] already exists in the database"); } final Map<String, String> result = new HashMap<>(); result.put(userId.toString(), userPassword); return result; }</code><technical_language>Do need this log, log else this catch a NoSuchAlgorithmException</technical_language>

Target:
public Map<String, String> createNewUser(final String userName) throws AuthenticationException, DatabaseAccessException { final ObjectId userId = new ObjectId(); final String userPassword = AbstractServerWebSocketHandler.Encoder.nextID().toString(); String hashPassword; try { hashPassword = HashManager.createHash(userPassword); } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("Invalid algorithm when creating a new user", e); } final DBCollection userCollection = database.getCollection(DatabaseStringConstants.USER_COLLECTION); final BasicDBObject query = new BasicDBObject(DatabaseStringConstants.USER_NAME, userName); final DBObject cursor = userCollection.findOne(query); if (cursor == null) { userCollection.insert(new BasicDBObject(DatabaseStringConstants.SELF_ID, userId) .append(DatabaseStringConstants.USER_NAME, userName) .append(DatabaseStringConstants.PASSWORD, hashPassword)); } else { throw new DatabaseAccessException("User [" + userName + "] already exists in the database"); } final Map<String, String> result = new HashMap<>(); result.put(userId.toString(), userPassword); return result; }
Source:
<code>void subSubjectByType() { int messageCount = 3; int otherMessageCount = 2; Iterable<W> outerObjects = ImmutableList .<W>builder() .addAll(messages(messageCount)) .addAll(messages(otherMessageCount, this::createAnotherMessage)) .build(); Class<M> cls1 = typeOf(createMessage()); <START> Class<M> cls2 = typeOf(createAnotherMessage()); <END> S subject = assertWithSubjectThat(outerObjects); S subSubject1 = subject.withType(cls1); subSubject1.hasSize(messageCount); S subSubject2 = subject.withType(cls2); subSubject2.hasSize(otherMessageCount); }</code><technical_language>Please message other instead of 1 2 for readability</technical_language>

Target:
void subSubjectByType() { int messageCount = 3; int otherMessageCount = 2; Iterable<W> outerObjects = ImmutableList .<W>builder() .addAll(messages(messageCount)) .addAll(messages(otherMessageCount, this::createAnotherMessage)) .build(); Class<M> type = typeOf(createMessage()); Class<M> anotherType = typeOf(createAnotherMessage()); S subject = assertWithSubjectThat(outerObjects); S subSubject = subject.withType(type); subSubject.hasSize(messageCount); S anotherSubSubject = subject.withType(anotherType); anotherSubSubject.hasSize(otherMessageCount); }
Source:
<code>public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { <START> final String upperCaseIsolationLevelName = Optional.of(transactionIsolationName.toUpperCase(Locale.ENGLISH)) <END> .orElseThrow(IllegalArgumentException::new); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }</code><technical_language>Optional is here? absolutely redundant</technical_language>

Target:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { final String upperCaseIsolationLevelName = transactionIsolationName.toUpperCase(Locale.ENGLISH); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }
Source:
<code>public JSONObject callConduit(Launcher.ProcStarter starter, PrintStream stderr) throws IOException, InterruptedException { JSONObject obj = new JSONObject(); obj.putAll(this.params); <START> List<String> command = new ArrayList<String>( <END> Arrays.asList("sh", "-c", "echo '" + obj.toString() + "' | " + this.getConduitCommand(this.methodName))); ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream(); starter.cmds(command).stdout(stdoutBuffer).stderr(stderr).join(); JsonSlurper jsonParser = new JsonSlurper(); try { return (JSONObject) jsonParser.parseText(stdoutBuffer.toString()); } catch(net.sf.json.JSONException e) { stderr.println("[phabricator] Unable to parse JSON from response: " + stdoutBuffer.toString()); throw e; } }</code><technical_language>Arrays.asList returns a list, need create a new ArrayList List</technical_language>

Target:
public JSONObject callConduit(Launcher.ProcStarter starter, PrintStream stderr) throws IOException, InterruptedException { JSONObject obj = new JSONObject(); obj.putAll(this.params); List<String> command = Arrays.asList( "sh", "-c", "echo '" + obj.toString() + "' | " + this.getConduitCommand(this.methodName)); ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream(); starter.quiet(true).cmds(command).stdout(stdoutBuffer).stderr(stderr).join(); JsonSlurper jsonParser = new JsonSlurper(); try { return (JSONObject) jsonParser.parseText(stdoutBuffer.toString()); } catch(net.sf.json.JSONException e) { stderr.println("[phabricator] Unable to parse JSON from response: " + stdoutBuffer.toString()); throw e; } }
Source:
<code><START> private void updateLog() { <END> if (fetchLogTask != null) fetchLogTask.cancel(true); mLog.setText("Retrieving logs..."); fetchLogTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { if (syncthingLog) { return getSyncthingLog(); } else { return getAndroidLog(); } } @Override protected void onPostExecute(String log) { mLog.setText(log); mShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, log); scrollToBottom(); } }.execute(); }</code><technical_language>need for a function, class UpdateLogTask (like in SyncthinkService). Also, getSyncthingLog() getAndroidLog() some duplicate code. I put in doInBackground() if choose logcat command/parameters</technical_language>

Target:
private void updateLog() { if (mFetchLogTask != null) mFetchLogTask.cancel(true); mLog.setText("Retrieving logs..."); mFetchLogTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { return getLog(mSyncthingLog); } @Override protected void onPostExecute(String log) { mLog.setText(log); if (mShareIntent != null) mShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, log); scrollToBottom(); } }.execute(); }
Source:
<code><START> public ServerRequest(BattleFragment battleFragment, JSONObject request) throws JSONException { <END> setRqId(request.getInt("rqid")); JSONObject side = request.getJSONObject("side"); JSONArray team = side.getJSONArray("pokemon"); for (int i = 0; i < team.length(); i++) { JSONObject info = team.getJSONObject(i); PokemonInfo pkm = BattleMessage.parsePokemonInfo(battleFragment, info); getPkmTeam().add(pkm); } if (request.has("teamPreview")) { setTeamPreview(request.getBoolean("teamPreview")); } if (request.has("active")) { JSONArray active = request.getJSONArray("active"); for (int i = 0; i < active.length(); i++) { ActiveMoveInfo info = new ActiveMoveInfo(active.getJSONObject(i)); getMovesToDo().add(info); } } if (request.has("forceSwitch")) { JSONArray forceSwitchArray = request.getJSONArray("forceSwitch"); for (int i = 0; i < forceSwitchArray.length(); i++) { getForceSwitch().add(forceSwitchArray.getBoolean(i)); } } }</code><technical_language>BattleMessage. I prefer together</technical_language>

Target:
public ServerRequest(BattleFragment battleFragment, JSONObject request) throws JSONException { setRqId(request.getInt("rqid")); JSONObject side = request.getJSONObject("side"); JSONArray team = side.getJSONArray("pokemon"); for (int i = 0; i < team.length(); i++) { JSONObject info = team.getJSONObject(i); PokemonInfo pkm = BattleMessage.parsePokemonInfo(battleFragment, info); getPkmTeam().add(pkm); } if (request.has("teamPreview")) { setTeamPreview(request.getBoolean("teamPreview")); } if (request.has("wait")) { wait = request.getBoolean("wait"); } if (request.has("active")) { JSONArray active = request.getJSONArray("active"); for (int i = 0; i < active.length(); i++) { ActiveMoveInfo info = new ActiveMoveInfo(active.getJSONObject(i)); getMovesToDo().add(info); } } if (request.has("forceSwitch")) { JSONArray forceSwitchArray = request.getJSONArray("forceSwitch"); for (int i = 0; i < forceSwitchArray.length(); i++) { getForceSwitch().add(forceSwitchArray.getBoolean(i)); } } }
Source:
<code>public SPathConverter(ISarosSession session, IPathFactory pathFactory) { this.session = session; this.pathFactory = pathFactory; <START> this.referencePointManager = session <END> .getComponent(IReferencePointManager.class); }</code><technical_language>Throw exception if referencePointManager is null (if is currently session running)</technical_language>

Target:
public SPathConverter(ISarosSession session, IPathFactory pathFactory) { this.session = session; this.pathFactory = pathFactory; this.referencePointManager = session .getComponent(IReferencePointManager.class); if (this.referencePointManager == null) throw new IllegalStateException( "ReferencePointManager is null. Session is not running"); }
Source:
<code>public static void main(String[] args) { try { LOGGER.info("Start frame-based game loop:"); <START> GameLoop gameLoop = new FrameBasedGameLoop(); <END> gameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); gameLoop.stop(); LOGGER.info("Stop frame-based game loop."); LOGGER.info("Start variable-step game loop:"); gameLoop = new VariableStepGameLoop(); gameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); gameLoop.stop(); LOGGER.info("Stop variable-step game loop."); LOGGER.info("Start fixed-step game loop:"); gameLoop = new FixedStepGameLoop(); gameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); gameLoop.stop(); LOGGER.info("Stop variable-step game loop."); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } }</code><technical_language>newer Java style i.e. local variable type inference var</technical_language>

Target:
public static void main(String[] args) { try { LOGGER.info("Start frame-based game loop:"); var frameBasedGameLoop = new FrameBasedGameLoop(); frameBasedGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); frameBasedGameLoop.stop(); LOGGER.info("Stop frame-based game loop."); LOGGER.info("Start variable-step game loop:"); var variableStepGameLoop = new VariableStepGameLoop(); variableStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); variableStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); LOGGER.info("Start fixed-step game loop:"); var fixedStepGameLoop = new FixedStepGameLoop(); fixedStepGameLoop.run(); Thread.sleep(GAME_LOOP_DURATION_TIME); fixedStepGameLoop.stop(); LOGGER.info("Stop variable-step game loop."); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } }
Source:
<code>public GroupByColumnSelectorStrategy makeColumnSelectorStrategy( ColumnCapabilities capabilities, ColumnValueSelector selector ) { ValueType type = capabilities.getType(); switch(type) { case STRING: DimensionSelector dimSelector = (DimensionSelector) selector; <START> if (dimSelector.nameLookupPossibleInAdvance()) { <END> return new StringGroupByColumnSelectorStrategy(); } else { return new DictionaryBuildingStringGroupByColumnSelectorStrategy(); } case LONG: return new LongGroupByColumnSelectorStrategy(); case FLOAT: return new FloatGroupByColumnSelectorStrategy(); default: throw new IAE("Cannot create query type helper from invalid type [%s]", type); } }</code><technical_language>I this right check. groupBy need names looked in advance, _after_ iteration cursor. this dimSelector.getValueCardinality() >= 0. good changing is avoid creating dictionaries for SingleScanTimeDimSelector</technical_language>

Target:
public GroupByColumnSelectorStrategy makeColumnSelectorStrategy( ColumnCapabilities capabilities, ColumnValueSelector selector ) { ValueType type = capabilities.getType(); switch(type) { case STRING: DimensionSelector dimSelector = (DimensionSelector) selector; if (dimSelector.getValueCardinality() >= 0) { return new StringGroupByColumnSelectorStrategy(); } else { return new DictionaryBuildingStringGroupByColumnSelectorStrategy(); } case LONG: return new LongGroupByColumnSelectorStrategy(); case FLOAT: return new FloatGroupByColumnSelectorStrategy(); default: throw new IAE("Cannot create query type helper from invalid type [%s]", type); } }
Source:
<code>public static BlockedErrorExtension from(Message message) { <START> return message.getError().getExtension(ELEMENT, NAMESPACE); <END> }</code><technical_language>this check for null</technical_language>

Target:
public static BlockedErrorExtension from(Message message) { XMPPError error = message.getError(); if (error == null) { return null; } return error.getExtension(ELEMENT, NAMESPACE); }
Source:
<code>public void setUp() throws Exception { final SnapshotDao snapshotDao = mock(SnapshotDao.class); final EventService eventService = mock(EventService.class); <START> machineLogsDir = targetDir().resolve("logs-dir").toString(); <END> manager = spy(new MachineManager(snapshotDao, machineRegistry, machineInstanceProviders, machineLogsDir, eventService, DEFAULT_MACHINE_MEMORY_SIZE_MB, wsAgentLauncher)); EnvironmentContext envCont = new EnvironmentContext(); envCont.setSubject(new SubjectImpl(null, USER_ID, null, null, false)); EnvironmentContext.setCurrent(envCont); RecipeImpl recipe = new RecipeImpl().withScript("script").withType("Dockerfile"); doReturn(MACHINE_ID).when(manager).generateMachineId(); when(machineInstanceProviders.getProvider(anyString())).thenReturn(instanceProvider); HashSet<String> recipeTypes = new HashSet<>(); recipeTypes.add("test type 1"); recipeTypes.add("dockerfile"); when(instanceProvider.getRecipeTypes()).thenReturn(recipeTypes); when(instanceProvider.createInstance(any(Machine.class), any(LineConsumer.class))).thenReturn(instance); when(machineRegistry.getInstance(anyString())).thenReturn(instance); }</code><technical_language>happen if previous test is stopped teardown method call files removal accomplished</technical_language>

Target:
public void setUp() throws Exception { final SnapshotDao snapshotDao = mock(SnapshotDao.class); final EventService eventService = mock(EventService.class); final String machineLogsDir = targetDir().resolve("logs-dir").toString(); IoUtil.deleteRecursive(new File(machineLogsDir)); manager = spy(new MachineManager(snapshotDao, machineRegistry, machineInstanceProviders, machineLogsDir, eventService, DEFAULT_MACHINE_MEMORY_SIZE_MB, wsAgentLauncher)); EnvironmentContext envCont = new EnvironmentContext(); envCont.setSubject(new SubjectImpl(null, USER_ID, null, null, false)); EnvironmentContext.setCurrent(envCont); RecipeImpl recipe = new RecipeImpl().withScript("script").withType("Dockerfile"); doReturn(MACHINE_ID).when(manager).generateMachineId(); doReturn(processLogger).when(manager).getProcessLogger(MACHINE_ID, 111, "outputChannel"); when(machineInstanceProviders.getProvider(anyString())).thenReturn(instanceProvider); HashSet<String> recipeTypes = new HashSet<>(); recipeTypes.add("test type 1"); recipeTypes.add("dockerfile"); when(instanceProvider.getRecipeTypes()).thenReturn(recipeTypes); when(instanceProvider.createInstance(any(Machine.class), any(LineConsumer.class))).thenReturn(instance); when(machineRegistry.getInstance(anyString())).thenReturn(instance); when(command.getCommandLine()).thenReturn("CommandLine"); when(command.getName()).thenReturn("CommandName"); when(command.getType()).thenReturn("CommandType"); when(machineRegistry.getInstance(MACHINE_ID)).thenReturn(instance); when(instance.createProcess(command, "outputChannel")).thenReturn(instanceProcess); when(instanceProcess.getPid()).thenReturn(111); }
Source:
<code>public static Request setFakeCodeRequest(Request request){ Code fakeCode; <START> if(!request.getOptions().hasObserve()){ <END> fakeCode = Code.POST; }else{ fakeCode = Code.FETCH; } return requestWithNewCode(request, fakeCode); }</code><technical_language>whitespace</technical_language>

Target:
public static Request setFakeCodeRequest(Request request) { Code fakeCode = request.getOptions().hasObserve() ? Code.FETCH : Code.POST; return requestWithNewCode(request, fakeCode); }
Source:
<code>private Throwable createTimeoutException(Thread thread) { List<Throwable> exceptions = new ArrayList<Throwable>(); exceptions.add(createCurrentThreadException(thread)); exceptions.addAll(createAdditionalTimeoutExceptions(thread)); <START> return exceptions.size() == 1 ? exceptions.get(0) : new MultipleFailureException(exceptions); <END> }</code><technical_language>This simplified MultipleFailureException.assertEmpty, for worth</technical_language>

Target:
protected Throwable createTimeoutException(Thread thread) { List<Throwable> exceptions = new ArrayList<Throwable>(); exceptions.add(createCurrentThreadException(thread)); exceptions.addAll(createAdditionalTimeoutExceptions(thread)); return exceptions.size() == 1 ? exceptions.get(0) : new MultipleFailureException(exceptions); }
Source:
<code>public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } <START> Collection<RepositoryMapping> mappings = getMappings(project); <END> for (RepositoryMapping mapping : mappings) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }</code><technical_language>style nit: this inlined</technical_language>

Target:
public static RepositoryMapping getMapping(@NonNull IPath path) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); IPath bestWorkingTree = null; RepositoryMapping bestMapping = null; for (IProject project : projects) { if (isNonWorkspace(project)) { continue; } Map<IPath, RepositoryMapping> mappings = getMappings(project); for (RepositoryMapping mapping : mappings.values()) { File workTree = mapping.getWorkTree(); if (workTree == null) { continue; } IPath workingTree = new Path(workTree.toString()); if (workingTree.isPrefixOf(path)) { if (bestWorkingTree == null || workingTree .segmentCount() > bestWorkingTree.segmentCount()) { bestWorkingTree = workingTree; bestMapping = mapping; } } } } return bestMapping; }
Source:
<code>public void testStringHeaderSerialization() throws IOException, ClassNotFoundException { <START> Header header = new StringHeader("some value"); <END> Header deserializedHeader = TestUtil.serializeAndDeserialize(header); Assert.assertEquals(deserializedHeader, header); }</code><technical_language>final below</technical_language>

Target:
public void testStringHeaderSerialization() throws IOException, ClassNotFoundException { final Header header = new StringHeader("some value"); final Header deserializedHeader = TestUtil.serializeAndDeserialize(header); Assert.assertEquals(deserializedHeader, header); }
Source:
<code>public static RunResolution resolve(Project project, Processor actualProperties, Collection<ResolutionCallback> callbacks) { if (callbacks == null) callbacks = Collections.emptyList(); try (ResolverLogger logger = new ResolverLogger()) { try { ResolveProcess resolve = new ResolveProcess(); Resolver resolver = new BndResolver(logger); resolve.resolveRequired(actualProperties, project, project, resolver, callbacks, logger); return new RunResolution(project, actualProperties, resolve.getRequiredWiring(), resolve.getOptionalWiring(), logger.getLog()); <START> } catch (ResolutionException e) { <END> return new RunResolution(project, actualProperties, e, logger.getLog()); } catch (Exception e) { return new RunResolution(project, actualProperties, e, logger.getLog()); } } finally { } }</code><technical_language>do multi-catch catch blocks identical</technical_language>

Target:
public static RunResolution resolve(Project project, Processor actualProperties, Collection<ResolutionCallback> callbacks) { if (callbacks == null) callbacks = Collections.emptyList(); try (ResolverLogger logger = new ResolverLogger()) { try { ResolveProcess resolve = new ResolveProcess(); Resolver resolver = new BndResolver(logger); resolve.resolveRequired(actualProperties, project, project, resolver, callbacks, logger); return new RunResolution(project, actualProperties, resolve.getRequiredWiring(), resolve.getOptionalWiring(), logger.getLog()); } catch (Exception e) { return new RunResolution(project, actualProperties, e, logger.getLog()); } } finally { } }
Source:
<code>public List<HueLamp> getLamps() { <START> return hueFacade.getAvailableLamps().entrySet().stream() <END> .map(Map.Entry::getValue) .collect(Collectors.toList()); }</code><technical_language>[return hueFacade.getAvailableLamps().values();](<LINK_0></technical_language>

Target:
public SortedSet<HueLamp> getLamps() { return new TreeSet<>(hueFacade.getAvailableLamps().values()); }
Source:
<code>protected FileStatus[] listStatus(JobConf job) throws IOException { if(listsToFetch == null || listsToFetch.isEmpty()) { return super.listStatus(job); } List<FileStatus> fsStatusList = new ArrayList<>(); for(Path path:listsToFetch) { FileSystem fs = path.getFileSystem(job); <START> FileStatus fsStatus = fs.getFileStatus(path); <END> fsStatusList.add(fsStatus); } FileStatus[] fsStatusArray = new FileStatus[fsStatusList.size()]; return fsStatusList.toArray(fsStatusArray); }</code><technical_language>I avoid this call, if carry statuslist FS operator</technical_language>

Target:
protected FileStatus[] listStatus(JobConf job) throws IOException { if(fileStatuses== null || fileStatuses.isEmpty()) { return super.listStatus(job); } FileStatus[] fsStatusArray = new FileStatus[fileStatuses.size()]; return fileStatuses.toArray(fsStatusArray); }
Source:
<code>private EventHttpMetadata generateHttpMetadata(HttpServletRequest httpServletRequest, int responseStatusCode) { Map<String, String> headers = Collections.list(httpServletRequest.getHeaderNames()).stream() .collect(Collectors.toMap(Function.identity(), <START> name -> String.join(",", Collections.list(httpServletRequest.getHeaders(name))))); <END> return new EventHttpMetadata(httpServletRequest.getMethod(), httpServletRequest.getRemoteAddr(), Collections.unmodifiableMap(headers), httpServletRequest.getCookies() != null, responseStatusCode); }</code><technical_language>escaped, in case if header values comma</technical_language>

Target:
private EventHttpMetadata generateHttpMetadata(HttpServletRequest httpServletRequest, int responseStatusCode) { Map<String, String> headers = list(httpServletRequest.getHeaderNames()).stream() .collect(Collectors.toMap(Function.identity(), name -> joinWithComma(list(httpServletRequest.getHeaders(name))))); return new EventHttpMetadata(httpServletRequest.getMethod(), httpServletRequest.getRemoteAddr(), Collections.unmodifiableMap(headers), httpServletRequest.getCookies() != null, responseStatusCode); }
Source:
<code>private List<Snak> getQualifiers(JSONArray jsonQualifiers) { <START> List<Snak> result = new LinkedList<Snak>(); <END> for (int i = 0; i < jsonQualifiers.length(); i++) { try { JSONArray currentValueSnak = jsonQualifiers.getJSONArray(i); result.add(this.getSnak(currentValueSnak)); } catch (JSONException e) { continue; } } return result; }</code><technical_language>pick a linked list instead of array list? number of qualifiers upfront, initialise array exact size need</technical_language>

Target:
private List<Snak> getQualifiers(JSONArray jsonQualifiers) throws JSONException { List<Snak> result = new ArrayList<Snak>(jsonQualifiers.length()); for (int i = 0; i < jsonQualifiers.length(); i++) { JSONArray currentSnak = jsonQualifiers.getJSONArray(i); result.add(this.getSnak(currentSnak)); } return result; }
Source:
<code>protected void runPages(List<WikiPage> pages, RunNotifier notifier) { boolean seleniumConfigOverridden = configureSeleniumIfNeeded(); try { <START> if ("true".equalsIgnoreCase(System.getProperty(allureEnablerVariableName))){ <END> notifier.addListener(new JUnitAllureFrameworkListener(pages)); } super.runPages(pages, notifier); } finally { if (seleniumConfigOverridden) { try { shutdownSelenium(); } catch (Exception e) { } } try { Class<?> suiteClass = getTestClass().getJavaClass(); String outputDir = getOutputDir(suiteClass); String suiteName = getSuiteName(suiteClass); String filename = suiteName + ".html"; File overviewFile = new File(outputDir, filename); if (overviewFile.exists()) { String path = overviewFile.getAbsolutePath(); String overviewHtml = FileUtil.streamToString(new FileInputStream(path), path); if (overviewHtml != null) { String indexHtml = getIndexHtmlContent(overviewHtml); FileUtil.writeFile(new File(outputDir, "index.html").getAbsolutePath(), indexHtml); } } } catch (Exception e) { } } }</code><technical_language>This (of course) done in pom.xml (where I add 2 listeners default). this need happen in code (triggered a system property)</technical_language>

Target:
protected void runPages(List<WikiPage> pages, RunNotifier notifier) { boolean seleniumConfigOverridden = configureSeleniumIfNeeded(); try { super.runPages(pages, notifier); } finally { if (seleniumConfigOverridden) { try { shutdownSelenium(); } catch (Exception e) { } } try { Class<?> suiteClass = getTestClass().getJavaClass(); String outputDir = getOutputDir(suiteClass); String suiteName = getSuiteName(suiteClass); String filename = suiteName + ".html"; File overviewFile = new File(outputDir, filename); if (overviewFile.exists()) { String path = overviewFile.getAbsolutePath(); String overviewHtml = FileUtil.streamToString(new FileInputStream(path), path); if (overviewHtml != null) { String indexHtml = getIndexHtmlContent(overviewHtml); FileUtil.writeFile(new File(outputDir, "index.html").getAbsolutePath(), indexHtml); } } } catch (Exception e) { } } }
Source:
<code>public void testKafkaSourceAndSink() throws Exception { String topicName = generateStreamName(); final String stringToPost = "Hi there!"; <START> AdminUtils.createTopic(kafkaTestSupport.getZkClient(), topicName, 1, 1, new Properties()); <END> final HttpSource httpSource = newHttpSource(); stream().create(topicName, "%s | kafka --topic='%s'", httpSource, topicName); Thread.sleep(1000); final CounterSink counter = metrics().newCounterSink(); stream().create(generateStreamName(), "kafka --topic='%s' --zkconnect=%s | " + "filter --expression=payload.toString().contains('%s') | %s", topicName, zkConnectString, stringToPost, counter ); Thread.sleep(1000); httpSource.ensureReady().postData(stringToPost); Thread.sleep(5000); assertThat(counter, eventually(exists())); AdminUtils.deleteTopic(kafkaTestSupport.getZkClient(), topicName); }</code><technical_language>createTopic deleteTopic in @Before/@After</technical_language>

Target:
public void testKafkaSourceAndSink() throws Exception { final String stringToPost = "Hi there!"; final HttpSource httpSource = newHttpSource(); stream().create(generateStreamName(), "%s | kafka --topic='%s'", httpSource, topicToUse); final CounterSink counter = metrics().newCounterSink(); stream().create(generateStreamName(), "kafka --topic='%s' --zkconnect=%s --consumerTimeout=-1 | " + "filter --expression=payload.toString().contains('%s') | %s", topicToUse, zkConnectString, stringToPost, counter ); httpSource.ensureReady().postData(stringToPost); assertThat(counter, eventually(exists())); }
Source:
<code>public static void e(String TAG, String message) { <START> Timber.d(message); <END> }</code><technical_language>format, Timber.e(message)</technical_language>

Target:
public static void e(String TAG, String message) { Timber.e(message); }
Source:
<code>public static SpawnDataStore makeSpawnDataStore(DataStoreType type) throws Exception { Properties properties = new Properties(); if (sqlUser != null) { properties.put("user", sqlUser); <START> if(sqlPasspath.length() != 0) { <END> VaultWrapper vaultClient = (VaultWrapper) Class.forName("com.addthis.hydra.vault.VaultWrapperImpl").newInstance(); vaultClient.login("<LINK_0>"); sqlPassword = vaultClient.getSecret(sqlPasspath).get("value"); } properties.put("password", sqlPassword); } switch (type) { case FS: return new FilesystemDataStore(new File(fsDataStoreFileRoot)); case ZK: return new ZookeeperDataStore(null); case MYSQL: return new MysqlDataStore("jdbc:mysql://" + sqlHostName + ":" + sqlPort + "/", sqlDbName, sqlTableName, properties); case POSTGRES: return new PostgresDataStore("jdbc:postgres://" + sqlHostName + ":" + sqlPort + "/", sqlDbName, sqlTableName, properties); default: throw new IllegalArgumentException("Unexpected DataStoreType " + type); } }</code><technical_language>!isEmpty() :)</technical_language>

Target:
public static SpawnDataStore makeSpawnDataStore(DataStoreType type) throws Exception { Properties properties = new Properties(); if (sqlUser != null) { properties.put("user", sqlUser); if(!sqlPasspath.isEmpty()) { VaultWrapper vaultClient = (VaultWrapper) Class.forName(vaultClassName).newInstance(); vaultClient.login(vaultServer); sqlPassword = vaultClient.getSecret(sqlPasspath).get("value"); } properties.put("password", sqlPassword); } switch (type) { case FS: return new FilesystemDataStore(new File(fsDataStoreFileRoot)); case ZK: return new ZookeeperDataStore(null); case MYSQL: return new MysqlDataStore("jdbc:mysql://" + sqlHostName + ":" + sqlPort + "/", sqlDbName, sqlTableName, properties); case POSTGRES: return new PostgresDataStore("jdbc:postgres://" + sqlHostName + ":" + sqlPort + "/", sqlDbName, sqlTableName, properties); default: throw new IllegalArgumentException("Unexpected DataStoreType " + type); } }
Source:
<code>private Trigger addBuildInfo(@NonNull Trigger inputTrigger) { String master = inputTrigger.getMaster(); Integer buildNumber = inputTrigger.getBuildNumber(); String job = inputTrigger.getJob(); String propertyFile = inputTrigger.getPropertyFile(); Map<String, Object> buildInfo = null; Map<String, Object> properties = null; if (master != null && buildNumber != null && StringUtils.isNotEmpty(job)) { <START> buildInfo = igorService.getBuild(buildNumber, master, job); <END> if (StringUtils.isNotEmpty(propertyFile)) { properties = igorService.getPropertyFile(buildNumber, propertyFile, master, job); } } return inputTrigger.withBuildInfo(buildInfo).withProperties(properties); }</code><technical_language>igor/jenkins pretty flaky ... if this call fails? retries</technical_language>

Target:
private Trigger addBuildInfo(@NonNull Trigger inputTrigger) { String master = inputTrigger.getMaster(); Integer buildNumber = inputTrigger.getBuildNumber(); String job = inputTrigger.getJob(); String propertyFile = inputTrigger.getPropertyFile(); Map<String, Object> buildInfo = null; Map<String, Object> properties = null; if (master != null && buildNumber != null && StringUtils.isNotEmpty(job)) { buildInfo = retry(() -> igorService.getBuild(buildNumber, master, job)); if (StringUtils.isNotEmpty(propertyFile)) { properties = retry(() -> igorService.getPropertyFile(buildNumber, propertyFile, master, job)); } } return inputTrigger.withBuildInfo(buildInfo).withProperties(properties); }
Source:
<code>public void defaultTest() throws Exception { ILaunchConfigurationType launchConfigType = mock(ILaunchConfigurationType.class); ILaunchConfiguration launchConfig = mock(ILaunchConfiguration.class); doReturn(launchConfigType).when(launchConfig).getType(); doReturn("dummy").when(launchConfigType).getIdentifier(); doReturn(true).when(launchConfigType).supportsMode("run"); doReturn(true).when(launchConfigType).supportsMode("debug"); LaunchBarManager manager = new LaunchBarManager(false) { <START> @Override <END> void saveActiveTargetMapping(ILaunchConfiguration activeConfig, IRemoteConnection target) { } }; manager.init(); manager.launchConfigurationAdded(launchConfig); assertNotNull(manager.getActiveLaunchDescriptor()); assertEquals(launchConfig, manager.getActiveLaunchDescriptor().getAdapter(ILaunchConfiguration.class)); IRemoteServicesManager remoteManager = Activator.getService(IRemoteServicesManager.class); IRemoteConnectionType localServices = remoteManager.getLocalConnectionType(); IRemoteConnection localConnection = localServices.getConnections().get(0); assertNotNull(manager.getActiveLaunchTarget()); assertEquals(localConnection, manager.getActiveLaunchTarget()); assertNotNull(manager.getActiveLaunchMode()); assertEquals("run", manager.getActiveLaunchMode().getIdentifier()); assertEquals(launchConfig, manager.getActiveLaunchConfiguration()); }</code><technical_language>mocking out service</technical_language>

Target:
public void defaultTest() throws Exception { ILaunchConfigurationType launchConfigType = mock(ILaunchConfigurationType.class); ILaunchConfiguration launchConfig = mock(ILaunchConfiguration.class); doReturn(launchConfigType).when(launchConfig).getType(); doReturn("dummy").when(launchConfigType).getIdentifier(); doReturn(true).when(launchConfigType).supportsMode("run"); doReturn(true).when(launchConfigType).supportsMode("debug"); LaunchBarManager manager = new LaunchBarManager(false) { IRemoteLaunchConfigService getRemoteLaunchConfigService() { return mock(IRemoteLaunchConfigService.class); } }; manager.init(); manager.launchConfigurationAdded(launchConfig); assertNotNull(manager.getActiveLaunchDescriptor()); assertEquals(launchConfig, manager.getActiveLaunchDescriptor().getAdapter(ILaunchConfiguration.class)); IRemoteServicesManager remoteManager = Activator.getService(IRemoteServicesManager.class); IRemoteConnectionType localServices = remoteManager.getLocalConnectionType(); IRemoteConnection localConnection = localServices.getConnections().get(0); assertNotNull(manager.getActiveLaunchTarget()); assertEquals(localConnection, manager.getActiveLaunchTarget()); assertNotNull(manager.getActiveLaunchMode()); assertEquals("run", manager.getActiveLaunchMode().getIdentifier()); assertEquals(launchConfig, manager.getActiveLaunchConfiguration()); }
Source:
<code>public static String convertFromIpsecString(String str) { if (str == null) return null; try { return str.replace('-', '_').toUpperCase(); <START> } catch (IllegalArgumentException ex) { <END> return null; } }</code><technical_language>This get thrown</technical_language>

Target:
public static String convertFromIpsecString(String str) { if (str == null) { return null; } return str.replace('-', '_').toUpperCase(); }
Source:
<code>public String identifier() { <START> return GcsSecretEngine.IDENTIFIER; <END> }</code><technical_language>Super minor, call this IDENTIFIER class a qualified reference</technical_language>

Target:
public String identifier() { return IDENTIFIER; }
Source:
<code><START> public IterableSizeAssert<T, Integer> size() { <END> Preconditions.checkNotNull(actual, "Can not assert on size of iterable which is null."); return new IterableSizeAssert(this, IterableUtil.sizeOf(actual)); }</code><technical_language>try declare returning AbstractIterableAssert, I a need return IterableSizeAssert (but building IterableSizeAssert) if solved cast pb..</technical_language>

Target:
public AbstractIterableSizeAssert<S, A, T> size() { Preconditions.checkNotNull(actual, "Can not assert on size of iterable which is null."); return new IterableSizeAssert(this, IterableUtil.sizeOf(actual)); }
Source:
<code>public List<InputSplit> getSplits(JobContext job) throws IOException { initInputFormat(HadoopCompat.getConfiguration(job)); List<InputSplit> inputSplits; try { inputSplits = delegate.getSplits(job); } catch (InterruptedException e) { LOG.error("Thread interrupted", e); Thread.currentThread().interrupt(); throw new IOException(e); <START> } <END> List<InputSplit> combinedInputSplits = new ArrayList<InputSplit>(); Configuration conf = HadoopCompat.getConfiguration(job); try { for (CompositeInputSplit split : SplitUtil.getCombinedCompositeSplits(inputSplits, conf)) { split.setConf(conf); combinedInputSplits.add(split); } } catch (InterruptedException e) { LOG.error("Thread interrupted", e); Thread.currentThread().interrupt(); throw new IOException(e); } return combinedInputSplits; }</code><technical_language>add ", InterruptedException" in signature of this method, no</technical_language>

Target:
public List<InputSplit> getSplits(JobContext job) throws IOException { Configuration conf = HadoopCompat.getConfiguration(job); initInputFormat(conf); try { if (shouldCombine(conf)) { List<InputSplit> inputSplits = delegate.getSplits(job); List<InputSplit> combinedInputSplits = new ArrayList<InputSplit>(); for (CompositeInputSplit split : SplitUtil.getCombinedCompositeSplits(inputSplits, conf)) { split.setConf(conf); combinedInputSplits.add(split); } return combinedInputSplits; } else { return delegate.getSplits(job); } } catch (InterruptedException e) { LOG.error("Thread interrupted", e); Thread.currentThread().interrupt(); throw new IOException(e); } }