auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void changeDefaultLimitSerializationClassesValueToTrueIn7x() { String codeLocStr = DeploymentDescriptor.class.getProtectionDomain().getCodeSource().getLocation().toString(); Assume.assumeTrue("Test will not succeed in an IDE", codeLocStr.endsWith(".jar")); Matcher matcher = jarLocRegex.matcher(codeLocStr); assertTrue( "Fix regular expression: " + jarLocRegexStr, matcher.matches() ); double jarVersion = Double.parseDouble(matcher.group(1)); DeploymentDescriptorImpl depDesc = new DeploymentDescriptorImpl(); assertTrue( "The default value of 'limitSerializationClasses is FALSE in 6.x and TRUE in 7.x", jarVersion < 7.0d && ! depDesc.getLimitSerializationClasses() || jarVersion >= 7.0d && depDesc.getLimitSerializationClasses() ); }

Target:
public void changeDefaultLimitSerializationClassesValueToTrueIn7x() throws Exception { Properties props = new Properties(); String testPropsFileName = "test.properties"; InputStream testPropsStream = this.getClass().getResourceAsStream("/" + testPropsFileName); assertNotNull("Unable to find or open " + testPropsFileName, testPropsFileName); props.load(testPropsStream); String projectVersionStr = (String) props.get("project.version"); Matcher matcher = jarLocRegex.matcher(projectVersionStr); assertTrue( "Fix regular expression: " + jarLocRegexStr, matcher.matches() ); double jarVersion = Double.parseDouble(matcher.group(1)); DeploymentDescriptorImpl depDesc = new DeploymentDescriptorImpl(); assertTrue( "The default value of 'limitSerializationClasses is FALSE in 6.x and TRUE in 7.x", jarVersion < 7.0d && ! depDesc.getLimitSerializationClasses() || jarVersion >= 7.0d && depDesc.getLimitSerializationClasses() ); }
Source:
private ValidationResult validateVolumeIdAndUpdatePath(StorageServerConnections connection) { if (connection.getGlusterVolumeId() != null) { GlusterVolumeEntity glusterVolume = glusterVolumeDao.getById(connection.getGlusterVolumeId()); if (glusterVolume == null || glusterVolume.getBricks().isEmpty()) { return new ValidationResult(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_GLUSTER_VOLUME); } Set<String> addressSet = new LinkedHashSet<>(); glusterVolume.getBricks().forEach( brick -> addressSet.add(brick.getNetworkId() != null && !brick.getNetworkAddress().isEmpty() ? brick.getNetworkAddress() : brick.getServerName())); String firstHost = (String) addressSet.toArray()[0]; addressSet.remove(firstHost); connection.setConnection(firstHost + StorageConstants.GLUSTER_VOL_SEPARATOR + glusterVolume.getName()); String mountOptions=""; if (!addressSet.isEmpty()) { mountOptions += StorageConstants.GLUSTER_BACKUP_SERVERS_MNT_OPTION + KEY_VALUE_SEPARATOR + StringUtils.join(addressSet.toArray(), ':'); } if (StringUtils.isBlank(connection.getMountOptions())) { connection.setMountOptions(mountOptions); } else if (!connection.getMountOptions().contains(StorageConstants.GLUSTER_BACKUP_SERVERS_MNT_OPTION)) { mountOptions = connection.getMountOptions().concat("," + mountOptions); connection.setMountOptions(mountOptions); } } return ValidationResult.VALID; }

Target:
private ValidationResult validateVolumeIdAndUpdatePath(StorageServerConnections connection) { if (connection.getGlusterVolumeId() != null) { GlusterVolumeEntity glusterVolume = glusterVolumeDao.getById(connection.getGlusterVolumeId()); if (glusterVolume == null || glusterVolume.getBricks().isEmpty()) { return new ValidationResult(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_GLUSTER_VOLUME); } Set<String> addressSet = new LinkedHashSet<>(); glusterVolume.getBricks().forEach( brick -> addressSet.add(brick.getNetworkId() != null && !brick.getNetworkAddress().isEmpty() ? brick.getNetworkAddress() : brick.getServerName())); String firstHost = (String) addressSet.toArray()[0]; addressSet.remove(firstHost); connection.setConnection(firstHost + StorageConstants.GLUSTER_VOL_SEPARATOR + glusterVolume.getName()); String mountOptions = addressSet.stream().collect(Collectors.joining(":", StorageConstants.GLUSTER_BACKUP_SERVERS_MNT_OPTION + KEY_VALUE_SEPARATOR, "")); if (StringUtils.isBlank(connection.getMountOptions())) { connection.setMountOptions(mountOptions); } else if (!connection.getMountOptions().contains(StorageConstants.GLUSTER_BACKUP_SERVERS_MNT_OPTION)) { mountOptions = connection.getMountOptions().concat("," + mountOptions); connection.setMountOptions(mountOptions); } } return ValidationResult.VALID; }
Source:
private void addResetCurrentPerspectiveShortcut(Composite parent) { ResetLayoutButtonViewModel model = new ResetLayoutButtonViewModel(); model.addPropertyChangeListener("triggerReset", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { maximise(); } }); buttonModels.add(model); new ResetLayoutButton(parent, perspectivesProvider, model); }

