auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public NodeMetadata apply(InstanceInZone instanceInZone) { Instance input = instanceInZone.getInstance(); Map<URI, ? extends Image> imagesMap = images.get(); Image image = checkNotNull(imagesMap.get(checkNotNull(input.getImage(), "image")), "no image for %s. images: %s", input.getImage(), imagesMap.values()); return new NodeMetadataBuilder() .id(SlashEncodedIds.fromTwoIds(checkNotNull(locations.get().get(input.getZone()), "location for %s", input.getZone()).getId(), input.getName()).slashEncode()) .name(input.getName()) .providerId(input.getId()) .hostname(input.getName()) .imageId(image.getId()) .location(checkNotNull(locations.get().get(input.getZone()), "location for %s", input.getZone())) .hardware(checkNotNull(hardwares.get().get(input.getMachineType()), "hardware type for %s", <START> input.getMachineType().toString())) <END> .operatingSystem(image.getOperatingSystem()) .status(toPortableNodeStatus.get(input.getStatus())) .tags(input.getTags().getTags()) .uri(input.getSelfLink()) .userMetadata(input.getMetadata()) .group(nodeNamingConvention.groupInUniqueNameOrNull(input.getName())) .privateAddresses(collectPrivateAddresses(input)) .publicAddresses(collectPublicAddresses(input)) .build(); }</code><technical_language>Spacing</technical_language>

Target:
public NodeMetadata apply(InstanceInZone instanceInZone) { Instance input = instanceInZone.getInstance(); Map<URI, ? extends Image> imagesMap = images.get(); Image image = checkNotNull(imagesMap.get(checkNotNull(input.getImage(), "image")), "no image for %s. images: %s", input.getImage(), imagesMap.values()); return new NodeMetadataBuilder() .id(SlashEncodedIds.fromTwoIds(checkNotNull(locations.get().get(input.getZone()), "location for %s", input.getZone()).getId(), input.getName()).slashEncode()) .name(input.getName()) .providerId(input.getId()) .hostname(input.getName()) .imageId(image.getId()) .location(checkNotNull(locations.get().get(input.getZone()), "location for %s", input.getZone())) .hardware(checkNotNull(hardwares.get().get(input.getMachineType()), "hardware type for %s", input.getMachineType().toString())) .operatingSystem(image.getOperatingSystem()) .status(toPortableNodeStatus.get(input.getStatus())) .tags(input.getTags().getItems()) .uri(input.getSelfLink()) .userMetadata(input.getMetadata()) .group(nodeNamingConvention.groupInUniqueNameOrNull(input.getName())) .privateAddresses(collectPrivateAddresses(input)) .publicAddresses(collectPublicAddresses(input)) .build(); }
Source:
<code>private RemoteConfigurationRegistryClient createClient(RemoteConfigurationRegistryConfig config) { ACLProvider aclProvider; if (config.isSecureRegistry()) { configureSasl(config); if (!StringUtils.isBlank(config.getAuthType()) && config <START> .getAuthType().equalsIgnoreCase("Kerberos") && !config <END> .isBackwardsCompatible()) { aclProvider = new SASLOwnerACLProvider(true); } else { aclProvider = new SASLOwnerACLProvider(false); } } else { System.clearProperty(LOGIN_CONTEXT_NAME_PROPERTY); aclProvider = new DefaultACLProvider(); } CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(config.getConnectionString()) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .aclProvider(aclProvider) .build(); client.start(); return (new ClientAdapter(client, config)); }</code><technical_language>"Kerberos" a constant is elsewhere</technical_language>

Target:
private RemoteConfigurationRegistryClient createClient(RemoteConfigurationRegistryConfig config) { ACLProvider aclProvider; if (config.isSecureRegistry()) { configureSasl(config); if(AUTH_TYPE_KERBEROS.equalsIgnoreCase(config.getAuthType()) && !config.isBackwardsCompatible()) { aclProvider = new SASLOwnerACLProvider(true); } else { aclProvider = new SASLOwnerACLProvider(false); } } else { System.clearProperty(LOGIN_CONTEXT_NAME_PROPERTY); aclProvider = new DefaultACLProvider(); } CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(config.getConnectionString()) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .aclProvider(aclProvider) .build(); client.start(); return (new ClientAdapter(client, config)); }
Source:
<code>public DefaultKfsAccountForAwsResultWrapper getDefaultKfsAccountForAwsResultWrapper() throws URISyntaxException, IOException { String defaultAccountUrl = findDefaultAccountServiceEndPoint(); Response response = null; try { Invocation request = buildClientRequest(defaultAccountUrl, findDefaultAccountServiceXApiKey()); response = request.invoke(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(DefaultKfsAccountForAwsResultWrapper.class); } else { <START> LOG.error("getDefaultKfsAccountForAwsResultWrapper, error calling enpoint. The HTTP response was " + response.getStatus()); <END> throw new IOException("Invalid response code: " + response.getStatus()); } } finally { CURestClientUtils.closeQuietly(response); } }</code><technical_language>Minor typo in sentence of error message</technical_language>

