auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void updateEnsembleInfo( AsyncCallback.VoidCallback ensembleUpdatedCb, long fragmentStartId, LedgerHandle lh, Map<BookieSocketAddress, BookieSocketAddress> oldBookie2NewBookie) { List<BookieSocketAddress> ensemble = lh.getLedgerMetadata().getEnsembles().get(fragmentStartId); List<BookieSocketAddress> newEnsemble = new ArrayList<>(ensemble); for (Map.Entry<BookieSocketAddress, BookieSocketAddress> entry : oldBookie2NewBookie.entrySet()) { int deadBookieIndex = newEnsemble.indexOf(entry.getKey()); if (deadBookieIndex >= 0) { newEnsemble.set(deadBookieIndex, entry.getValue()); } else { LOG.info("Bookie doesn't exist in ensemble anymore.", entry.getKey(), ensemble); } } List<BookieSocketAddress> immutable = ImmutableList.copyOf(newEnsemble); lh.getLedgerMetadata().updateEnsemble(fragmentStartId, immutable); lh.writeLedgerConfig(new UpdateEnsembleCb(ensembleUpdatedCb, fragmentStartId, lh, oldBookie2NewBookie)); }

Target:
private static void updateEnsembleInfo( AsyncCallback.VoidCallback ensembleUpdatedCb, long fragmentStartId, LedgerHandle lh, Map<BookieSocketAddress, BookieSocketAddress> oldBookie2NewBookie) { List<BookieSocketAddress> ensemble = lh.getLedgerMetadata().getEnsembles().get(fragmentStartId); List<BookieSocketAddress> newEnsemble = new ArrayList<>(ensemble); for (Map.Entry<BookieSocketAddress, BookieSocketAddress> entry : oldBookie2NewBookie.entrySet()) { int deadBookieIndex = newEnsemble.indexOf(entry.getKey()); if (deadBookieIndex >= 0) { newEnsemble.set(deadBookieIndex, entry.getValue()); } else { LOG.info("Bookie doesn't exist in ensemble anymore.", entry.getKey(), ensemble); } } lh.getLedgerMetadata().updateEnsemble(fragmentStartId, newEnsemble); lh.writeLedgerConfig(new UpdateEnsembleCb(ensembleUpdatedCb, fragmentStartId, lh, oldBookie2NewBookie)); }
Source:
public Iterable<Issue> issues( @NotNull(message = "Search keywords can't be NULL") final String keywords, @NotNull(message = "Sort field can't be NULL") final String sort, @NotNull(message = "Sort order can't be NULL") final String order) throws IOException { return new RtPagination<Issue>( RtSearch.searchRequest( this.entry, "/search/issues", keywords, sort, order ), new RtPagination.Mapping<Issue>() { @Override public Issue map(final JsonObject object) { try { final String[] parts = RtSearch.SLASH.split( new URI(object.getString("url")).getPath() ); return new RtIssue( RtSearch.this.entry, new RtRepo( RtSearch.this.ghub, RtSearch.this.entry, new Coordinates.Simple(parts[2], parts[3]) ), object.getInt("number") ); } catch (final URISyntaxException ex) { throw new IllegalStateException(ex); } } } ); }

Target:
public Iterable<Issue> issues( @NotNull(message = "Search keywords can't be NULL") final String keywords, @NotNull(message = "Sort field can't be NULL") final String sort, @NotNull(message = "Sort order can't be NULL") final String order) throws IOException { return new RtSearchPagination<Issue>( this.request, "issues", keywords, sort, order, new RtPagination.Mapping<Issue, JsonObject>() { @Override public Issue map(final JsonObject object) { try { final String[] parts = RtSearch.SLASH.split( new URI(object.getString("url")).getPath() ); return RtSearch.this.ghub.repos().get( new Coordinates.Simple(parts[2], parts[3]) ).issues().get(object.getInt("number")); } catch (final URISyntaxException ex) { throw new IllegalStateException(ex); } } } ); }
Source:
public Object getParent(Object object, IMergeViewerItemProviderConfiguration configuration) { return ResourceAttachmentChangeMergeViewerItem.class.cast(object).getParent(); }

Target:
public Object getParent(Object object, IMergeViewerItemProviderConfiguration configuration) { return ((ResourceAttachmentChangeMergeViewerItem)object).getParent(); }
Source:
public PlanWithProperties visitStatisticsWriterNode(StatisticsWriterNode node, PreferredProperties context) { PlanWithProperties child = planChild(node, PreferredProperties.any()); if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType().equals(GATHER)) { return rebaseAndDeriveProperties(node, child); } if (!child.getProperties().isSingleNode() || !child.getProperties().isCoordinatorOnly()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }

Target:
public PlanWithProperties visitStatisticsWriterNode(StatisticsWriterNode node, PreferredProperties context) { PlanWithProperties child = planChild(node, PreferredProperties.any()); if ((child.getNode() instanceof ExchangeNode) && ((ExchangeNode) child.getNode()).getType().equals(GATHER)) { return rebaseAndDeriveProperties(node, child); } if (!child.getProperties().isCoordinatorOnly()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }
Source:
public void upload(InputStream input, OutputStream output, @Nullable OutputStream messages) throws IOException { PacketLineOut pckOut = null; try { rawIn = input; if (messages != null) msgOut = messages; if (timeout > 0) { final Thread caller = Thread.currentThread(); timer = new InterruptTimer(caller.getName() + "-Timer"); TimeoutInputStream i = new TimeoutInputStream(rawIn, timer); @SuppressWarnings("resource") TimeoutOutputStream o = new TimeoutOutputStream(output, timer); i.setTimeout(timeout * 1000); o.setTimeout(timeout * 1000); rawIn = i; output = o; } rawOut = new ResponseBufferedOutputStream(output); if (biDirectionalPipe) { rawOut.stopBuffering(); } pckIn = new PacketLineIn(rawIn); pckOut = new PacketLineOut(rawOut); if (useProtocolV2()) { serviceV2(pckOut); } else { service(pckOut); } } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { errOut.writeError(err.getMessage()); } catch (IOException e) { err.addSuppressed(e); throw err; } err.setOutput(); } throw err; } catch (IOException | RuntimeException | Error err) { if (pckOut != null) { String msg = err instanceof PackProtocolException ? err.getMessage() : JGitText.get().internalServerError; try { errOut.writeError(msg); } catch (IOException e) { err.addSuppressed(e); throw err; } throw new UploadPackInternalServerErrorException(err); } throw err; } finally { msgOut = NullOutputStream.INSTANCE; walk.close(); if (timer != null) { try { timer.terminate(); } finally { timer = null; } } } }

Target:
public void upload(InputStream input, OutputStream output, @Nullable OutputStream messages) throws IOException { PacketLineOut pckOut = null; try { rawIn = input; if (messages != null) msgOut = messages; if (timeout > 0) { final Thread caller = Thread.currentThread(); timer = new InterruptTimer(caller.getName() + "-Timer"); TimeoutInputStream i = new TimeoutInputStream(rawIn, timer); @SuppressWarnings("resource") TimeoutOutputStream o = new TimeoutOutputStream(output, timer); i.setTimeout(timeout * 1000); o.setTimeout(timeout * 1000); rawIn = i; output = o; } rawOut = new ResponseBufferedOutputStream(output); if (biDirectionalPipe) { rawOut.stopBuffering(); } pckIn = new PacketLineIn(rawIn); pckOut = new PacketLineOut(rawOut); if (useProtocolV2()) { serviceV2(pckOut); } else { service(pckOut); } } catch (UploadPackInternalServerErrorException err) { throw err; } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { errOut.writeError(err.getMessage()); } catch (IOException e) { err.addSuppressed(e); throw err; } err.setOutput(); } throw err; } catch (IOException | RuntimeException | Error err) { if (rawOut != null) { String msg = err instanceof PackProtocolException ? err.getMessage() : JGitText.get().internalServerError; try { errOut.writeError(msg); } catch (IOException e) { err.addSuppressed(e); throw err; } throw new UploadPackInternalServerErrorException(err); } throw err; } finally { msgOut = NullOutputStream.INSTANCE; walk.close(); if (timer != null) { try { timer.terminate(); } finally { timer = null; } } } }
Source:
public boolean retryRequest(IOException e, int retryCount, HttpContext httpContext) { if (e instanceof InterruptedIOException) { LOGGER.debug("Connection timeout."); } if (e instanceof UnknownHostException) { LOGGER.warn("Solr Client: Unknown host."); } if (e instanceof SSLException) { LOGGER.warn("Solr Client: SSL handshake exception."); } LOGGER.debug("Connection failed", e); try { long waitTime = (long) Math.pow(2, Math.min(retryCount, MAX_RETRY_COUNT)) * 50; if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Solr Client: Connection failed, waiting before retrying.", DurationFormatUtils.formatDurationWords(waitTime, true, true)); } synchronized (this) { wait(waitTime); } } catch (InterruptedException ie) { LOGGER.debug("Exception while waiting.", ie); Thread.currentThread().interrupt(); } return true; }

Target:
public boolean retryRequest(IOException e, int retryCount, HttpContext httpContext) { if (e instanceof InterruptedIOException) { LOGGER.debug("Connection timeout."); } if (e instanceof UnknownHostException) { LOGGER.warn("Solr Client: Unknown host."); } if (e instanceof SSLException) { LOGGER.warn("Solr Client: SSL handshake exception."); } LOGGER.debug("Connection failed", e); try { long waitTime = (long) Math.pow(2, Math.min(retryCount, MAX_RETRY_COUNT)) * 50; if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Solr Client: Connection failed, waiting before retrying.", DurationFormatUtils.formatDurationWords(waitTime, true, true)); } synchronized (this) { wait(waitTime); } } catch (InterruptedException ie) { LOGGER.debug("Exception while waiting.", ie); } return true; }
Source:
public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState.equals(ConnectionState.RECONNECTED)) { LOG.info("Reconnected to zookeeper, checking if configs are still in sync"); Optional<String> maybeLastRequestForGroup = loadBalancerDatastore.getLastRequestForGroup(configuration.getLoadBalancerConfiguration().getName()); if (!maybeLastRequestForGroup.isPresent() || !maybeLastRequestForGroup.get().equals(mostRecentRequestId.get())) { agentState.set(BaragonAgentState.BOOTSTRAPING); reapplyConfigsWithRetry(); agentState.set(BaragonAgentState.ACCEPTING); } } else if (newState.equals(ConnectionState.SUSPENDED) || newState.equals(ConnectionState.LOST)) { agentState.set(BaragonAgentState.DISCONNECTED); } }

Target:
public void stateChanged(CuratorFramework client, ConnectionState newState) { switch (newState) { case RECONNECTED: LOG.info("Reconnected to zookeeper, checking if configs are still in sync"); Optional<String> maybeLastRequestForGroup = loadBalancerDatastore.getLastRequestForGroup(configuration.getLoadBalancerConfiguration().getName()); if (!maybeLastRequestForGroup.isPresent() || !maybeLastRequestForGroup.get().equals(mostRecentRequestId.get())) { agentState.set(BaragonAgentState.BOOTSTRAPING); reapplyConfigsWithRetry(); } agentState.set(BaragonAgentState.ACCEPTING); break; case SUSPENDED: case LOST: agentState.set(BaragonAgentState.DISCONNECTED); break; case CONNECTED: agentState.set(BaragonAgentState.ACCEPTING); break; default: break; } }
Source:
public double getProgressionFactor() { final double extent = this.max - (double) this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) / extent; }

Target:
public double getProgressionFactor() { final int extent = this.max - this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) / extent; }
Source:
public Iterable<InstanceType> listHardwareProfiles() { final ImmutableSet.Builder<String> instanceTypeIds = ImmutableSet.builder(); final List<String> availableLocationNames = newArrayList( transform(listLocations(), new Function<Region, String>() { @Override public String apply(Region location) { return location.id(); } })); for (String regionId : availableLocationNames) { instanceTypeIds.addAll(getInstanceTypeId(regionId)); } List<InstanceType> instanceTypes = FluentIterable.from(api.instanceApi().listTypes()) .filter(new Predicate<InstanceType>() { @Override public boolean apply(@Nullable InstanceType input) { return contains(instanceTypeIds.build(), input.instanceTypeId()); } }).toList(); return instanceTypes; }