Target:
private void addResetCurrentPerspectiveShortcut(Composite parent) { ResetLayoutButtonViewModel model = new ResetLayoutButtonViewModel(); buttonModels.add(model); ResetLayoutButton button = new ResetLayoutButton(parent, perspectivesProvider, model); button.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { maximise(); } }); }
Source:
public static String getTextClassifierPath() { return getUserDirectory().getAbsolutePath() + File.separator + TEXT_CLASSIFIERS_SUBDIRECTORY; }

Target:
static String getTextClassifierPath() { return getUserDirectory().getAbsolutePath() + File.separator + TEXT_CLASSIFIERS_SUBDIRECTORY; }
Source:
protected IonSequence newEmptySequence() { return SYSTEM.newDatagram(); }

Target:
protected IonSequence newEmptySequence() { return SYSTEM.newEmptyList(); }
Source:
public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); log.infoFormat("GlusterManager: {0}", new Date()); }

Target:
public void create() { log.infoFormat("InitResourceManager: {0}", new Date()); ResourceManager.getInstance().init(); AsyncTaskManager.getInstance().InitAsyncTaskManager(); log.infoFormat("AsyncTaskManager: {0}", new Date()); if (Config.<Boolean> GetValue(ConfigValues.EnableVdsLoadBalancing)) { VdsLoadBalancer.EnableLoadBalancer(); } log.infoFormat("VdsLoadBalancer: {0}", new Date()); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("MacPoolManager started: {0}", new Date()); MacPoolManager.getInstance().initialize(); log.infoFormat("MacPoolManager finished: {0}", new Date()); } }); StoragePoolStatusHandler.Init(); GlusterManager.getInstance().init(); }
Source:
private List<ProjectInfo> list(final ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); Map<String, ProjectInfo> result = lp.apply(); return ImmutableList.copyOf(result.values()); }

Target:
private List<ProjectInfo> list(final ListRequest request) throws RestApiException { ListProjects lp = listProvider.get(); lp.setShowDescription(request.getDescription()); lp.setLimit(request.getLimit()); lp.setStart(request.getStart()); lp.setMatchPrefix(request.getPrefix()); return ImmutableList.copyOf(lp.apply().values()); }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials = null; if (config.isAcceptBasicAuthHeaders()) { credentials = SSOUtils.getUserCredentialsFromHeader(request); } if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else if (credentials != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } else if (config.isEnforceNego()) { enforceNego(response); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SSOConfig config = (SSOConfig) request.getServletContext().getAttribute(SSOUtils.SSO_CONFIG); Credentials credentials; if (doAuth(request, response)) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE4_URI); } else if (config.isAcceptBasicAuthHeaders() && (credentials = SSOUtils.getUserCredentialsFromHeader(request)) != null) { request.getSession(true).setAttribute(SSOUtils.USER_CREDENTIALS, credentials); response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE3_URI); } else if (config.isEnforceNego()) { enforceNego(response); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
public InternalFunctions getFunctions(RealmUser user, CodecRegistry codecRegistry) { return new InternalFunctions(user, codecRegistry); }

Target:
public Functions getFunctions(RealmUser user, CodecRegistry codecRegistry) { return new FunctionsImpl(user, codecRegistry); }
Source:
private StorageLocation fakeLocation(long total, long free, long max, Double percent) throws IOException { Configuration config = Configuration.builder(PathType.unix()) .setRoots("/") .setWorkingDirectory("/") .setAttributeViews("basic") .setMaxSize(total) .setBlockSize(1000) .build(); Path path = Jimfs.newFileSystem(config).getPath("/"); Files.write(path.resolve("junk"), new byte[(int) (total - free)]); Assert.assertEquals(free, Files.getFileStore(path).getUsableSpace()); return new StorageLocation(path, max, percent); }

Target:
private StorageLocation fakeLocation(long total, long free, long max, Double percent) { File file = EasyMock.mock(File.class); EasyMock.expect(file.getTotalSpace()).andReturn(total).anyTimes(); EasyMock.expect(file.getFreeSpace()).andReturn(free).anyTimes(); EasyMock.replay(file); return new StorageLocation(file, max, percent); }
Source:
public void testBasics() throws Exception { final Path tmpPath = Files.createTempFile("testfile", ".txt"); tmpPath.toFile().deleteOnExit(); try (final PathEntity httpentity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) { Assert.assertEquals(Files.size(tmpPath), httpentity.getContentLength()); try (final InputStream content = httpentity.getContent()) { Assert.assertNotNull(content); } Assert.assertTrue(httpentity.isRepeatable()); Assert.assertFalse(httpentity.isStreaming()); if (!Files.deleteIfExists(tmpPath)) { Assert.fail("Failed to delete: " + tmpPath); } } }

Target:
public void testBasics() throws Exception { final Path tmpPath = Files.createTempFile("testfile", ".txt"); tmpPath.toFile().deleteOnExit(); try (final PathEntity httpEntity = new PathEntity(tmpPath, ContentType.TEXT_PLAIN)) { Assert.assertEquals(Files.size(tmpPath), httpEntity.getContentLength()); try (final InputStream content = httpEntity.getContent()) { Assert.assertNotNull(content); } Assert.assertTrue(httpEntity.isRepeatable()); Assert.assertFalse(httpEntity.isStreaming()); if (!Files.deleteIfExists(tmpPath)) { Assert.fail("Failed to delete: " + tmpPath); } } }
Source:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { Files.setLastModifiedTime(f, FileTime.from(Instant.now())); } }