Target:
public DefaultKfsAccountForAwsResultWrapper getDefaultKfsAccountForAwsResultWrapper() throws URISyntaxException, IOException { String defaultAccountUrl = findDefaultAccountServiceEndPoint(); Response response = null; try { Invocation request = buildClientRequest(defaultAccountUrl, findDefaultAccountServiceXApiKey()); response = request.invoke(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(DefaultKfsAccountForAwsResultWrapper.class); } else { LOG.error("getDefaultKfsAccountForAwsResultWrapper, error calling endpoint. The HTTP response was " + response.getStatus()); throw new IOException("Invalid response code: " + response.getStatus()); } } finally { CURestClientUtils.closeQuietly(response); } }
Source:
<code>public static String formatTime(long time, TimeFormat format, Resolution resolution) { switch (format) { case CALENDAR: return formatTimeAbs(time, resolution); case NUMBER: return NumberFormat.getInstance().format(time); case CYCLES: return NumberFormat.getInstance().format(time) + Messages.Utils_ClockCyclesUnit; case RELATIVE: return formatTimeRelative(time, resolution); default: } StringBuilder str = new StringBuilder(); long t = time; boolean neg = t < 0; if (neg) { t = -t; str.append('-'); } long sec = t / SEC_IN_NS; str.append(sec); String ns = formatNs(t, resolution); if <START> (!ns.equals("")) { <END> str.append('.'); str.append(ns); } return str.toString(); }</code><technical_language>isEmpty instead</technical_language>

Target:
public static String formatTime(long time, TimeFormat format, Resolution resolution) { switch (format) { case CALENDAR: return formatTimeAbs(time, resolution); case NUMBER: return NumberFormat.getInstance().format(time); case CYCLES: return NumberFormat.getInstance().format(time) + Messages.Utils_ClockCyclesUnit; case RELATIVE: return formatTimeRelative(time, resolution); default: } StringBuilder str = new StringBuilder(); long t = time; boolean neg = t < 0; if (neg) { t = -t; str.append('-'); } long sec = t / SEC_IN_NS; str.append(sec); String ns = formatNs(t, resolution); if (!ns.isEmpty()) { str.append('.'); str.append(ns); } return str.toString(); }
Source:
<code>public static List<File> unzipFiles(File zippedfile, String destPath, IProgressMonitor monitor) throws FileNotFoundException, IOException { try (ZipFile zipFile = new ZipFile(zippedfile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); List<File> outputFiles = new ArrayList<File>(); File destinationFile = new File(destPath); if (!destinationFile.exists()) { destinationFile.mkdirs(); } while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File outputFile = new File(destinationFile, entry.getName()); if (entry.isDirectory() && !outputFile.exists()) { outputFile.mkdirs(); continue; } if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } <START> try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(entry))) { <END> try (OutputStream outStream = new BufferedOutputStream(new FileOutputStream(outputFile))) { copyStream(inputStream, outStream); } } outputFiles.add(outputFile); if (monitor != null) { monitor.worked(1); } } return outputFiles; } }</code><technical_language>74-75 this try for resources</technical_language>

Target:
public static List<File> unzipFiles(File zippedfile, String destPath, IProgressMonitor monitor) throws FileNotFoundException, IOException { try (ZipFile zipFile = new ZipFile(zippedfile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); List<File> outputFiles = new ArrayList<File>(); File destinationFile = new File(destPath); if (!destinationFile.exists()) { destinationFile.mkdirs(); } while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File outputFile = new File(destinationFile, entry.getName()); if (entry.isDirectory() && !outputFile.exists()) { outputFile.mkdirs(); continue; } if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(entry)); OutputStream outStream = new BufferedOutputStream(new FileOutputStream(outputFile))) { copyStream(inputStream, outStream); } outputFiles.add(outputFile); if (monitor != null) { monitor.worked(1); } } return outputFiles; } }
Source:
<code>public S3PublishHelper(S3Configuration s3, boolean verbose) { super(s3.isCompressionEnabled(), verbose); this.client = (AmazonS3Client)buildClient( s3.getAccessKey(), s3.getSecretKey(), s3.getSessionToken(), s3.getRegion(), s3.getServiceEndpoint(), s3.getSigningRegion() ); this.bucket = s3.getBucket().toLowerCase(); String path = s3.getPath(); <START> if (path != null && !path.isEmpty()) { <END> if (!path.endsWith("/")) { this.path = path + "/"; } else { this.path = path; } } else { this.path = null; } this.sseConfig = s3.getSseConfiguration(); }</code><technical_language>try StringUtils.isTruthy(path) here</technical_language>

Target:
public S3PublishHelper(S3Configuration s3, boolean verbose) { super(s3.isCompressionEnabled(), verbose); this.client = (AmazonS3Client)buildClient( s3.getAccessKey(), s3.getSecretKey(), s3.getSessionToken(), s3.getRegion(), s3.getServiceEndpoint(), s3.getSigningRegion() ); this.bucket = s3.getBucket().toLowerCase(); String path = s3.getPath(); if (StringUtils.isTruthy(path)) { if (!path.endsWith("/")) { this.path = path + "/"; } else { this.path = path; } } else { this.path = null; } this.sseConfig = s3.getSseConfiguration(); }
Source:
<code>protected void execute() { if (connector != null) <START> connector.refresh(); <END> }</code><technical_language>please curly braces this is a Oneliner</technical_language>