Target:
public Iterable<InstanceType> listHardwareProfiles() { final ImmutableSet.Builder<String> instanceTypeIdsBuilder = ImmutableSet.builder(); for (String regionId : getAvailableLocationNames()) { instanceTypeIdsBuilder.addAll(getInstanceTypeIds(regionId)); } final Set<String> ids = instanceTypeIdsBuilder.build(); List<InstanceType> instanceTypes = FluentIterable.from(api.instanceApi().listTypes()) .filter(new Predicate<InstanceType>() { @Override public boolean apply(@Nullable InstanceType input) { return contains(ids, input.id()); } }).toList(); return instanceTypes; }
Source:
public String serializeRaw(Object object) { final ClientLogger logger = new ClientLogger(JacksonAdapter.class); if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize to JSON.", object.getClass()); return null; } }

Target:
public String serializeRaw(Object object) { if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize to JSON.", object.getClass(), ex); return null; } }
Source:
public SolenoidSet(String name, SolenoidSubsystem system, SolenoidState state, BooleanSupplier... booleanSuppliers) { this.system = system; this.state = state; this.booleanSuppliers = booleanSuppliers; requirements = Set.of((Subsystem) system); }

Target:
public SolenoidSet(String name, SolenoidSubsystem system, SolenoidState state, BooleanSupplier... booleanSuppliers) { super(); setName(name); this.system = system; this.state = state; this.booleanSuppliers = booleanSuppliers; addRequirements(system); }
Source:
String getAzureContainerName(String partitionPath) { String rawContainerName = clusterName + SEPARATOR + partitionPath; return rawContainerName.toLowerCase(); }

Target:
private String getAzureContainerName(String partitionPath) { String rawContainerName = clusterName + SEPARATOR + partitionPath; return rawContainerName.toLowerCase(); }
Source:
public void generateConstantFieldDeclaration(VariableElement fieldElement) { if (isConstant(fieldElement)) { String constantValue = determineFinalConstantValue(fieldElement); if (constantValue != null) { Set<Modifier> modifiers = fieldElement.getModifiers(); println(" {0}{1} {2} = {3};", generateModifierList(modifiers.toArray(new Modifier[modifiers.size()])), fieldElement.asType().toString(), fieldElement.getSimpleName(), constantValue ); } else { Set<Modifier> modifiers = fieldElement.getModifiers(); println(" {0}{1} {2};", generateModifierList(modifiers.toArray(new Modifier[modifiers.size()])), fieldElement.asType().toString(), fieldElement.getSimpleName() ); } } }

Target:
public void generateConstantFieldDeclaration(VariableElement fieldElement) { if (isConstant(fieldElement)) { String constantValue = determineFinalConstantValue(fieldElement); Set<Modifier> modifiers = fieldElement.getModifiers(); String modifierList = generateModifierList(modifiers.toArray(new Modifier[modifiers.size()])); if (constantValue != null) { println(" {0}{1} {2} = {3};", modifierList, fieldElement.asType().toString(), fieldElement.getSimpleName(), constantValue ); } else { println(" {0}{1} {2};", modifierList, fieldElement.asType().toString(), fieldElement.getSimpleName() ); } } }
Source:
public static void validatePassword(String password, JsonMapper jsonMapper) { String authValidateUrl = AUTH_VALIDATE_URL.get(); if (!StringUtils.isBlank(authValidateUrl)) { try { Map<String, String> data = new HashMap<String, String>(); data.put("secret", password); String jsonString = jsonMapper.writeValueAsString(data); HttpResponse response = Request.Post(authValidateUrl).bodyString(jsonString, ContentType.APPLICATION_JSON).execute().returnResponse(); if (response.getStatusLine().getStatusCode() >=400 && response.getStatusLine().getStatusCode() <= 499) { Map<String, Object> jsonData; jsonData = jsonMapper.readValue(response.getEntity().getContent()); if (!jsonData.containsKey("type") || !jsonData.containsKey("message")) { throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "Incomplete JSON response"); } if (jsonData.get("type") != null) { throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, (String) jsonData.get("message")); } } else { if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) { throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "Error talking to validator"); } } } catch (IOException e) { throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "No response from validator"); } } }

