auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void addToIndex(final GitOutputConsole console) { Resource[] resources = appContext.getResources(); Path[] paths = new Path[resources.length]; for (int i = 0; i < resources.length; i++) { <START> Path path = resources[i].getLocation().removeFirstSegments(appContext.getRootProject().getLocation().segmentCount()); <END> 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); } }); }</code><technical_language>appContext.getRootProject().getLocation().segmentCount() equals 1, safely remove segment this checking</technical_language>

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:
<code>public static void main(String[] args) { <START> GamePlugin.getXStream(); <END> 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(); } }</code><technical_language>player load plugin some point? this superfluous</technical_language>

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:
<code>protected void enrichTuple(INPUT tuple) { Object key = getKey(tuple); if (key != null) { Object result = cacheManager.get(key); OUTPUT out = convert(tuple, result); <START> emitTuple(out); <END> } }</code><technical_language>rename else confuse emitTuple of input adapter. Suggestion: emitEnrichedTuple()</technical_language>

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:
<code>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()) { <START> log.debug(String.format("About to run task '%s' from {}", r.getClass().getName()), new Exception()); <END> } if (getQueue().size() > 5) { log.warn("Executing a command '{}', but note that there are tasks in the queue.", r.getClass().getName(), getQueue().size()); } }</code><technical_language>I do this... but... I do understand. anyway, please drop get translated</technical_language>

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:
<code>public void start() <START> throws InstantiationException { <END> logger.info("Admin blob storage service started"); }</code><technical_language>throws next line</technical_language>

Target:
public void start() throws InstantiationException { logger.info("AdminBlobStorageService has started"); }
Source:
<code>public void startup() throws Exception{ super.startup(); JsonObject json = readTrackingFile(); if (json != null && <START> json.getString(SERVER_HOST_PROPERTY) == serverHost && <END> 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); }</code><technical_language>This needs String.equals method</technical_language>

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:
<code>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(); <START> Optional<BearerToken> apiToken = originalConfig.apiToken().or(defaultApiToken()); <END> 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); }</code><technical_language>I this more clear follows: ServiceConfiguration configWithDefaults = ServiceConfiguration.builder() .apiToken(serviceConfig.apiToken().or(defaultApiToken()) .security(serviceConfig.security().or(defaultSecurity()) .uris(serviceConfig.uris()) .build();</technical_language>

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:
<code>public void consume(Runnable signalsInterrupt) { try { do { signalsInterrupt.run(); <START> } while (!inflightSemaphore.tryAcquire(500, TimeUnit.MILLISECONDS)); <END> 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); } }</code><technical_language>I 500 ms a decent default adjusted based output rate desired consumer responsiveness</technical_language>

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:
<code><START> protected int getTimeOut(Field field) { <END> 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; } }</code><technical_language>super-classes required annotation, for @FindBy annotation [here](<LINK_0></technical_language>

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:
<code>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); <START> tids.add(attributeName.startsWith("0_") ? 0 : Integer.parseInt(attributeName)); END> } return tids; } catch (AttributeNotFoundException e) { } return Collections.EMPTY_SET; }</code><technical_language>THREAD_0_SEPARATOR instead of a literal "_"</technical_language>

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:
<code>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( <START> config.get("path-style-access", Boolean.class) <END> )); } String bucket = config.get("bucket", String.class); return new S3Storage(client, bucket); }</code><technical_language>this config.get("path-style-access", boolean.class, false)</technical_language>

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:
<code>public void validate() { FieldValidator validator = new FieldValidator(); <START> assertTrue(validator.getInvalidityInfoForPersonName(this.instructorName.trim()).isEmpty(), "validate name"); <END> assertTrue(validator.getInvalidityInfoForInstituteName(this.instructorInstitution.trim()).isEmpty(), "validate institute"); assertTrue(validator.getInvalidityInfoForEmail(this.instructorEmail.trim()).isEmpty(), "validate email"); }</code><technical_language>parameter "validate name" is supposed error message is getInvalidityInfoForPersonName returned</technical_language>

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:
<code>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; <START> case STUDENTS_EXCLUDING_SELF: <END> 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; }</code><technical_language>This block identical STUDENTS one. block do extra logical steps option is STUDENTS_EXCLUDING_SELF</technical_language>

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:
<code><START> @Override public void onDestroy() { <END> disconnectGoogleClient(); AppLog.d(T.MAIN, "GOOGLE SIGNUP/IN: disconnecting google client"); mDispatcher.unregister(this); super.onDestroy(); }</code><technical_language>@Override annotation a separate line onDestroy method for code consistency</technical_language>

