auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected Map<String, Object> removeSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { int locationId = params.getInt("locationId"); CitationCollection collection = getCitationCollection(state, false); errorMessage = getCitationValidator().getRemoveSectionErrorMessage(collection, locationId); if (errorMessage==null){ getCitationService().removeLocation(collection.getId(), locationId); message = rb.getString("resource.updated"); results.put("sectionToRemove", "#sectionInlineEditor" + locationId); <START> logger.info("Reading list successfully updated."); <END> } else { message = errorMessage; logger.warn("Invalid citation list in removeSection(). " + errorMessage); } state.setAttribute(STATE_CITATION_COLLECTION, null); } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in removeSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }</code><technical_language>Logging messages for change is a verbose, log debug include details of citation updated section removed</technical_language>

Target:
protected Map<String, Object> removeSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { int locationId = params.getInt("locationId"); CitationCollection collection = getCitationCollection(state, false); errorMessage = getCitationValidator().getRemoveSectionErrorMessage(collection, locationId); if (errorMessage==null){ getCitationService().removeLocation(collection.getId(), locationId); message = rb.getString("resource.updated"); results.put("sectionToRemove", "#sectionInlineEditor" + locationId); logger.debug("Reading list with collection id: " + collection.getId() + " successfully updated. Section removed at location: " + locationId); } else { message = errorMessage; logger.warn("Invalid citation list with collection id: " + collection.getId() + " in removeSection(). " + errorMessage); } state.setAttribute(STATE_CITATION_COLLECTION, null); } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in removeSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }
Source:
<code>public QueryInterruptedException(Throwable cause) { super(cause); host = null; <START> causeMessage = null; <END> }</code><technical_language>set cause.getMessage()</technical_language>

Target:
public QueryInterruptedException(Throwable cause) { this(cause, null); }
Source:
<code>protected SafeHtml getImageSafeHtml(IconType iconType) { <START> return SafeHtmlUtils.fromTrustedString("<i class='fa "+ iconType.getCssName() + END> "' style='font-size:16px;color:orange'></i>"); }</code><technical_language>ApplicationTemplates store this html? (I'm top of head if GWT is ok a template {0} a class= I ok</technical_language>

Target:
protected SafeHtml getImageSafeHtml(IconType iconType) { return AssetProvider.getTemplates().iconTypeAlertTemplate(iconType.getCssName()); }
Source:
<code>public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) { String transactionManagerRef = source.getAttribute("transactionManagerRef"); builder.addPropertyValue("transactionManager", transactionManagerRef == null ? DEFAULT_TRANSACTION_MANAGER_BEAN_NAME : transactionManagerRef); String entityManagerFactoryRef = getEntityManagerFactoryRef(source); if (entityManagerFactoryRef != null) { builder.addPropertyValue("entityManager", getEntityManagerBeanDefinitionFor(entityManagerFactoryRef, source)); } builder.addPropertyReference("mappingContext", JPA_MAPPING_CONTEXT_BEAN_NAME); String expressionEvaluationContextProviderRef = source.getAttribute("expressionEvaluationContextProviderRef"); <START> if (StringUtils.hasText(expressionEvaluationContextProviderRef)) { <END> builder.addPropertyReference(DEFAULT_EXPRESSION_EVALUATION_CONTEXT_PROVIDER, expressionEvaluationContextProviderRef); } }</code><technical_language>I guess this kick in for annotation based solution default present</technical_language>

Target:
public void postProcess(BeanDefinitionBuilder builder, RepositoryConfigurationSource source) { String transactionManagerRef = source.getAttribute("transactionManagerRef"); builder.addPropertyValue("transactionManager", transactionManagerRef == null ? DEFAULT_TRANSACTION_MANAGER_BEAN_NAME : transactionManagerRef); String entityManagerFactoryRef = getEntityManagerFactoryRef(source); if (entityManagerFactoryRef != null) { builder.addPropertyValue("entityManager", getEntityManagerBeanDefinitionFor(entityManagerFactoryRef, source)); } builder.addPropertyReference("mappingContext", JPA_MAPPING_CONTEXT_BEAN_NAME); }
Source:
<code>protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { <START> Exceptions.propagateIfFatal(e); <END> LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }</code><technical_language>done this 3 lines up</technical_language>

Target:
protected void handleGenerateMementoException(Exception e, String context) { Exceptions.propagateIfFatal(e); if (isActive()) { LOG.warn("Problem generating memento for "+context, e); } else { LOG.debug("Problem generating memento for "+context+", but no longer active (ignoring)", e); } }
Source:
<code>public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { super.placeBlock(player, state, face, holding, clickedLoc); final MaterialData data = state.getData(); if (!(data instanceof Button)) { GlowServer.logger.warning("Placing " + getMaterial().name() + ": MaterialData was of wrong type (" + data.getClass().getName() + ")"); return; } <START> final Button button = (Button) data; <END> setAttachedFace(button, face.getOppositeFace()); }</code><technical_language>this whitespace weird. rid of variable? need final</technical_language>

