auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = ChangeVmClusterValidator.create(this, newClusterId, getParameters().getVmCustomCompatibilityVersion()); if (macPoolChanged()) { ReadMacPool macPoolForTargetCluster = macPoolPerCluster.getMacPoolForCluster(newClusterId); ValidationResult validationResult = validator.validateCanMoveMacs(macPoolForTargetCluster, getMacsToMigrate()); if (!validationResult.isValid()) { return validate(validationResult); } } return validator.validate(); }

Target:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = ChangeVmClusterValidator.create(this, newClusterId, getParameters().getVmCustomCompatibilityVersion()); if (macPoolChanged()) { ReadMacPool macPoolForTargetCluster = macPoolPerCluster.getMacPoolForCluster(newClusterId); ValidationResult validationResult = moveMacs.canMigrateMacsToAnotherMacPool(macPoolForTargetCluster, getMacsToMigrate()); if (!validationResult.isValid()) { return validate(validationResult); } } return validator.validate(); }
Source:
public void createDispoDiscrepancies(BranchId branch, String itemId, List<Discrepancy> discrepancies, String userName) { String idOfNewDiscrepancy = ""; DispoItem dispoItem = getQuery().findDispoItemById(branch, itemId); if (dispoItem != null) { Map<String, Discrepancy> discrepancyList = dispoItem.getDiscrepanciesList(); Collection<DispoItem> dispoItems = new ArrayList<>(); for (Discrepancy discrepancy : discrepancies) { idOfNewDiscrepancy = dataFactory.getNewId(); discrepancy.setId(idOfNewDiscrepancy); if (discrepancy.getLocation() == null) { discrepancy.setLocation(""); } if (discrepancy.getText() == null) { discrepancy.setText(""); } discrepancyList.put(idOfNewDiscrepancy, discrepancy); DispoItemData newItem = new DispoItemData(); newItem.setDiscrepanciesList(discrepancyList); newItem.setStatus(dispoConnector.getItemStatus(newItem)); dispoItems.add(newItem); } ArtifactReadable author = getQuery().findUser(); DispoStorageMetadata metadata = new DispoStorageMetadata(); String operation = String.format("Create Dispo Discrepancies in Program [%s], Item [%s]", branch, itemId); getWriter().updateDispoItems(author, branch, dispoItems, false, operation, metadata); if (!metadata.getIdsOfUpdatedItems().isEmpty()) { updateBroadcaster.broadcastUpdateItems(metadata.getIdsOfUpdatedItems(), singleton(dispoItem), getDispoItemParentSet(branch, itemId)); } } }

Target:
public void createDispoDiscrepancies(BranchId branch, String itemId, List<Discrepancy> discrepancies, String userName) { DispoItem dispoItem = getQuery().findDispoItemById(branch, itemId); if (dispoItem != null) { Map<String, Discrepancy> discrepancyList = dispoItem.getDiscrepanciesList(); Collection<DispoItem> dispoItems = new ArrayList<>(); for (Discrepancy discrepancy : discrepancies) { String idOfNewDiscrepancy = ""; idOfNewDiscrepancy = dataFactory.getNewId(); discrepancy.setId(idOfNewDiscrepancy); if (discrepancy.getLocation() == null) { discrepancy.setLocation(""); } if (discrepancy.getText() == null) { discrepancy.setText(""); } discrepancyList.put(idOfNewDiscrepancy, discrepancy); DispoItemData newItem = new DispoItemData(); newItem.setDiscrepanciesList(discrepancyList); newItem.setStatus(dispoConnector.getItemStatus(newItem)); dispoItems.add(newItem); } ArtifactReadable author = getQuery().findUser(); DispoStorageMetadata metadata = new DispoStorageMetadata(); String operation = String.format("Create Dispo Discrepancies in Program [%s], Item [%s]", branch, itemId); getWriter().updateDispoItems(author, branch, dispoItems, false, operation, metadata); if (!metadata.getIdsOfUpdatedItems().isEmpty()) { updateBroadcaster.broadcastUpdateItems(metadata.getIdsOfUpdatedItems(), singleton(dispoItem), getDispoItemParentSet(branch, itemId)); } } }
Source:
public Action getActionObject(String uri, String method, String body, Map<String, Part> parts, List<Cookie> cookies, String... params) { try { MockHttpServletRequest req = new MockHttpServletRequest(method, Const.ResourceURIs.URI_PREFIX + uri); for (int i = 0; i < params.length; i = i + 2) { req.addParam(params[i], params[i + 1]); } if (body != null) { req.setBody(body); } if (parts != null) { parts.forEach((key, part) -> { try { req.addPart(key, part); } catch (IOException e) { throw new RuntimeException(e); } }); } if (cookies != null) { for (Cookie cookie : cookies) { req.addCookie(new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, cookie.getValue())); } } MockHttpServletResponse resp = new MockHttpServletResponse(); Action action = new ActionFactory().getAction(req, method, resp); action.setTaskQueuer(new MockTaskQueuer()); action.setEmailSender(new MockEmailSender()); return action; } catch (ActionMappingException e) { throw new RuntimeException(e); } }