Target:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { } Files.setLastModifiedTime(f, FileTime.from(Instant.now())); }
Source:
AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (more == null) { more = new String[0]; } this.parentFileSystem = parentFileSystem; Flux<String> elementFlux = Flux.fromArray(first.split(this.parentFileSystem.getSeparator())) .concatWith(Flux.fromArray(more) .flatMap(str -> Flux.fromArray(str.split(this.parentFileSystem.getSeparator())))) .filter(str -> !str.isEmpty()); this.pathString = String.join(this.parentFileSystem.getSeparator(), elementFlux.toIterable()); elementFlux.skip(1) .flatMap(str -> str.contains(ROOT_DIR_SUFFIX) ? Mono.error(Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " is an invalid character except to identify the root element of this path if there is one."))) : Mono.just(str)).blockLast(); elementFlux.take(1) .flatMap(str -> str.contains(ROOT_DIR_SUFFIX) && str.indexOf(ROOT_DIR_SUFFIX) < str.length() - 1 ? Mono.error(Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " may" + " only be used as the last character in the root component of a path"))) : Mono.just(str)).blockLast(); }

Target:
AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.parentFileSystem = parentFileSystem; List<String> elements = new ArrayList<>(Arrays.asList(first.split(parentFileSystem.getSeparator()))); if (more != null) { for (String next : more) { elements.addAll(Arrays.asList(next.split(parentFileSystem.getSeparator()))); } } elements.removeIf(String::isEmpty); this.pathString = String.join(this.parentFileSystem.getSeparator(), elements); for (int i = 0; i < elements.size(); i++) { String element = elements.get(i); if (i == 0) { if (element.contains(ROOT_DIR_SUFFIX) && element.indexOf(ROOT_DIR_SUFFIX) < element.length() - 1) { throw Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " may" + " only be used as the last character in the root component of a path")); } } else if (element.contains(ROOT_DIR_SUFFIX)) { throw Utility.logError(logger, new InvalidPathException(this.pathString, ROOT_DIR_SUFFIX + " is an " + "invalid character except to identify the root element of this path if there is one.")); } } }
Source:
private static MultitenantBlackBoxContext multiTenant(String name, EventEnricher enricher) { return new MultitenantBlackBoxContext(name, enricher); }

Target:
public static MultitenantBlackBoxContext multiTenant(String name, EventEnricher enricher) { return new MultitenantBlackBoxContext(name, enricher); }
Source:
private void shiftBaseTemplateToSuccessor() { try { final Guid newBaseTemplateId = findIdOfOldestTemplate(templateSubVersions); updateBaseTemplateId(newBaseTemplateId, templateSubVersions); } finally { freeSubTemplatesLock(); } }

Target:
private void shiftBaseTemplateToSuccessor() { try { getVmTemplateDao().shiftBaseTemplate(getVmTemplateId()); } finally { freeSubTemplatesLock(); } }
Source:
public String getCookie(URL url){ try { URL sessionURL = new URL(String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort())); HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); HttpURLConnection connection = conn.execute().getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); int responseCode = connection.getResponseCode(); if(responseCode / 100 == 2){ if(sessionHasStarted(connection.getInputStream())) { return cookieHeader.substring(0, cookieHeader.indexOf(";")); } else { return null; } } else if(responseCode == 401){ shouldAttemptCookieRequest = false; logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this interceptor object"); } else if (responseCode / 100 == 5){ logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth", responseCode); } else { logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, " + "cookie authentication will not be attempted again", responseCode); shouldAttemptCookieRequest = false; } } catch (MalformedURLException e) { logger.log(Level.SEVERE,"Failed to create URL for _session endpoint",e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); } return null; }

Target:
private String getCookie(URL url){ try { URL sessionURL = new URL(String.format("%s://%s:%d/_session", url.getProtocol(), url.getHost(), url.getPort())); HttpConnection conn = Http.POST(sessionURL, "application/x-www-form-urlencoded"); conn.setRequestBody(sessionRequestBody); HttpURLConnection connection = conn.execute().getConnection(); String cookieHeader = connection.getHeaderField("Set-Cookie"); int responseCode = connection.getResponseCode(); if(responseCode / 100 == 2){ if(sessionHasStarted(connection.getInputStream())) { return cookieHeader.substring(0, cookieHeader.indexOf(";")); } else { return null; } } else if(responseCode == 401){ shouldAttemptCookieRequest = false; logger.severe("Credentials are incorrect, cookie authentication will not be" + " attempted again by this interceptor object"); } else if (responseCode / 100 == 5){ logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, cookie auth", responseCode); } else { logger.log(Level.SEVERE, "Failed to get cookie from server, response code %s, " + "cookie authentication will not be attempted again", responseCode); shouldAttemptCookieRequest = false; } } catch (MalformedURLException e) { logger.log(Level.SEVERE,"Failed to create URL for _session endpoint",e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to encode cookieRequest body", e); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); } return null; }
Source:
protected void init() { if (getEntity() == null) { return; } allowDuplicates.setEntity(getEntity().isAllowDuplicateMacAddresses()); if (getEntity().getId() != null) { Frontend.getInstance() .runAction(ActionType.GetAvailableMacsForMacPool, new IdParameters(getEntity().getId()), result -> { initRanges(); Map<Pair<String, String>, Integer> availableMacsPerRange = result.getReturnValue().getActionReturnValue(); macRanges.getItems().forEach(macRangeModel -> { MacRange macRange = macRangeModel.getMacRange(); Integer availableMacs = availableMacsPerRange.get(new Pair<>(macRange.getMacFrom(), macRange.getMacTo())); if (availableMacs != null) { macRangeModel.setAvailableMacs(availableMacs); } macRangeModel.recalculateMacsCount(); }); }); } else { initRanges(); } }