Target:
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { super.placeBlock(player, state, face, holding, clickedLoc); MaterialData data = state.getData(); if (!(data instanceof Button)) { warnMaterialData(Button.class, data); return; } setAttachedFace(state, face.getOppositeFace()); }
Source:
<code>public static VM buildVmsDataFromExternalProvider(Map<String, Object> xmlRpcStruct) { VmStatic vmStatic = buildVmStaticDataFromExternalProvider(xmlRpcStruct); if (vmStatic == null) { return null; } VmDynamic vmDynamic = buildVMDynamicDataFromList(xmlRpcStruct); VM vm = new VM(vmStatic, vmDynamic, new VmStatistics()); for (DiskImage image : vm.getImages()) { vm.getDiskMap().put(Guid.newGuid(), image); } try { vm.setClusterArch(parseArchitecture(xmlRpcStruct)); } catch (IllegalArgumentException ex) { <START> log.error("Illegal architecture type, error: %s", ex.getMessage()); <END> vm.setClusterArch(ArchitectureType.x86_64); } return vm; }</code><technical_language>message include type for right? I worth adding log message</technical_language>

Target:
public static VM buildVmsDataFromExternalProvider(Map<String, Object> xmlRpcStruct) { VmStatic vmStatic = buildVmStaticDataFromExternalProvider(xmlRpcStruct); if (vmStatic == null) { return null; } VmDynamic vmDynamic = buildVMDynamicDataFromList(xmlRpcStruct); VM vm = new VM(vmStatic, vmDynamic, new VmStatistics()); for (DiskImage image : vm.getImages()) { vm.getDiskMap().put(Guid.newGuid(), image); } try { vm.setClusterArch(parseArchitecture(xmlRpcStruct)); } catch (IllegalArgumentException ex) { log.error("Illegal architecture type while trying to read %s, error: %s", VdsProperties.vm_arch, ex.getMessage()); vm.setClusterArch(ArchitectureType.x86_64); } return vm; }
Source:
<code>private Object getDhisResponseForHttpResponse(String json, String uri, CloseableHttpResponse response, Class responseType) { Object status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", contentString, json)); status = new ObjectMapper().readValue(contentString, responseType); <START> if (status.toString().contains("ERROR")) { <END> String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); } } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }</code><technical_language>enum instead of string. I solution creating new AbstractClass. DhisDataValueStatusResponse DhisStatusResponse extend this new class getStatus method</technical_language>

Target:
private DhisResponse getDhisResponseForHttpResponse(String json, String uri, CloseableHttpResponse response, Class responseType) { DhisResponse status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", contentString, json)); if(responseType == DhisStatusResponse.class) { status = new ObjectMapper().readValue(contentString, DhisStatusResponse.class); } else { status = new ObjectMapper().readValue(contentString, DhisDataValueStatusResponse.class); } if (status.getStatus() == DhisStatus.ERROR) { String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); } } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }
Source:
<code>IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); relatedMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; accountId = UNKNOWN_ACCOUNT_ID; containerId = UNKNOWN_CONTAINER_ID; break; case PersistentIndex.VERSION_1: case PersistentIndex.VERSION_2: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); <START> expiresAtMs = expiresAtMs != Utils.Infinite_Time && expiresAt >= 0 ? TimeUnit.SECONDS.toMillis(expiresAt) <END> : Utils.Infinite_Time; relatedMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? TimeUnit.SECONDS.toMillis(operationTimeInSecs) : Utils.Infinite_Time; accountId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }</code><technical_language>expiresAtMs instead of expiresAt in part of check. of tests caught this? IntelliJ warn this. In 2017 version, "Preferences -> Editor -> Inspections -> Initialization Issues" check "Instance field initialization"</technical_language>

Target:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; accountId = UNKNOWN_ACCOUNT_ID; containerId = UNKNOWN_CONTAINER_ID; break; case PersistentIndex.VERSION_1: case PersistentIndex.VERSION_2: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); expiresAtMs = expiresAt != Utils.Infinite_Time && expiresAt >= 0 ? TimeUnit.SECONDS.toMillis(expiresAt) : Utils.Infinite_Time; originalMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? TimeUnit.SECONDS.toMillis(operationTimeInSecs) : Utils.Infinite_Time; accountId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }
Source:
<code><START> protected void clearData() <END></code><technical_language>In order this a breaking change this method clear data</technical_language>

