auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { return traverseMapBySortedKeyOrder? new JacksonTraverseCallbackMapKeyOrdered(generator): new JacksonTraverseCallback(generator); }

Target:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { return new JacksonTraverseCallback(generator, traverseMapBySortedKeyOrder); }
Source:
static boolean isSingleItem(final Memory mem) { final boolean preLongs = extractPreLongs(mem) == 1; final boolean serVer = extractSerVer(mem) >= 3; final boolean famId = extractFamilyID(mem) == 3; final boolean flags = (extractFlags(mem) & 0x1F) == 0x1A; return preLongs && serVer && famId && flags; }

Target:
static boolean isSingleItem(final Memory mem) { final boolean preLongs = extractPreLongs(mem) == 1; final boolean serVer = extractSerVer(mem) >= 3; final boolean famId = extractFamilyID(mem) == Family.COMPACT.getID(); final boolean flags = (extractFlags(mem) & 0x1F) == 0x1A; return preLongs && serVer && famId && flags; }
Source:
public void setRefSpecs(RefSpec... specs) { this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); }

Target:
public FetchCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); return this; }
Source:
public Boolean ChangeState(String deviceId, Boolean newStateIsOn) { Reader reader = null; logger.debug( "Change state for device id '{}', new state is on: '{}'", deviceId, newStateIsOn); try { HttpURLConnection httpURLConnection; httpURLConnection = (HttpURLConnection) new URL(API_URL + "device/switch" + "?authToken=" + this.authToken + "&id=" + deviceId + "&on=" + newStateIsOn.toString()) .openConnection(); InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if(!status.equals("ok")){ String error = jsonObject.get("error").getAsString(); logger.error("Unable to switch state for device '{}' error '{}'", deviceId, error); return false; } String newState = jsonObject.get("state").getAsString(); logger.debug( "Switch state for device '{}' successfull, state is '{}'", deviceId, newState); return true; } catch(Exception ex) { logger.error("Error set state: '{}'", ex.toString()); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }

Target:
public Boolean ChangeState(String deviceId, Boolean newStateIsOn) { Reader reader = null; logger.debug("Change state for device id '{}', new state is on: '{}'", deviceId, newStateIsOn); try { String url = API_URL + "device/switch" + "?authToken=" + this.authToken + "&id=" + deviceId + "&on=" + newStateIsOn.toString(); HttpURLConnection httpURLConnection; httpURLConnection = (HttpURLConnection) new URL(url) .openConnection(); InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if (!status.equals("ok")) { String error = jsonObject.get("error").getAsString(); logger.error( "Unable to switch state for device '{}' error '{}'", deviceId, error); return false; } String newState = jsonObject.get("state").getAsString(); logger.debug( "Switch state for device '{}' successfull, state is '{}'", deviceId, newState); return true; } catch (Exception ex) { logger.error("Error set state: '{}'", ex.toString()); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }
Source:
public String decode(String encodedData) { String decodedData = ""; Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z\\s]"); Matcher matcher = pattern.matcher(encodedData); while (matcher.find()) { try { int number = Integer.parseInt(matcher.group()); matcher.find(); while (number-- != 0) { decodedData += matcher.group(); } } catch (NumberFormatException e) { decodedData += matcher.group(); } } return decodedData; }

Target:
public String decode(String encodedData) { StringBuilder decodedData = new StringBuilder(); Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z\\s]"); Matcher matcher = pattern.matcher(encodedData); while (matcher.find()) { try { int number = Integer.parseInt(matcher.group()); matcher.find(); for (int i = 0; i<number; i++) { decodedData.append(matcher.group()); } } catch (NumberFormatException e) { decodedData.append(matcher.group()); } } return decodedData.toString(); }
Source:
protected IConfigurationElement[] getConfigurationElements( String extensionPointId) { if (contributorId == null) { return new IConfigurationElement[0]; } IExtensionPoint point = Platform.getExtensionRegistry() .getExtensionPoint( TabbedPropertyViewPlugin.getPlugin().getBundle() .getSymbolicName(), extensionPointId); IConfigurationElement[] extensions = point.getConfigurationElements(); List unordered = new ArrayList(extensions.length); for (IConfigurationElement extension2 : extensions) { IConfigurationElement extension = extension2; if (!extension.getName().equals(extensionPointId)) { continue; } String contributor = extension.getAttribute(ATT_CONTRIBUTOR_ID); if (!contributorId.equals(contributor)) { continue; } unordered.add(extension); } return (IConfigurationElement[]) unordered .toArray(new IConfigurationElement[unordered.size()]); }

Target:
protected IConfigurationElement[] getConfigurationElements( String extensionPointId) { if (contributorId == null) { return new IConfigurationElement[0]; } IExtensionPoint point = Platform.getExtensionRegistry() .getExtensionPoint( TabbedPropertyViewPlugin.getPlugin().getBundle() .getSymbolicName(), extensionPointId); IConfigurationElement[] extensions = point.getConfigurationElements(); List unordered = new ArrayList(extensions.length); for (IConfigurationElement extension : extensions) { if (!extension.getName().equals(extensionPointId)) { continue; } String contributor = extension.getAttribute(ATT_CONTRIBUTOR_ID); if (!contributorId.equals(contributor)) { continue; } unordered.add(extension); } return (IConfigurationElement[]) unordered .toArray(new IConfigurationElement[unordered.size()]); }
Source:
public IContentProposal[] getProposals(final String contents, int position) { final List<RefContentProposal> result = new ArrayList<>(); if (contents.indexOf('*') != -1 || contents.indexOf('?') != -1) { if (isValidRefExpression(contents)) result.add(new RefContentProposal(localDb, contents, null, true)); final String regex = ".*" + contents.replace("*", ".*").replace("?", ".?") + ".*"; final Pattern p = Pattern.compile(regex); for (final RefContentProposal prop : proposals) if (p.matcher(prop.getContent()).matches()) result.add(prop); } else { for (final RefContentProposal prop : proposals) if (prop.getContent().contains(contents)) result.add(prop); if (tryResolvingLocally && result.isEmpty()) { final ObjectId id = tryResolveLocalRef(contents); if (id != null) result .add(new RefContentProposal(localDb, contents, id, false)); } } return result.toArray(new IContentProposal[0]); }

Target:
public IContentProposal[] getProposals(final String contents, int position) { final List<RefContentProposal> result = new ArrayList<>(); if (contents.indexOf('*') != -1 || contents.indexOf('?') != -1) { if (isValidRefExpression(contents)) { result.add(new RefContentProposal(localDb, contents, null, true)); } final String regex = ".*" + contents.replace("*", ".*").replace("?", ".?") + ".*"; final Pattern p = Pattern.compile(regex); for (final RefContentProposal prop : proposals) { if (p.matcher(prop.getContent()).matches()) { result.add(prop); } } } else { for (final RefContentProposal prop : proposals) { if (prop.getContent().contains(contents)) { result.add(prop); } } if (tryResolvingLocally && result.isEmpty()) { final ObjectId id = tryResolveLocalRef(contents); if (id != null) { result.add(new RefContentProposal(localDb, contents, id, false)); } } } return result.toArray(new IContentProposal[0]); }
Source:
public static void closeBufferedReader(BufferedReader stream, String tag){ if(stream!=null){ try { stream.close(); } catch (IOException e) { if (Constants.DEBUG_MODE_ENABLED) { Log.e(tag, "Exception occured when closing BufferedReader."+e); } } } }

Target:
public static void closeBufferedReader(BufferedReader stream, String tag) { if (stream != null) { try { stream.close(); } catch (IOException e) { Log.e(tag, "Exception occured when closing BufferedReader." + e); } } }
Source:
public void shouldHandleAnAuthorisedNotification_whenChargeIsInAuthorisationSubmittedState() throws Exception { String transactionId = "transaction-id"; String chargeId = createNewChargeWith(AUTHORISATION_SUBMITTED, transactionId); String epdqAuthorisedNotificationCode = "5"; String response = notifyConnector( transactionId, "1", epdqAuthorisedNotificationCode, getCredentials().get(CREDENTIALS_SHA_OUT_PASSPHRASE) ) .statusCode(200) .extract().body() .asString(); assertThat(response, is(RESPONSE_EXPECTED_BY_EPDQ)); assertFrontendChargeStatusIs(chargeId, AUTHORISATION_SUCCESS.getValue()); }

Target:
public void shouldHandleAnAuthorisedNotification_whenChargeIsInAuthorisationSubmittedState() throws Exception { String transactionId = "transaction-id"; String chargeId = createNewChargeWith(AUTHORISATION_SUBMITTED, transactionId); String epdqAuthorisedNotificationCode = EPDQ_AUTHORISED.getCode(); String response = notifyConnector( transactionId, "1", epdqAuthorisedNotificationCode, getCredentials().get(CREDENTIALS_SHA_OUT_PASSPHRASE) ) .statusCode(200) .extract().body() .asString(); assertThat(response, is(RESPONSE_EXPECTED_BY_EPDQ)); assertFrontendChargeStatusIs(chargeId, AUTHORISATION_SUCCESS.getValue()); }
Source:
protected void onLoad() { super.onLoad(); CallbackGroup cbs = new CallbackGroup(); ConfigServerApi.capabilities().get(cbs.add(new AsyncCallback<CapabilityMap>() { @Override public void onSuccess(CapabilityMap result) { capabilityMap = result; } @Override public void onFailure(Throwable caught) { } })); Util.PROJECT_SVC.projectAccess(getProjectKey(), cbs.addGwtjsonrpc(new ScreenLoadCallback<ProjectAccess>(this) { @Override public void preDisplay(ProjectAccess access) { displayReadOnly(access); } })); savedPanel = ACCESS; }

Target:
protected void onLoad() { super.onLoad(); CallbackGroup cbs = new CallbackGroup(); ConfigServerApi.capabilities( cbs.add(new AsyncCallback<NativeMap<CapabilityInfo>>() { @Override public void onSuccess(NativeMap<CapabilityInfo> result) { capabilityMap = result; } @Override public void onFailure(Throwable caught) { } })); Util.PROJECT_SVC.projectAccess(getProjectKey(), cbs.addGwtjsonrpc(new ScreenLoadCallback<ProjectAccess>(this) { @Override public void preDisplay(ProjectAccess access) { displayReadOnly(access); } })); savedPanel = ACCESS; }
Source:
public JiraRestService(URI uri, JiraRestClient jiraRestClient, String username, String password) { this.uri = uri; this.objectMapper = new ObjectMapper(); final String login = username + ":" + password; try { byte[] encodeBase64 = Base64.encodeBase64(login.getBytes("UTF-8")); this.authHeader = "Basic " + new String(encodeBase64, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.warning("jira rest encode username:password error. cause: " + e.getMessage()); throw new RuntimeException("failed to encode username:password using Base64"); } this.jiraRestClient = jiraRestClient; final StringBuilder buffer = new StringBuilder(); if (uri.getPath() != null) { buffer.append(uri.getPath()); if (!uri.getPath().endsWith("/")) { buffer.append('/'); } } else { buffer.append('/'); } buffer.append(BASE_API_PATH); baseApiPath = buffer.toString(); }

Target:
public JiraRestService(URI uri, JiraRestClient jiraRestClient, String username, String password) { this.uri = uri; this.objectMapper = new ObjectMapper(); final String login = username + ":" + password; try { byte[] encodeBase64 = Base64.encodeBase64(login.getBytes("UTF-8")); this.authHeader = "Basic " + new String(encodeBase64, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.warning("jira rest encode username:password error. cause: " + e.getMessage()); throw new RuntimeException("failed to encode username:password using Base64"); } this.jiraRestClient = jiraRestClient; final StringBuilder builder = new StringBuilder(); if (uri.getPath() != null) { builder.append(uri.getPath()); if (!uri.getPath().endsWith("/")) { builder.append('/'); } } else { builder.append('/'); } builder.append(BASE_API_PATH); baseApiPath = builder.toString(); }
Source:
protected Saver<AuthenticationResult> createInstance(ServletContext servletContext) throws Exception { Config config = ConfigResolver.INSTANCE.getConfig(servletContext); CookieConfig accessTokenCookieConfig = config.getAccessTokenCookieConfig(); CookieConfig refreshTokenCookieConfig = config.getRefreshTokenCookieConfig(); Resolver<Boolean> secureCookieRequired = config.getInstance(COOKIE_SECURE_RESOLVER); Application application = ApplicationResolver.INSTANCE.getApplication(servletContext); return new CookieAuthenticationResultSaver( accessTokenCookieConfig, refreshTokenCookieConfig, secureCookieRequired, application, ClientResolver.INSTANCE.getClient(servletContext) ); }

Target:
protected Saver<AuthenticationResult> createInstance(ServletContext servletContext) throws Exception { Config config = ConfigResolver.INSTANCE.getConfig(servletContext); CookieConfig accessTokenCookieConfig = config.getAccessTokenCookieConfig(); CookieConfig refreshTokenCookieConfig = config.getRefreshTokenCookieConfig(); Resolver<Boolean> secureCookieRequired = config.getInstance(COOKIE_SECURE_RESOLVER); return new CookieAuthenticationResultSaver( accessTokenCookieConfig, refreshTokenCookieConfig, secureCookieRequired ); }
Source:
public PalantirContent updateMapPosition(double lat, double lng, int zoom) { waitForElementVisibleByElement(mapFrame); driver.switchTo().activeElement(); JavascriptExecutor jsexec = (JavascriptExecutor) driver; driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS); Object res = jsexec.executeAsyncScript( PalantirContent.PONTO_UPDATEPOSITION, lat, lng, zoom ); PalantirContent handle = new PalantirContent(); try { JSONObject json = new JSONObject(res.toString()); handle.success = json.getString(PalantirContent.PONTO_MSG_SUCCESS); handle.responseCode = json.getString(PalantirContent.PONTO_MSG_RESPONSECODE); handle.message = json.getString(PalantirContent.PONTO_MSG_MESSAGE); PageObjectLogging.log( "updateMapPosition", handle.message, true ); }catch (JSONException e) { PageObjectLogging.log( "updateMapPosition", "Map position was not changed", true); } return handle; }

Target:
public PalantirContent updateMapPosition(double lat, double lng, int zoom) { waitForElementVisibleByElement(mapFrame); JavascriptExecutor jsexec = (JavascriptExecutor) driver; driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS); Object res = jsexec.executeAsyncScript( PalantirContent.PONTO_UPDATEPOSITION, lat, lng, zoom ); return getResponse(res, "updateMapPosition"); }
Source:
public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh() && model.getSsh().isSetPort() && model.getSsh().getPort() > 0) { entity.setSshPort(model.getSsh().getPort()); } else { entity.setSshPort(DEFAULT_SSH_PORT); } if (model.isSetSsh() && model.getSsh().isSetFingerprint()) { entity.setSshKeyFingerprint(model.getSsh().getFingerprint()); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }

Target:
public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh()) { map(model.getSsh(), entity); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }
Source:
public AuditEventName eventName(StructuredFlowEvent structuredEvent) { String flowEvent = structuredEvent.getFlow().getFlowEvent(); switch (flowEvent) { case "TERMINATION_EVENT": return AuditEventName.DATAHUB_CLUSTER_DELETION; case "START_CREATION_EVENT": return AuditEventName.DATAHUB_CLUSTER_CREATION; case "STACK_STOP_EVENT": return AuditEventName.DATAHUB_CLUSTER_STOPPAGE; case "STACK_START_EVENT": return AuditEventName.DATAHUB_CLUSTER_STARTING; case "CLUSTER_UPSCALE_TRIGGER_EVENT": case "DECOMMISSION_EVENT": return AuditEventName.DATAHUB_CLUSTER_RESIZING; case "MANUAL_STACK_REPAIR_TRIGGER_EVENT": return AuditEventName.DATAHUB_CLUSTER_MANUAL_REPAIR; case "DATAHUB_CLUSTER_SYNC":// we dont do this in a flow return AuditEventName.DATAHUB_CLUSTER_SYNC; case "DATAHUB_CLUSTER_RETRY": return AuditEventName.DATAHUB_CLUSTER_RETRY; case "DATAHUB_CLUSTER_INSTANCE_DELETION": return AuditEventName.DATAHUB_CLUSTER_INSTANCE_DELETION; case "START_VALIDATION_FLOW_EVENT": return AuditEventName.DATAHUB_CLUSTER_MAINTENANCE; } throw new UnsupportedOperationException(String.format("The `%s` does not support for auditing", flowEvent)); }

Target:
public AuditEventName eventName(StructuredFlowEvent structuredEvent) { FlowDetails flow = structuredEvent.getFlow(); String flowEvent = flow.getFlowEvent(); AuditEventName eventName = null; String resourceType = structuredEvent.getOperation().getResourceType(); FlowResourceAuditEventConverter flowResourceAuditEventConverter = getConverter(resourceType); if (flowResourceAuditEventConverter != null) { eventName = flowResourceAuditEventConverter.auditEventName(structuredEvent); } if (eventName != null) { return eventName; } String flowState = flow.getFlowState(); String flowType = flow.getFlowType(); throw new UnsupportedOperationException(String.format("The %s, %s and %s does not support for auditing for %s", flowType, flowEvent, flowState, resourceType)); }
Source:
protected void buildAndTag(ServiceHub hub, ImageConfiguration imageConfig) throws MojoExecutionException, IOException { EnvUtil.storeTimestamp(getBuildTimestampFile(), getBuildTimestamp()); BuildService.BuildContext buildContext = getBuildContext(); ImagePullManager pullManager = getImagePullManager(determinePullPolicy(imageConfig.getBuildConfiguration()), autoPull); BuildService buildService = hub.getBuildService(); File buildArchiveFile = buildService.buildArchive(imageConfig, buildContext, buildArchiveOnly); if (buildArchiveOnly.isEmpty() || buildArchiveOnly.equalsIgnoreCase(Boolean.FALSE.toString())) { buildService.buildImage(imageConfig, pullManager, buildContext, buildArchiveFile); } if (!skipTag) { buildService.tagImage(imageConfig.getName(), imageConfig); } }

Target:
protected void buildAndTag(ServiceHub hub, ImageConfiguration imageConfig) throws MojoExecutionException, IOException { EnvUtil.storeTimestamp(getBuildTimestampFile(), getBuildTimestamp()); BuildService.BuildContext buildContext = getBuildContext(); ImagePullManager pullManager = getImagePullManager(determinePullPolicy(imageConfig.getBuildConfiguration()), autoPull); BuildService buildService = hub.getBuildService(); File buildArchiveFile = buildService.buildArchive(imageConfig, buildContext, resolveBuildArchiveParameter()); if (Boolean.FALSE.equals(shallBuildArchiveOnly())) { buildService.buildImage(imageConfig, pullManager, buildContext, buildArchiveFile); } if (!skipTag) { buildService.tagImage(imageConfig.getName(), imageConfig); } }
Source:
public final void setup() throws Exception { if (inAS) return; File file = new File(System.getProperty("user.dir") + "/ObjectStore"); if (file.exists()) { Utils.removeRecursive(file.toPath()); } System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); System.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); namingBeanImpl = new NamingBeanImpl(); namingBeanImpl.start(); resetPropertiesFile = System .getProperty("com.arjuna.ats.arjuna.common.propertiesFile"); if (resetPropertiesFile == null || !resetPropertiesFile.equals("commitmarkableresourcejbossts-properties.xml")) { System.setProperty("com.arjuna.ats.arjuna.common.propertiesFile", "commitmarkableresourcejbossts-properties.xml"); } manager = RecoveryManager.manager(RecoveryManager.DIRECT_MANAGEMENT); }