Target:
protected void execute() { if (connector != null) { connector.refresh(); } }
Source:
<code>public void testMigrationThroughService() { CommentManager commentManager; commentManager = Framework.getService(CommentManager.class); assertTrue(commentManager.getClass().getName(), commentManager instanceof CommentManagerImpl); MigrationService.MigrationStatus status = migrationService.getStatus(MIGRATION_ID); assertNotNull(status); assertFalse(status.isRunning()); assertEquals(MIGRATION_STATE_RELATION, status.getState()); runMigration(() -> { migrationService.runStep(MIGRATION_ID, MIGRATION_STEP_RELATION_TO_PROPERTY); <START> await().atLeast(1, SECONDS); <END> await().pollInterval(1, SECONDS).until(() -> !migrationService.getStatus(MIGRATION_ID).isRunning()); }); commentManager = Framework.getService(CommentManager.class); assertTrue(commentManager.getClass().getName(), commentManager instanceof PropertyCommentManager); status = migrationService.getStatus(MIGRATION_ID); assertNotNull(status); assertFalse(status.isRunning()); assertEquals(MIGRATION_STATE_PROPERTY, status.getState()); }</code><technical_language>merged next of pollDelay</technical_language>

Target:
public void testMigrationThroughService() { CommentManager commentManager; commentManager = Framework.getService(CommentManager.class); assertTrue(commentManager.getClass().getName(), commentManager instanceof CommentManagerImpl); MigrationService.MigrationStatus status = migrationService.getStatus(MIGRATION_ID); assertNotNull(status); assertFalse(status.isRunning()); assertEquals(MIGRATION_STATE_RELATION, status.getState()); testMigration(() -> { migrationService.runStep(MIGRATION_ID, MIGRATION_STEP_RELATION_TO_PROPERTY); sleep(1000); long deadline = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1); while (System.currentTimeMillis() < deadline) { if (!migrationService.getStatus(MIGRATION_ID).isRunning()) { break; } sleep(100); } }); commentManager = Framework.getService(CommentManager.class); assertTrue(commentManager.getClass().getName(), commentManager instanceof PropertyCommentManager); status = migrationService.getStatus(MIGRATION_ID); assertNotNull(status); assertFalse(status.isRunning()); assertEquals(MIGRATION_STATE_PROPERTY, status.getState()); }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { <START> super.visitFunctionOrMethodDeclaration(o); <END> check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); check(o.getSignature(), o.getBlock(), holder); } }; }</code><technical_language>check checkCanceled</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { check(o.getSignature(), o.getBlock(), holder); } }; }
Source:
<code>ProcessorContextImpl(final TaskId id, final StreamTask streamTask, final StreamsConfig config, final RecordCollector collector, final ProcessorStateManager stateMgr, final StreamsMetricsImpl metrics, final ThreadCache cache) { super(id, config, metrics, stateMgr, cache); <START> this.streamTask = streamTask; <END> this.collector = collector; }</code><technical_language>nit: add a validation if streamTask != null stateMgr.taskType() == ACTIVE</technical_language>

Target:
ProcessorContextImpl(final TaskId id, final StreamTask streamTask, final StreamsConfig config, final RecordCollector collector, final ProcessorStateManager stateMgr, final StreamsMetricsImpl metrics, final ThreadCache cache) { super(id, config, metrics, stateMgr, cache); this.streamTask = streamTask; this.collector = collector; if (streamTask == null && taskType() == TaskType.ACTIVE) { throw new IllegalStateException("Tried to create context for active task but the streamtask was null"); } }
Source:
<code>public void registerTracerBean(@Observes AfterBeanDiscovery abd) { abd.addBean().addTransitiveTypeClosure(Tracer.class).produceWith(i -> { ClassLoader loader; if (!WildFlySecurityManager.isChecking()) { loader = Thread.currentThread().getContextClassLoader(); } else { loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); } <START> return TRACERS.get(loader); <END> }); }</code><technical_language>This TRACERS.get(WildFlySecurityManager.getCurrentContextClassLoader())</technical_language>

Target:
public void registerTracerBean(@Observes AfterBeanDiscovery abd) { abd.addBean().addTransitiveTypeClosure(Tracer.class).produceWith(i -> { return TRACERS.get(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()); }); }
Source:
<code>public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getExtensions()) { if (EngineLocalConfig.getInstance().getBoolean(ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), true)) { try { instance.activate( extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), EngineLocalConfig.getInstance().getBoolean( ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME) <START> ) <END> ); } catch (Exception ex) { log.error(ex.getMessage()); log.debug(ex); } } } } } } instance.dump(); return instance; }</code><technical_language>hmmm.... this is confusing... a while... getExtensionConfiguration(String) in order allow interception</technical_language>

Target:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getLoadedExtensions()) { if (EngineLocalConfig.getInstance().getBoolean( ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), Boolean.parseBoolean( extension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION).getProperty(Base.ConfigKeys.ENABLED,"true") ) )) { instance.initialize(extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME)); } } } } } instance.dump(); return instance; }
Source:
<code>public boolean equals(Object o) { <START> return true; <END> }</code><technical_language>atleast check o non-null instanceof IdentityExtractionFn</technical_language>