Target:
protected void init() { if (getEntity() == null) { return; } allowDuplicates.setEntity(getEntity().isAllowDuplicateMacAddresses()); if (getEntity().getId() != null) { Frontend.getInstance() .runAction(ActionType.GetAvailableMacsForMacPool, new IdParameters(getEntity().getId()), result -> { initRanges(); Map<MacRange, Integer> availableMacsPerRange = result.getReturnValue().getActionReturnValue(); macRanges.getItems().forEach(macRangeModel -> { Integer availableMacs = availableMacsPerRange.get(macRangeModel.getMacRange()); if (availableMacs != null) { macRangeModel.setAvailableMacsCount(availableMacs); } }); }); } else { initRanges(); } }
Source:
public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException { if (proxyUrl != null) { connection.setProxy(proxyUrl); } connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream is = null; InputStream es = null; String response = null; int code = -1; Throwable cause = null; try { is = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; } try { code = connection.getConnection().getResponseCode(); response = connection.getConnection().getResponseMessage(); if (code / 100 == 2) { return is; } else if (code == 404) { throw new NoDocumentException(response, cause); } else if(code == 412) { throw new PreconditionFailedException(response, cause); } else { CouchDbException ex = null; try { es = connection.getConnection().getErrorStream(); ex = getGson().fromJson(new InputStreamReader(es), CouchDbException.class); } catch(Exception e) { ex = new CouchDbException(response, code); } finally { if (ex == null) { ex = new CouchDbException(response, code); } ex.setStatusCode(code); throw ex; } } } catch (IOException ioe) { throw new CouchDbException("Error retrieving server response", ioe, code); } finally { if (es != null) { try { es.close(); } catch (IOException ioe) { ; } } } }

Target:
public InputStream executeToInputStream(HttpConnection connection) throws CouchDbException { if (proxyUrl != null) { connection.setProxy(proxyUrl); } connection.requestProperties.put("Accept", "application/json"); connection.responseInterceptors.addAll(this.responseInterceptors); connection.requestInterceptors.addAll(this.requestInterceptors); InputStream is = null; InputStream es = null; String response = null; int code = -1; Throwable cause = null; try { is = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; } try { code = connection.getConnection().getResponseCode(); response = connection.getConnection().getResponseMessage(); if (code / 100 == 2) { return is; } else if (code == 404) { throw new NoDocumentException(response, cause); } else if (code == 412) { throw new PreconditionFailedException(response, cause); } else { CouchDbException ex = new CouchDbException(response, code); es = connection.getConnection().getErrorStream(); if (es != null) { try { ex = getGson().fromJson(new InputStreamReader(es), CouchDbException.class); ex.setStatusCode(code); } catch (JsonParseException e) { } } throw ex; } } catch (IOException ioe) { throw new CouchDbException("Error retrieving server response", ioe, code); } finally { close(es); } }
Source:
public void testSomeUser3() { List<Integer> lightData = Lists.newArrayList(); final URL userCSVFile = Resources.getResource("insights/bedlightduration/lightDataUser3.csv"); try { final String csvString = Resources.toString(userCSVFile, Charsets.UTF_8); final String[] lightDataStringList = csvString.replaceAll("\\s+","").split(","); for (String lightDataString : lightDataStringList) { lightData.add(Integer.parseInt(lightDataString)); } } catch (IOException ioexception) { ioexception.printStackTrace(); } List<Long> timeStamps = Lists.newArrayList(); final URL timeStampCSVFile = Resources.getResource("insights/bedlightduration/timeStampUser3.csv"); try { final String csvString = Resources.toString(timeStampCSVFile, Charsets.UTF_8); final String[] timeStampStringList = csvString.replaceAll("\\s+","").replaceAll("L","").split(","); for (String timeStampString : timeStampStringList) { timeStamps.add(Long.parseLong(timeStampString)); } } catch (IOException ioexception) { ioexception.printStackTrace(); } final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(176)); }

