auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public StructDefinition getContext() { final StructDefinition streamContext = streamInputReader.getPacketReader().getStreamEventContextDef(); if (streamContext == null) { return context; } if (context == null) { return streamContext; } StructDeclaration mergedDeclaration = new StructDeclaration(1); HashMap<String, Definition> defs = streamContext.getDefinitions(); Iterator<Entry<String, Definition>> it = defs.entrySet().iterator(); while (it.hasNext()) { Entry<String, Definition> entry = it.next(); mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } it = context.getDefinitions().entrySet().iterator(); while (it.hasNext()) { Entry<String, Definition> entry = it.next(); mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } StructDefinition mergedContext = mergedDeclaration.createDefinition( null, "context"); Set<String> keys = mergedContext.getDefinitions().keySet(); for (String key : keys) { final Definition lookupDefinition = context.lookupDefinition(key); if (lookupDefinition != null) { mergedContext.getDefinitions().put(key, lookupDefinition); } else { mergedContext.getDefinitions().put(key, streamContext.lookupDefinition(key)); } } return mergedContext; }

Target:
public StructDefinition getContext() { final StructDefinition streamContext = streamInputReader.getPacketReader().getStreamEventContextDef(); if (streamContext == null) { return context; } if (context == null) { return streamContext; } StructDeclaration mergedDeclaration = new StructDeclaration(1); HashMap<String, Definition> defs = streamContext.getDefinitions(); for (Entry<String, Definition> entry : defs.entrySet()) { mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } for (Entry<String, Definition> entry : context.getDefinitions().entrySet()) { mergedDeclaration.addField(entry.getKey(), entry.getValue().getDeclaration()); } StructDefinition mergedContext = mergedDeclaration.createDefinition( null, "context"); Set<String> keys = mergedContext.getDefinitions().keySet(); for (String key : keys) { final Definition lookupDefinition = context.lookupDefinition(key); if (lookupDefinition != null) { mergedContext.getDefinitions().put(key, lookupDefinition); } else { mergedContext.getDefinitions().put(key, streamContext.lookupDefinition(key)); } } return mergedContext; }
Source:
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(); IJob job = spawn.getJob(jobId); 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); } }

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:
public void disableAccelerometer() { 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); } } }

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:
private void updateItemState(CalDavNextEventConfig config, List<CalDavEvent> events) { String itemName = config.getItemNameToListenTo(); String itemNamePreview = config.getItemName(); logger.trace("update item state for item: {}", itemName); Command state = null; DateTime time = null; if (calDavLoader == null) { logger.warn("caldav loader is not set"); return; } for (CalDavEvent calDavEvent : events) { Item item = null; try { item = this.itemRegistry.getItem(itemName); } catch (ItemNotFoundException e) { logger.error("item could not be found", itemName); continue; } final List<EventUtils.EventContent> parseContent = EventUtils.parseContent(calDavEvent, item); for (EventUtils.EventContent eventContent : parseContent) { if (eventContent.getTime().isBefore(DateTime.now())) { continue; } if (time == null || time.isAfter(eventContent.getTime())) { time = eventContent.getTime(); state = eventContent.getCommand(); } } } if (time == null) { eventPublisher.postUpdate(itemNamePreview, org.openhab.core.types.UnDefType.UNDEF); return; } CalDavType type = config.getType(); logger.trace("handling event of type: {}", type); if (type == CalDavType.VALUE) { logger.debug("setting value for '{}' to: {}", itemNamePreview, state); eventPublisher.sendCommand(itemNamePreview, state); } else if (type == CalDavType.DATE) { Command c = new DateTimeType(FORMATTER.print(time)); logger.debug("setting value for '{}' to: {}", itemNamePreview, c); eventPublisher.sendCommand(itemNamePreview, c); } else if (type == CalDavType.DISABLE) { } else { logger.warn("unhandled type: " + type); } }