Target:
public Action getActionObject(String uri, String method, String body, Map<String, Part> parts, List<Cookie> cookies, String... params) { try { MockHttpServletRequest req = new MockHttpServletRequest(method, Const.ResourceURIs.URI_PREFIX + uri); for (int i = 0; i < params.length; i = i + 2) { req.addParam(params[i], params[i + 1]); } if (body != null) { req.setBody(body); } if (parts != null) { parts.forEach((key, part) -> { try { req.addPart(key, part); } catch (IOException e) { throw new RuntimeException(e); } }); } if (cookies != null) { for (Cookie cookie : cookies) { req.addCookie(cookie); } } Action action = new ActionFactory().getAction(req, method); action.setTaskQueuer(new MockTaskQueuer()); action.setEmailSender(new MockEmailSender()); return action; } catch (ActionMappingException e) { throw new RuntimeException(e); } }
Source:
public static Color toColor(RGB rgb) { return new Color(rgb.red / 255, rgb.green / 255, rgb.blue / 255, 1); }

Target:
public static Color toColor(RGB rgb) { return new Color(rgb.red / 255d, rgb.green / 255d, rgb.blue / 255d, 1); }
Source:
public @NotNull Span currentSpan() throws EmptyStackException { if (!hasSpan()) { throw new EmptyStackException(); } else { return scopeManager.activeSpan(); } }

Target:
public @NotNull Span currentSpan() throws EmptyStackException { Span span = scopeManager.activeSpan(); if (span == null) { throw new EmptyStackException(); } return span; }
Source:
public void startLdapServer() throws Exception { UnboundIdContainer server = new UnboundIdContainer( validRootDn, validLdifClassPath); server.setApplicationContext(new GenericApplicationContext()); List<Integer> ports = getDefaultPorts(1); server.setPort(ports.get(0)); try { server.afterPropertiesSet(); assertThat(server.getPort()).isEqualTo(ports.get(0)); } finally { server.destroy(); } }

Target:
public void startLdapServer() throws Exception { UnboundIdContainer server = new UnboundIdContainer( validRootDn, validLdifClassPath); createAndRunServer(server); }
Source:
public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_WGET, String.format("wget --no-check-certificate %s -O %s > /dev/null 2>&1", url, dest))); } if (result != 0) { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }

Target:
public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_CURL, String.format("curl --silent --insecure %s -o %s", url, dest))); } if (result != 0) { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }
Source:
private void addToIndex(final GitOutputConsole console) { Resource[] resources = appContext.getResources(); Path[] paths = new Path[resources.length]; for (int i = 0; i < resources.length; i++) { Path path = resources[i].getLocation().removeFirstSegments(appContext.getRootProject().getLocation().segmentCount()); paths[i] = path.segmentCount() == 0 ? Path.EMPTY : path; } service.add(appContext.getDevMachine(), appContext.getRootProject().getLocation(), false, paths) .then(new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { console.print(constant.addSuccess()); notificationManager.notify(constant.addSuccess()); } }) .catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { console.printError(constant.addFailed()); notificationManager.notify(constant.addFailed(), FAIL, FLOAT_MODE); } }); }

Target:
private void addToIndex(final GitOutputConsole console) { Resource[] resources = appContext.getResources(); Path[] paths = new Path[resources.length]; for (int i = 0; i < resources.length; i++) { Path path = resources[i].getLocation().removeFirstSegments(1); paths[i] = path.segmentCount() == 0 ? Path.EMPTY : path; } service.add(appContext.getDevMachine(), appContext.getRootProject().getLocation(), false, paths) .then(new Operation<Void>() { @Override public void apply(Void arg) throws OperationException { console.print(constant.addSuccess()); notificationManager.notify(constant.addSuccess()); } }) .catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { console.printError(constant.addFailed()); notificationManager.notify(constant.addFailed(), FAIL, FLOAT_MODE); } }); }
Source:
public static void main(String[] args) { GamePlugin.getXStream(); System.setProperty("file.encoding", "UTF-8"); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option hostOption = parser.addStringOption('h', "host"); CmdLineParser.Option portOption = parser.addIntegerOption('p', "port"); CmdLineParser.Option reservationOption = parser.addStringOption('r', "reservation"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { showHelp(e.getMessage()); System.exit(2); } String host = (String) parser.getOptionValue(hostOption, "localhost"); int port = (Integer) parser.getOptionValue(portOption, SharedConfiguration.DEFAULT_PORT); String reservation = (String) parser.getOptionValue(reservationOption, ""); try { new Starter(host, port, reservation); } catch (Exception e) { logger.error("Beim Starten den Clients ist ein Fehler aufgetreten:", e); e.printStackTrace(); } }

Target:
public static void main(String[] args) { System.setProperty("file.encoding", "UTF-8"); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option hostOption = parser.addStringOption('h', "host"); CmdLineParser.Option portOption = parser.addIntegerOption('p', "port"); CmdLineParser.Option reservationOption = parser.addStringOption('r', "reservation"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { showHelp(e.getMessage()); System.exit(2); } String host = (String) parser.getOptionValue(hostOption, "localhost"); int port = (Integer) parser.getOptionValue(portOption, SharedConfiguration.DEFAULT_PORT); String reservation = (String) parser.getOptionValue(reservationOption, ""); try { new Starter(host, port, reservation); } catch (Exception e) { logger.error("Beim Starten den Clients ist ein Fehler aufgetreten:", e); e.printStackTrace(); } }
Source:
protected void enrichTuple(INPUT tuple) { Object key = getKey(tuple); if (key != null) { Object result = cacheManager.get(key); OUTPUT out = convert(tuple, result); emitTuple(out); } }

Target:
protected void enrichTuple(INPUT tuple) { Object key = getKey(tuple); if (key != null) { Object result = cacheManager.get(key); OUTPUT out = convert(tuple, result); if (out != null) { emitEnrichedTuple(out); } } }
Source:
protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); String threadName = t.getName(); if (!threadName.startsWith("org.ovirt.thread.")) { t.setName("org.ovirt.thread." + threadName); } if (log.isDebugEnabled()) { log.debug(String.format("About to run task '%s' from {}", r.getClass().getName()), new Exception()); } if (getQueue().size() > 5) { log.warn("Executing a command '{}', but note that there are tasks in the queue.", r.getClass().getName(), getQueue().size()); } }