Target:
public boolean equals(Object o) { return o != null && o instanceof IdentityExtractionFn; }
Source:
<code>public void destroyPersistenceContext(Object identifier) throws CachePersistenceException { String stringIdentifier = validateIdentifier(identifier); FileBasedPersistenceContext persistenceContext = knownPersistenceContexts.remove(stringIdentifier); if (persistenceContext == null) { <START> throw new CachePersistenceException("Identifier " + identifier + " not known to this persistence service"); <END> } else { destroy(stringIdentifier, persistenceContext, true); } }</code><technical_language>do that, want scenario possible: 1. Create a persistent cache "foo" fill 2. Shut VM 3. Restart VM, initialise cache manager initialising caches 4. Destroy cache "foo"'s persistence context initialising it. I point, context is marked known</technical_language>

Target:
public void destroyPersistenceContext(Object identifier) throws CachePersistenceException { String stringIdentifier = validateIdentifier(identifier); FileBasedPersistenceContext persistenceContext = knownPersistenceContexts.remove(stringIdentifier); if (persistenceContext == null) { destroy(stringIdentifier, new DefaultFileBasedPersistenceContext(getDirectoryFor(stringIdentifier)), true); } else { destroy(stringIdentifier, persistenceContext, true); } }
Source:
<code>public void gatewayDiagnostics() { <START> CosmosClient gatewayClient = null; <END> try { gatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); CosmosContainer container = gatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); validateJson(diagnostics); } finally { if (gatewayClient != null) { gatewayClient.close(); } } }</code><technical_language>a class field name this hides class field. this named for more clarity in test? suggestion CosmosClient testGatewayClient = null;</technical_language>

Target:
public void gatewayDiagnostics() { CosmosClient testGatewayClient = null; try { testGatewayClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .gatewayMode() .buildClient(); CosmosContainer container = testGatewayClient.getDatabase(cosmosAsyncContainer.getDatabase().getId()).getContainer(cosmosAsyncContainer.getId()); InternalObjectNode internalObjectNode = getInternalObjectNode(); CosmosItemResponse<InternalObjectNode> createResponse = container.createItem(internalObjectNode); String diagnostics = createResponse.getDiagnostics().toString(); assertThat(diagnostics).contains("\"connectionMode\":\"GATEWAY\""); assertThat(diagnostics).doesNotContain(("\"gatewayStatistics\":null")); assertThat(diagnostics).contains("\"operationType\":\"Create\""); assertThat(diagnostics).contains("\"metaDataName\":\"CONTAINER_LOOK_UP\""); assertThat(diagnostics).contains("\"serializationType\":\"PARTITION_KEY_FETCH_SERIALIZATION\""); assertThat(diagnostics).contains("\"userAgent\":\"" + Utils.getUserAgent() + "\""); assertThat(createResponse.getDiagnostics().getDuration()).isNotNull(); validateTransportRequestTimelineGateway(diagnostics); validateJson(diagnostics); } finally { if (testGatewayClient != null) { testGatewayClient.close(); } } }
Source:
<code>private Optional<InsightCard.Category> generateNewUserInsights(final Long accountId, final DeviceId deviceId, final int accountAge, final DeviceDataInsightQueryDAO deviceDataInsightQueryDAO) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); InsightCard.Category categoryToGenerate; switch (accountAge) { case 1: categoryToGenerate = InsightCard.Category.LIGHT; break; case 2: categoryToGenerate = InsightCard.Category.SLEEP_QUALITY; <START> break; <END> default: return Optional.absent(); } if (recentCategories.contains(categoryToGenerate)) { return Optional.absent(); } LOGGER.debug("Trying to generate category insight for new user accountId {}", categoryToGenerate, accountId); final Optional<InsightCard.Category> generatedNewUserCategory = this.generateInsightsByCategory(accountId, deviceId, deviceDataInsightQueryDAO, categoryToGenerate); if (generatedNewUserCategory.isPresent()) { LOGGER.debug("Successfully generated category insight for new user accountId {}", generatedNewUserCategory.get(), accountId); return generatedNewUserCategory; } return Optional.absent(); }</code><technical_language>removing Temperature Insight for new users well</technical_language>

Target:
private Optional<InsightCard.Category> generateNewUserInsights(final Long accountId, final DeviceId deviceId, final int accountAge, final DeviceDataInsightQueryDAO deviceDataInsightQueryDAO) { final Set<InsightCard.Category> recentCategories = this.getRecentInsightsCategories(accountId); InsightCard.Category categoryToGenerate; switch (accountAge) { case 1: categoryToGenerate = InsightCard.Category.LIGHT; break; case 2: categoryToGenerate = InsightCard.Category.TEMPERATURE; break; case 3: categoryToGenerate = InsightCard.Category.SLEEP_QUALITY; break; default: return Optional.absent(); } if (recentCategories.contains(categoryToGenerate)) { return Optional.absent(); } LOGGER.debug("Trying to generate category insight for new user accountId {}", categoryToGenerate, accountId); final Optional<InsightCard.Category> generatedNewUserCategory = this.generateInsightsByCategory(accountId, deviceId, deviceDataInsightQueryDAO, categoryToGenerate); if (generatedNewUserCategory.isPresent()) { LOGGER.debug("Successfully generated category insight for new user accountId {}", generatedNewUserCategory.get(), accountId); return generatedNewUserCategory; } return Optional.absent(); }
Source:
<code>public void platformMotionDownAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.EMPTY, Cell.WALL, Cell.WALL, Cell.PLATFORM, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 4)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1.1), new Point(2, 2.1)), new Point(0, 1)); <START> assertFalse(cell.getType() == Cell.EMPTY); <END> }</code><technical_language>assertNotEquals instead of == operator combined assertFalse, == work properly for non-objects. <testing</technical_language>