Target:
public static void validatePassword(String password, JsonMapper jsonMapper) { String authValidateUrl = AUTH_VALIDATE_URL.get(); if (StringUtils.isBlank(authValidateUrl)) { return; } Map<String, String> data = new HashMap<String, String>(); data.put("secret", password); String jsonString = ""; Integer code; HttpResponse response = null; try { jsonString = jsonMapper.writeValueAsString(data); } catch (IOException e) { log.error("Error in creating json for POST request", e); } try { response = Request.Post(authValidateUrl).bodyString(jsonString, ContentType.APPLICATION_JSON).execute().returnResponse(); } catch (IOException e) { log.error("Error sending POST request", e); throw new ClientVisibleException(ResponseCodes.BAD_REQUEST, "Error sending POST request"); } code = response.getStatusLine().getStatusCode(); if (code >=400 && code <= 499) { Map<String, Object> jsonData = new HashMap<String, Object>(); try { jsonData = jsonMapper.readValue(response.getEntity().getContent()); } catch (IOException e) { log.error("No JSON response from validator", e); } if (!jsonData.containsKey("type") || !jsonData.containsKey("message")) { throw new ClientVisibleException(code, "Incomplete JSON response"); } if (jsonData.get("type") != null) { throw new ClientVisibleException(code, (String) jsonData.get("message")); } } else if (code < 200 || code > 299) { throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "Error talking to validator"); } }
Source:
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String sessionId = (String) request.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (sessionId == null) { throw new ServletException("Engine session missing"); } Current current = new Current(); current.setSessionId(sessionId); current.setApplicationMode(findApplicationMode(sessionId)); current.setUser(findPrincipal(sessionId)); current.setRoot(getRoot(request)); current.setPrefix(getPrefix(request)); current.setPath(getPath(request)); current.setBackend(backend); CorrelationIdTracker.fromRequest(request, response); CurrentManager.put(current); try { chain.doFilter(request, response); } finally { CurrentManager.remove(); } }

Target:
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String sessionId = (String) request.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (sessionId == null) { throw new ServletException("Engine session missing"); } Current current = new Current(); current.setSessionId(sessionId); current.setApplicationMode(findApplicationMode(sessionId)); current.setUser(findPrincipal(sessionId)); current.setRoot(getRoot(request)); current.setPrefix(getPrefix(request)); current.setPath(getPath(request)); current.setBackend(backend); fromRequest(request, response, current); CurrentManager.put(current); try { chain.doFilter(request, response); } finally { CurrentManager.remove(); } }
Source:
public MetricValueForCommit[] get(GetMetricsForCommitCommand command, Long projectId) { if (getProjectPort.existsById(projectId)) { return getMetricValuesOfCommitPort.get(command, projectId); } else { throw new ProjectNotFoundException(projectId); } }

Target:
public List<MetricValueForCommit> get(GetMetricsForCommitCommand command, Long projectId) { if (getProjectPort.existsById(projectId)) { return getMetricValuesOfCommitPort.get(command, projectId); } else { throw new ProjectNotFoundException(projectId); } }
Source:
public void processElement(ProcessContext context) throws IOException { if (context.element() != null) { if (converter == null) { AvroRegistry registry = new AvroRegistry(); converter = registry.createIndexedRecordConverter(context.element().getClass()); } IndexedRecord input = (IndexedRecord) converter.convertToAvro(context.element()); if (schema == null) { schema = input.getSchema(); } if (reader == null) { reader = new GenericDatumReader<>(schema); } if (MapType.MAP.equals(properties.mapType.getValue())) { map(input, context); } else { flatMap(input, context); } } python.cleanup(); }

Target:
public void processElement(ProcessContext context) throws IOException { if (context.element() != null) { if (converter == null) { AvroRegistry registry = new AvroRegistry(); converter = registry.createIndexedRecordConverter(context.element().getClass()); } IndexedRecord input = (IndexedRecord) converter.convertToAvro(context.element()); if (MapType.MAP.equals(properties.mapType.getValue())) { map(input, context); } else { flatMap(input, context); } } python.cleanup(); }
Source:
public FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate) { return new LazyFluentIterable<TYPE>() { @Override public Iterator<TYPE> iterator() { return new DecoratingIterator<TYPE>(iterable.iterator()) { @Override public TYPE computeNext() { while(true) { if(fromIterator.hasNext()) { TYPE candidate = fromIterator.next(); if(!predicate.test(candidate)) { continue; } return candidate; } return null; } } }; } }; }

Target:
public FluentIterable<TYPE> filter(Predicate<? super TYPE> predicate) { return new LazyFluentIterable<TYPE>() { @Override public Iterator<TYPE> iterator() { return new DecoratingIterator<TYPE>(iterable.iterator()) { @Override public TYPE computeNext() { while (fromIterator.hasNext()) { TYPE candidate = fromIterator.next(); if (!predicate.test(candidate)) { continue; } return candidate; } return null; } }; } }; }
Source:
@Test void createAsyncIdentityClientUsingConnectionString() { asyncClient = getCommunicationIdentityClientUsingConnectionString().buildAsyncClient(); assertNotNull(asyncClient); Mono<CommunicationUser> response = asyncClient.createUser(); String id = response.block().getId(); assertNotNull(id); assertFalse(id.isEmpty()); }