Target:
protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); String threadName = t.getName(); if (!threadName.startsWith("org.ovirt.thread.")) { t.setName("org.ovirt.thread." + threadName); } if (log.isDebugEnabled()) { log.debug(String.format("About to run task '%s' from", r.getClass().getName()), new Exception()); } if (getQueue().size() > 5) { log.warn("Executing a command '{}', but note that there are tasks in the queue.", r.getClass().getName(), getQueue().size()); } }
Source:
public void start() throws InstantiationException { logger.info("Admin blob storage service started"); }

Target:
public void start() throws InstantiationException { logger.info("AdminBlobStorageService has started"); }
Source:
public void startup() throws Exception{ super.startup(); JsonObject json = readTrackingFile(); if (json != null && json.getString(SERVER_HOST_PROPERTY) == serverHost && json.getString(SERVER_PORT_PROPERTY) == serverPort && json.getString(SERVER_PATH_PROPERTY) == serverPath) { sequence = json.getString(SEQUENCE_PROPERTY); } client = new WebSocketClient(new URI(serverHost + ":" + serverPort + serverPath + sequence), this, attempts, timeout, true); }

Target:
public void startup() throws Exception{ super.startup(); JsonObject json = readTrackingFile(); if (json != null && json.getString(SERVER_HOST_PROPERTY).equals(serverHost) && json.getString(SERVER_PORT_PROPERTY).equals(serverPort) && json.getString(SERVER_PATH_PROPERTY).equals(serverPath)) { sequence = json.getString(SEQUENCE_PROPERTY); } client = new WebSocketClient(new URI(serverHost + ":" + serverPort + serverPath + sequence), this, attempts, timeout, true); }
Source:
public Map<String, ServiceConfiguration> getServices() { Map<String, ServiceConfiguration> intializedServices = new HashMap<String, ServiceConfiguration>(); for (Map.Entry<String, ServiceConfiguration> entry : originalServices().entrySet()) { ServiceConfiguration originalConfig = entry.getValue(); Optional<BearerToken> apiToken = originalConfig.apiToken().or(defaultApiToken()); Optional<SslConfiguration> security = originalConfig.security().or(defaultSecurity()); ServiceConfiguration configWithDefaults = ImmutableServiceConfiguration.builder() .apiToken(apiToken).security(security).uris(originalConfig.uris()).build(); intializedServices.put(entry.getKey(), configWithDefaults); } return Collections.unmodifiableMap(intializedServices); }

Target:
public Map<String, ServiceConfiguration> getServices() { Map<String, ServiceConfiguration> intializedServices = new HashMap<String, ServiceConfiguration>(); for (Map.Entry<String, ServiceConfiguration> entry : originalServices().entrySet()) { ServiceConfiguration originalConfig = entry.getValue(); ServiceConfiguration configWithDefaults = ImmutableServiceConfiguration.builder() .apiToken(originalConfig.apiToken().or(defaultApiToken())) .security(originalConfig.security().or(defaultSecurity())) .uris(originalConfig.uris()).build(); intializedServices.put(entry.getKey(), configWithDefaults); } return Collections.unmodifiableMap(intializedServices); }
Source:
public void consume(Runnable signalsInterrupt) { try { do { signalsInterrupt.run(); } while (!inflightSemaphore.tryAcquire(500, TimeUnit.MILLISECONDS)); Message message = messageReceiver.next(); logger.debug("Read message partition offset {}", message.getContentType(), message.getPartition(), message.getOffset()); Message convertedMessage = messageConverterResolver.converterFor(message, subscription).convert(message, topic); sendMessage(convertedMessage); } catch (MessageReceivingTimeoutException messageReceivingTimeoutException) { inflightSemaphore.release(); logger.debug("Timeout while reading message from topic. Trying to read message again", messageReceivingTimeoutException); } catch (Exception e) { logger.error("Consumer loop failed for " + getId(), e); } }