Target:
protected void clearData() { getSnapshots().clear(); mObjectCache.clear(); }
Source:
<code>public static SourceFile fromZipEntry( String originalZipPath, String absoluteZipPath, String entryPath, Charset inputCharset) throws MalformedURLException { <START> String zipEntryPath = JAR_URL_PREFIX + absoluteZipPath + BANG_SLASH + entryPath.replace(File.pathSeparatorChar, '/'); <END> URL zipEntryUrl = new URL(zipEntryPath); return builder() .withCharset(inputCharset) .withOriginalPath(originalZipPath + BANG_SLASH + entryPath) .buildFromUrl(zipEntryUrl); }</code><technical_language>this File.separatorChar instead of File.pathSeparatorChar? understanding is separatorChar is path component separator (/ Unix, \ Windows), while pathSeparatorChar is PATH environment variable separator (: Unix, ; Windows)</technical_language>

Target:
public static SourceFile fromZipEntry( String originalZipPath, String absoluteZipPath, String entryPath, Charset inputCharset) throws MalformedURLException { String zipEntryPath = JAR_URL_PREFIX + absoluteZipPath + BANG_SLASH + entryPath.replace(File.separator, "/"); URL zipEntryUrl = new URL(zipEntryPath); return builder() .withCharset(inputCharset) .withOriginalPath(originalZipPath + BANG_SLASH + entryPath) .buildFromUrl(zipEntryUrl); }
Source:
<code>public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { <START> OsStats.Cpu cpu = osService.stats().getCpu(); <END> return super.doRewrite(condition -> condition.test(cpu)); }</code><technical_language>I need SearchService this query is cachable. do this is call context.nowInMillis(), this is method set cachable flag false getClient() getSearchScript()</technical_language>

Target:
public QueryBuilder doRewrite(QueryRewriteContext context) throws IOException { context.nowInMillis(); OsStats.Cpu cpu = osService.stats().getCpu(); return super.doRewrite(condition -> condition.test(cpu)); }
Source:
<code>private static Integer runCommandAndWait( String command, String workingDir, String extraPath ) throws Exception { String path = System.getenv( "PATH" ); if (extraPath != null) { path = extraPath + File.pathSeparator + path; } <START> <END> Process proc = Runtime.getRuntime().exec(command, new String[] {"M2_HOME=" + MVN_LOCATION, "PATH=" + path}, new File(workingDir)); File buildlog = new File(workingDir, "build.log"); try ( BufferedReader stdout = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); BufferedReader stderr = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( buildlog, true ) ) ) ) { String line; String errline = null; while ( ( line = stdout.readLine() ) != null || ( errline = stderr.readLine() ) != null ) { if ( line != null ) { out.println( line ); } if ( errline != null ) { out.println( errline ); } } return proc.waitFor(); } }</code><technical_language>Hmmm. thoughts, I occasionally run Maven 3.0.5 check compatibility I leave it. ( I removed >= 3.4 (?) )</technical_language>

Target:
private static Integer runCommandAndWait( String command, String workingDir, String extraPath ) throws Exception { String path = System.getenv( "PATH" ); if (extraPath != null) { path = extraPath + File.pathSeparator + path; } Process proc = Runtime.getRuntime().exec(command, new String[] {"PATH=" + path}, new File(workingDir)); File buildlog = new File(workingDir, "build.log"); try ( BufferedReader stdout = new BufferedReader( new InputStreamReader( proc.getInputStream() ) ); BufferedReader stderr = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) ); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( buildlog, true ) ) ) ) { String line; String errline = null; while ( ( line = stdout.readLine() ) != null || ( errline = stderr.readLine() ) != null ) { if ( line != null ) { out.println( line ); } if ( errline != null ) { out.println( errline ); } } return proc.waitFor(); } }
Source:
<code>public void connect() { if (countRetry == 0) { return; } if (!connected) { terminalHolder .getInitializerPromise() .then( aVoid -> { ServerImpl terminalServer = machine .getServerByName(SERVER_TERMINAL_REFERENCE) .orElseThrow( () -> new OperationException( "Machine " + machine.getName() + " doesn't provide terminal server.")); <START> connectToTerminal(wsAgentURLModifier.modify(terminalServer.getUrl())); <END> }) .catchError( arg -> { notificationManager.notify( locale.failedToConnectTheTerminal(), locale.terminalCanNotLoadScript(), FAIL, NOT_EMERGE_MODE); reconnect(); }); } }</code><technical_language>This is wsagent related class</technical_language>