Target:
public void platformMotionDownAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.EMPTY, Cell.WALL, Cell.WALL, Cell.PLATFORM, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 4)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1.1), new Point(2, 2.1)), new Point(0, 1)); assertNotEquals(cell, Cell.EMPTY); }
Source:
<code><START> public Iterable<Listener<K, V>> getListeners() { <END> return listeners; }</code><technical_language>suggest returning ImmutableList Collections.unmodifiable list here, generally iffy give control of member variables other classes. For example, if in future additional logic is add in addListener/removeListener this give people a remove listeners triggering logic</technical_language>

Target:
public List<Listener<K, V>> getListeners() { return Collections.unmodifiableList(listeners); }
Source:
<code>public PlayerBackpack(@Nonnull PlayerProfile profile, int id, int size) { if (size < 9 || size > 54 || size % 9 != 0) { throw new IllegalArgumentException("Invalid size! Size must be one of: [9, 18, 27, 36, 45, 54]"); } this.profile = profile; this.id = id; this.cfg = profile.getConfig(); this.size = size; <START> cfg.setValue(PlayerBackpack.backpacks + id + ".size", size); <END> markDirty(); inventory = Bukkit.createInventory(null, size, "Backpack [" + size + " Slots]"); }</code><technical_language>PlayerBackpack is redundant here, need class in</technical_language>

Target:
public PlayerBackpack(@Nonnull PlayerProfile profile, int id, int size) { if (size < 9 || size > 54 || size % 9 != 0) { throw new IllegalArgumentException("Invalid size! Size must be one of: [9, 18, 27, 36, 45, 54]"); } this.profile = profile; this.id = id; this.cfg = profile.getConfig(); this.size = size; cfg.setValue(CONFIG_PREFIX + id + ".size", size); markDirty(); inventory = Bukkit.createInventory(null, size, "Backpack [" + size + " Slots]"); }
Source:
<code>private void applySubsetMultiThread(Path tmpDir, GoGoDuckModule module, int threadCount) throws GoGoDuckException { logger.info(String.format("Applying subset on directory '%s'", tmpDir)); File[] directoryListing = tmpDir.toFile().listFiles(); ExecutorService executorService = Executors.newFixedThreadPool(threadCount); List<String> ncksSubsetParameters = null; for (final File file : directoryListing) { if (ncksSubsetParameters == null) { <START> ncksSubsetParameters = module.getNcksSubsetParameters(file.getAbsoluteFile().toString()).getNcksParameters(); <END> logger.info(String.format("Subset for operation is '%s'", ncksSubsetParameters)); userLog.log(String.format("Applying subset '%s'", ncksSubsetParameters)); } executorService.submit(new NcksRunnable(file, module, this, ncksSubsetParameters)); } executorService.shutdown(); try { executorService.awaitTermination(MAX_EXECUTION_TIME_DAYS, TimeUnit.DAYS); } catch (InterruptedException e) { throw new GoGoDuckException("Task interrupted while waiting to complete", e); } }</code><technical_language>probe files for collection metadata in place instead of i.e. setup</technical_language>

Target:
private void applySubsetMultiThread(Path tmpDir, GoGoDuckModule module, int threadCount) throws GoGoDuckException { logger.info(String.format("Applying subset on directory '%s'", tmpDir)); List<String> ncksSubsetParameters; try { File[] directoryListing = tmpDir.toFile().listFiles(); if (directoryListing != null) { ExecutorService executorService = Executors.newFixedThreadPool(threadCount); for (File file : directoryListing) { ncksSubsetParameters = module.getSubsetParameters().getNcksParameters(); logger.info(String.format("Subset for operation is '%s'", ncksSubsetParameters)); userLog.log(String.format("Applying subset '%s'", ncksSubsetParameters)); executorService.submit(new NcksRunnable(file, module, this)); } executorService.shutdown(); executorService.awaitTermination(MAX_EXECUTION_TIME_DAYS, TimeUnit.DAYS); } else { throw new GoGoDuckException("No files available for sub-setting"); } } catch (InterruptedException e) { throw new GoGoDuckException("Task interrupted while waiting to complete", e); } catch (Exception e) { throw new GoGoDuckException(e.getMessage(), e); } }
Source:
<code>protected void checkConverterAvailability(String converterName) { ConverterCheckResult check = cs.isConverterAvailable(converterName); assertNotNull(check); <START> assertTrue(String.format( <END> "Skipping %s tests since commandLine is not installed:\n" + "- installation message: %s\n- error message: %s", converterName, check.getInstallationMessage(), check.getErrorMessage()), check.isAvailable()); }</code><technical_language>This Assume.assumeTrue, assertTrue</technical_language>