Target:
public void consume(Runnable signalsInterrupt) { try { do { signalsInterrupt.run(); } while (!inflightSemaphore.tryAcquire(signalProcessingInterval, TimeUnit.MILLISECONDS)); Message message = messageReceiver.next(); logger.debug("Read message partition offset {}", message.getContentType(), message.getPartition(), message.getOffset()); Message convertedMessage = messageConverterResolver.converterFor(message, subscription).convert(message, topic); sendMessage(convertedMessage); } catch (MessageReceivingTimeoutException messageReceivingTimeoutException) { inflightSemaphore.release(); logger.trace("Timeout while reading message for subscription {}. Trying to read message again", subscription.getQualifiedName(), messageReceivingTimeoutException); } catch (Exception e) { logger.error("Consumer loop failed for {}", subscription.getQualifiedName(), e); } }
Source:
protected int getTimeOut(Field field) { if (field.isAnnotationPresent(Timeout.class)) { return field.getDeclaredAnnotation(Timeout.class).value(); } if (field.getType().isAnnotationPresent(Timeout.class)) { return field.getType().getDeclaredAnnotation(Timeout.class).value(); } try { return (Integer) Timeout.class.getMethod("value").getDefaultValue(); } catch (NoSuchMethodException e) { return 1; } }

Target:
public int getTimeOut(Field field) { if (field.isAnnotationPresent(Timeout.class)) { return field.getAnnotation(Timeout.class).value(); } if (field.getGenericType() instanceof Class) { return getTimeOut((Class) field.getGenericType()); } return getTimeOut((Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]); }
Source:
public static Collection<Integer> getThreadIds(KernelAnalysisModule module) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return Collections.EMPTY_SET; } int threadQuark; try { threadQuark = ss.getQuarkAbsolute(Attributes.THREADS); Set<@NonNull Integer> tids = new TreeSet<>(); for (Integer quark : ss.getSubAttributes(threadQuark, false)) { final @NonNull String attributeName = ss.getAttributeName(quark); tids.add(attributeName.startsWith("0_") ? 0 : Integer.parseInt(attributeName)); } return tids; } catch (AttributeNotFoundException e) { } return Collections.EMPTY_SET; }

Target:
public static Collection<Integer> getThreadIds(KernelAnalysisModule module) { ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return Collections.EMPTY_SET; } int threadQuark; try { threadQuark = ss.getQuarkAbsolute(Attributes.THREADS); Set<@NonNull Integer> tids = new TreeSet<>(); for (Integer quark : ss.getSubAttributes(threadQuark, false)) { final @NonNull String attributeName = ss.getAttributeName(quark); tids.add(attributeName.startsWith(Attributes.THREAD_0_PREFIX) ? 0 : Integer.parseInt(attributeName)); } return tids; } catch (AttributeNotFoundException e) { } return Collections.EMPTY_SET; }
Source:
public Storage newStorage(Config config) { AmazonS3Client client = new AmazonS3Client( buildCredentialsProvider(config), buildClientConfiguration(config)); if (config.has("endpoint")) { client.setEndpoint(config.get("endpoint", String.class)); } if (config.has("path-style-access")) { client.setS3ClientOptions( new S3ClientOptions().withPathStyleAccess( config.get("path-style-access", Boolean.class) )); } String bucket = config.get("bucket", String.class); return new S3Storage(client, bucket); }

Target:
public Storage newStorage(Config config) { AmazonS3Client client = new AmazonS3Client( buildCredentialsProvider(config), buildClientConfiguration(config)); if (config.has("endpoint")) { client.setEndpoint(config.get("endpoint", String.class)); } if (config.has("path-style-access")) { client.setS3ClientOptions( S3ClientOptions.builder().setPathStyleAccess( config.get("path-style-access", Boolean.class, false) ).build()); } String bucket = config.get("bucket", String.class); return new S3Storage(client, bucket); }
Source:
public void validate() { FieldValidator validator = new FieldValidator(); assertTrue(validator.getInvalidityInfoForPersonName(this.instructorName.trim()).isEmpty(), "validate name"); assertTrue(validator.getInvalidityInfoForInstituteName(this.instructorInstitution.trim()).isEmpty(), "validate institute"); assertTrue(validator.getInvalidityInfoForEmail(this.instructorEmail.trim()).isEmpty(), "validate email"); }

Target:
public void validate() { FieldValidator validator = new FieldValidator(); assertTrue(this.instructorEmail != null, "email cannot be null"); assertTrue(this.instructorName != null, "name cannot be null"); assertTrue(this.instructorInstitution != null, "institute cannot be null"); List<String> errors = new ArrayList<>(); String nameError = validator.getInvalidityInfoForPersonName(this.instructorName.trim()); if (!nameError.isEmpty()) { errors.add(nameError); } String emailError = validator.getInvalidityInfoForEmail(this.instructorEmail.trim()); if (!emailError.isEmpty()) { errors.add(emailError); } String instituteError = validator.getInvalidityInfoForInstituteName(this.instructorInstitution.trim()); if (!instituteError.isEmpty()) { errors.add(instituteError); } assertTrue(errors.isEmpty(), StringHelper.toString(errors)); }
Source:
private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = mcqChoices; break; case STUDENTS: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case STUDENTS_EXCLUDING_SELF: List<StudentAttributes> studentListExcludingSelf = StudentsLogic.inst().getStudentsForCourse(courseId); String thisStudentEmail = studentDoingQuestion.email; for (StudentAttributes student : studentListExcludingSelf) { if (thisStudentEmail.equals(student.email)) { continue; } optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }

Target:
private List<String> generateOptionList(String courseId) { List<String> optionList = new ArrayList<>(); switch (generateOptionsFor) { case NONE: optionList = mcqChoices; break; case STUDENTS: case STUDENTS_EXCLUDING_SELF: List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); if (generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { studentList.removeIf(studentInList -> studentInList.email.equals(studentDoingQuestion.email)); } for (StudentAttributes student : studentList) { optionList.add(student.name + " (" + student.team + ")"); } optionList.sort(null); break; case TEAMS: try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); for (TeamDetailsBundle team : teamList) { optionList.add(team.name); } optionList.sort(null); } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } break; case INSTRUCTORS: List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); for (InstructorAttributes instructor : instructorList) { optionList.add(instructor.name); } optionList.sort(null); break; default: Assumption.fail("Trying to generate options for neither students, teams nor instructors"); break; } return optionList; }
Source:
@Override public void onDestroy() { disconnectGoogleClient(); AppLog.d(T.MAIN, "GOOGLE SIGNUP/IN: disconnecting google client"); mDispatcher.unregister(this); super.onDestroy(); }

Target:
public void onDestroy() { disconnectGoogleClient(); AppLog.d(T.MAIN, "GOOGLE SIGNUP/LOGIN: disconnecting google client"); mDispatcher.unregister(this); super.onDestroy(); }
Source:
public void testV2OnlyStats() { testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_8).named(""), Byte.MAX_VALUE, Byte.MIN_VALUE)); testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_16).named(""), Short.MAX_VALUE, Short.MIN_VALUE)); testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_32).named(""), Integer.MAX_VALUE, Integer.MIN_VALUE)); testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT64).as(OriginalType.UINT_64).named(""), Long.MAX_VALUE, Long.MIN_VALUE)); testV2OnlyStats( createStats(Types.optional(PrimitiveTypeName.BINARY).as(OriginalType.DECIMAL).precision(6).named(""), new BigInteger("-123456"), new BigInteger("123456"))); testV2OnlyStats(createStats( Types.optional(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY).length(14).as(OriginalType.DECIMAL).precision(7) .named(""), new BigInteger("-1234567"), new BigInteger("1234567"))); testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT96).named(""), new BigInteger("-12345678"), new BigInteger("12345678"))); }

Target:
public void testV2OnlyStats() { testV2OnlyStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_8).named(""), 0x7F, 0x80); testV2OnlyStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_16).named(""), 0x7FFF, 0x8000); testV2OnlyStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_32).named(""), 0x7FFFFFFF, 0x80000000); testV2OnlyStats(Types.optional(PrimitiveTypeName.INT64).as(OriginalType.UINT_64).named(""), 0x7FFFFFFFFFFFFFFFL, 0x8000000000000000L); testV2OnlyStats(Types.optional(PrimitiveTypeName.BINARY).as(OriginalType.DECIMAL).precision(6).named(""), new BigInteger("-765875"), new BigInteger("876856")); testV2OnlyStats( Types.optional(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY).length(14).as(OriginalType.DECIMAL).precision(7) .named(""), new BigInteger("-6769643"), new BigInteger("9864675")); }
Source:
public void shouldNotStartTwoSolverTasksWithSameProblemId() { TestdataSolution problem = createTestProblem(tenantId); solverManager.solve(tenantId, problem, null, null); try { solverManager.solve(tenantId, problem, null, null); } catch (IllegalArgumentException e) { assertEquals("Problem (" + tenantId + ") already exists.", e.getMessage()); } }

Target:
public void shouldNotStartTwoSolverTasksWithSameProblemId() { TestdataSolution problem = createTestProblem(tenantId); solverManager.solve(tenantId, problem, null, null); assertThatThrownBy(() -> solverManager.solve(tenantId, problem, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Problem (" + tenantId + ") already exists."); }
Source:
private static boolean sendPush(String botName, String recipient, String title, String body, String type) { boolean result = false; logger.trace(" Botname is '{}'", botName); PushbulletBot bot = bots.get(botName); if (bot == null) { logger.error("Unconfigured pushbullet bot, please check configuration"); return false; } logger.trace(" Bot is '{}'", bot); logger.trace(" Recipient is '{}'", recipient); logger.trace(" Title is '{}'", title); logger.trace(" Message is '{}'", body); Push push = new Push(); push.setTitle(title); push.setBody(body); push.setType(type); push.setEmail(recipient); logger.trace(" Push: {}", push); String request = gson.toJson(push); logger.trace(" Packed Request: {}", request); try (InputStream stream = new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))) { Properties headers = new Properties(); headers.put("User-Agent", "openHAB / pushbullet action " + VERSION.toString()); headers.put("Access-Token", bot.getToken()); String responseString = HttpUtil.executeUrl(METHOD, API_URL_PUSHES, headers, stream, CONTENT_TYPE, TIMEOUT); logger.trace(" Got Response: {}", responseString); PushResponse response = gson.fromJson(responseString, PushResponse.class); logger.trace(" Unpacked Response: {}", response); stream.close(); if (null == response.getPushError()) { result = true; } } catch (IOException e) { logger.trace("IO problems pushing note: {}", e.getMessage()); } return result; }

Target:
private static boolean sendPush(String botName, String recipient, String title, String body, String type) { boolean result = false; logger.trace(" Botname is '{}'", botName); PushbulletBot bot = bots.get(botName); if (bot == null) { logger.warn("Unconfigured pushbullet bot, please check configuration"); return false; } logger.trace(" Bot is '{}'", bot); logger.trace(" Recipient is '{}'", recipient); logger.trace(" Title is '{}'", title); logger.trace(" Message is '{}'", body); Push push = new Push(); push.setTitle(title); push.setBody(body); push.setType(type); push.setEmail(recipient); logger.trace(" Push: {}", push); String request = gson.toJson(push); logger.trace(" Packed Request: {}", request); try (InputStream stream = new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))) { Properties headers = new Properties(); headers.put("User-Agent", "openHAB / pushbullet action " + VERSION.toString()); headers.put("Access-Token", bot.getToken()); String responseString = HttpUtil.executeUrl(METHOD, API_URL_PUSHES, headers, stream, CONTENT_TYPE, TIMEOUT); logger.trace(" Got Response: {}", responseString); PushResponse response = gson.fromJson(responseString, PushResponse.class); logger.trace(" Unpacked Response: {}", response); stream.close(); if ((null != response) && (null == response.getPushError())) { result = true; } } catch (IOException e) { logger.warn("IO problems pushing note: {}", e.getMessage()); } return result; }
Source:
public void initFromPage(int valueCountL, ByteBuffer page, int offset) throws IOException { ByteBufferInputStream in = new ByteBufferInputStream(page.duplicate(), offset, page.limit() - offset); int length = BytesUtils.readIntLittleEndian(in); decoder = new RunLengthBitPackingHybridDecoder(bitWidth, in); this.nextOffset = offset + length + 4; }