Target:
private void updateItemState(CalDavNextEventConfig config, List<CalDavEvent> events) { String itemName = config.getItemNameToListenTo(); String itemNamePreview = config.getItemName(); logger.trace("update item state for item: {}", itemName); Command state = null; DateTime time = null; if (calDavLoader == null) { logger.warn("caldav loader is not set"); return; } for (CalDavEvent calDavEvent : events) { try { final Item item = this.itemRegistry.getItem(itemName); final List<EventUtils.EventContent> parseContent = EventUtils.parseContent(calDavEvent, item); for (EventUtils.EventContent eventContent : parseContent) { if (!eventContent.getTime().isBefore(DateTime.now()) && (time == null || time.isAfter(eventContent.getTime()))) { time = eventContent.getTime(); state = eventContent.getCommand(); } } } catch (ItemNotFoundException e) { logger.error("item could not be found", itemName); } } if (time == null) { eventPublisher.postUpdate(itemNamePreview, org.openhab.core.types.UnDefType.UNDEF); return; } CalDavType type = config.getType(); logger.trace("handling event of type: {}", type); if (type == CalDavType.VALUE) { logger.debug("setting value for '{}' to: {}", itemNamePreview, state); eventPublisher.sendCommand(itemNamePreview, state); } else if (type == CalDavType.DATE) { Command c = new DateTimeType(FORMATTER.print(time)); logger.debug("setting value for '{}' to: {}", itemNamePreview, c); eventPublisher.sendCommand(itemNamePreview, c); } else if (type == CalDavType.DISABLE) { return; } else { logger.warn("unhandled type: {}", type); } }
Source:
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); if (isSolidRun(target)) applySolidChanges((SolidRun) target, (SolidRun) source); }

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:
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)); } catch (JsonParseException e) { 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())); } } } }

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:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { if (other.getName().equals(this.getName()) && this.getClass().getName().equals(other.getClass().getName())) { return getCombiningFactory(); } else { throw new AggregatorFactoryNotMergeableException( "can't merge [%s : %s] and [%s : %s]", this.getName(), this.getClass().getName(), other.getName(), other.getClass().getName() ); } }

Target:
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException { throw new UnsupportedOperationException(String.format("[%s] does not implement getMergingFactory(..)", this.getClass().getName())); }
Source:
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) { LOG.error("Algorithm could not be found", e); 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; }

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:
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()); Class<M> cls2 = typeOf(createAnotherMessage()); S subject = assertWithSubjectThat(outerObjects); S subSubject1 = subject.withType(cls1); subSubject1.hasSize(messageCount); S subSubject2 = subject.withType(cls2); subSubject2.hasSize(otherMessageCount); }

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:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { final String upperCaseIsolationLevelName = Optional.of(transactionIsolationName.toUpperCase(Locale.ENGLISH)) .orElseThrow(IllegalArgumentException::new); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }

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:
public JSONObject callConduit(Launcher.ProcStarter starter, PrintStream stderr) throws IOException, InterruptedException { JSONObject obj = new JSONObject(); obj.putAll(this.params); List<String> command = new ArrayList<String>( 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; } }

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:
private void updateLog() { 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(); }

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:
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("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)); } } }

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:
public SPathConverter(ISarosSession session, IPathFactory pathFactory) { this.session = session; this.pathFactory = pathFactory; this.referencePointManager = session .getComponent(IReferencePointManager.class); }

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:
public static void main(String[] args) { try { LOGGER.info("Start frame-based game loop:"); GameLoop gameLoop = new FrameBasedGameLoop(); 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()); } }

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:
public GroupByColumnSelectorStrategy makeColumnSelectorStrategy( ColumnCapabilities capabilities, ColumnValueSelector selector ) { ValueType type = capabilities.getType(); switch(type) { case STRING: DimensionSelector dimSelector = (DimensionSelector) selector; if (dimSelector.nameLookupPossibleInAdvance()) { 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); } }

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:
public static BlockedErrorExtension from(Message message) { return message.getError().getExtension(ELEMENT, NAMESPACE); }

Target:
public static BlockedErrorExtension from(Message message) { XMPPError error = message.getError(); if (error == null) { return null; } return error.getExtension(ELEMENT, NAMESPACE); }
Source:
public void setUp() throws Exception { final SnapshotDao snapshotDao = mock(SnapshotDao.class); final EventService eventService = mock(EventService.class); machineLogsDir = targetDir().resolve("logs-dir").toString(); 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); }

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:
public static Request setFakeCodeRequest(Request request){ Code fakeCode; if(!request.getOptions().hasObserve()){ fakeCode = Code.POST; }else{ fakeCode = Code.FETCH; } return requestWithNewCode(request, fakeCode); }