Target:
public final void setup() throws Exception { if (inAS) return; File file = new File(System.getProperty("user.dir") + "/ObjectStore"); if (file.exists()) { Utils.removeRecursive(file.toPath()); } System.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); System.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); namingBeanImpl = new NamingBeanImpl(); namingBeanImpl.start(); resetPropertiesFile = System .getProperty("com.arjuna.ats.arjuna.common.propertiesFile"); System.setProperty("com.arjuna.ats.arjuna.common.propertiesFile", "commitmarkableresourcejbossts-properties.xml"); manager = RecoveryManager.manager(RecoveryManager.DIRECT_MANAGEMENT); }
Source:
public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout.getMillis(), s_logger); cmd.add("destroy_ovs_bridge"); cmd.add("--bridge", bridge); final String result = cmd.execute(); if (result != null) { s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result); return false; } return true; }

Target:
public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("destroy_ovs_bridge"); cmd.add("--bridge", bridge); final String result = cmd.execute(); if (result != null) { s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result); return false; } return true; }
Source:
public Table<String, String, Object> initializeAggregateValue(StructuredRecord record) { Table<String, String, Object> table = HashBasedTable.create(); table.put(SCHEMA, "", record.getSchema()); if (aggregateFunctions == null) { initAggregates(record.getSchema()); } updateAggregates(table, record); return table; }