Target:
public void createAsyncIdentityClientUsingConnectionString() { asyncClient = getCommunicationIdentityClientUsingConnectionString().buildAsyncClient(); assertNotNull(asyncClient); Mono<CommunicationUser> response = asyncClient.createUser(); String id = response.block().getId(); assertNotNull(id); assertFalse(id.isEmpty()); }
Source:
public void postCommit() { switch (state()) { case RUNNING: case RESTORING: commitNeeded = false; commitRequested = false; if (eosDisabled) { stateMgr.checkpoint(checkpointableOffsets()); } log.info("Committed"); break; default: throw new IllegalStateException("Illegal state " + state() + " while post committing active task " + id); } }

Target:
public void postCommit() { switch (state()) { case RUNNING: commitNeeded = false; commitRequested = false; if (eosDisabled) { stateMgr.checkpoint(checkpointableOffsets()); } log.info("Committed"); break; case RESTORING: commitNeeded = false; commitRequested = false; stateMgr.checkpoint(checkpointableOffsets()); log.info("Committed"); break; default: throw new IllegalStateException("Illegal state " + state() + " while post committing active task " + id); } }
Source:
private boolean canPrefixApply(String fieldName, String prefix) { final int prefixLength = prefix.length(); return prefixLength == 0 || fieldName.startsWith(prefix) && fieldName.length() > prefixLength && (!Character.isLetter(prefix.charAt(prefix.length() - 1)) || Character.isUpperCase(fieldName.charAt(prefixLength)) || Character.isDigit(fieldName.charAt(prefixLength))); }

Target:
private boolean canPrefixApply(String fieldName, String prefix) { final int prefixLength = prefix.length(); return prefixLength == 0 || fieldName.startsWith(prefix) && fieldName.length() > prefixLength && (!Character.isLetter(prefix.charAt(prefix.length() - 1)) || !Character.isLowerCase(fieldName.charAt(prefixLength))); }
Source:
private static void checkGeometryToBingTilesLimits(OGCGeometry geometry, boolean pointOrRectangle, int tileCount) { if (pointOrRectangle) { checkCondition(tileCount <= 1_000_000, "The number of input tiles is too large (more than 1M) to compute a set of covering bing tiles."); } else { long complexity = (long) tileCount * getPointCount(geometry.getEsriGeometry()); checkCondition(complexity <= 25_000_000, "The zoom level is too high or the geometry is too complex to compute a set of covering bing tiles. " + "Please use a lower zoom level or convert the geometry to its bounding box using the ST_Envelope function."); } }

Target:
private static void checkGeometryToBingTilesLimits(OGCGeometry geometry, boolean pointOrRectangle, int tileCount) { if (pointOrRectangle) { checkCondition(tileCount <= 1_000_000, "The number of input tiles is too large (more than 1M) to compute a set of covering bing tiles."); } else { long complexity = ((long) tileCount) * getPointCount(geometry.getEsriGeometry()); checkCondition(complexity <= 25_000_000, "The zoom level is too high or the geometry is too complex to compute a set of covering bing tiles. " + "Please use a lower zoom level or convert the geometry to its bounding box using the ST_Envelope function."); } }
Source:
private void fetchVmsStatus(Guid storageDomainId, List<StorageOvfExtraData> storageExtraData, Map<String, Object> diskDescriptionMap) { Map<String, String> vmsStatus = (Map<String, String>) diskDescriptionMap.get(OvfInfoFileConstants.VmStatus); if (vmsStatus == null) { log.error("VMs status could not be fetched from metadata json file for storage id '{}'.", storageDomainId); } else { for (Map.Entry<String, String> entry : vmsStatus.entrySet()) { log.debug("VM '{}' fetched from metadata json file with status '{}' for storage domain id '{}.", entry.getKey(), entry.getValue(), storageDomainId); storageExtraData.add(new StorageOvfExtraData(storageDomainId, VdcObjectType.VM, storageDomainId, vmsStatus.get(entry.getKey()))); } } }