Target:
public void connect() { if (countRetry == 0) { return; } if (!connected) { terminalHolder .getInitializerPromise() .then( aVoid -> { ServerImpl terminalServer = machine .getServerByName(SERVER_TERMINAL_REFERENCE) .orElseThrow( () -> new OperationException( "Machine " + machine.getName() + " doesn't provide terminal server.")); connectToTerminal(agentURLModifier.modify(terminalServer.getUrl())); }) .catchError( arg -> { notificationManager.notify( locale.failedToConnectTheTerminal(), locale.terminalCanNotLoadScript(), FAIL, NOT_EMERGE_MODE); reconnect(); }); } }
Source:
<code>private void createPreparedStatements() { Select.Where select = QueryBuilder .select() .all() .from( CassandraModel.CF_METRICS_LOCATOR_NAME ) <START> .where( eq ( "key", bindMarker() )); <END> getValue = DatastaxIO.getSession().prepare( select ); Insert insert = QueryBuilder.insertInto(CassandraModel.QUOTED_KEYSPACE, CassandraModel.CF_METRICS_LOCATOR_NAME) .using(ttl(TenantTtlProvider.LOCATOR_TTL)) .value(KEY, bindMarker()) .value(COLUMN1, bindMarker()) .value(VALUE, bindMarker()); putValue = DatastaxIO.getSession() .prepare(insert) .setConsistencyLevel( ConsistencyLevel.ONE); }</code><technical_language>public static final String KEY here</technical_language>

Target:
private void createPreparedStatements() { Select.Where select = QueryBuilder .select() .all() .from( CassandraModel.CF_METRICS_LOCATOR_NAME ) .where( eq ( KEY, bindMarker() )); getValue = DatastaxIO.getSession().prepare( select ); Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME) .using(ttl(TenantTtlProvider.LOCATOR_TTL)) .value(KEY, bindMarker()) .value(COLUMN1, bindMarker()) .value(VALUE, bindMarker()); putValue = DatastaxIO.getSession() .prepare(insert) .setConsistencyLevel( ConsistencyLevel.ONE); }
Source:
<code>public ImportApplicationViewImpl(OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants, org.eclipse.che.ide.Resources resources, OpenshiftResources openshiftResources) { this.locale = locale; this.openshiftResources = openshiftResources; <START> openshiftResources.css().ensureInjected(); <END> ensureDebugId("importApplication"); setTitle(locale.importApplicationViewTitle()); setWidget(uiBinder.createAndBindUi(this)); importButton = createPrimaryButton(locale.importApplicationImportButton(), "importApplication-import-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onImportApplicationClicked(); } }); addButtonToFooter(importButton); cancelButton = createButton(constants.cancel(), "importApplication-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelButton); buildConfigList = new CategoriesList(resources); categoriesPanel.add(buildConfigList); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); }</code><technical_language>remove this, inject css in org.eclipse.che.ide.ext.openshift.client.OpenshiftExtension</technical_language>

Target:
public ImportApplicationViewImpl(OpenshiftLocalizationConstant locale, CoreLocalizationConstant constants, org.eclipse.che.ide.Resources resources, OpenshiftResources openshiftResources) { this.locale = locale; this.openshiftResources = openshiftResources; ensureDebugId("importApplication"); setTitle(locale.importApplicationViewTitle()); setWidget(uiBinder.createAndBindUi(this)); importButton = createPrimaryButton(locale.importApplicationImportButton(), "importApplication-import-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onImportApplicationClicked(); } }); addButtonToFooter(importButton); cancelButton = createButton(constants.cancel(), "importApplication-cancel-button", new ClickHandler() { @Override public void onClick(ClickEvent event) { delegate.onCancelClicked(); } }); addButtonToFooter(cancelButton); buildConfigList = new CategoriesList(resources); categoriesPanel.add(buildConfigList); getWidget().getElement().getStyle().setPadding(0, Style.Unit.PX); }
Source:
<code>public void multiple_callbacks_should_be_invoked_realmresults_sync() { final int NUMBER_OF_LISTENERS = 7; final Realm realm = looperThread.realm; realm.addChangeListener(new RealmChangeListener<Realm>() { @Override public void onChange(Realm object) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertEquals(NUMBER_OF_LISTENERS, typebasedCommitInvocations.get()); looperThread.testComplete(); } }); } }); realm.beginTransaction(); Dog akamaru = realm.createObject(Dog.class); realm.commitTransaction(); <START> looperThread.keepStrongReference.add(akamaru); <END> RealmResults<Dog> dogs = realm.where(Dog.class).findAll(); looperThread.keepStrongReference.add(dogs); for (int i = 0; i < NUMBER_OF_LISTENERS; i++) { dogs.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> object) { typebasedCommitInvocations.incrementAndGet(); } }); } realm.beginTransaction(); akamaru.setAge(17); realm.commitTransaction(); }</code><technical_language>This is necessary. This flaky test fixed #4209</technical_language>