Target:
protected void checkConverterAvailability(String converterName) { ConverterCheckResult check = cs.isConverterAvailable(converterName); assertNotNull(check); assumeTrue(String.format( "Skipping %s tests since commandLine is not installed:\n" + "- installation message: %s\n- error message: %s", converterName, check.getInstallationMessage(), check.getErrorMessage()), check.isAvailable()); }
Source:
<code>public void version(Actor actor) { actor.printInfo(TranslatableComponent.of("worldedit.version.version", TextComponent.of(WorldEdit.getVersion()))); actor.printInfo(TextComponent.of("<LINK_1>")); PlatformManager pm = we.getPlatformManager(); TextComponentProducer producer = new TextComponentProducer(); for (Platform platform : pm.getPlatforms()) { producer.append( TextComponent.of("* ", TextColor.GRAY) .append(TextComponent.of(platform.getPlatformName())) .append(TextComponent.of("(" + platform.getPlatformVersion() + ")")) ).newline(); } actor.print(new MessageBox("Platforms", producer, TextColor.GRAY).create()); producer.reset(); for (Capability capability : Capability.values()) { Platform platform = pm.queryCapability(capability); producer.append( TextComponent.of(capability.name(), TextColor.GRAY) .append(TextComponent.of(": ") <START> .append(TextComponent.of(platform != null ? platform.getPlatformName() : "NONE"))) <END> ).newline(); } actor.print(new MessageBox("Capabilities", producer, TextColor.GRAY).create()); }</code><technical_language>Do need a key for NONE</technical_language>

Target:
public void version(Actor actor) { actor.printInfo(TranslatableComponent.of("worldedit.version.version", TextComponent.of(WorldEdit.getVersion()))); actor.printInfo(TextComponent.of("<LINK_0>")); PlatformManager pm = we.getPlatformManager(); TextComponentProducer producer = new TextComponentProducer(); for (Platform platform : pm.getPlatforms()) { producer.append( TextComponent.of("* ", TextColor.GRAY) .append(TextComponent.of(platform.getPlatformName())) .append(TextComponent.of("(" + platform.getPlatformVersion() + ")")) ).newline(); } actor.print(new MessageBox("Platforms", producer, TextColor.GRAY).create()); producer.reset(); for (Capability capability : Capability.values()) { Platform platform = pm.queryCapability(capability); producer.append( TextComponent.of(capability.name(), TextColor.GRAY) .append(TextComponent.of(": ") .append(TextComponent.of(platform != null ? platform.getPlatformName() : "NONE"))) ).newline(); } actor.print(new MessageBox("Capabilities", producer, TextColor.GRAY).create()); }
Source:
<code>public void bind() { getOnStateChangeCallback().ifPresent(callback -> callback.accept(mUpdaterState.get())); <START> mStateValidityEnsured.set(false); <END> this.mUpdateEngine.bind(mUpdateEngineCallback); }</code><technical_language>nit:mStateSynchronized</technical_language>

Target:
public void bind() { getOnStateChangeCallback().ifPresent(callback -> callback.accept(mUpdaterState.get())); mStateSynchronized.set(false); this.mUpdateEngine.bind(mUpdateEngineCallback); }
Source:
<code>public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; <START> LOG.error("Authentication success on server side"); <END> } else { LOG.debug("Authentication failed on server side"); } }</code><technical_language>'info'</technical_language>

Target:
public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; LOG.info("Authentication success on server side"); } else { LOG.debug("Authentication failed on server side"); } }
Source:
<code><START> public Cursor getWordMatches(String query, String[] columns) { <END> String selection = KEY_ADDRESS + " LIKE ?"; String[] selectionArgs = new String[] {"%" + query + "%"}; return query(selection, selectionArgs, columns); }</code><technical_language>final</technical_language>

Target:
public final Cursor getWordMatches(String query, String[] columns) { String selection = KEY_ADDRESS + " LIKE ?"; String[] selectionArgs = new String[] {"%" + query + "%"}; return query(selection, selectionArgs, columns); }
Source:
<code>public void testReassignNotCompletedWithBadTimeFormat() throws Exception { changeUser(USER_ADMINISTRATOR); Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = null; try { processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); TaskSummary task = tasks.get(0); OrgEntities reassign = OrgEntities.builder().users(Arrays.asList(USER_JOHN)).build(); assertExceptionContainsCorrectMessage(() -> userTaskAdminClient.reassignWhenNotCompleted(CONTAINER_ID, task.getId(), "2sssss", reassign) <START> , "Error code: 500"); <END> } finally { if (processInstanceId != null) { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } } }</code><technical_language>I Kie server return HTTP status 4xx in this case (possibly 400) request parameter parsed</technical_language>