Target:
public void testSomeUser3() throws IOException{ final List<Integer> lightData = readLightData("insights/bedlightduration/lightDataUser3.csv"); final List<Long> timeStamps = readTimeStamps("insights/bedlightduration/timeStampUser3.csv"); final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(176)); }
Source:
public void close() { lastUsed.set(System.currentTimeMillis()); useCnt.decrementAndGet(); }

Target:
public void close() { lastUsed.set(System.currentTimeMillis()); useCnt.decrementAndGet(); if (RepositoryCache.isCached(this)) { evict(0); } }
Source:
public void shouldComplainAboutInvalidNumber() { try { converter.convert("---", BigInteger.class); fail("Should throws an exception"); } catch (ConversionException e) { assertThat(e.getValidationMessage(), hasMessage("--- is not a valid integer.")); } }

Target:
public void shouldComplainAboutInvalidNumber() { try { converter.convert("---", BigInteger.class); fail("should throw an exception"); } catch (ConversionException e) { assertThat(e.getValidationMessage(), hasMessage("--- is not a valid integer.")); } }
Source:
private AttributesNode getCurrentAttributesNode(OperationType opType, WorkingTreeIterator workingTreeIterator, DirCacheIterator dirCacheIterator) throws IOException { AttributesNode attributesNode = null; switch (opType) { case CHECKIN_OP: if (workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } if (attributesNode == null && dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } break; case CHECKOUT_OP: if (dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } if (attributesNode == null && workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } break; default: throw new IllegalStateException( "The only operation type handled are:" + OperationType.CHECKIN_OP + "," + OperationType.CHECKOUT_OP); } return attributesNode; }

Target:
private AttributesNode getCurrentAttributesNode(OperationType opType, WorkingTreeIterator workingTreeIterator, DirCacheIterator dirCacheIterator) throws IOException { AttributesNode attributesNode = null; switch (opType) { case CHECKIN_OP: if (workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } if (attributesNode == null && dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } break; case CHECKOUT_OP: if (dirCacheIterator != null) { attributesNode = dirCacheIterator .getEntryAttributesNode(getObjectReader()); } if (attributesNode == null && workingTreeIterator != null) { attributesNode = workingTreeIterator.getEntryAttributesNode(); } break; default: throw new IllegalStateException( "The only supported operation types are:" + OperationType.CHECKIN_OP + "," + OperationType.CHECKOUT_OP); } return attributesNode; }
Source:
public void processWorkerMetrics(Map<String, Object> conf, WorkerMetrics metrics) throws MetricException { try (NimbusClient client = NimbusClient.getConfiguredClient(conf)) { client.getClient().processWorkerMetrics(metrics); } catch (Exception e) { throw new MetricException("Failed to process metrics", e); } }

Target:
public void processWorkerMetrics(Map<String, Object> conf, WorkerMetrics metrics) throws MetricException { try (NimbusClient client = NimbusClient.getConfiguredClient(conf)) { client.getClient().processWorkerMetrics(metrics); } catch (TException | NimbusLeaderNotFoundException e) { throw new MetricException("Failed to process metrics", e); } }
Source:
public void generateStreetTransfers(TransportNetwork transportNetwork, ProfileRequest request) { Map<Integer, List<Transfer>> transfersWithSameStart = transferToOption.keySet().stream() .collect(Collectors.groupingBy(Transfer::getAlightStop)); boolean prevReverseSearch = request.reverseSearch; request.reverseSearch = false; for (Map.Entry<Integer, List<Transfer>> entry: transfersWithSameStart.entrySet()) { StreetRouter streetRouter = new StreetRouter(transportNetwork.streetLayer); streetRouter.streetMode = StreetMode.WALK; streetRouter.profileRequest = request; streetRouter.distanceLimitMeters = TransitLayer.TRANSFER_DISTANCE_LIMIT_METERS; int stopIndex = transportNetwork.transitLayer.streetVertexForStop.get(entry.getKey()); streetRouter.setOrigin(stopIndex); streetRouter.route(); for (Transfer transfer: entry.getValue()) { int endIndex = transportNetwork.transitLayer.streetVertexForStop.get(transfer.boardStop); StreetRouter.State lastState = streetRouter.getStateAtVertex(endIndex); if (lastState != null) { StreetPath streetPath = new StreetPath(lastState, transportNetwork, false); StreetSegment streetSegment = new StreetSegment(streetPath, LegMode.WALK, transportNetwork.streetLayer); for (ProfileOption profileOption: transferToOption.get(transfer)) { profileOption.addMiddle(streetSegment, transfer); } } else { LOG.warn("Street transfer: not found in streetlayer", transfer); } } } request.reverseSearch = prevReverseSearch; }