Target:
public void multiple_callbacks_should_be_invoked_realmresults_sync() { final int NUMBER_OF_LISTENERS = 7; final Realm realm = looperThread.realm; realm.addChangeListener(new RealmChangeListener<Realm>() { @Override public void onChange(Realm object) { looperThread.postRunnable(new Runnable() { @Override public void run() { assertEquals(NUMBER_OF_LISTENERS, typebasedCommitInvocations.get()); looperThread.testComplete(); } }); } }); realm.beginTransaction(); Dog akamaru = realm.createObject(Dog.class); realm.commitTransaction(); RealmResults<Dog> dogs = realm.where(Dog.class).findAll(); looperThread.keepStrongReference.add(dogs); for (int i = 0; i < NUMBER_OF_LISTENERS; i++) { dogs.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> object) { typebasedCommitInvocations.incrementAndGet(); } }); } realm.beginTransaction(); akamaru.setAge(17); realm.commitTransaction(); }
Source:
<code>public static MixpanelAPI getInstance(Context context, String token) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token); instances.put(appContext, instance); } if (context instanceof Activity) { try { Class<?> clazz = Class.forName("bolts.AppLinks"); Intent intent = ((Activity) context).getIntent(); Method getTargetUrlFromInboundIntent = clazz.getMethod("getTargetUrlFromInboundIntent", Context.class, Intent.class); getTargetUrlFromInboundIntent.invoke(null, context, intent); <START> } catch (Exception e) { <END> Log.d(LOGTAG, "Unable to detect inbound App Links.", e); } } else { Log.d(LOGTAG, "Context is not an instance of Activity. To detect inbound App Links, pass an instance of an Activity to getInstance."); } return instance; } }</code><technical_language>nice catch exceptions (and handle InvocationException specially)</technical_language>

Target:
public static MixpanelAPI getInstance(Context context, String token) { if (null == token || null == context) { return null; } synchronized (sInstanceMap) { final Context appContext = context.getApplicationContext(); if (null == sReferrerPrefs) { sReferrerPrefs = sPrefsLoader.loadPreferences(context, MPConfig.REFERRER_PREFS_NAME, null); } Map <Context, MixpanelAPI> instances = sInstanceMap.get(token); if (null == instances) { instances = new HashMap<Context, MixpanelAPI>(); sInstanceMap.put(token, instances); } MixpanelAPI instance = instances.get(appContext); if (null == instance) { instance = new MixpanelAPI(appContext, sReferrerPrefs, token); registerAppLinksListeners(context, instance); instances.put(appContext, instance); } checkIntentForInboundAppLink(context); return instance; } }
Source:
<code>public String validateUserCredentials(String url, String username, char[] password) { try (CloseableHttpClient httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build()) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(USER_KEY, username)); <START> params.add(new BasicNameValuePair(SECRET_KEY, String.valueOf(password))); <END> httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) || (null == httpResponse.getEntity())) throw new IAMException("Failed to validate credentials of user '" + username, new HTTPException(httpResponse.getStatusLine().getStatusCode())); return EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { throw new IAMException("Error occurred while validating credentials of user [" + username + "]", e); } }</code><technical_language>aware password is stored in String</technical_language>

Target:
public String validateUserCredentials(String url, String username, char[] password) { try (CloseableHttpClient httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build()) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair(USER_KEY, username)); params.add(new BasicNameValuePair(SECRET_KEY, String.valueOf(password))); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) || (null == httpResponse.getEntity())) { throw new IAMException("Failed to validate credentials of user '" + username, new HTTPException(httpResponse.getStatusLine().getStatusCode())); } return EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) { throw new IAMException("Error occurred while validating credentials of user [" + username + "]", e); } }
Source:
<code>public static int discoverPartitions(Path basePath) { try (Stream<Path> paths = Files.list(basePath)) { int ret = (int) paths.filter( <START> path -> (path.toFile().isDirectory() && path.getFileName().toString().startsWith(PARTITION_PREFIX))) <END> .count(); if (ret == 0) { throw new IOException("No chronicles queues file found"); } return ret; } catch (IOException e) { throw new IllegalArgumentException("Invalid basePath for queue: " + basePath, e); } }</code><technical_language>This in a helper method isChroniclePartitionDirectory</technical_language>