Target:
public void testReassignNotCompletedWithBadTimeFormat() throws Exception { changeUser(USER_ADMINISTRATOR); Map<String, Object> parameters = new HashMap<>(); Long processInstanceId = null; try { processInstanceId = processClient.startProcess(CONTAINER_ID, PROCESS_ID_EVALUATION, parameters); List<TaskSummary> tasks = taskClient.findTasksAssignedAsBusinessAdministrator(USER_ADMINISTRATOR, 0, 10); TaskSummary task = tasks.get(0); OrgEntities reassign = OrgEntities.builder().users(Arrays.asList(USER_JOHN)).build(); assertExceptionContainsCorrectMessage(() -> userTaskAdminClient.reassignWhenNotCompleted(CONTAINER_ID, task.getId(), "2sssss", reassign) , "Error code: 400", "Error parsing time string:"); } finally { if (processInstanceId != null) { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } } }
Source:
<code>public IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid) { if (logger.isDebugEnabled()) { logger.debug("getMostOptimalIncomingPhoneNumber: " + phone + ",srcOrg:" + sourceOrganizationSid + ",destOrg:" + destinationOrganizationSid); } List<String> numberQueries = createPhoneQuery(phone); IncomingPhoneNumber numberfound = findByNumber(numberQueries, sourceOrganizationSid, destinationOrganizationSid); if (numberfound == null) { <START> numberfound = findSingleNumber("*", sourceOrganizationSid, destinationOrganizationSid); <END> if (numberfound == null) { if (destinationOrganizationSid != null && phone.matches("[\\d,*,#,+]+")) { numberfound = findByRegex(numberQueries, sourceOrganizationSid, destinationOrganizationSid); } } } return numberfound; }</code><technical_language>@jaimecasero I REGEX numbers higher priority * choice if else matched. order specific catch-em-all option, so: specific number -> regex -> '*'</technical_language>

Target:
public IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid) { if (logger.isDebugEnabled()) { logger.debug("getMostOptimalIncomingPhoneNumber: " + phone + ",srcOrg:" + sourceOrganizationSid + ",destOrg:" + destinationOrganizationSid); } List<String> numberQueries = createPhoneQuery(phone); IncomingPhoneNumber numberfound = findByNumber(numberQueries, sourceOrganizationSid, destinationOrganizationSid); if (numberfound == null) { if (destinationOrganizationSid != null && destinationOrganizationSid.equals(sourceOrganizationSid) && phone.matches("[\\d,*,#,+]+")) { numberfound = findByRegex(numberQueries, sourceOrganizationSid, destinationOrganizationSid); } if (numberfound == null) { numberfound = findSingleNumber("*", sourceOrganizationSid, destinationOrganizationSid); } } return numberfound; }
Source:
<code>public boolean isHighSpeedConnection() { <START> return telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS || <END> telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSUPA || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EVDO_0 || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EVDO_A; }</code><technical_language>call telephonyManager.getNetworkType()</technical_language>

Target:
public boolean isHighSpeedConnection() { final int networkType = telephonyManager.getNetworkType(); return networkType == TelephonyManager.NETWORK_TYPE_UMTS || networkType == TelephonyManager.NETWORK_TYPE_HSUPA || networkType == TelephonyManager.NETWORK_TYPE_HSPA || networkType == TelephonyManager.NETWORK_TYPE_HSDPA || networkType == TelephonyManager.NETWORK_TYPE_EVDO_0 || networkType == TelephonyManager.NETWORK_TYPE_EVDO_A; }
Source:
<code>public void emitData(final I input) { if (generateEvent(input) != null) { <START> outputEmitter.emitData(generateEvent(input)); <END> } }</code><technical_language>invoking generateEvent</technical_language>

Target:
public void emitData(final I input) { MistDataEvent newInputEvent = generateEvent(input); if (newInputEvent != null) { outputEmitter.emitData(newInputEvent); } }
Source:
<code>public ChatComponent addWith(JsonElement element) { <START> $lock.writeLock().lock(); <END> with.add(element); $lock.writeLock().unlock(); return this; }</code><technical_language>THREAD-SAFETY need mind, locks thread-safe collection</technical_language>

Target:
public ChatComponent addWith(JsonElement element) { with.add(element); return this; }
Source:
<code>public void justWorks() throws Exception { <START> for (final String method:TkProxyTest.METHODS) { <END> new FtRemote(new TkFixed("hello, world!")).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { MatcherAssert.assertThat( new RsPrint( new TkProxy(home).act(new RqFake(method)) ).print(), Matchers.containsString("hello") ); } } ); } }</code><technical_language>@sebing please put spaces :</technical_language>

Target:
public void justWorks() throws Exception { new FtRemote(new TkFixed("hello, world!")).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { MatcherAssert.assertThat( new RsPrint( new TkProxy(home).act(new RqFake("PUT")) ).print(), Matchers.containsString("hello") ); } } ); }
Source:
<code>public CountryListAdapter(Context context) { <START> super(context, R.layout.fui_dgts__country_row, android.R.id.text1); <END> }</code><technical_language>While renaming, remove extra _</technical_language>

Target:
public CountryListAdapter(Context context) { super(context, R.layout.fui_dgts_country_row, android.R.id.text1); }
Source:
<code>public void setIdName(final String idName) { if (Util.empty(idName)) { throw new IllegalArgumentException("idName cannot be null or empty"); } Matcher matcher = ID_PATTERN.matcher(idName); if (!matcher.matches()) { throw new IllegalArgumentException( "idName " + idName + " must start with a letter and followed by letters, digits and or underscores."); } <START> if (getIdName() == null || !getIdName().equals(idName)) { <END> ComponentModel model = getOrCreateComponentModel(); model.setIdName(idName); } }</code><technical_language>Store a reference result of getIdName() calling multiple times</technical_language>