Target:
public void initFromPage(int valueCountL, ByteBuffer page, int offset) throws IOException { ByteBufferInputStream in = new ByteBufferInputStream(page, offset, page.limit() - offset); int length = BytesUtils.readIntLittleEndian(in); decoder = new RunLengthBitPackingHybridDecoder(bitWidth, in); this.nextOffset = offset + length + 4; }
Source:
public RequestIdPolicy(Supplier<HttpHeaders> requestIdSupplier) { this.requestIdSupplier = requestIdSupplier; }

Target:
public RequestIdPolicy(Supplier<HttpHeaders> requestIdSupplier) { this.requestIdSupplier = Objects.requireNonNull(requestIdSupplier, "'requestIdSupplier' must not be null"); }
Source:
public boolean containsAny(ExternalIdBundle bundle) { ArgChecker.notNull(bundle, "bundle"); for (ExternalId externalId : bundle.externalIds) { if (externalIds.contains(externalId)) { return true; } } return false; }

Target:
public boolean containsAny(ExternalIdBundle bundle) { ArgChecker.notNull(bundle, "bundle"); return bundle.externalIds.stream().anyMatch(id -> externalIds.contains(id)); }
Source:
public static void deleteOrphanContentTypeFields() throws SQLException { String query = "DELETE FROM field WHERE NOT EXISTS (SELECT * FROM structure WHERE structure.inode = field.structure_inode)"; DotConnect dc = new DotConnect(); dc.executeStatement(query); query = String.format("DELETE FROM inode WHERE NOT EXISTS (SELECT * FROM field " + "WHERE field.inode = inode.inode) and inode.type like '%s' ",Inode.Type.FIELD.getTableName()); dc.executeStatement(query); }

Target:
public static void deleteOrphanContentTypeFields() throws SQLException { String query = "DELETE FROM field WHERE NOT EXISTS (SELECT * FROM structure WHERE structure.inode = field.structure_inode)"; DotConnect dc = new DotConnect(); dc.executeStatement(query); query = String.format("DELETE FROM inode WHERE NOT EXISTS (SELECT * FROM field " + "WHERE field.inode = inode.inode) and inode.type = '%s' ",Inode.Type.FIELD.getTableName()); dc.executeStatement(query); }
Source:
public void onBindViewHolder(@NonNull RecentFilesViewHolder holder, int position) { if (showShimmer) { holder.shimmerFrameLayout.startShimmer(); } else { holder.shimmerFrameLayout.stopShimmer(); holder.shimmerFrameLayout.setShimmer(null); holder.fileIconView.setBackground(null); holder.fileTextView.setBackground(null); holder.moreOptions.setBackground(null); holder.fileSize.setBackground(null); holder.fileLastVisited.setBackground(null); RecentFile file = recentFiles.get(position); setUpViewHolder(file, holder); } }

Target:
public void onBindViewHolder(@NonNull RecentFilesViewHolder holder, int position) { if (showShimmer) { holder.shimmerFrameLayout.startShimmer(); } else { stopShimmer(holder); RecentFile file = recentFiles.get(position); setUpViewHolder(file, holder); } }
Source:
public void start(BundleContext bc) throws Exception { context = bc; logger.info("Slack action has been started."); }

Target:
public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Slack action has been started."); }
Source:
protected Traverser.Admin<ComputerResult> processNextStart() throws NoSuchElementException { Future<ComputerResult> future = null; try { if (this.first && this.getPreviousStep() instanceof EmptyStep) { this.first = false; final Graph graph = this.getTraversal().getGraph().get(); future = this.getComputer().apply(graph).program(this.generateProgram(EmptyMemory.instance(), graph)).submit(); final ComputerResult result = future.get(); this.processMemorySideEffects(result.memory()); return this.getTraversal().getTraverserGenerator().generate(result, this, 1l); } else { final Traverser.Admin<ComputerResult> traverser = this.starts.next(); final Graph graph = traverser.get().graph(); final Memory memory = traverser.get().memory(); future = this.getComputer().apply(graph).program(this.generateProgram(memory, graph)).submit(); final ComputerResult result = future.get(); this.processMemorySideEffects(result.memory()); return traverser.split(result, this); } } catch (final InterruptedException ie) { if (future != null) future.cancel(true); throw new TraversalInterruptedException(); } catch (ExecutionException e) { throw new IllegalStateException(e.getMessage(), e); } }