Target:
public static int discoverPartitions(Path basePath) { try (Stream<Path> paths = Files.list(basePath)) { int ret = (int) paths.filter(ChronicleLogAppender::isPartitionDirectory).count(); if (ret == 0) { throw new IOException("No chronicles queues file found"); } return ret; } catch (IOException e) { throw new IllegalArgumentException("Invalid basePath for queue: " + basePath, e); } }
Source:
<code>public Storage update(Storage connection) { <START> validateParameters(connection, "address", "type", "host"); <END> validateEnums(Storage.class, connection); return performUpdate(connection, new QueryIdResolver<String>(VdcQueryType.GetStorageServerConnectionById, StorageServerConnectionQueryParametersBase.class), VdcActionType.UpdateStorageServerConnection, new UpdateParametersProvider()); }</code><technical_language>update require fields? restrictions all. of want update 'description', supply "address", "type", "host" ... in api 'PATCH PUT' concept for update, i.e update pass need change, other data reside server side completed runtime (this in mapper methods 'entity' 'template' arguments)</technical_language>

Target:
public Storage update(Storage connection) { validateParameters(connection, "host.id|name"); validateEnums(Storage.class, connection); return performUpdate(connection, new QueryIdResolver<String>(VdcQueryType.GetStorageServerConnectionById, StorageServerConnectionQueryParametersBase.class), VdcActionType.UpdateStorageServerConnection, new UpdateParametersProvider()); }
Source:
<code>public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isAvailable(); if(isConnected && !NetworkUtil.isOnZeroRatedNetwork(context)) { logger.debug("Have reconnected, testing download speed."); <START> Intent speedTestIntent = new Intent(context, DownloadSpeedService.class); <END> String downloadEndpoint = context.getString(R.string.speed_test_url); speedTestIntent.putExtra(DownloadSpeedService.EXTRA_FILE_DESC, new DownloadDescriptor(downloadEndpoint, !isFirstStart)); context.startService(speedTestIntent); isFirstStart = true; } if (NetworkUtil.isConnectedMobile(context)){ ISegment segIO = SegmentFactory.getInstance(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String carrierName = manager.getNetworkOperatorName(); segIO.trackUserCellConnection(carrierName, NetworkUtil.isOnZeroRatedNetwork(context)); } }</code><technical_language>if goal is check traffic zero rated network, NetworkUtil.isOnZeroRatedNetwork() check start of method call</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if(Config.getInstance().isSpeedTestEnabled()) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isAvailable(); if (isConnected) { logger.debug("Have reconnected, testing download speed."); Intent speedTestIntent = new Intent(context, DownloadSpeedService.class); String downloadEndpoint = context.getString(R.string.speed_test_url); speedTestIntent.putExtra(DownloadSpeedService.EXTRA_FILE_DESC, new DownloadDescriptor(downloadEndpoint, !isFirstStart)); context.startService(speedTestIntent); isFirstStart = true; } } if (NetworkUtil.isConnectedMobile(context)){ ISegment segIO = SegmentFactory.getInstance(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String carrierName = manager.getNetworkOperatorName(); segIO.trackUserCellConnection(carrierName, NetworkUtil.isOnZeroRatedNetwork(context)); } }
Source:
<code>public boolean isTotalOrderCache(String cacheName) { if (!running) { if (log.isDebugEnabled()) { log.debugf("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isDebugEnabled()) { log.debugf("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isDebugEnabled()) { <START> log.debugf("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); <END> } return totalOrder; }</code><technical_language>I messages trace</technical_language>

Target:
public boolean isTotalOrderCache(String cacheName) { if (!running) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); } return totalOrder; }
Source:
<code>Optional<User> getUser(final UUID uuid) { <START> this.pollFilesystemWatcher(); <END> if (this.knownUUIDs.contains(uuid)) { return this.getUser((GameProfile) this.server.getPlayerProfileCache().getProfileByUUID(uuid), false); } return Optional.empty(); }</code><technical_language>This method (getUser) is equivalent this.getUser(this.server.getPlayerProfileCache().getProfileByUUID(uuid), true);</technical_language>

Target:
Optional<User> getUser(final UUID uuid) { return this.getUser((GameProfile) this.server.getPlayerProfileCache().getProfileByUUID(uuid)); }
Source:
<code>public void onSendTagsClicked(View v) { try { <START> OneSignal.setExternalUserId("mikechoch_" + sendTagsCounter, new OneSignal.ExternalUserIdUpdateHandler() { <END> @Override public void onSuccess(String newExternalUserId) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, newExternalUserId + " was set SUCCESS"); } @Override public void onFailure(OneSignal.ExternalUserIdError error) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Error setting external id: " + error.getMessage() + " with code: " + error.getCode()); } }); OneSignal.sendTags(new JSONObject("{\"counter\" : " + sendTagsCounter + ", \"test_value\" : \"test_key\"}"), new OneSignal.ChangeTagsUpdateHandler() { @Override public void onSuccess(JSONObject tags) { updateTextView("Successfully sent tags: " + tags.toString()); } @Override public void onFailure(OneSignal.SendTagsError error) { updateTextView("Failed to send tags: " + error.toString()); } }); sendTagsCounter++; } catch (JSONException exception) { updateTextView("Failed to serialize tags into JSON: " + exception.getMessage()); } }</code><technical_language>id a generic one? a demo app, exclude reference developers, do think</technical_language>

Target:
public void onSendTagsClicked(View v) { try { OneSignal.sendTags(new JSONObject("{\"counter\" : " + sendTagsCounter + ", \"test_value\" : \"test_key\"}"), new OneSignal.ChangeTagsUpdateHandler() { @Override public void onSuccess(JSONObject tags) { updateTextView("Successfully sent tags: " + tags.toString()); } @Override public void onFailure(OneSignal.SendTagsError error) { updateTextView("Failed to send tags: " + error.toString()); } }); sendTagsCounter++; } catch (JSONException exception) { updateTextView("Failed to serialize tags into JSON: " + exception.getMessage()); } }
Source:
<code>public Collection<LivingEntity> getEntitiesInRange() { <START> return getWorld().getNearbyEntitiesByType(Player.class, getLocation(), getTier() * 10 + 10, getWorld().getMaxHeight()); <END> }</code><technical_language>extract 10 a class constant</technical_language>

Target:
public Collection<LivingEntity> getEntitiesInRange() { return getWorld().getNearbyEntitiesByType(Player.class, getLocation(), getTier() * RADIUS_MULTIPLIER, getWorld().getMaxHeight()); }
Source:
<code>public void handle(MotechEvent event) throws TriggerNotFoundException { <START> LOGGER.debug("Handling the motech event with subject: {}", event.getSubject()); <END> Map<String, Object> eventParams = event.getParameters(); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } TriggerEvent trigger = taskService.findTrigger(parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), event.getParameters())); Map<String, Object> parameters = parser == null ? event.getParameters() : parser.parseEventParameters(event.getSubject(), event.getParameters()); List<Task> tasks = taskService.findActiveTasksForTrigger(trigger); for (Task task : tasks) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); try { if (initializer.evalConfigSteps(dataProviders)) { for (TaskActionInformation action : task.getActions()) { executor.execute(task, action, taskContext); } handleSuccess(parameters, task); } } catch (TaskHandlerException e) { handleError(parameters, task, e); } catch (Exception e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); } } }</code><technical_language>This info</technical_language>