Target:
public AggregateResult initializeAggregateValue(StructuredRecord record) { Map<String, AggregateFunction> functions = initAggregates(record.getSchema()); updateAggregates(functions, record); return new AggregateResult(record.getSchema(), functions); }
Source:
public Level getLevel(int id) throws IllegalArgumentException { switch (id) { case 1: return getLevel1(); case 2: return getLevel2(); case 3: return getLevel3(); case 4: return getLevel4(); case 5: return getBossLevel(); default: throw new IllegalArgumentException(); } }

Target:
public Level getLevel(int id) throws IllegalArgumentException { switch (id) { case 1: return getLevel1(); case 2: return getBossLevel(); case 3: return getLevel3(); case 4: return getLevel4(); case 5: return getLevel2(); default: throw new IllegalArgumentException(); } }
Source:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { throw new IOException("End of input while parsing object."); } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }

Target:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { return null; } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }
Source:
private boolean willChangeStatus(Item item) throws SQLException { List<ResourcePolicy> policies = authorizeService.getPoliciesActionFilter(context, item, Constants.READ); for (ResourcePolicy policy : policies) { if (policy.getGroup().getName().equals("Anonymous")) { System.out.println("found anonymous READ for item " + item.getID()); if (policy.getStartDate() != null && policy.getStartDate().after(new Date())) { System.out.println("policy has start date after current date: " + policy.getStartDate()); return true; } if (policy.getEndDate() != null && policy.getEndDate().after(new Date())) { System.out.println("policy has end date after current date: " + policy.getEndDate()); return true; } } } System.out.println("all policies processed for item " + item.getID() + "; based on current information, item will not change visibility in the future."); return false; }