Target:
private void fetchVmsStatus(Guid storageDomainId, List<StorageOvfExtraData> storageExtraData, Map<String, Object> diskDescriptionMap) { Map<String, String> vmsStatus = (Map<String, String>) diskDescriptionMap.get(OvfInfoFileConstants.VmStatus); if (vmsStatus == null) { log.error("VMs status could not be fetched from metadata json file for storage id '{}'.", storageDomainId); } else { for (Map.Entry<String, String> entry : vmsStatus.entrySet()) { log.debug("VM '{}' fetched from metadata json file with status '{}' for storage domain id '{}.", entry.getKey(), entry.getValue(), storageDomainId); storageExtraData.add(new StorageOvfExtraData(storageDomainId, VdcObjectType.VM, Guid.createGuidFromString(entry.getKey()), vmsStatus.get(entry.getKey()))); } } }
Source:
public void testCreateProjectCheckGoodName() throws Exception{ String xmlFile = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<project>\n" + "<description></description>\n" + "<keepDependencies>false</keepDependencies>\n" + "<properties/>\n" + "<triggers/>\n" + "<concurrentBuild>false</concurrentBuild>\n" + "<builders/>\n" + "<publishers/>\n" + "<buildWrappers/>\n" + "</project>"; String[] illegalNames = {"ab\\c", "abc/", "ab/c", "", " ", " ", "..", ".", "?", "*", "6%", "x!", "-@", "#", "$", "^", "&", "|", "<", ">", "[", "]", ":", ";", "../.", null}; Jenkins j = Jenkins.getInstance(); int created = 0; for (String name : illegalNames){ try{ InputStream is = new ByteArrayInputStream(xmlFile.getBytes()); j.createProjectFromXML(name, is); created++; } catch (Failure e){ assertEquals(Failure.class, e.getClass()); } catch (IOException e){ assertEquals(IOException.class, e.getClass()); } } for (String name : illegalNames){ try{ j.createProject(FreeStyleProject.class, name); created++; } catch (Failure e){ assertEquals(Failure.class, e.getClass()); } catch (IOException e){ assertEquals(IOException.class, e.getClass()); } } assertEquals(0, created); }

Target:
public void testCreateProjectCheckGoodName() throws Exception{ String xmlFile = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<project>\n" + "<description></description>\n" + "<keepDependencies>false</keepDependencies>\n" + "<properties/>\n" + "<triggers/>\n" + "<concurrentBuild>false</concurrentBuild>\n" + "<builders/>\n" + "<publishers/>\n" + "<buildWrappers/>\n" + "</project>"; String[] illegalNames = {"ab\\c", "abc/", "ab/c", "", " ", " ", "..", ".", "?", "*", "6%", "x!", "-@", "#", "$", "^", "&", "|", "<", ">", "[", "]", ":", ";", "../.", null}; Jenkins j = Jenkins.getInstance(); int created = 0; for (String name : illegalNames){ try{ InputStream is = new ByteArrayInputStream(xmlFile.getBytes()); j.createProjectFromXML(name, is); created++; } catch (IOException e){} } for (String name : illegalNames){ try{ j.createProject(FreeStyleProject.class, name); created++; } catch (IOException e){} } assertEquals(0, created); }
Source:
public Timestamp getSessionCreatedTime(String key, String type) { Timestamp timestamp = null; if (!enablePersist) { return timestamp; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_TIME_CREATED); preparedStatement.setString(1, key); preparedStatement.setString(2, type); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { timestamp = resultSet.getTimestamp(1); } if (preparedStatement != null) { preparedStatement.close(); } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return timestamp; }

Target:
public Timestamp getSessionCreatedTime(String key, String type) { Timestamp timestamp = null; if (!enablePersist) { return timestamp; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_TIME_CREATED); preparedStatement.setString(1, key); preparedStatement.setString(2, type); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { timestamp = resultSet.getTimestamp(1); } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return timestamp; }
Source:
public void foo() { Properties props = new Properties(); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session s = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username@gmail.com", "password"); } }); }

Target:
public void foo() { Properties props = new Properties(); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }
Source:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, true); node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }

Target:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, false); node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }
Source:
public void readValues() { SML_File smlFile = null; do { clearValueCache(); if(connector == null){ logger.error(this.toString() + " connector is not instantiated"); break; } try { smlFile = connector.getMeterValues(); } catch(ConnectorException ex) { logger.error(this.toString() + ": Error during receive values from device: " + ex.getMessage()); break; } populateValueCache(smlFile); }while (false); }

Target:
public void readValues() { SML_File smlFile = null; do { clearValueCache(); if(connector == null){ logger.error("{}: connector is not instantiated", this.toString()); break; } try { smlFile = connector.getMeterValues(); } catch(Exception ex) { logger.error("{}: Error during receive values from device: {}", this.toString(), ex.getMessage()); break; } populateValueCache(smlFile); }while (false); }
Source:
public void testStarted(Description description){ Log.i("test started", description.getDisplayName()); if(description.isTest()) { currentTest = new TestResults(description.getDisplayName()); } else { currentTest = null; } }

Target:
public void testStarted(Description description){ Log.i("Test started", description.getDisplayName()); if(description.isTest()) { currentTest = new TestResults(description.getDisplayName()); } else { currentTest = null; } }
Source:
public String toString() { return "TaskSummary{" + "description='" + description + '\'' + ", status='" + status + '\'' + ", priority=" + priority + ", actualOwner='" + actualOwner + '\'' + ", createdBy='" + createdBy + '\'' + ", createdOn=" + createdOn + ", activationTime=" + activationTime + ", expirationTime=" + expirationTime + ", lastModificationDate=" + lastModificationDate + ", processInstanceId=" + processInstanceId + ", processInstanceCorrelationKey='" + processInstanceCorrelationKey + '\'' + ", processInstanceDescription='" + processInstanceDescription + '\'' + ", processId='" + processId + '\'' + ", errorCount=" + errorCount + ", deploymentId='" + deploymentId + '\'' + ", isForAdmin=" + isForAdmin + ", isLogOnly=" + isLogOnly + ", parentId=" + parentId + ", domainData=" + domainData + "} " + super.toString(); }

Target:
public String toString() { return "TaskSummary{" + "description='" + description + '\'' + ", status='" + status + '\'' + ", priority=" + priority + ", actualOwner='" + actualOwner + '\'' + ", createdBy='" + createdBy + '\'' + ", createdOn=" + createdOn + ", activationTime=" + activationTime + ", expirationTime=" + expirationTime + ", lastModificationDate=" + lastModificationDate + ", processInstanceId=" + processInstanceId + ", processInstanceCorrelationKey='" + processInstanceCorrelationKey + '\'' + ", processInstanceDescription='" + processInstanceDescription + '\'' + ", processId='" + processId + '\'' + ", deploymentId='" + deploymentId + '\'' + ", isForAdmin=" + isForAdmin + ", isLogOnly=" + isLogOnly + ", parentId=" + parentId + ", domainData=" + domainData + "} " + super.toString(); }
Source:
public List<ExchangeDownloadStatus> refreshExchangeManager() { LOG.info("force the exchangeManager to refresh: {}"); ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }

Target:
public List<ExchangeDownloadStatus> refreshExchangeManager() { ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }
Source:
private String getUrl() throws CoreException { String urlString = null; IServer server = getServer(); if(server!=null && server.getServerState() == IServer.STATE_STARTED) { ModuleServer ms = getModuleServer(); if(ms!=null) { urlString = getWelcomePageURL(ms); } else { ServerExtendedProperties props = (ServerExtendedProperties)server.loadAdapter(ServerExtendedProperties.class, new NullProgressMonitor()); if( props != null ) { try { urlString = props.getWelcomePageUrl(); } catch (GetWelcomePageURLException e) { Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openWarning( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "No Welcome URL to Show", e.getMessage()); } }); } } } } return urlString; }

Target:
private String getUrl() throws CoreException { String urlString = null; IServer server = getServer(); if(server!=null && server.getServerState() == IServer.STATE_STARTED) { ModuleServer ms = getModuleServer(); if(ms!=null) { urlString = getWelcomePageURL(ms); } else { ServerExtendedProperties props = (ServerExtendedProperties)server.loadAdapter(ServerExtendedProperties.class, new NullProgressMonitor()); if( props != null ) { try { urlString = props.getWelcomePageUrl(); } catch (GetWelcomePageURLException e) { if(e.getCause() != null) { JBossServerUIPlugin.log(new Status(IStatus.WARNING, JBossServerUIPlugin.PLUGIN_ID, "No URL found for current selection '" + server.getName() + "'.")); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openWarning( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "No URL found for current selection", e.getMessage()); } }); } } } } return urlString; }
Source:
private void transitionToMain() { Thread.dumpStack(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); }

Target:
private void transitionToMain() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); }
Source:
public void testRetainUntilDateSaved() throws InterruptedException { RetentionRule testRule = createManualImmediateRuleMillis(100L); file = service.attachRule(file, testRule, session); Calendar original = file.getRetainUntil(); awaitRetentionExpiration(1000L); Record record = session.getDocument(file.getRef()).getAdapter(Record.class); Calendar saved = record.getSavedRetainUntil(); assertNotNull(saved); assertEquals(original.getTimeInMillis(), saved.getTimeInMillis()); }

Target:
public void testRetainUntilDateSaved() throws InterruptedException { RetentionRule testRule = createManualImmediateRuleMillis(100); file = service.attachRule(file, testRule, session); Calendar original = file.getRetainUntil(); awaitRetentionExpiration(1000); Record record = session.getDocument(file.getRef()).getAdapter(Record.class); Calendar saved = record.getSavedRetainUntil(); assertNotNull(saved); assertEquals(original.getTimeInMillis(), saved.getTimeInMillis()); }
Source:
cfg != null ? cfg.getBoolean(ENABLE_AST_RBE_PNAME, ENABLE_AST_RBE_DEFAULT) : ENABLE_AST_RBE_DEFAULT; private static final long SS_THRESHOLD = 30; private final RemoteBitrateObserver observer; private int minBitrateBps = -1; private int astExtensionID = -1; private int tccExtensionID = -1; private boolean supportsRemb = false; private boolean usingAbsoluteSendTime = false; private int packetsSinceAbsoluteSendTime = 0; private RemoteBitrateEstimator rbe; private final DiagnosticContextProvider diagnosticContextProvider; public RemoteBitrateEstimatorWrapper( RemoteBitrateObserver observer, DiagnosticContextProvider diagnosticContextProvider) { this.observer = observer; this.rbe = new RemoteBitrateEstimatorSingleStream( observer, diagnosticContextProvider); this.diagnosticContextProvider = diagnosticContextProvider; }

Target:
cfg != null ? cfg.getBoolean(ENABLE_AST_RBE_PNAME, ENABLE_AST_RBE_DEFAULT) : ENABLE_AST_RBE_DEFAULT; private static final long SS_THRESHOLD = 30; private final RemoteBitrateObserver observer; private int minBitrateBps = -1; private int astExtensionID = -1; private int tccExtensionID = -1; private boolean supportsRemb = false; private boolean usingAbsoluteSendTime = false; private int packetsSinceAbsoluteSendTime = 0; private RemoteBitrateEstimator rbe; private final DiagnosticContext diagnosticContext; public RemoteBitrateEstimatorWrapper( RemoteBitrateObserver observer, @NotNull DiagnosticContext diagnosticContext) { this.observer = observer; this.diagnosticContext = diagnosticContext; this.rbe = new RemoteBitrateEstimatorSingleStream( observer, diagnosticContext); }
Source:
private JobEventMonitor removeJobEvent(JobId id, SchedulerEvent event) { JobEventMonitor tmp = new JobEventMonitor(event, id); if (jobsEvents.containsKey(id) && jobsEvents.get(id).contains(tmp)) { return jobsEvents.get(id).remove((jobsEvents.get(id).indexOf(tmp))); } else return null; }

Target:
private Optional<JobEventMonitor> removeJobEvent(JobId id, SchedulerEvent event) { JobEventMonitor tmp = new JobEventMonitor(event, id); if (jobsEvents.containsKey(id) && jobsEvents.get(id).contains(tmp)) { return Optional.of(jobsEvents.get(id).remove((jobsEvents.get(id).indexOf(tmp)))); } else return Optional.empty(); }
Source:
public void testTokenRenewal_Enabled_WithConfigurableMaxTokenLifetime() throws Exception { final String caller = "yarn"; Pair<TestTokenStateService, Response> testResult = doTestTokenRenewal(true, caller, 10L, createTestSubject(caller)); TestTokenStateService tss = testResult.getLeft(); assertEquals(1, tss.issueTimes.size()); String token = tss.issueTimes.keySet().iterator().next(); assertEquals(10L, tss.getMaxLifetime(token) - tss.getIssueTime(token)); }