Target:
public void handle(MotechEvent event) throws TriggerNotFoundException { LOGGER.info("Handling the motech event with subject: {}", event.getSubject()); Map<String, Object> eventParams = event.getParameters(); TasksEventParser parser = null; if (eventParams != null) { parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY)); } TriggerEvent trigger = taskService.findTrigger(parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), event.getParameters())); Map<String, Object> parameters = parser == null ? event.getParameters() : parser.parseEventParameters(event.getSubject(), event.getParameters()); List<Task> tasks = taskService.findActiveTasksForTrigger(trigger); for (Task task : tasks) { TaskContext taskContext = new TaskContext(task, parameters, activityService); TaskInitializer initializer = new TaskInitializer(taskContext); try { LOGGER.info("Executing all actions from task: {}", task.getName()); if (initializer.evalConfigSteps(dataProviders)) { for (TaskActionInformation action : task.getActions()) { executor.execute(task, action, taskContext); } handleSuccess(parameters, task); } LOGGER.warn("Actions from task: weren't executed, because config steps didn't pass the evaluation", task.getName()); } catch (TaskHandlerException e) { handleError(parameters, task, e); } catch (Exception e) { handleError(parameters, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e)); } } }
Source:
<code>public int getItemCount() { <START> return contributions==null?0:contributions.size(); <END> }</code><technical_language>contributions null? Create field level if want. final. minor style violations in this file, spaces operators</technical_language>

Target:
public int getItemCount() { return contributions.size(); }
Source:
<code>public void changeAnnouncement(Intent data) { int type = data.getIntExtra(getString(R.string.announcement_type), AnnouncementActivity.ORIGINAL); <START> if (type == AnnouncementActivity.DELETED) { <END> String string = data.getStringExtra(getString(R.string.delete_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { mAnnouncements.remove(i); } } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); } else if (type == AnnouncementActivity.EDITED) { String string = data.getStringExtra(getString(R.string.edit_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { mAnnouncements.set(i, announcement); } } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); } }</code><technical_language>switch pls</technical_language>