Target:
private boolean willChangeStatus(Item item) throws SQLException { List<ResourcePolicy> policies = authorizeService.getPoliciesActionFilter(context, item, Constants.READ); for (ResourcePolicy policy : policies) { if (policy.getGroup().getName().equals("Anonymous")) { if (policy.getStartDate() != null && policy.getStartDate().after(new Date())) { return true; } if (policy.getEndDate() != null && policy.getEndDate().after(new Date())) { return true; } } } return false; }
Source:
public ImmutableRatesProviderBuilder overnightIndexCurve( OvernightIndex index, Curve forwardCurve, LocalDateDoubleTimeSeries timeSeries) { ArgChecker.notNull(index, "currency"); ArgChecker.notNull(forwardCurve, "forwardCurve"); ArgChecker.notNull(timeSeries, "timeSeries"); this.indexCurves.put(index, forwardCurve); this.timeSeries.put(index, timeSeries); return this; }

Target:
public ImmutableRatesProviderBuilder overnightIndexCurve( OvernightIndex index, Curve forwardCurve, LocalDateDoubleTimeSeries timeSeries) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(forwardCurve, "forwardCurve"); ArgChecker.notNull(timeSeries, "timeSeries"); this.indexCurves.put(index, forwardCurve); this.timeSeries.put(index, timeSeries); return this; }
Source:
public void flushCache(IDMContext context) { fCommandCache.reset(context); IMemoryDMContext memoryDMC = DMContexts.getAncestorOfType(context, IMemoryDMContext.class); if (fMemoryCaches.containsKey(memoryDMC)) { fMemoryCaches.get(memoryDMC).reset(); } }