Target:
protected Traverser.Admin<ComputerResult> processNextStart() throws NoSuchElementException { Future<ComputerResult> future = null; try { if (this.first && this.getPreviousStep() instanceof EmptyStep) { this.first = false; final Graph graph = this.getTraversal().getGraph().get(); future = this.getComputer().apply(graph).program(this.generateProgram(EmptyMemory.instance(), graph)).submit(); final ComputerResult result = future.get(); this.processMemorySideEffects(result.memory()); return this.getTraversal().getTraverserGenerator().generate(result, this, 1l); } else { final Traverser.Admin<ComputerResult> traverser = this.starts.next(); final Graph graph = traverser.get().graph(); final Memory memory = traverser.get().memory(); future = this.generateComputer(graph).program(this.generateProgram(memory, graph)).submit(); final ComputerResult result = future.get(); this.processMemorySideEffects(result.memory()); return traverser.split(result, this); } } catch (final InterruptedException ie) { if (future != null) future.cancel(true); throw new TraversalInterruptedException(); } catch (ExecutionException e) { throw new IllegalStateException(e.getMessage(), e); } }
Source:
public MainDesktop() throws URISyntaxException { this.injector = Guice.createInjector(this); Client client = new Client("localhost", this.configureRendererProtocol()); RenderController cntrl = this.injector.getInstance(RenderController.class); cntrl.setClient(client); client.setController(cntrl); this.setupGraphics(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.injector.getInstance(EventDispatcher.class).dispatch(new GameAboutToStartEvent()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.injector.getInstance(EventDispatcher.class).dispatch(new GameStartedEvent()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } AnimalAddedEvent ev = new AnimalAddedEvent(); for (int i = 0; i < 5; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } ev = new AnimalAddedEvent(); ev.setAnimal(i); ev.setTeam(i % 2); this.injector.getInstance(EventDispatcher.class).dispatch(ev); } AnimalJumpedEvent jev = new AnimalJumpedEvent(); for (int i = 0; i < 5; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } jev = new AnimalJumpedEvent(); jev.setAnimal(i); jev.setTeam(i % 2); this.injector.getInstance(EventDispatcher.class).dispatch(jev); } GameFinishedEvent fev = new GameFinishedEvent(); this.injector.getInstance(EventDispatcher.class).dispatch(fev); }

Target:
public MainDesktop() throws URISyntaxException { this.injector = Guice.createInjector(this); Client client = new Client("localhost", this.configureRendererProtocol()); RenderController cntrl = this.injector.getInstance(RenderController.class); cntrl.setClient(client); client.setController(cntrl); this.setupGraphics(); }
Source:
@Test public void constructor_nullDelegate() { try { new ForwardingOs(null) { }; fail(); } catch (NullPointerException expected) { } }

Target:
public void constructor_nullDelegate() { try { new ForwardingOs(null) {}; fail(); } catch (NullPointerException expected) { } }
Source:
public Page<Element> traverse(Element startingPoint, Query query, Pager pager) { HawkularPipeline<?, ? extends Element> q = translate(startingPoint, query); q.counter("total").page(pager); return new Page<>(q.cast(Element.class).iterator(), pager, q.getCount("total")); }

Target:
public Page<Element> traverse(Element startingPoint, Query query, Pager pager) { HawkularPipeline<?, ? extends Element> q = translate(startingPoint, query); q.counter("total").page(pager); return new SizeAwarePage<>(q.cast(Element.class).iterator(), pager, () -> q.getCount("total")); }
Source:
public void bulkReassign(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } final StringBuilder taskIdsParam = new StringBuilder(); final StringBuilder deploymentIdsParam = new StringBuilder(); for (TaskSummary selected : taskSummaries) { taskIdsParam.append(selected.getId() + ","); deploymentIdsParam.append(selected.getDeploymentId() + ","); } if (taskIdsParam.length() == 0) { return; } else { taskIdsParam.deleteCharAt(taskIdsParam.length() - 1); deploymentIdsParam.deleteCharAt(deploymentIdsParam.length() - 1); } PlaceRequest placeRequestImpl = new DefaultPlaceRequest(TasksReassignmentPresenter.TASKS_REASSIGNMENT_POPUP); placeRequestImpl.addParameter("taskIds", taskIdsParam.toString()); placeRequestImpl.addParameter("deploymentIds", deploymentIdsParam.toString()); placeRequestImpl.addParameter("serverTemplateId", getSelectedServerTemplate()); placeManager.goTo(placeRequestImpl); }