Target:
public void generateStreetTransfers(TransportNetwork transportNetwork, ProfileRequest request) { Map<Integer, List<Transfer>> transfersWithSameStart = transferToOption.keySet().stream() .collect(Collectors.groupingBy(Transfer::getAlightStop)); boolean prevReverseSearch = request.reverseSearch; request.reverseSearch = false; for (Map.Entry<Integer, List<Transfer>> entry: transfersWithSameStart.entrySet()) { StreetRouter streetRouter = new StreetRouter(transportNetwork.streetLayer); streetRouter.streetMode = StreetMode.WALK; streetRouter.profileRequest = request; streetRouter.distanceLimitMeters = TRANSFER_DISTANCE_LIMIT_METERS; int stopIndex = transportNetwork.transitLayer.streetVertexForStop.get(entry.getKey()); streetRouter.setOrigin(stopIndex); streetRouter.route(); for (Transfer transfer: entry.getValue()) { int endIndex = transportNetwork.transitLayer.streetVertexForStop.get(transfer.boardStop); StreetRouter.State lastState = streetRouter.getStateAtVertex(endIndex); if (lastState != null) { StreetPath streetPath = new StreetPath(lastState, transportNetwork, false); StreetSegment streetSegment = new StreetSegment(streetPath, LegMode.WALK, transportNetwork.streetLayer); for (ProfileOption profileOption: transferToOption.get(transfer)) { profileOption.addMiddle(streetSegment, transfer); } } else { LOG.warn("Street transfer: not found in streetlayer", transfer); } } } request.reverseSearch = prevReverseSearch; }
Source:
public void testScanByArrayValue() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); createTableWithArray(BaseConnectedQueryTest.getUrl(), getDefaultSplits(tenantId), null, ts - 2); initTablesWithArrays(tenantId, null, ts); String query = "SELECT a_double_array, b_string, a_float FROM table_with_array WHERE ?=organization_id and ?=a_float"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setFloat(2, 0.01f); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[2]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; PhoenixArray array = (PhoenixArray) conn.createArrayOf("DOUBLE", doubleArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } }

Target:
public void testScanByArrayValue() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); createTableWithArray(BaseConnectedQueryTest.getUrl(), getDefaultSplits(tenantId), null, ts - 2); initTablesWithArrays(tenantId, null, ts); String query = "SELECT a_double_array, b_string, a_float FROM table_with_array WHERE ?=organization_id and ?=a_float"; Properties props = new Properties(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setFloat(2, 0.01f); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[4]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; doubleArr[2] = 37.56; doubleArr[3] = 386.63; Array array = conn.createArrayOf("DOUBLE", doubleArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } }
Source:
public Optional<SystemDescriptor> getSystemDescriptor() { return this.systemDescriptorOptional; }

Target:
public SystemDescriptor getSystemDescriptor() { return this.systemDescriptor; }
Source:
private void applyModuleConfiguration(@NotNull IProject wrappedModule) { Module module = wrappedModule.adaptTo(IntelliJProjectImpl.class).getModule(); ModuleConfiguration moduleConfiguration = queuedModuleOptions.remove(module); if (moduleConfiguration == null) { log.debug("Skipped module root model adjustment as not options were found - " + module); return; } if (!moduleConfiguration.isExistingModule()) { ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> applyModuleConfiguration(modifiableRootModel, moduleConfiguration)); } else { ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); if (contentEntries.length != 1) { log.error("Encountered shared module with multiple content roots - " + module); return; } ContentEntry contentEntry = contentEntries[0]; if (configurationDiffers(contentEntry, moduleConfiguration.getRootPaths())) { Runnable changeModuleConfiguration = () -> ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> { resetModuleConfiguration(modifiableRootModel); applyModuleConfiguration(modifiableRootModel, moduleConfiguration); }); SafeDialogUtils.showYesNoDialog( module.getProject(), Messages.ModuleConfigurationInitializer_override_module_config_message, Messages.ModuleConfigurationInitializer_override_module_config_title, changeModuleConfiguration); } } }

Target:
private void applyModuleConfiguration(@NotNull IProject wrappedModule) { Module module = wrappedModule.adaptTo(IntelliJProjectImpl.class).getModule(); ModuleConfiguration moduleConfiguration = queuedModuleOptions.remove(module); if (moduleConfiguration == null) { log.debug("Skipped module root model adjustment as not options were found - " + module); return; } if (!moduleConfiguration.isExistingModule()) { ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> applyModuleConfiguration(modifiableRootModel, moduleConfiguration)); return; } ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); if (contentEntries.length != 1) { log.error("Encountered shared module with multiple content roots - " + module); return; } ContentEntry contentEntry = contentEntries[0]; if (!configurationDiffers(contentEntry, moduleConfiguration.getRootPaths())) { return; } Runnable changeModuleConfiguration = () -> ModuleRootModificationUtil.updateModel( module, modifiableRootModel -> { resetModuleConfiguration(modifiableRootModel); applyModuleConfiguration(modifiableRootModel, moduleConfiguration); }); SafeDialogUtils.showYesNoDialog( module.getProject(), Messages.ModuleConfigurationInitializer_override_module_config_message, Messages.ModuleConfigurationInitializer_override_module_config_title, changeModuleConfiguration); }
Source:
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); } finally { final long time = System.currentTimeMillis(); final Long timing = time - start; final String userAgent = Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"); final String user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName).orElse("-"); final String method = request.getMethod(); final String path = request.getRequestURI(); final String query = Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""); final String contentEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.CONTENT_ENCODING)) .orElse("-"); final String acceptEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.ACCEPT_ENCODING)) .orElse("-"); LOG.info("[ACCESS_LOG] \"{}{}\" \"{}\" \"{}\" statusCode: ms \"{}\" \"{}\"", method, path, query, userAgent, user, response.getStatus(), timing, contentEncoding, acceptEncoding); publisher.publish(method,path, query,user, response.getStatus(), timing); } }