Target:
public static Request setFakeCodeRequest(Request request) { Code fakeCode = request.getOptions().hasObserve() ? Code.FETCH : Code.POST; return requestWithNewCode(request, fakeCode); }
Source:
private 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); }

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:
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; } Collection<RepositoryMapping> mappings = getMappings(project); 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; }

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:
public void testStringHeaderSerialization() throws IOException, ClassNotFoundException { Header header = new StringHeader("some value"); Header deserializedHeader = TestUtil.serializeAndDeserialize(header); Assert.assertEquals(deserializedHeader, header); }

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:
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 (ResolutionException e) { return new RunResolution(project, actualProperties, e, logger.getLog()); } catch (Exception e) { return new RunResolution(project, actualProperties, e, logger.getLog()); } } finally { } }

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:
public List<HueLamp> getLamps() { return hueFacade.getAvailableLamps().entrySet().stream() .map(Map.Entry::getValue) .collect(Collectors.toList()); }

Target:
public SortedSet<HueLamp> getLamps() { return new TreeSet<>(hueFacade.getAvailableLamps().values()); }
Source:
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); FileStatus fsStatus = fs.getFileStatus(path); fsStatusList.add(fsStatus); } FileStatus[] fsStatusArray = new FileStatus[fsStatusList.size()]; return fsStatusList.toArray(fsStatusArray); }

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:
private EventHttpMetadata generateHttpMetadata(HttpServletRequest httpServletRequest, int responseStatusCode) { Map<String, String> headers = Collections.list(httpServletRequest.getHeaderNames()).stream() .collect(Collectors.toMap(Function.identity(), name -> String.join(",", Collections.list(httpServletRequest.getHeaders(name))))); return new EventHttpMetadata(httpServletRequest.getMethod(), httpServletRequest.getRemoteAddr(), Collections.unmodifiableMap(headers), httpServletRequest.getCookies() != null, responseStatusCode); }

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:
private List<Snak> getQualifiers(JSONArray jsonQualifiers) { List<Snak> result = new LinkedList<Snak>(); 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; }

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:
protected void runPages(List<WikiPage> pages, RunNotifier notifier) { boolean seleniumConfigOverridden = configureSeleniumIfNeeded(); try { if ("true".equalsIgnoreCase(System.getProperty(allureEnablerVariableName))){ 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) { } } }

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:
public void testKafkaSourceAndSink() throws Exception { String topicName = generateStreamName(); final String stringToPost = "Hi there!"; AdminUtils.createTopic(kafkaTestSupport.getZkClient(), topicName, 1, 1, new Properties()); 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); }

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:
public static void e(String TAG, String message) { Timber.d(message); }

Target:
public static void e(String TAG, String message) { Timber.e(message); }
Source:
public static SpawnDataStore makeSpawnDataStore(DataStoreType type) throws Exception { Properties properties = new Properties(); if (sqlUser != null) { properties.put("user", sqlUser); if(sqlPasspath.length() != 0) { 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); } }

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:
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 = igorService.getBuild(buildNumber, master, job); if (StringUtils.isNotEmpty(propertyFile)) { properties = igorService.getPropertyFile(buildNumber, propertyFile, master, job); } } return inputTrigger.withBuildInfo(buildInfo).withProperties(properties); }

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:
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) { @Override 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()); }

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:
public static String convertFromIpsecString(String str) { if (str == null) return null; try { return str.replace('-', '_').toUpperCase(); } catch (IllegalArgumentException ex) { return null; } }

Target:
public static String convertFromIpsecString(String str) { if (str == null) { return null; } return str.replace('-', '_').toUpperCase(); }
Source:
public String identifier() { return GcsSecretEngine.IDENTIFIER; }

Target:
public String identifier() { return IDENTIFIER; }
Source:
public IterableSizeAssert<T, Integer> size() { Preconditions.checkNotNull(actual, "Can not assert on size of iterable which is null."); return new IterableSizeAssert(this, IterableUtil.sizeOf(actual)); }

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)); }