Target:
public void bulkReassign(List<TaskSummary> taskSummaries) { if (taskSummaries == null || taskSummaries.isEmpty()) { return; } String taskIdsParam = taskSummaries.stream().map(s -> s.getId().toString()).collect(Collectors.joining(",")); String deploymentIdsParam = taskSummaries.stream().map(s -> s.getDeploymentId()).collect(Collectors.joining(",")); if (taskIdsParam.isEmpty()) { return; } PlaceRequest placeRequestImpl = new DefaultPlaceRequest(TasksReassignmentPresenter.TASKS_REASSIGNMENT_POPUP); placeRequestImpl.addParameter("taskIds", taskIdsParam); placeRequestImpl.addParameter("deploymentIds", deploymentIdsParam); placeRequestImpl.addParameter("serverTemplateId", getSelectedServerTemplate()); placeManager.goTo(placeRequestImpl); }
Source:
public static DefaultWorkerBehaviorConfig getDefaultWorkerBehaviorConfig( Supplier<WorkerBehaviorConfig> workerConfigRef, String action ) { final WorkerBehaviorConfig workerBehaviorConfig = workerConfigRef.get(); if (workerBehaviorConfig == null) { log.error("No workerConfig available, cannot %s workers.", action); return null; } if (!(workerBehaviorConfig instanceof DefaultWorkerBehaviorConfig)) { log.error( "Only DefaultWorkerBehaviorConfig is supported as WorkerBehaviorConfig, [%s] given, cannot %s workers", workerBehaviorConfig, action ); return null; } final DefaultWorkerBehaviorConfig workerConfig = (DefaultWorkerBehaviorConfig) workerBehaviorConfig; if (workerConfig.getAutoScalers() == null) { log.error("No autoScaler available, cannot %s workers", action); return null; } return workerConfig; }

Target:
public static DefaultWorkerBehaviorConfig getDefaultWorkerBehaviorConfig( Supplier<WorkerBehaviorConfig> workerConfigRef, String action ) { final WorkerBehaviorConfig workerBehaviorConfig = workerConfigRef.get(); if (workerBehaviorConfig == null) { log.error("No workerConfig available, cannot %s workers.", action); return null; } if (!(workerBehaviorConfig instanceof DefaultWorkerBehaviorConfig)) { log.error( "Only DefaultWorkerBehaviorConfig is supported as WorkerBehaviorConfig, [%s] given, cannot %s workers", workerBehaviorConfig, action ); return null; } return (DefaultWorkerBehaviorConfig) workerBehaviorConfig; }
Source:
private void runLoop() { subscribeConsumer(); while (isRunning() || taskManager.isRebalanceInProgress()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.REBALANCE_NEEDED.code()) { log.info("Detected that the assignor requested a rebalance. Rejoining the consumer group to " + "trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); mainConsumer.enforceRebalance(); } else if (nextProbingRebalanceMs.get() < System.currentTimeMillis()) { log.info("The probing rebalance interval has elapsed since the last rebalance, triggering a " + "rebalance to probe for newly aught-up clients"); mainConsumer.enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks " + e.corruptedTaskWithChangelogs() + " are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group.", e); taskManager.handleLostAll(); mainConsumer.unsubscribe(); subscribeConsumer(); } } }

Target:
private void runLoop() { subscribeConsumer(); while (isRunning() || taskManager.isRebalanceInProgress()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.REBALANCE_NEEDED.code()) { log.info("Detected that the assignor requested a rebalance. Rejoining the consumer group to " + "trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); mainConsumer.enforceRebalance(); } else if (nextProbingRebalanceMs.get() < time.milliseconds()) { log.info("The probing rebalance interval has elapsed since the last rebalance, triggering a " + "rebalance to probe for newly caught-up clients"); mainConsumer.enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks " + e.corruptedTaskWithChangelogs() + " are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group.", e); taskManager.handleLostAll(); mainConsumer.unsubscribe(); subscribeConsumer(); } } }
Source:
public boolean isEndpointExist(String endpointName) throws EndpointAdminException { if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { if (endpointAdmin.isEndpointExist(endpointName)) { return true; } } else { if (endpointAdmin.isEndpointExistForTenant(endpointName, tenantDomain)) { return true; } } return false; }

Target:
public boolean isEndpointExist(String endpointName) throws EndpointAdminException { if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { return endpointAdmin.isEndpointExist(endpointName); } else { return endpointAdmin.isEndpointExistForTenant(endpointName, tenantDomain); } }
Source:
public <T extends Problem> ProblemAdapterFactory registerSubtype(Class<T> clazz, URI type) { Objects.requireNonNull(clazz); Objects.requireNonNull(type); if (subtypes.containsKey(type) || subtypes.containsValue(clazz)) { throw new IllegalArgumentException("class & type must be unique"); } subtypes.put(type, clazz); return new ProblemAdapterFactory(stackTraces, statusAdapter, subtypes); }

Target:
public <T extends Problem> ProblemAdapterFactory registerSubtype(Class<T> clazz, URI type) { Objects.requireNonNull(clazz); Objects.requireNonNull(type); if (subtypes.containsKey(type)) { throw new IllegalArgumentException("class & type must be unique"); } HashMap<URI, Class<? extends Problem>> map = new HashMap<>(subtypes); map.put(type, clazz); return new ProblemAdapterFactory(stackTraces, statusAdapter, map); }
Source:
private void cleanup() { try { FileUtils.deleteDirectory(new File(directory)); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public void cleanup() { FileUtils.deleteQuietly(new File(directory)); }