Target:
public void onDestroy() { disconnectGoogleClient(); AppLog.d(T.MAIN, "GOOGLE SIGNUP/LOGIN: disconnecting google client"); mDispatcher.unregister(this); super.onDestroy(); }
Source:
<code>public void testV2OnlyStats() { testV2OnlyStats(createStats(Types.optional(PrimitiveTypeName.INT32).as(OriginalType.UINT_8).named(""), <START> Byte.MAX_VALUE, <END> 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"))); }</code><technical_language>In for UINT_8 0x00 min 0xFF max (or some arbitrary values, constants). for decimal arbitrary values (+-123456), Byte.MIN_VALUE Byte.MAX_VALUE arbitrary values, is misleading them, because: 1. do arbitrary values special values instead, while in reality values special in unsigned interpretation (specifically extreme values of allowed range for unsigned bytes). 2. Byte.MIN_VALUE = -128 = 0x80 Byte.MAX_VALUE = 127 = 0x7F in unsigned comparison 0x80 > 0x7F, min is larger max value. Similarly for bigger unsigned types below</technical_language>

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:
<code>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()); <START> } <END> }</code><technical_language>test pass if exception is thrown. I recommend AssertJ: java assertThatIllegalArgumentException() .isThrownBy(() -> solverManager.solve(tenantId, problem, null, null)) .withMessageContaining("Problem (" + tenantId + ") exists.");</technical_language>

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:
<code>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(); <START> if (null == response.getPushError()) { <END> result = true; } } catch (IOException e) { logger.trace("IO problems pushing note: {}", e.getMessage()); } return result; }</code><technical_language>Need protect NPE here</technical_language>

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:
<code>public void initFromPage(int valueCountL, ByteBuffer page, int offset) throws IOException { <START> ByteBufferInputStream in = new ByteBufferInputStream(page.duplicate(), offset, page.limit() - offset); <END> int length = BytesUtils.readIntLittleEndian(in); decoder = new RunLengthBitPackingHybridDecoder(bitWidth, in); this.nextOffset = offset + length + 4; }</code><technical_language>duplicate</technical_language>

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:
<code>public RequestIdPolicy(Supplier<HttpHeaders> requestIdSupplier) { <START> this.requestIdSupplier = requestIdSupplier; <END> }</code><technical_language>Do want this nullable</technical_language>

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

Target:
public boolean containsAny(ExternalIdBundle bundle) { ArgChecker.notNull(bundle, "bundle"); return bundle.externalIds.stream().anyMatch(id -> externalIds.contains(id)); }
Source:
<code>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 " + <START> "WHERE field.inode = inode.inode) and inode.type like '%s' ",Inode.Type.FIELD.getTableName()); <END> dc.executeStatement(query); }</code><technical_language>@joseorsini instead of a I a = case</technical_language>

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:
<code>public void onBindViewHolder(@NonNull RecentFilesViewHolder holder, int position) { if (showShimmer) { holder.shimmerFrameLayout.startShimmer(); } else { <START> 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); <END> RecentFile file = recentFiles.get(position); setUpViewHolder(file, holder); } }</code><technical_language>Please create a new function dedicated stopping shimmer for code readability</technical_language>

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:
<code>public void start(BundleContext bc) throws Exception { context = bc; <START> logger.info("Slack action has been started."); <END> }</code><technical_language>this next logger statement reduced debug</technical_language>

Target:
public void start(BundleContext bc) throws Exception { context = bc; logger.debug("Slack action has been started."); }
Source:
<code>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(); <START> future = this.getComputer().apply(graph).program(this.generateProgram(memory, graph)).submit(); <END> 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); } }</code><technical_language>reason this logic is changed? generateComputer() getComputer().apply()</technical_language>

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:
<code>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(); } <START> AnimalAddedEvent ev = new AnimalAddedEvent(); <END> 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); }</code><technical_language>threads test code</technical_language>

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:
<code>@Test <START> public void <END> constructor_nullDelegate() { try { new ForwardingOs(null) { }; fail(); } catch (NullPointerException expected) { } }</code><technical_language>Newline @Test public. 4 instances this in libcore source, hundreds line</technical_language>