Target:
public void changeAnnouncement(Intent data) { int type = data.getIntExtra(getString(R.string.announcement_type), AnnouncementActivity.ORIGINAL); String string = data.getStringExtra(getString(R.string.change_announcement)); Announcement announcement = NetworkUtils.writeAsObject(getActivity(), string, new TypeReference<Announcement>() {}); if (type == AnnouncementActivity.ORIGINAL) { return; } int index = 0; for (int i = 0; i < mAnnouncements.size(); i++) { if (mAnnouncements.get(i).getId() == announcement.getId()) { index = i; } } switch (type) { case AnnouncementActivity.DELETED: mAnnouncements.remove(index); break; case AnnouncementActivity.EDITED: mAnnouncements.set(index, announcement); break; } mAdapter.setAnnouncements(mAnnouncements); mAdapter.notifyDataSetChanged(); }
Source:
<code>public void testValidateSnapshotVersionWithInvalidVersions() { assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3", "OSGi version 1.2.3 must have .qualifier qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3", "1.2.3.qualifier", "Maven version 1.2.3 must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.0.qualifier", "Unqualified OSGi version 1.2.0.qualifier must match unqualified Maven version 1.2.3-SNAPSHOT for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3.qualifier", "1.2.3.qualifier", "Maven version 1.2.3.qualifier must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", <START> "1.2.3.SHAPSHOT", <END> "OSGi version 1.2.3.SHAPSHOT must have .qualifier qualifier for SNAPSHOT builds"); }</code><technical_language>"N"? is semantically relevant</technical_language>

Target:
public void testValidateSnapshotVersionWithInvalidVersions() { assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3", "OSGi version 1.2.3 must have .qualifier qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3", "1.2.3.qualifier", "Maven version 1.2.3 must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.0.qualifier", "Unqualified OSGi version 1.2.0.qualifier must match unqualified Maven version 1.2.3-SNAPSHOT for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3.qualifier", "1.2.3.qualifier", "Maven version 1.2.3.qualifier must have -SNAPSHOT qualifier for SNAPSHOT builds"); assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3.SNAPSHOT", "OSGi version 1.2.3.SNAPSHOT must have .qualifier qualifier for SNAPSHOT builds"); }
Source:
<code>public AlphaNumericTopNMetricSpec( @JsonProperty("previousStop") String previousStop ) { super((previousStop == null) ? "" : previousStop); <START> this.previousStop = (previousStop == null) ? "" : previousStop; <END> }</code><technical_language>instead, put this.previousStop = (previousStop == null) ? "" : previousStop; in constructor of LexicographicTopNMetricSpec , replace line#191 this.previousStop = super.getPreviousStop()</technical_language>

Target:
public AlphaNumericTopNMetricSpec( @JsonProperty("previousStop") String previousStop ) { super(previousStop); }
Source:
<code>public API getApiByContextAndVersion(String context, String version) { <START> return null; <END> }</code><technical_language>missed implement</technical_language>

Target:
public API getApiByContextAndVersion(String context, String version) { String key = context + DELEM_PERIOD + version; return apiMap.get(key); }
Source:
<code>public void simplePhenotypeSearchNoFind() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype("FooBar"); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); <START> assertThat(response).isNotNull(); <END> assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().size()).isEqualTo(0) ; }</code><technical_language>Another null test of response. I mark others I this point, fixed</technical_language>

Target:
public void simplePhenotypeSearchNoFind() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); request.setPhenotype(Utils.randomName()); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations()).isEmpty(); }
Source:
<code>public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) { if (null == input) { throw new IllegalArgumentException("The collection can't be null."); } if (startIndex < 0) { <START> throw new IndexOutOfBoundsException("The start index can't less than 0."); <END> } if (count < 0) { throw new IndexOutOfBoundsException("The count can't less than 0."); } if (input.size() < startIndex + count) { throw new IndexOutOfBoundsException( "The sum of start index and count can't be greater than the size of collection."); } Collection<E> result = new ArrayList<E>(count); Iterator<E> iterator = input.iterator(); while (count > 0) { if (startIndex > 0) { startIndex = startIndex - 1; iterator.next(); continue; } count = count - 1; result.add(iterator.next()); iterator.remove(); } return result; }</code><technical_language>missing words in exception messages: "The start index 0." -> "The start index **be** 0."</technical_language>

Target:
public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) { if (null == input) { throw new IllegalArgumentException("The collection can't be null."); } if (startIndex < 0) { throw new IndexOutOfBoundsException("The start index can't be less than 0."); } if (count < 0) { throw new IndexOutOfBoundsException("The count can't be less than 0."); } if (input.size() < startIndex + count) { throw new IndexOutOfBoundsException( "The sum of start index and count can't be greater than the size of collection."); } Collection<E> result = new ArrayList<E>(count); Iterator<E> iterator = input.iterator(); while (count > 0) { if (startIndex > 0) { startIndex = startIndex - 1; iterator.next(); continue; } count = count - 1; result.add(iterator.next()); iterator.remove(); } return result; }