Target:
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { filterChain.doFilter(request, response); } finally { final long time = System.currentTimeMillis(); final Long timing = time - start; final String userAgent = Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"); final String user = Optional.ofNullable(request.getUserPrincipal()).map(Principal::getName).orElse("-"); final String method = request.getMethod(); final String path = request.getRequestURI(); final String query = Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""); final String contentEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.CONTENT_ENCODING)) .orElse("-"); final String acceptEncoding = Optional.ofNullable(request.getHeader(HttpHeaders.ACCEPT_ENCODING)) .orElse("-"); LOG.info("[ACCESS_LOG] \"{}{}\" \"{}\" \"{}\" statusCode: ms \"{}\" \"{}\"", method, path, query, userAgent, user, response.getStatus(), timing, contentEncoding, acceptEncoding); nakadiKpiPublisher.publish(accessLogEventType, () -> new JSONObject() .put("method", method) .put("path", path) .put("query", query) .put("app", user) .put("app_hashed", Hex.encodeHexString(sha256MessageDigest.digest(user.getBytes(Charsets.UTF_8)))) .put("status_code", response.getStatus()) .put("response_time_ms", timing)); } }
Source:
public List<String> missingClusterCpuFlags(String clusterCpuFlagsString, String serverFlagsString) { List<String> missingFlags = null; List<String> clusterFlags = StringUtils.isEmpty(clusterCpuFlagsString) ? new ArrayList<>() : Arrays.asList(clusterCpuFlagsString.split("[,]", -1)); Set<String> serverFlags = StringUtils.isEmpty(serverFlagsString) ? new HashSet<>() : new HashSet<>(Arrays.asList(serverFlagsString.split("[,]", -1))); for (String flag : clusterFlags) { if (!serverFlags.contains(flag)) { if (missingFlags == null) { missingFlags = new ArrayList<>(); } missingFlags.add(flag); } } return missingFlags; }

Target:
public List<String> missingClusterCpuFlags(String clusterCpuFlagsString, String serverFlagsString) { List<String> clusterFlags = StringUtils.isEmpty(clusterCpuFlagsString) ? Collections.emptyList() : Arrays.asList(clusterCpuFlagsString.split("[,]", -1)); Set<String> serverFlags = StringUtils.isEmpty(serverFlagsString) ? Collections.emptySet() : new HashSet<>(Arrays.asList(serverFlagsString.split("[,]", -1))); return clusterFlags.stream().filter(flag -> !serverFlags.contains(flag)).collect(Collectors.toList()); }
Source:
public void reload(Page page) { m_transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { reset(); List<T> beans = getItemsForCache(m_datasource, page); if (beans == null) return; int rowNumber = page.getStart(); for (T eachBean : beans) { addItem(rowNumber, getId(eachBean), eachBean); doItemAddedCallBack(rowNumber, getId(eachBean), eachBean); rowNumber++; } } }); }

Target:
public void reload(Page page) { reset(); List<T> beans = getItemsForCache(m_datasource, page); if (beans == null) return; int rowNumber = page.getStart(); for (T eachBean : beans) { addItem(rowNumber, getId(eachBean), eachBean); rowNumber++; } if (beans.size() != rowMap.size()) { throw new IllegalStateException("The cache is supposed to carry " + beans.size() + " but only contains " + rowMap.size() + " items."); } }
Source:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { MDC.put(REQUEST_ID, idGenerator.generate()); String loginName = appTokenParser.getLoginName(request); if (StringUtils.isNotEmpty(loginName)) { MDC.put(USER_ID, loginName); } return true; }

Target:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { MDC.put(REQUEST_ID, UUIDGenerator.generate()); String loginName = StringUtils.isNotEmpty(LoginUserInfo.getLoginName()) ? LoginUserInfo.getLoginName() : ANONYMOUS; MDC.put(USER_ID, loginName); return true; }
Source:
public void testNoSubText() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); verify(builderSpy, never()).setSubText("MESSAGE"); }

Target:
public void testNoSubText() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); Notification notification = mpPushSpy.createNotification(intent); verify(builderSpy, never()).setSubText(any(String.class)); }
Source:
void init() { if (mDbHelper == null || mDbHelper.getAppId() != ProviderUtils.getSeatedOrInstallingAppId()) { String dbName = ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.INSTANCES, ProviderUtils.getSeatedOrInstallingAppId()); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName); } }