Target:
public void constructor_nullDelegate() { try { new ForwardingOs(null) {}; fail(); } catch (NullPointerException expected) { } }
Source:
<code>public Page<Element> traverse(Element startingPoint, Query query, Pager pager) { HawkularPipeline<?, ? extends Element> q = translate(startingPoint, query); q.counter("total").page(pager); <START> return new Page<>(q.cast(Element.class).iterator(), pager, q.getCount("total")); <END> }</code><technical_language>I if q.getCount() call report correct number toList(). checked that</technical_language>

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:
<code>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) { <START> taskIdsParam.append(selected.getId() + ","); <END> 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); }</code><technical_language>try stream instead, like: taskSummaries.stream().map(s -> s.getDeploymentId()).collect(Collectors.joining(","))</technical_language>

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:
<code>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; <START> if (workerConfig.getAutoScalers() == null) { <END> log.error("No autoScaler available, cannot %s workers", action); return null; } return workerConfig; }</code><technical_language>DefaultWorkerBehaviorConfig constructor shouldn't/doesn't allow instantiation null autoScalers this check is redundant</technical_language>

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:
<code>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(); <START> } else if (nextProbingRebalanceMs.get() < System.currentTimeMillis()) { <END> 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(); } } }</code><technical_language>suggestion } else if (nextProbingRebalanceMs.get() < Time.milliseconds()) { This control in testing, do</technical_language>

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:
<code>public boolean isEndpointExist(String endpointName) throws EndpointAdminException { if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { if (endpointAdmin.isEndpointExist(endpointName)) { <START> return true; <END> } } else { if (endpointAdmin.isEndpointExistForTenant(endpointName, tenantDomain)) { return true; } } return false; }</code><technical_language>do in line</technical_language>

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:
<code>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"); } <START> subtypes.put(type, clazz); <END> return new ProblemAdapterFactory(stackTraces, statusAdapter, subtypes); }</code><technical_language>warning: mutates map in original instance of factory. need create a copy. safe side, wrap Collections.unmodifableMap(..) in constructor</technical_language>

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:
<code><START> private void cleanup() <END> { try { FileUtils.deleteDirectory(new File(directory)); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>is calling cleanup? if is done Junit after/afterclass annotations</technical_language>

Target:
public void cleanup() { FileUtils.deleteQuietly(new File(directory)); }
Source:
<code>public void OnInstall() { <START> InstallModel model = (InstallModel) getWindow(); <END> boolean isOVirt = getEntity().getVdsType() == VDSType.oVirtNode; if (!model.Validate(isOVirt)) { return; } UpdateVdsActionParameters param = new UpdateVdsActionParameters(); param.setvds(getEntity()); param.setVdsId(getEntity().getId()); param.setRootPassword((String) model.getRootPassword().getEntity()); param.setIsReinstallOrUpgrade(true); param.setInstallVds(true); param.setoVirtIsoFile(isOVirt ? ((RpmVersion) model.getOVirtISO().getSelectedItem()).getRpmName() : null); param.setOverrideFirewall((Boolean) model.getOverrideIpTables().getEntity()); param.setRebootAfterInstallation(isOVirt); Frontend.RunAction( VdcActionType.UpdateVds, param, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); if (returnValue != null && returnValue.getSucceeded()) { Cancel(); } } } ); }</code><technical_language>consifer declare isOvirt final</technical_language>

Target:
public void OnInstall() { InstallModel model = (InstallModel) getWindow(); final boolean isOVirt = getEntity().getVdsType() == VDSType.oVirtNode; if (!model.Validate(isOVirt)) { return; } UpdateVdsActionParameters param = new UpdateVdsActionParameters(); param.setvds(getEntity()); param.setVdsId(getEntity().getId()); param.setRootPassword((String) model.getRootPassword().getEntity()); param.setIsReinstallOrUpgrade(true); param.setInstallVds(true); param.setoVirtIsoFile(isOVirt ? ((RpmVersion) model.getOVirtISO().getSelectedItem()).getRpmName() : null); param.setOverrideFirewall((Boolean) model.getOverrideIpTables().getEntity()); param.setRebootAfterInstallation(isOVirt); Frontend.RunAction( VdcActionType.UpdateVds, param, new IFrontendActionAsyncCallback() { @Override public void Executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); if (returnValue != null && returnValue.getSucceeded()) { Cancel(); } } } ); }
Source:
<code>private String getPassword() { String password = null; String passwordType = (String)actionArgs.get("password"); if(passwordType.startsWith("interactive")) { System.out.print("Please enter password: "); <START> password = System.console().readLine(); <END> } else if(passwordType.startsWith("pass:")) { password = passwordType.substring(5); } else if(passwordType.startsWith("env:")) { password = System.getenv(passwordType.substring(4)); } else if(passwordType.startsWith("file:")) { try { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(passwordType.substring(5)), Charset.forName("UTF-8")))) { password = reader.readLine(); } } catch (IOException ex) { throw new RuntimeException(ex); } } else { throw new RuntimeException(String.format("Unknown file type: '%1$s'", passwordType)); } return password; }</code><technical_language>hmmm :) this hidden input</technical_language>

Target:
private String getPassword() { String password = null; String passwordType = (String)actionArgs.get("password"); if(passwordType.startsWith("interactive")) { System.out.print("Please enter password: "); password = System.console().readLine(); } else if(passwordType.startsWith("pass:")) { password = passwordType.substring(5); } else if(passwordType.startsWith("env:")) { password = System.getenv(passwordType.substring(4)); } else if(passwordType.startsWith("file:")) { try( InputStream is = new FileInputStream(passwordType.substring(5)); Reader reader = new InputStreamReader(is, Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(reader) ) { password = br.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } else { throw new RuntimeException(String.format("Unknown file type: '%1$s'", passwordType)); } return password; }
Source:
<code>public ReplTxnWork(String replPolicy, String dbName, String tableName, Long txnId, OperationType type, ReplicationSpec replicationSpec) { <START> this(replPolicy, dbName, tableName, Lists.newArrayList(txnId), type, null, replicationSpec); <END> }</code><technical_language>Singleton list used</technical_language>

Target:
public ReplTxnWork(String replPolicy, String dbName, String tableName, Long txnId, OperationType type, ReplicationSpec replicationSpec) { this(replPolicy, dbName, tableName, Collections.singletonList(txnId), type, null, replicationSpec); }