Target:
public void setIdName(final String idName) { if (Util.empty(idName)) { throw new IllegalArgumentException("idName cannot be null or empty"); } Matcher matcher = ID_PATTERN.matcher(idName); if (!matcher.matches()) { throw new IllegalArgumentException( "idName " + idName + " must start with a letter and followed by letters, digits and or underscores."); } String currIdName = getIdName(); if (!Objects.equals(idName, currIdName)) { ComponentModel model = getOrCreateComponentModel(); model.setIdName(idName); } }
Source:
<code>@Override public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) { final Map map = (Map) operand; final ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); try { final String coordinatesString = (String) map.get("coordinates"); Preconditions.checkState(coordinatesString != null, "'coordinates' is missing in configuration"); final Map<String, Integer> coordinates = mapper.readValue(coordinatesString, new TypeReference<Map<String, Integer>>() { }); <START> final String scheme = (String) map.get("scheme"); <END> final RestClient client = connect(coordinates, scheme); final String index = (String) map.get("index"); return new ElasticsearchSchema(client, new ObjectMapper(), index); } catch (IOException e) { throw new RuntimeException("Cannot parse values from json", e); } }</code><technical_language>scheme hardcoded in configuration ? auto-detected programmatically</technical_language>

Target:
@Override public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) { final Map map = (Map) operand; final ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); try { List<HttpHost> hosts; if (map.containsKey("hosts")) { final List<String> configHosts = mapper.readValue((String) map.get("hosts"), new TypeReference<List<String>>() { }); hosts = configHosts .stream() .map(host -> HttpHost.create(host)) .collect(Collectors.toList()); } else if (map.containsKey("coordinates")) { final Map<String, Integer> coordinates = mapper.readValue((String) map.get("coordinates"), new TypeReference<Map<String, Integer>>() { }); hosts = coordinates .entrySet() .stream() .map(entry -> new HttpHost(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); LOGGER.warn("Prefer using hosts, coordinates is deprecated."); } else { throw new IllegalArgumentException ("Both 'coordinates' and 'hosts' is missing in configuration. Provide one of them."); } final RestClient client = connect(hosts); final String index = (String) map.get("index"); return new ElasticsearchSchema(client, new ObjectMapper(), index); } catch (IOException e) { throw new RuntimeException("Cannot parse values from json", e); } }
Source:
<code>public void testSanitizeForSaving() { AdminEmailAttributes actualAdminEmail = adminEmailAttributes; <START> AdminEmailAttributes expectedAdminEmail = adminEmailAttributes; <END> actualAdminEmail.sanitizeForSaving(); assertEquals(SanitizationHelper.sanitizeTextField(expectedAdminEmail.subject), actualAdminEmail.subject); assertEquals(SanitizationHelper.sanitizeForRichText(expectedAdminEmail.content), actualAdminEmail.content); }</code><technical_language>This work for reasons: - Java assigns Object variable reference essentially expected actual same. - attribute's subject content clean texts; sanitizing difference. test this simply creating a new attribute object, sanitize it, check subject content fields post-sanitization</technical_language>

Target:
public void testSanitizeForSaving() { String subjectWithWhitespaces = " subject to be sanitized by removing leading/trailing whitespace "; Text contentWithWhitespaces = new Text(" content to be sanitized by removing leading/trailing whitespace "); ______TS("valid sanitation of admin email"); AdminEmailAttributes adminEmailAttributes = new AdminEmailAttributes( subjectWithWhitespaces, addressReceiverListString, groupReceiverListFileKey, contentWithWhitespaces, date); ______TS("success: sanitized whitespace"); adminEmailAttributes.sanitizeForSaving(); assertEquals("subject to be sanitized by removing leading/trailing whitespace", adminEmailAttributes.getSubject()); assertEquals("content to be sanitized by removing leading/trailing whitespace", adminEmailAttributes.getContentValue()); ______TS("success: sanitized code block"); adminEmailAttributes.content = new Text("<code>System.out.println(\"Hello World\");</code>"); adminEmailAttributes.sanitizeForSaving(); assertEquals("<code>System.out.println(&#34;Hello World&#34;);</code>", adminEmailAttributes.getContentValue()); ______TS("success: sanitized superscript"); adminEmailAttributes.content = new Text("f(x) = x<sup>2</sup>"); adminEmailAttributes.sanitizeForSaving(); assertEquals("f(x) &#61; x<sup>2</sup>", adminEmailAttributes.getContentValue()); ______TS("success: sanitized chemical formula"); adminEmailAttributes.content = new Text("<p>Chemical formula: C<sub>6</sub>H<sub>12</sub>O<sub>6</sub></p>"); adminEmailAttributes.sanitizeForSaving(); assertEquals("<p>Chemical formula: C<sub>6</sub>H<sub>12</sub>O<sub>6</sub></p>", adminEmailAttributes.getContentValue()); ______TS("success: sanitized invalid closing tag"); adminEmailAttributes.content = new Text("</td></option></div> invalid closing tags"); adminEmailAttributes.sanitizeForSaving(); assertEquals(" invalid closing tags", adminEmailAttributes.getContentValue()); }