Target:
public void flushCache(IDMContext context) { fCommandCache.reset(context); IMemoryDMContext memoryDMC = DMContexts.getAncestorOfType(context, IMemoryDMContext.class); if (memoryDMC != null) { memoryCacheReset(memoryDMC); } }
Source:
public void searchedAddress(VoterInfo voterInfo) { app.setVoterInfo(voterInfo); if (voterInfo != null) { Election el = voterInfo.election; String show = "Election:\n" + el.id + ": " + el.name + "\n" + el.electionDay + "\n\n"; State state = voterInfo.state.get(0); show += "State: " + state.name + "\n"; show += "Sources:\n" + state.sources.get(0).name; Log.d("HomeActivity", "Result: " + show); } else { Log.d("HomeActivity", "VoterInfo set to null"); } }

Target:
public void searchedAddress(VoterInfo voterInfo) { app.setVoterInfo(voterInfo); }
Source:
public static void main(String[] args) { if (args.length < 3) { System.out.println("Please specify your access key and call id and leg id and recording id example :" + " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final RecordingResponse recordings = messageBirdClient.listRecordings(callId, legId, 0, 0); if (recordings.getData() == null) { System.out.println("No record data found"); } for(int i = 0; i< recordings.getData().size(); i++) { System.out.println(recordings.getData().get(i).toString()); System.out.println(); } } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }

Target:
public static void main(String[] args) { if (args.length < 3) { System.out.println("Please specify your access key and call id and leg id example :" + " java -jar <this jar file> test_accesskey e8077d803532c0b5937c639b60216938 e8077d803532c0b5937c639b60216938"); return; } final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { System.out.println("Getting a recording"); final String callId = args[1]; final String legId = args[2]; final RecordingResponse recordings = messageBirdClient.listRecordings(callId, legId, 0, 0); if (recordings.getData() == null) { System.out.println("No record data found"); } for(int i = 0; i< recordings.getData().size(); i++) { System.out.println(recordings.getData().get(i).toString()); System.out.println(); } } catch (GeneralException | UnauthorizedException exception) { exception.printStackTrace(); } }
Source:
private void prepareWikipediaLanguagesList() { wikipediaLanguages.clear(); wikipediaLanguages.add(EMPTY_STRING); wikipediaLanguages.addAll(app.getAppLanguageCodes()); wikipediaLanguages.add(EMPTY_STRING); }

Target:
private void prepareWikipediaLanguagesList() { wikipediaLanguages.clear(); wikipediaLanguages.addAll(app.getAppLanguageCodes()); }
Source:
public BugzillaRestConnector(Duration refreshAfterWriteDuration) { super(); configurationCache = createCacheBuilder(CONFIGURATION_CACHE_EXPIRE_DURATION, refreshAfterWriteDuration).build( new CacheLoader<RepositoryKey, Optional<BugzillaRestConfiguration>>() { @Override public Optional<BugzillaRestConfiguration> load(RepositoryKey key) throws Exception { BugzillaRestClient client = clientCache.get(key); return Optional.fromNullable(client.getConfiguration(key.getRepository(), context.get())); } @Override public ListenableFuture<Optional<BugzillaRestConfiguration>> reload(final RepositoryKey key, Optional<BugzillaRestConfiguration> oldValue) throws Exception { ListenableFutureJob<Optional<BugzillaRestConfiguration>> job = new ListenableFutureJob("") { @Override protected IStatus run(IProgressMonitor monitor) { BugzillaRestClient client; try { client = clientCache.get(key); set(Optional.fromNullable(client.getConfiguration(key.getRepository(), context.get()))); } catch (ExecutionException e) { e.printStackTrace(); } return Status.OK_STATUS; } }; job.schedule(); return job; } }); }

Target:
public BugzillaRestConnector(Duration refreshAfterWriteDuration) { super(); configurationCache = createCacheBuilder(CONFIGURATION_CACHE_EXPIRE_DURATION, refreshAfterWriteDuration).build( new CacheLoader<RepositoryKey, Optional<BugzillaRestConfiguration>>() { @Override public Optional<BugzillaRestConfiguration> load(RepositoryKey key) throws Exception { BugzillaRestClient client = clientCache.get(key); return Optional.fromNullable(client.getConfiguration(key.getRepository(), context.get())); } @Override public ListenableFuture<Optional<BugzillaRestConfiguration>> reload(final RepositoryKey key, Optional<BugzillaRestConfiguration> oldValue) throws Exception { ListenableFutureJob<Optional<BugzillaRestConfiguration>> job = new ListenableFutureJob("") { @Override protected IStatus run(IProgressMonitor monitor) { BugzillaRestClient client; try { client = clientCache.get(key); set(Optional.fromNullable(client.getConfiguration(key.getRepository(), context.get()))); } catch (ExecutionException e) { e.printStackTrace(); return new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "BugzillaRestConnector reload Configuration", e); } return Status.OK_STATUS; } }; job.schedule(); return job; } }); }
Source:
public void onPiglinDropItem(EntityDropItemEvent e) { if (e.getEntity() instanceof Piglin) { Set<ItemStack> drops = SlimefunPlugin.getRegistry().getBarterDrops(); for (ItemStack is : drops) { SlimefunItem sfi = SlimefunItem.getByItem(is); if (sfi instanceof RandomMobDrop && ((RandomMobDrop)sfi).getMobDropChance() >= ThreadLocalRandom.current().nextInt(100)) { Item drop = e.getEntity().getWorld().dropItemNaturally(((Piglin)e.getEntity()).getEyeLocation(), sfi.getItem()); drop.setVelocity(e.getItemDrop().getVelocity()); e.getItemDrop().remove(); return; } } } }

Target:
public void onPiglinDropItem(EntityDropItemEvent e) { if (e.getEntity() instanceof Piglin) { Piglin piglin = (Piglin) e.getEntity(); Set<ItemStack> drops = SlimefunPlugin.getRegistry().getBarterDrops(); for (ItemStack is : drops) { SlimefunItem sfi = SlimefunItem.getByItem(is); if (sfi instanceof PiglinBarterDrop && ((PiglinBarterDrop)sfi).getBarteringLootChance() > ThreadLocalRandom.current().nextInt(100)) { e.getItemDrop().setItemStack(sfi.getItem().clone()); return; } } } }
Source:
public QName(final String namespaceURI, final String localPart, final String prefix) { if (Objects.isNull(namespaceURI)) { setNamespaceURI(XMLConstants.NULL_NS_URI); } else { setNamespaceURI(namespaceURI); } if (Objects.isNull(localPart)) { throw new IllegalArgumentException("local part cannot be \"null\" when creating a QName"); } setLocalPart(localPart); if (Objects.isNull(prefix)) { throw new IllegalArgumentException("prefix cannot be \"null\" when creating a QName"); } setPrefix(prefix); setKey(toString()); String retrievedPrefix = getPrefix(); final String usedPrefix = (retrievedPrefix == null || retrievedPrefix.isEmpty()) ? "" : retrievedPrefix + ":"; final String string = "{" + getNamespaceURI() + "}" + usedPrefix + getLocalPart(); setString(string); }

Target:
public QName(final String namespaceURI, final String localPart, final String prefix) { if (Objects.isNull(namespaceURI)) { setNamespaceURI(XMLConstants.NULL_NS_URI); } else { setNamespaceURI(namespaceURI); } if (Objects.isNull(localPart)) { throw new IllegalArgumentException("local part cannot be \"null\" when creating a QName"); } setLocalPart(localPart); if (Objects.isNull(prefix)) { throw new IllegalArgumentException("prefix cannot be \"null\" when creating a QName"); } setPrefix(prefix); setKey(toString()); String retrievedPrefix = getPrefix(); final String usedPrefix = (retrievedPrefix == null || retrievedPrefix.trim().isEmpty()) ? "" : retrievedPrefix + ":"; final String string = "{" + getNamespaceURI() + "}" + usedPrefix + getLocalPart(); setString(string); }
Source:
public T create(BeanInstance beanInstance) { try { final T instance = super.create(beanInstance); if (beanIdField == null) { final Field f = AccessController.doPrivileged(new GetDeclaredFieldAction(instance.getClass(), BEAN_ID_FIELD)); AccessController.doPrivileged(SetAccessibleAction.of(f)); beanIdField = f; } if (contextIdField == null) { final Field f = AccessController.doPrivileged(new GetDeclaredFieldAction(instance.getClass(), CONTEXT_ID_FIELD)); AccessController.doPrivileged(SetAccessibleAction.of(f)); contextIdField = f; } beanIdField.set(instance, beanId); contextIdField.set(instance, contextId); return instance; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (PrivilegedActionException e) { throw new RuntimeException(e.getCause()); } }

Target:
public T create(BeanInstance beanInstance) { try { final T instance = super.create(beanInstance); if (beanIdField == null) { final Field f = AccessController.doPrivileged(new GetDeclaredFieldAction(instance.getClass(), BEAN_ID_FIELD)); AccessController.doPrivileged(SetAccessibleAction.of(f)); beanIdField = f; } if (contextIdField == null) { final Field f = AccessController.doPrivileged(new GetDeclaredFieldAction(instance.getClass(), CONTEXT_ID_FIELD)); AccessController.doPrivileged(SetAccessibleAction.of(f)); contextIdField = f; } beanIdField.set(instance, beanId); contextIdField.set(instance, getContextId()); return instance; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (PrivilegedActionException e) { throw new RuntimeException(e.getCause()); } }
Source:
public void writeCheckpoint(TaskName taskName, Checkpoint checkpoint) { if (!taskNames.contains(taskName)) { throw new SamzaException("writing checkpoint of unregistered task"); } TableBatchOperation batchOperation = new TableBatchOperation(); checkpoint.getOffsets().forEach((ssp, offset) -> { TaskCheckpointEntity taskCheckpoint = new TaskCheckpointEntity(taskName.toString(), serializeSystemStreamPartition(ssp)); taskCheckpoint.setOffset(offset); batchOperation.insertOrReplace(taskCheckpoint); if (batchOperation.size() >= MAX_WRITE_BATCH_SIZE) { try { cloudTable.execute(batchOperation); } catch (StorageException e) { LOG.error("Executing batch failed for task: {}", taskName); throw new AzureException(e); } batchOperation.clear(); } }); if (batchOperation.size() > 0) { try { cloudTable.execute(batchOperation); } catch (StorageException e) { LOG.error("Executing batch failed for task: {}", taskName); throw new AzureException(e); } } }

Target:
public void writeCheckpoint(TaskName taskName, Checkpoint checkpoint) { if (!taskNames.contains(taskName)) { throw new SamzaException("writing checkpoint of unregistered task"); } TableBatchOperation batchOperation = new TableBatchOperation(); Iterator<Map.Entry<SystemStreamPartition, String>> iterator = checkpoint.getOffsets().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<SystemStreamPartition, String> entry = iterator.next(); SystemStreamPartition ssp = entry.getKey(); String offset = entry.getValue(); TaskCheckpointEntity taskCheckpoint = new TaskCheckpointEntity(taskName.toString(), serializeSystemStreamPartition(ssp), offset); batchOperation.insertOrReplace(taskCheckpoint); if (batchOperation.size() >= MAX_WRITE_BATCH_SIZE || !iterator.hasNext()) { try { cloudTable.execute(batchOperation); } catch (StorageException e) { LOG.error("Executing batch failed for task: {}", taskName); throw new AzureException(e); } batchOperation.clear(); } } }
Source:
public void evaluate() throws Throwable { if (this.timeout == 0) { this.next.evaluate(); } else { long startTime = System.currentTimeMillis(); Exception failure = null; try { this.next.evaluate(); } catch (Exception e){ failure = e; } finally { long elapsed = System.currentTimeMillis() - startTime; if (elapsed > this.timeout) { TimeoutException timeoutException = new TimeoutException( String.format("Test took %s ms; limit was %s ms.", elapsed, this.timeout)); if(failure != null && timeoutException.getCause() == null){ timeoutException.initCause(failure); } throw timeoutException; } } } }

Target:
public void evaluate() throws Throwable { if (this.timeout == 0) { this.next.evaluate(); } else { long startTime = System.currentTimeMillis(); this.next.evaluate(); long elapsed = System.currentTimeMillis() - startTime; if (elapsed > this.timeout) { throw new TimeoutException( String.format("Test took %s ms; limit was %s ms.", elapsed, this.timeout)); } } }
Source:
public BlockInsert chooseBlock() { synchronized(cooldownLock) { synchronized(this) { if(status == Status.FAILED || status == Status.SUCCEEDED || status == Status.GENERATING_METADATA || failing != null) return null; } for (int i = 0; i < segments.length; i++) { int j = random.nextInt(segments.length - i) + i; int chosen = segmentIndexPermutation[j]; segmentIndexPermutation[j] = segmentIndexPermutation[i]; segmentIndexPermutation[i] = chosen; BlockInsert ret = segments[chosen].chooseBlock(); if(ret != null) { noBlocksToSend = false; return ret; } } noBlocksToSend = true; return null; } }

Target:
public BlockInsert chooseBlock() { synchronized(cooldownLock) { synchronized(this) { if (status == Status.FAILED || status == Status.SUCCEEDED || status == Status.GENERATING_METADATA || failing != null) { return null; } } randomSegmentIterator.reset(random); while (randomSegmentIterator.hasNext()) { SplitFileInserterSegmentStorage segment = randomSegmentIterator.next(); BlockInsert ret = segment.chooseBlock(); if (ret != null) { noBlocksToSend = false; return ret; } } noBlocksToSend = true; return null; } }
Source:
void createPerPipelineMetrics(Pipeline pipeline) { System.out.println("add pipeline " + pipeline.getId() + " to metrics map"); numBlocksAllocated.put(pipeline.getId(), new MutableCounterLong(Interns .info(getBlockAllocationMetricName(pipeline), "Number of blocks allocated in pipeline " + pipeline.getId()), 0L)); }

Target:
void createPerPipelineMetrics(Pipeline pipeline) { numBlocksAllocated.put(pipeline.getId(), new MutableCounterLong(Interns .info(getBlockAllocationMetricName(pipeline), "Number of blocks allocated in pipeline " + pipeline.getId()), 0L)); }
Source:
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction, CredentialsException { init(context); final String username = credentials.getUsername(); final String password = credentials.getPassword(); if (CommonHelper.isBlank(username) || CommonHelper.isBlank(password)) { logger.error("Empty username or password"); return; } final String body = callRestApi(username, password); logger.debug("body: {}", body); if (body != null) { buildProfile(credentials, body); } }

Target:
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws HttpAction, CredentialsException { init(context); final String username = credentials.getUsername(); final String password = credentials.getPassword(); if (CommonHelper.isBlank(username) || CommonHelper.isBlank(password)) { logger.info("Empty username or password"); return; } final String body = callRestApi(username, password); logger.debug("body: {}", body); if (body != null) { buildProfile(credentials, body); } }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); textViewTitle.setText(discussionTopic.getTitle()); textViewResponse.setText(Html.fromHtml(discussionTopic.getRenderedBody())); textViewTimeAuthor.setText(DiscussionTextUtils.getAuthorAttributionText(discussionTopic, getResources(), discussionTopic.getType() == DiscussionThread.ThreadType.DISCUSSION ? DiscussionTextUtils.AuthorAttributionType.DISCUSSION : DiscussionTextUtils.AuthorAttributionType.QUESTION)); buttonAddComment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createComment(); } }); buttonAddComment.setEnabled(false); editTextNewComment.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { buttonAddComment.setEnabled(s.toString().trim().length() > 0); } }); }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); textViewTitle.setText(discussionTopic.getTitle()); textViewResponse.setText(Html.fromHtml(discussionTopic.getRenderedBody())); textViewTimeAuthor.setText(DiscussionTextUtils.getAuthorAttributionText(discussionTopic, getResources())); buttonAddComment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createComment(); } }); buttonAddComment.setEnabled(false); editTextNewComment.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { buttonAddComment.setEnabled(s.toString().trim().length() > 0); } }); }
Source:
public AirMapGroundOverlay build() { return new AirMapGroundOverlay(id, bounds, imageUrl, imageId, bitmap, bearing, zIndex, visible); }