Target:
public void testTokenRenewal_Enabled_WithConfigurableMaxTokenLifetime() throws Exception { final String caller = "yarn"; Map.Entry<TestTokenStateService, Response> testResult = doTestTokenRenewal(true, caller, 10L, createTestSubject(caller)); TestTokenStateService tss = testResult.getKey(); assertEquals(1, tss.issueTimes.size()); String token = tss.issueTimes.keySet().iterator().next(); assertEquals(10L, tss.getMaxLifetime(token) - tss.getIssueTime(token)); }
Source:
UserAgent() { String version = UNKNOWN_VERSION; try { ; Properties props = new Properties(); props.load(UserAgent.class.getResourceAsStream(VERSION_TXT)); version = props.getProperty("version", UNKNOWN_VERSION); } catch (Throwable t) { LOG.warn("Could not resolve 'VERSION' for user-agent"); } this.agentName = PREFIX + " (" + version + ")"; }

Target:
UserAgent() { String version = UNKNOWN_VERSION; try { ; Properties props = new Properties(); props.load(UserAgent.class.getResourceAsStream(VERSION_TXT)); version = props.getProperty("version", UNKNOWN_VERSION); } catch (Throwable t) { LOG.warn("Could not resolve 'VERSION' for user-agent"); } this.agentName = PREFIX + "/" + version; }
Source:
protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select id, prop_key from properties " + " where prop_key like ?") .setString(1, "%" + LICENSE_HASH_SECURED_SUFFIX); massUpdate.update("delete from properties where prop_key = ? or prop_key = ?"); massUpdate.rowPluralName("old license properties"); massUpdate.execute((row, update) -> { String key = row.getString(2); String prefix = key.replace(LICENSE_HASH_SECURED_SUFFIX, ""); update.setString(1, key); update.setString(2, prefix + LICENSE_SECURED_SUFFIX); return true; }); }

Target:
protected void execute(Context context) throws SQLException { MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select prop_key from properties where prop_key like ?") .setString(1, "%" + LICENSE_HASH_SECURED_SUFFIX); massUpdate.update("delete from properties where prop_key = ? or prop_key = ?"); massUpdate.rowPluralName("old license properties"); massUpdate.execute((row, update) -> { String licenseHashKey = row.getString(1); String licenseKey = licenseHashKey.replace(LICENSE_HASH_SECURED_SUFFIX, "") + LICENSE_SECURED_SUFFIX; update.setString(1, licenseHashKey); update.setString(2, licenseKey); return true; }); }
Source:
static URL[] getClasspathAsURLs(File jarsLocation) { validateCanAccess(jarsLocation); File[] filesInJarsLocation = jarsLocation.listFiles(); if (filesInJarsLocation == null) { throw new SamzaException( String.format("Could not find any files inside %s, probably because it is not a directory", jarsLocation.getPath())); } URL[] urls = Stream.of(filesInJarsLocation) .filter(file -> file.getName().endsWith(".jar") || file.getName().endsWith(".war")) .map(IsolatingClassLoaderFactory::fileURL) .toArray(URL[]::new); LOG.info("Found items to load into classpath from {}", urls.length, jarsLocation); return urls; }

Target:
static URL[] getClasspathAsURLs(File jarsLocation) { validateCanAccess(jarsLocation); File[] filesInJarsLocation = jarsLocation.listFiles(); if (filesInJarsLocation == null) { throw new SamzaException( String.format("Could not find any files inside %s, probably because it is not a directory", jarsLocation.getPath())); } URL[] urls = Stream.of(filesInJarsLocation) .filter(file -> file.getName().endsWith(".jar") || file.getName().endsWith(".war")) .map(IsolatingClassLoaderFactory::fileURL) .toArray(URL[]::new); LOG.info("Found items to load into classpath from {}", urls.length, jarsLocation); Stream.of(urls).forEach(url -> LOG.debug("Found from {}", url, jarsLocation)); return urls; }
Source:
private String getQualifiedClassName(DetailAST classAst) { final String className = classAst.findFirstToken(TokenTypes.IDENT).getText(); String outerClassQualifiedName = null; if (currentDepthLevel > 1) { final Iterator<ClassDesc> iterator = classes.iterator(); while (outerClassQualifiedName == null) { final ClassDesc desc = iterator.next(); if (desc.depthLevel == currentDepthLevel - 1) { outerClassQualifiedName = desc.qualifiedName; } } } return getQualifiedClassName(packageName, outerClassQualifiedName, className); }

Target:
private String getQualifiedClassName(DetailAST classAst) { final String className = classAst.findFirstToken(TokenTypes.IDENT).getText(); String outerClassQualifiedName = null; for (ClassDesc desc : classes) { if (desc.depthLevel == currentDepthLevel - 1) { outerClassQualifiedName = desc.getQualifiedName(); break; } } return getQualifiedClassName(packageName, outerClassQualifiedName, className); }
Source:
public void addData(final String key, final byte[] data) { ModelNode dataNode = get(SECRET_DATA); if (dataNode == null) { dataNode = new ModelNode(); get(SECRET_DATA).set(dataNode); } dataNode.get(key).set(Base64Coder.encode(data)); }

Target:
public void addData(final String key, final byte[] data) { ModelNode dataNode = get(SECRET_DATA); dataNode.get(key).set(Base64Coder.encode(data)); }