Target:
void init() { String appId = ProviderUtils.getSandboxedAppId(); if (mDbHelper == null || mDbHelper.getAppId() != appId) { String dbName = ProviderUtils.getProviderDbName(ProviderUtils.ProviderType.INSTANCES, appId); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName, appId); } }
Source:
public ContentLengthNotMatchException(final String fileName, final long contentLenght, final long totalBytes) { super(String.format("The Content length for %s (%d) not match the number of byte read (%d)", fileName, contentLenght, totalBytes)); }

Target:
public ContentLengthNotMatchException(final String fileName, final long contentLenght, final long totalBytes) { super(String.format("The Content length for %s (%d) not match the number of byte read (%d)", fileName, contentLenght, totalBytes)); this.fileName = fileName; this.contentLenght = contentLenght; this.totalBytes = totalBytes; }
Source:
@Override public boolean next(List<Cell> result) throws IOException { try { boolean hasMore; do { hasMore = scanner.next(result); if (result.isEmpty()) { break; } numRowsScanned++; if (maskIfExpired && checkRowNotExpired(result)) { break; } if (deleteIfExpired && deleteRowIfExpired(result)) { numRowsDeleted++; break; } if (maskIfExpired) { numRowsExpired++; } result.clear(); } while (hasMore); return hasMore; } catch (Throwable t) { ServerUtil.throwIOException(region.getRegionInfo().getRegionNameAsString(), t); return false; } }

Target:
@Override public boolean next(List<Cell> result) throws IOException { return doNext(result, false); }
Source:
private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) { Environment result = new Environment(environment); for (PropertySource source : environment.getPropertySources()) { Map<Object, Object> map = new LinkedHashMap<Object, Object>( source.getSource()); for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) { Object key = entry.getKey(); String name = key.toString(); String value = null; if(entry.getValue() != null){ value = entry.getValue().toString(); } if (value != null && value.startsWith("{cipher}")) { map.remove(key); try { value = value.substring("{cipher}".length()); value = encryptor.locate( this.helper.getEncryptorKeys(name, StringUtils .arrayToCommaDelimitedString(environment .getProfiles()), value)).decrypt(this.helper.stripPrefix(value)); } catch (Exception e) { value = "<n/a>"; name = "invalid." + name; String message = "Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage() + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); } else if (logger.isWarnEnabled()) { logger.warn(message); } } map.put(name, value); } } result.add(new PropertySource(source.getName(), map)); } return result; }

Target:
private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) { Environment result = new Environment(environment); for (PropertySource source : environment.getPropertySources()) { Map<Object, Object> map = new LinkedHashMap<Object, Object>( source.getSource()); for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) { Object key = entry.getKey(); String name = key.toString(); if(entry.getValue() != null && entry.getValue().toString().startsWith("{cipher}")){ String value = entry.getValue().toString(); map.remove(key); try { value = value.substring("{cipher}".length()); value = encryptor.locate( this.helper.getEncryptorKeys(name, StringUtils .arrayToCommaDelimitedString(environment .getProfiles()), value)).decrypt(this.helper.stripPrefix(value)); } catch (Exception e) { value = "<n/a>"; name = "invalid." + name; String message = "Cannot decrypt key: " + key + " (" + e.getClass() + ": " + e.getMessage() + ")"; if (logger.isDebugEnabled()) { logger.debug(message, e); } else if (logger.isWarnEnabled()) { logger.warn(message); } } map.put(name, value); } } result.add(new PropertySource(source.getName(), map)); } return result; }
Source:
private VirtualFileGroupInterface setVirtualFileGroup(ProjectFileGroup projectFileGroup, VariableReplacer variableReplacer) { VirtualFileGroupInterface virtualFileGroupInterface = UghImplementation.INSTANCE.createVirtualFileGroup(); virtualFileGroupInterface.setName(projectFileGroup.getName()); virtualFileGroupInterface.setPathToFiles(variableReplacer.replace(projectFileGroup.getPath())); virtualFileGroupInterface.setMimetype(projectFileGroup.getMimeType()); virtualFileGroupInterface.setFileSuffix(projectFileGroup.getSuffix()); virtualFileGroupInterface.setOrdinary(!projectFileGroup.isPreviewImage()); return virtualFileGroupInterface; }

Target:
private VirtualFileGroupInterface setVirtualFileGroup(ProjectFileGroup projectFileGroup, VariableReplacer variableReplacer) { VirtualFileGroupInterface virtualFileGroup = UghImplementation.INSTANCE.createVirtualFileGroup(); virtualFileGroup.setName(projectFileGroup.getName()); virtualFileGroup.setPathToFiles(variableReplacer.replace(projectFileGroup.getPath())); virtualFileGroup.setMimetype(projectFileGroup.getMimeType()); virtualFileGroup.setFileSuffix(projectFileGroup.getSuffix()); virtualFileGroup.setOrdinary(!projectFileGroup.isPreviewImage()); return virtualFileGroup; }