Target:
public AirMapGroundOverlay build() { if (imageId == 0 && imageUrl == null) { throw new IllegalStateException("You should provide an imageId or an imageUrl to your ground overlay."); } return new AirMapGroundOverlay(id, bounds, imageUrl, imageId, bitmap, bearing, zIndex, visible); }
Source:
public int getOrCreateVertexNear(double lat, double lon, StreetMode streetMode) { Split split = findSplit(lat, lon, LINK_RADIUS_METERS, streetMode); if (split == null) { return -1; } Edge edge = edgeStore.getCursor(split.edge); if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { return edge.getFromVertex(); } else { return edge.getToVertex(); } } int newVertexIndex = vertexStore.addVertexFixed((int) split.fixedLat, (int) split.fixedLon); int oldToVertex = edge.getToVertex(); ArrayList<int[]> geoms = new ArrayList<>(); if (edge.isMutable()) { edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); geoms = edge.splitGeometryAfter(split.seg); edge.setGeometry(geoms.get(0)); } else { EdgeStore.Edge newEdge0 = edgeStore.addStreetPair(edge.getFromVertex(), newVertexIndex, split.distance0_mm, edge.getOSMID()); newEdge0.copyPairFlagsAndSpeeds(edge); temporaryEdgeIndex.insert(newEdge0.getEnvelope(), newEdge0.edgeIndex); edgeStore.temporarilyDeletedEdges.add(edge.edgeIndex); } EdgeStore.Edge newEdge1 = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); newEdge1.copyPairFlagsAndSpeeds(edge); if (geoms.size() > 1) newEdge1.setGeometry(geoms.get(1)); if (!edgeStore.isExtendOnlyCopy()) { spatialIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } else { temporaryEdgeIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } return newVertexIndex; }

Target:
public int getOrCreateVertexNear(double lat, double lon, StreetMode streetMode) { Split split = findSplit(lat, lon, LINK_RADIUS_METERS, streetMode); if (split == null) { return -1; } Edge edge = edgeStore.getCursor(split.edge); if (split.distance0_mm < SNAP_RADIUS_MM || split.distance1_mm < SNAP_RADIUS_MM) { if (split.distance0_mm < split.distance1_mm) { return edge.getFromVertex(); } else { return edge.getToVertex(); } } int newVertexIndex = vertexStore.addVertexFixed((int) split.fixedLat, (int) split.fixedLon); int oldToVertex = edge.getToVertex(); P2<int[]> geoms = edge.splitGeometryAfter(split.seg); if (edge.isMutable()) { edge.setLengthMm(split.distance0_mm); edge.setToVertex(newVertexIndex); edge.setGeometry(geoms.a); } else { EdgeStore.Edge newEdge0 = edgeStore.addStreetPair(edge.getFromVertex(), newVertexIndex, split.distance0_mm, edge.getOSMID()); newEdge0.copyPairFlagsAndSpeeds(edge); newEdge0.setGeometry(geoms.a); temporaryEdgeIndex.insert(newEdge0.getEnvelope(), newEdge0.edgeIndex); edgeStore.temporarilyDeletedEdges.add(edge.edgeIndex); } EdgeStore.Edge newEdge1 = edgeStore.addStreetPair(newVertexIndex, oldToVertex, split.distance1_mm, edge.getOSMID()); newEdge1.copyPairFlagsAndSpeeds(edge); newEdge1.setGeometry(geoms.b); if (!edgeStore.isExtendOnlyCopy()) { spatialIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } else { temporaryEdgeIndex.insert(newEdge1.getEnvelope(), newEdge1.edgeIndex); } return newVertexIndex; }