auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { <START> LOGGER.debug("Skipping because the requestBody is null or empty", this); <END> return new ArrayList<>(0); } final String token = requestBody.getFirst(PARAMETER_NAME_GAUTH_OTP); LOGGER.debug("Google authenticator token in the request body: [{}]", token); if (StringUtils.isBlank(token)) { return new ArrayList<>(0); } return CollectionUtils.wrap(new GoogleAuthenticatorTokenCredential(token)); }</code><technical_language>above; Consider getClass().getSimpleName() instead of this</technical_language>

Target:
public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { LOGGER.debug("Skipping because the requestBody is null or empty", getClass().getSimpleName()); return new ArrayList<>(0); } final String token = requestBody.getFirst(PARAMETER_NAME_GAUTH_OTP); LOGGER.debug("Google authenticator token in the request body: [{}]", token); if (StringUtils.isBlank(token)) { return new ArrayList<>(0); } return CollectionUtils.wrap(new GoogleAuthenticatorTokenCredential(token)); }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeShareFilter that = (TimeShareFilter) o; return (mode == that.mode) && (Double.compare(that.minShare, minShare) == 0); }</code><technical_language>whitespace/style</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TimeShareFilter that = (TimeShareFilter) o; return (mode == that.mode) && (Double.compare(that.minShare, minShare) == 0); }
Source:
<code>protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { if (buffer.readableBytes() < 1) return; int version = buffer.getByte(0); version = version & 0x7F; DecoderForStreamIdSize decoder = decoderForStreamIdSize.get(); <START> if (decoder == null) { <END> decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1); if (!decoderForStreamIdSize.compareAndSet(null, decoder)) { decoder = decoderForStreamIdSize.get(); } } assert decoder.protocolVersion == version; Object frame = decoder.decode(ctx, buffer); if (frame != null) out.add(frame); }</code><technical_language>Hmm I see. Conceptually speaking, right Decoder instantiate DecoderForStreamIdSize consistently, ok approach well</technical_language>

Target:
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { if (buffer.readableBytes() < 1) return; if (decoder == null) { int version = buffer.getByte(buffer.readerIndex()); version = version & 0x7F; decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1); } Object frame = decoder.decode(ctx, buffer); if (frame != null) out.add(frame); }
Source:
<code>private void initializeLoader(StoreConfiguration cfg, CacheLoader loader, InitializationContextImpl ctx) { if (loader != null) { if (loader instanceof DelegatingCacheLoader) loader.init(ctx); storesMutex.writeLock().lock(); try { loaders.add(loader); long interval = configuration.persistence().availabilityInterval(); ConnectableObservable<StoreAvailability> observable = Observable.interval(interval, TimeUnit.MILLISECONDS, Schedulers.from(persistenceExecutor)) .map(t -> new StoreAvailability(loader, loader.isAvailable())) <START> .doOnError(err -> log.debugf("Error encountered when calling isAvailable on %s: %s", loader, err)) <END> .retry() .publish(); storeStatuses.put(loader, new StoreStatus(cfg, observable)); } finally { storesMutex.writeLock().unlock(); } } }</code><technical_language>want do <LINK_0> print error change a status new StoreAvailability(loader, false)</technical_language>

Target:
private void initializeLoader(StoreConfiguration cfg, CacheLoader loader, InitializationContextImpl ctx) { if (loader != null) { if (loader instanceof DelegatingCacheLoader) loader.init(ctx); storesMutex.writeLock().lock(); try { loaders.add(loader); storeStatuses.put(loader, new StoreStatus(loader, cfg)); } finally { storesMutex.writeLock().unlock(); } } }
Source:
<code>private void addExternalNames(DetailedSample sample, SampleIdentity identityCopy) throws IOException { if (identityCopy == null || identityCopy.getExternalName() == null) return; SampleIdentity identity = (SampleIdentity) get(getIdentity(sample).getId()); Set<String> identityExternalNames = SampleIdentityImpl.getSetFromString(identity.getExternalName()); Set<String> tempExternalNames = SampleIdentityImpl.getSetFromString(identityCopy.getExternalName()); Set<String> lowerCaseIdentityExternalNames = identityExternalNames.stream().map(String::toLowerCase).collect(Collectors.toSet()); tempExternalNames.stream().forEach(name -> { try { if (!lowerCaseIdentityExternalNames.contains(name.toLowerCase()) && !(isUniqueExternalNameWithinProjectRequired() && (identity.getProject() == null || getIdentitiesByExternalNameOrAliasAndProject(name, identity.getProject().getId(), true).size() > 0))) { identityExternalNames.add(name); } } catch (IOException e) { log.error("Failed to retrieve all external names: " + e); } }); identity.setExternalName(String.join(",", identityExternalNames)); if (identityExternalNames.size() > lowerCaseIdentityExternalNames.size()) { sampleStore.update(identity); <START> } <END> }</code><technical_language>Please call setChangeDetails(identity) save, lastModified lastModifier values get set</technical_language>

Target:
private void addExternalNames(DetailedSample sample, SampleIdentity identityCopy) throws IOException { if (identityCopy == null || identityCopy.getExternalName() == null) return; SampleIdentity identity = (SampleIdentity) get(getIdentity(sample).getId()); Set<String> identityExternalNames = SampleIdentityImpl.getSetFromString(identity.getExternalName()); Set<String> tempExternalNames = SampleIdentityImpl.getSetFromString(identityCopy.getExternalName()); Set<String> lowerCaseIdentityExternalNames = identityExternalNames.stream().map(String::toLowerCase).collect(Collectors.toSet()); tempExternalNames.stream().forEach(name -> { try { if (!lowerCaseIdentityExternalNames.contains(name.toLowerCase()) && !(isUniqueExternalNameWithinProjectRequired() && (identity.getProject() == null || getIdentitiesByExternalNameOrAliasAndProject(name, identity.getProject().getId(), true).size() > 0))) { identityExternalNames.add(name); } } catch (IOException e) { log.error("Failed to retrieve all external names: " + e); } }); identity.setExternalName(String.join(",", identityExternalNames)); if (identityExternalNames.size() > lowerCaseIdentityExternalNames.size()) { setChangeDetails(identity); sampleStore.update(identity); } }
Source:
<code>protected String getRouteURL(List<String> urls) { <START> return urls.stream().filter(this::isInternalDomain).findFirst().orElse(""); <END> }</code><technical_language>stream apis please</technical_language>

Target:
protected String getRouteURL(List<String> urls) { for (String url : urls) { if (isInternalDomain(url)) { return url; } } return ""; }
Source:
<code>public boolean equals(Object other) { if (other instanceof ImapFolder) { <START> return other.hashCode() == hashCode() ; <END> } return super.equals(other); }</code><technical_language>This is wrong. need folder name for equality checks</technical_language>

Target:
public boolean equals(Object other) { if (other instanceof ImapFolder) { ImapFolder otherFolder = (ImapFolder) other; if (otherFolder.getName().equalsIgnoreCase("INBOX")) { return otherFolder.getName().equalsIgnoreCase(getName()); } return otherFolder.getName().equals(getName()); } return super.equals(other); }
Source:
<code>public void processDataObject( DataObject dataObject, DataModel dataModel ) { if ( dataModel != null ) { boolean hasPlanningEntity = dataObject.getAnnotation( PlannerDomainAnnotations.PLANNING_ENTITY_ANNOTATION ) != null; boolean hasComparatorDefinition = dataObject.getAnnotation( ComparatorDefinition.class.getName() ) != null; if ( hasPlanningEntity && hasComparatorDefinition ) { try { ComparatorObject comparatorObject = plannerDataObjectEditorService.extractComparatorObject( dataObject, dataModel ); dataObject.getNestedClasses().clear(); dataObject.getNestedClasses().add( comparatorObject ); <START> } catch ( Exception e ) { <END> logger.error( "Unable to extract comparator object from " + dataObject.getClassName() ); } } } }</code><technical_language>catch Exception Throwable, overkill. If of code throws a checked exception, catch that, optionally RuntimeException if needed. If want catch 2 exceptions, java 7 style "catch (FooException | BarException e)" Catching Exception is bad if code checked exceptions, catch RuntimeException. If has, catch optionally RuntimeException (if sense sense catch RuntimeException) Catching Throwable worse, catches OutOfMemoryError etc, need bubble stack</technical_language>

Target:
public void processDataObject( DataObject dataObject, DataModel dataModel ) { if ( dataObject != null ) { boolean hasPlanningEntity = dataObject.getAnnotation( PlannerDomainAnnotations.PLANNING_ENTITY_ANNOTATION ) != null; boolean hasComparatorDefinition = dataObject.getAnnotation( ComparatorDefinition.class.getName() ) != null; if ( hasPlanningEntity && hasComparatorDefinition ) { try { ComparatorObject comparatorObject = plannerDataObjectEditorService.extractComparatorObject( dataObject, dataModel ); dataObject.getNestedClasses().clear(); dataObject.getNestedClasses().add( comparatorObject ); } catch ( Exception e ) { logger.error( "Unable to extract comparator object from " + dataObject.getClassName() ); } } } }
Source:
<code>public SchedulerRestClient(String restEndpointURL, ClientHttpEngine httpEngine) { if (sslContext == null) { <START> setBlindTrustSSLContext(); <END> } if (httpEngine == null) { SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).build(); httpEngine = new ApacheHttpClient4Engine(httpClient); } this.httpEngine = httpEngine; this.restEndpointURL = restEndpointURL; providerFactory = ResteasyProviderFactory.getInstance(); if (!providerFactory.isRegistered(JacksonContextResolver.class)) { providerFactory.registerProvider(JacksonContextResolver.class); } registerGzipEncoding(providerFactory); scheduler = createRestProxy(providerFactory, restEndpointURL, httpEngine); }</code><technical_language>if block ? null here</technical_language>

Target:
public SchedulerRestClient(String restEndpointURL, ClientHttpEngine httpEngine) { if (httpEngine == null) { setBlindTrustSSLContext(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).build(); httpEngine = new ApacheHttpClient4Engine(httpClient); } this.httpEngine = httpEngine; this.restEndpointURL = restEndpointURL; providerFactory = ResteasyProviderFactory.getInstance(); if (!providerFactory.isRegistered(JacksonContextResolver.class)) { providerFactory.registerProvider(JacksonContextResolver.class); } registerGzipEncoding(providerFactory); scheduler = createRestProxy(providerFactory, restEndpointURL, httpEngine); }
Source:
<code>public AuditLogType getAuditLogTypeValue() { <START> if(getSucceeded()) <END> return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE; else return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE_FAILED; }</code><technical_language>apply a formatting style in Eclipse</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { if (getSucceeded()) { return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE; } else { return AuditLogType.GLUSTER_VOLUME_GEO_REP_PAUSE_FAILED; } }
Source:
<code>public void testCreate() throws Exception { server.enqueue(jsonResponse("/storageCreateResponse.json")); final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); assertEquals(storageAPI.create("name-of-storage-account", "westus", ImmutableMap.of("property_name", "property_value"), ImmutableMap.of("accountType", StorageService.AccountType.Premium_LRS.toString())), getCreateResponse()); assertSent(server, "PUT", "/subscriptions/" + subsriptionId + "/resourcegroups/resourceGroup/providers/Microsoft.Storage/" + <START> "storageAccounts/name-of-storage-account?api-version=2015-06-15"); <END> }</code><technical_language>For methods generate a body need verify generated body is expected one</technical_language>

Target:
public void testCreate() throws Exception { final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); server.enqueue(response202WithHeader()); URI uri = storageAPI.create("name-of-storage-account", "westus", ImmutableMap.of("property_name", "property_value"), ImmutableMap.of("accountType", StorageService.AccountType.Premium_LRS.toString())); assertNotNull(uri); assertSent(server, "PUT", "/subscriptions/" + subsriptionId + "/resourcegroups/resourceGroup/providers/Microsoft.Storage/" + "storageAccounts/name-of-storage-account?api-version=2015-06-15", String.format("{\"location\":\"westus\",\"tags\":{\"property_name\":\"property_value\"},\"properties\":{\"accountType\":\"Premium_LRS\"}}")); }
Source:
<code>private boolean checkAddressMatch(List<String> addresses, String host, int port) { for (String address : addresses) { try { if (NetUtils.matchIpExpression(address, host, port)) { return true; } <START> if ((ALL_IP_MATCH + ":" + port).equals(address)) { <END> return true; } } catch (UnknownHostException e) { logger.error("The format of ip address is invalid in tag route. Address :" + address, e); } catch (Exception e) { logger.error("The format of ip address is invalid in tag route. Address :" + address, e); } } return false; }</code><technical_language>Reuse CommonConstants.ANYHOST better</technical_language>

Target:
private boolean checkAddressMatch(List<String> addresses, String host, int port) { for (String address : addresses) { try { if (NetUtils.matchIpExpression(address, host, port)) { return true; } if ((ANYHOST_VALUE + ":" + port).equals(address)) { return true; } } catch (UnknownHostException e) { logger.error("The format of ip address is invalid in tag route. Address :" + address, e); } catch (Exception e) { logger.error("The format of ip address is invalid in tag route. Address :" + address, e); } } return false; }
Source:
<code><START> @Test public void invalidSourceArgumentExecutorTest() { <END> Path destination = Paths.get(System.getProperty("java.io.tmpdir")); executeConversion(null, destination); Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(destination.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }</code><technical_language>check formatting</technical_language>

Target:
public void invalidSourceArgumentExecutorTest() { Path destination = Paths.get(System.getProperty("java.io.tmpdir")); executeConversion(null, destination); Path jarFilePath = TestConstants.SAMPLE_JAR_FILE.getFileName(); if (jarFilePath != null) { String jarFileName = getBundleSymbolicName(jarFilePath); String bundleName = jarFileName + "_1.0.0.jar"; Path bundlePath = Paths.get(destination.toString(), bundleName); Assert.assertFalse(Files.exists(bundlePath)); } else { assert false; } }
Source:
<code>public void testIteratorBehavior3() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'eric')"); assertThat(h.createQuery("select * from something order by id").mapToBean(Something.class)) .hasSize(2) .extracting(Something::getName) <START> .containsOnly("eric"); <END> }</code><technical_language>This usage ends running query twice. ok though</technical_language>

Target:
public void testIteratorBehavior3() throws Exception { h.insert("insert into something (id, name) values (1, 'eric')"); h.insert("insert into something (id, name) values (2, 'eric')"); assertThat(h.createQuery("select * from something order by id").mapToBean(Something.class)) .extracting(Something::getName) .containsExactly("eric", "eric"); }
Source:
<code>public PartitionCreator withDisplayNames(String[] displayNames){ descriptor.setValue(SIConstants.SCHEMA_DISPLAY_NAME_ATTR, displayNames[0]); <START> descriptor.setValue(SIConstants.TABLE_DISPLAY_NAME_ATTR, displayNames[0] != null ? displayNames[0] : descriptor.getNameAsString()); <END> descriptor.setValue(SIConstants.INDEX_DISPLAY_NAME_ATTR, displayNames[1]); return this; }</code><technical_language>In other platforms forgot update (increment 1) displayNames indexes for TABLE/INDEX attributes</technical_language>

Target:
public PartitionCreator withDisplayNames(String[] displayNames){ descriptor.setValue(SIConstants.SCHEMA_DISPLAY_NAME_ATTR, displayNames[0]); descriptor.setValue(SIConstants.TABLE_DISPLAY_NAME_ATTR, displayNames[1] != null ? displayNames[1] : descriptor.getNameAsString()); descriptor.setValue(SIConstants.INDEX_DISPLAY_NAME_ATTR, displayNames[2]); return this; }
Source:
<code>public static AlertDialog show(Context context, FormController formController, Listener listener) { String title; <START> { <END> title = (formController == null) ? null : formController.getFormTitle(); if (title == null) { title = context.getString(R.string.no_form_loaded); } } List<IconMenuItem> items; if ((boolean) AdminSharedPreferences.getInstance().get(AdminKeys.KEY_SAVE_MID)) { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_save, R.string.keep_changes), new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } else { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } ListView listView = DialogUtils.createActionListView(context); final IconMenuListAdapter adapter = new IconMenuListAdapter(context, items); listView.setAdapter(adapter); listView.setOnItemClickListener((parent, view, position, id) -> { IconMenuItem item = (IconMenuItem) adapter.getItem(position); if (item.getTextResId() == R.string.keep_changes) { listener.onSaveChangedClicked(); } else { listener.onIgnoreChangesClicked(); } }); AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( context.getString(R.string.quit_application, title)) .setPositiveButton(context.getString(R.string.do_not_exit), (dialog, id) -> { dialog.cancel(); }) .setView(listView) .create(); alertDialog.show(); return alertDialog; }</code><technical_language>add this block</technical_language>

Target:
public static AlertDialog show(Context context, FormController formController, Listener listener) { String title = (formController == null) ? null : formController.getFormTitle(); if (title == null) { title = context.getString(R.string.no_form_loaded); } List<IconMenuItem> items; if ((boolean) AdminSharedPreferences.getInstance().get(AdminKeys.KEY_SAVE_MID)) { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_save, R.string.keep_changes), new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } else { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } ListView listView = DialogUtils.createActionListView(context); final IconMenuListAdapter adapter = new IconMenuListAdapter(context, items); listView.setAdapter(adapter); listView.setOnItemClickListener((parent, view, position, id) -> { IconMenuItem item = (IconMenuItem) adapter.getItem(position); if (item.getTextResId() == R.string.keep_changes) { listener.onSaveChangedClicked(); } else { listener.onIgnoreChangesClicked(); } }); AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( context.getString(R.string.quit_application, title)) .setPositiveButton(context.getString(R.string.do_not_exit), (dialog, id) -> { dialog.cancel(); }) .setView(listView) .create(); alertDialog.show(); return alertDialog; }
Source:
<code>public void abortReceived(ChannelHandlerContext ctx, MessageEvent evt) throws Exception { AbortMessage abort = (AbortMessage) evt.getMessage(); if (logger.isInfoEnabled()) { logger.debug("Aborting script " + abort.getName()); } <START> if (robot == null <END> || (robot.getScriptCompleteFuture().isDone() && time.containsKey(abort.getName()) && (System .currentTimeMillis() - ((Date) time.get(abort.getName())).getTime()) > 500)) { time.remove(abort.getName()); sendBadRequestMessage(ctx, "The script cannot be aborted from the current state", abort.getName()); } else { robot.abort(); FinishedMessage finished = new FinishedMessage(); finished.setName(abort.getName()); finished.setExpectedScript(robot.getScriptCompleteFuture().getExpectedScript()); finished.setObservedScript(robot.getScriptCompleteFuture().getObservedScript()); Channels.write(ctx, Channels.future(null), finished); FinishMessage finish = new FinishMessage(); finish.setName(abort.getName()); Channels.write(ctx, Channels.future(null), finish); } }</code><technical_language>Time is freeing resources if script is cached. This ideal</technical_language>

Target:
public void abortReceived(ChannelHandlerContext ctx, MessageEvent evt) throws Exception { AbortMessage abort = (AbortMessage) evt.getMessage(); if (logger.isInfoEnabled()) { logger.debug("Aborting script " + abort.getName()); } robot.abort(); if (robot != null && robot.getScriptCompleteFuture().isDone()) { FinishedMessage finished = new FinishedMessage(); finished.setName(abort.getName()); finished.setExpectedScript(robot.getScriptCompleteFuture().getExpectedScript()); finished.setObservedScript(robot.getScriptCompleteFuture().getObservedScript()); Channels.write(ctx, Channels.future(null), finished); } }
Source:
<code>public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { <START> IDomain domain; <END> domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }</code><technical_language>please dont remove explicit initialization</technical_language>

Target:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { IDomain domain = null; domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }
Source:
<code>private void getOptimizedRoute(@NonNull final Style style, List<Point> coordinates) { optimizedClient = MapboxOptimization.builder() .source(FIRST) .destination(ANY) .coordinates(coordinates) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .accessToken(Mapbox.getAccessToken()) .build(); optimizedClient.enqueueCall(new Callback<OptimizationResponse>() { @Override public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) { if (!response.isSuccessful()) { Timber.d(getString(R.string.no_success)); Toast.makeText(OptimizationActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show(); } else { if (response.body() != null) { List<DirectionsRoute> routes = response.body().trips(); if (routes != null) { if (routes.isEmpty()) { Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), routes.size()); Toast.makeText(OptimizationActivity.this, R.string.successful_but_no_routes, Toast.LENGTH_SHORT).show(); } else { optimizedRoute = routes.get(0); drawOptimizedRoute(style, optimizedRoute); } } } <START> } <END> } @Override public void onFailure(Call<OptimizationResponse> call, Throwable throwable) { Timber.d("Error: %s", throwable.getMessage()); } }); }</code><technical_language>Do need print some logs response.body() is null routes is null</technical_language>

Target:
private void getOptimizedRoute(@NonNull final Style style, List<Point> coordinates) { optimizedClient = MapboxOptimization.builder() .source(FIRST) .destination(ANY) .coordinates(coordinates) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .accessToken(Mapbox.getAccessToken()) .build(); optimizedClient.enqueueCall(new Callback<OptimizationResponse>() { @Override public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) { if (!response.isSuccessful()) { Timber.d(getString(R.string.no_success)); Toast.makeText(OptimizationActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show(); } else { if (response.body() != null) { List<DirectionsRoute> routes = response.body().trips(); if (routes != null) { if (routes.isEmpty()) { Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), routes.size()); Toast.makeText(OptimizationActivity.this, R.string.successful_but_no_routes, Toast.LENGTH_SHORT).show(); } else { optimizedRoute = routes.get(0); drawOptimizedRoute(style, optimizedRoute); } } else { Timber.d("list of routes in the response is null"); Toast.makeText(OptimizationActivity.this, String.format(getString(R.string.null_in_response), "The Optimization API response's list of routes"), Toast.LENGTH_SHORT).show(); } } else { Timber.d("response.body() is null"); Toast.makeText(OptimizationActivity.this, String.format(getString(R.string.null_in_response), "The Optimization API response's body"), Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<OptimizationResponse> call, Throwable throwable) { Timber.d("Error: %s", throwable.getMessage()); } }); }
Source:
<code>private void doDisposeHandler(final ThingHandler thingHandler) { logger.debug("Calling dispose handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.dispose(); return null; } }); } catch (TimeoutException ex) { logger.warn("Disposing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception ex) { <START> logger.error("Exception occured while disposing handler of thing '" + thingHandler.getThing().getUID() <END> + "': " + ex.getMessage(), ex); } }</code><technical_language>wrong commit, touched this line instead of string concatenation</technical_language>

Target:
private void doDisposeHandler(final ThingHandler thingHandler) { logger.debug("Calling dispose handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.dispose(); return null; } }); } catch (TimeoutException ex) { logger.warn("Disposing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception e) { logger.error("Exception occured while disposing handler of thing '{}': {}", thingHandler.getThing().getUID(), e.getMessage(), e); } }
Source:
<code>public List<TmfTraceAnalysis> getAvailableAnalysis() { List<TmfTraceAnalysis> list = new ArrayList<TmfTraceAnalysis>(); TraceTypeHelper helper = TmfTraceType.getInstance().getTraceType(getTraceType()); if (helper == null) { return list; } for (IAnalysisModule module : TmfAnalysisManager.getAnalysisModules(helper.getTraceClass()).values()) { <START> if (fResource instanceof IFolder) { <END> IFolder folder = (IFolder) fResource; IPath path = folder.getFullPath().append(module.getId()); IFolder newresource = ResourcesPlugin.getWorkspace().getRoot().getFolder(path); if (!newresource.exists()) { try { newresource.create(true, true, null); } catch (CoreException e) { e.printStackTrace(); } } TmfTraceAnalysis analysis = new TmfTraceAnalysis(module.getName(), newresource, this, module.getId(), module); list.add(analysis); } } return list; }</code><technical_language>This applies for traces folders (e.g. LTTng CTF). This work for traces files</technical_language>

Target:
public List<TmfAnalysisElement> getAvailableAnalysis() { List<TmfAnalysisElement> list = new ArrayList<TmfAnalysisElement>(); TraceTypeHelper helper = TmfTraceType.getInstance().getTraceType(getTraceType()); Class<? extends ITmfTrace> traceClass = null; if (helper == null && fTraceTypeId != null) { if (fTraceTypeId.startsWith(CustomTxtTrace.class.getCanonicalName())) { for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { if (fTraceTypeId.equals(CustomTxtTrace.class.getCanonicalName() + ":" + def.definitionName)) { traceClass = CustomTxtTrace.class; } } } if (fTraceTypeId.startsWith(CustomXmlTrace.class.getCanonicalName())) { for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { if (fTraceTypeId.equals(CustomXmlTrace.class.getCanonicalName() + ":" + def.definitionName)) { traceClass = CustomTxtTrace.class; } } } } else if (helper != null) { traceClass = helper.getTraceClass(); } if (traceClass == null) { return list; } IPath path = getProject().getTracesFolder().getPath(); if (fResource instanceof IFolder) { IFolder folder = (IFolder) fResource; path = folder.getFullPath(); } else if (fResource instanceof IFile) { IFile file = (IFile) fResource; path = path.append(file.getName()); } for (IAnalysisModule module : TmfAnalysisManager.getAnalysisModules(traceClass).values()) { IFolder newresource = ResourcesPlugin.getWorkspace().getRoot().getFolder(path.append(module.getId())); TmfAnalysisElement analysis = new TmfAnalysisElement(module.getName(), newresource, this, module.getId(), module); list.add(analysis); } return list; }
Source:
<code>public synchronized String getScheme() { <START> return isRunning() ? !this.ssl ? "http" : "https" : null; <END> }</code><technical_language>in this case I return isRunning() ? this.ssl ? "https" : "http" : null; reads cleaner</technical_language>

Target:
public synchronized String getScheme() { return isRunning() ? this.useSsl ? "https" : "http" : null; }
Source:
<code>void should_be_injected_correct_instance_of_mock() { <START> assertThat(classWithDependency.dependency).isEqualTo(rootMock); <END> }</code><technical_language>Lets isSame here, literally want this object there</technical_language>

Target:
void should_be_injected_correct_instance_of_mock() { assertThat(classWithDependency.dependency).isSameAs(rootMock); }
Source:
<code><T> Iterator<T> asIterator(final String _tailApiUrl, final Class<T> type) { method("GET"); final StringBuilder strBuilder = new StringBuilder(_tailApiUrl); if (!args.isEmpty()) { boolean first=true; try { for (Entry a : args) { strBuilder.append(first ? '?' : '&'); first = false; <START> strBuilder.append(URLEncoder.encode(a.key, "UTF-8")); <END> strBuilder.append('='); strBuilder.append(URLEncoder.encode(a.value.toString(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } final String tailApiUrl = _tailApiUrl; return new Iterator<T>() { T next; URL url; { try { url = root.getApiURL(tailApiUrl); } catch (IOException e) { throw new Error(e); } } public boolean hasNext() { fetch(); return next!=null; } public T next() { fetch(); T r = next; if (r==null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next!=null) return; if (url==null) return; try { while (true) { setupConnection(url); try { next = parse(type,null); assert next!=null; findNextURL(); return; } catch (IOException e) { handleApiError(e); } } } catch (IOException e) { throw new Error(e); } } private void findNextURL() throws MalformedURLException { url = null; String link = uc.getHeaderField("Link"); if (link==null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { int idx = token.indexOf('>'); url = new URL(token.substring(1,idx)); return; } } } }; }</code><technical_language>append.append.append</technical_language>

Target:
<T> Iterator<T> asIterator(final String _tailApiUrl, final Class<T> type) { method("GET"); final StringBuilder strBuilder = new StringBuilder(_tailApiUrl); if (!args.isEmpty()) { boolean first=true; try { for (Entry a : args) { strBuilder.append(first ? '?' : '&'); first = false; strBuilder.append(URLEncoder.encode(a.key, "UTF-8")); strBuilder.append('='); strBuilder.append(URLEncoder.encode(a.value.toString(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } final String tailApiUrl = strBuilder.toString(); return new Iterator<T>() { T next; URL url; { try { url = root.getApiURL(tailApiUrl); } catch (IOException e) { throw new Error(e); } } public boolean hasNext() { fetch(); return next!=null; } public T next() { fetch(); T r = next; if (r==null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next!=null) return; if (url==null) return; try { while (true) { setupConnection(url); try { next = parse(type,null); assert next!=null; findNextURL(); return; } catch (IOException e) { handleApiError(e); } } } catch (IOException e) { throw new Error(e); } } private void findNextURL() throws MalformedURLException { url = null; String link = uc.getHeaderField("Link"); if (link==null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { int idx = token.indexOf('>'); url = new URL(token.substring(1,idx)); return; } } } }; }
Source:
<code>public void reset() { colorChangeBitSet = false; <START> firstPoint = false; <END> header.reset(); }</code><technical_language>Please check if points.clear() called</technical_language>

Target:
public void reset() { colorChangeBitSet = false; points.clear(); header.reset(); }
Source:
<code>private Optional<Contentlet> findUrlContentlet(final HttpServletRequest request) throws DotDataException, DotSecurityException { Contentlet contentlet = null; if (request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE) != null) { final String inode = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); contentlet = this.contentletAPI.find(inode, user, false); <START> } else if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET)) { <END> final String id = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET); contentlet = this.contentletAPI.findContentletByIdentifierAnyLanguage(id); } return Optional.ofNullable(contentlet); }</code><technical_language>is condition inverted above</technical_language>

Target:
private Optional<Contentlet> findUrlContentlet(final HttpServletRequest request) throws DotDataException, DotSecurityException { Contentlet contentlet = null; if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE)) { final String inode = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); contentlet = this.contentletAPI.find(inode, user, false); } else if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET)) { final String id = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET); contentlet = this.contentletAPI.findContentletByIdentifierAnyLanguage(id); } return Optional.ofNullable(contentlet); }
Source:
<code>public Label getToolchainLabel() { <START> if (useRemoteJavaToolchain) { <END> return Label.parseAbsoluteUnchecked("@bazel_tools } return toolchainLabel; }</code><technical_language>If people explicitly a toolchain, get selection. This is important want turn this incompatible flag default in 0.24 so. current code override this remote toolchain</technical_language>

Target:
public Label getToolchainLabel() { return toolchainLabel; }
Source:
<code>public void handleConfigurationUpdate(Map<String, Object> configurationParameters) { validateConfigurationParameters(configurationParameters); Configuration configuration = editConfiguration(); for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) { configuration.put(configurationParmeter.getKey(), configurationParmeter.getValue()); } <START> if (ThingHandlerHelper.isHandlerInitialized(this)) { <END> dispose(); updateConfiguration(configuration); initialize(); } else { updateConfiguration(configuration); callback.configurationUpdated(getThing()); } }</code><technical_language>binding developers need this feature well, I prefer a protectedisInitialized() method BaseThingHandler (which in turn call ThingHandlerHelper). This easier for developers find out existence of ThingHandlerHelper all</technical_language>

Target:
public void handleConfigurationUpdate(Map<String, Object> configurationParameters) { validateConfigurationParameters(configurationParameters); Configuration configuration = editConfiguration(); for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) { configuration.put(configurationParmeter.getKey(), configurationParmeter.getValue()); } if (isInitialized()) { dispose(); updateConfiguration(configuration); initialize(); } else { updateConfiguration(configuration); callback.configurationUpdated(getThing()); } }
Source:
<code>public void testInvokeSLSBthoughSingleton() { String echo = "this it testing string"; String sss = ""; try { sss = testSingleton.test(echo); } catch (Exception ee) { <START> Assert.fail("It is not possible to invoke SLSB through singleton, when ClientInterceptor is registered via META-INF/services"); <END> } Assert.assertTrue("SLSB returned wrong value through singleton", sss.equals(echo)); }</code><technical_language>This is a bad practice, if test is fail exception propagate, more info for figure out failed a generic log message</technical_language>

Target:
public void testInvokeSLSBthoughSingleton() throws Exception { String echo = "this it testing string"; String result = testSingleton.test(echo); Assert.assertTrue("SLSB returned wrong value through singleton", result.equals(clientInterceptorPrefix + echo)); }
Source:
<code>public void finish() { String shelltext = getText(); new PushButton("Finish").click(); <START> new WaitWhile(new ShellIsActive(shelltext)); <END> }</code><technical_language>ShellIsAvailable(this)</technical_language>

Target:
public void finish() { new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(this)); }
Source:
<code>protected void onPinnedEndpointsChangedEvent( JSONObject jsonObject, Set<String> newPinnedEndpoints) { <START> pinnedEndpointConstraintsStream = newPinnedEndpoints <END> .stream() .map(EndpointConstraints::makePinnedEndpointConstraints); onEndpointConstraintsChangedEvent(); }</code><technical_language>setting a member variable firing event for read variable, I this step pass new list onEndpointConstraintsChangedEvent, handler for place sets member variable pinnedEndpointConstraintsStream</technical_language>

Target:
protected void onPinnedEndpointsChangedEvent( JSONObject jsonObject, Set<String> newPinnedEndpoints) { videoConstraintsCompatibility.setPinnedEndpoints(newPinnedEndpoints); onVideoConstraintsChangedEvent( videoConstraintsCompatibility.computeVideoConstraints()); }
Source:
<code>public static @NonNull String duration() { return Objects.requireNonNull(Messages.TmfTime_Duration); <START> } <END></code><technical_language>strong a convention this is, prefix is class used, TmfStrings_*</technical_language>

Target:
public static @NonNull String duration() { return Objects.requireNonNull(Messages.TmfStrings_Duration); }
Source:
<code>public Comment createComment(CoreSession session, Comment comment) throws IllegalArgumentException { DocumentRef commentRef = new IdRef(comment.getDocumentId()); if (!session.exists(commentRef)) { throw new IllegalArgumentException("The document " + comment.getDocumentId() + " does not exist."); } DocumentModel docToComment = session.getDocument(commentRef); DocumentModel commentModel = session.createDocumentModel(COMMENT_DOC_TYPE); commentModel.setPropertyValue("dc:created", Calendar.getInstance()); <START> <END> Comments.externalCommentToDocumentModel().accept(comment, commentModel); DocumentModel createdCommentModel = createComment(docToComment, commentModel); return Comments.newComment(createdCommentModel); }</code><technical_language>do need this ? done DublinCoreService</technical_language>

Target:
public Comment createComment(CoreSession session, Comment comment) throws IllegalArgumentException { DocumentRef commentRef = new IdRef(comment.getDocumentId()); if (!session.exists(commentRef)) { throw new IllegalArgumentException("The document " + comment.getDocumentId() + " does not exist."); } DocumentModel docToComment = session.getDocument(commentRef); DocumentModel commentModel = session.createDocumentModel(COMMENT_DOC_TYPE); commentModel.setPropertyValue("dc:created", Calendar.getInstance()); Comments.commentToDocumentModel(comment, commentModel); if (comment instanceof ExternalEntity) { commentModel.addFacet(EXTERNAL_ENTITY_FACET); Comments.externalEntityToDocumentModel((ExternalEntity) comment, commentModel); } DocumentModel createdCommentModel = createComment(docToComment, commentModel); return Comments.newComment(createdCommentModel); }
Source:
<code>private static String formatString(String sep, Object... msg) { <START> String m = ""; <END> for (Object o : msg) { m += String.valueOf(o) + sep; } return m; }</code><technical_language>stringbuilder</technical_language>

Target:
private static String formatString(String sep, Object... msg) { StringBuilder stringBuilder = new StringBuilder(); for (Object o : msg) { stringBuilder.append(String.valueOf(o)).append(sep); } return stringBuilder.toString(); }
Source:
<code>public FileIteratingFirehose( Iterator<LineIterator> lineIterators, StringInputRowParser parser ) { this.lineIterators = lineIterators; this.parser = parser; final ParseSpec parseSpec = parser.getParseSpec(); <START> if (parseSpec instanceof CSVParseSpec) { <END> final Integer maxNumSkipHeadRows = ((CSVParseSpec) parseSpec).getMaxNumSkipHeadRows(); this.maxNumSkipHeadRows = maxNumSkipHeadRows == null ? DEFAULT_NUM_SKIP_HEAD_ROWS : maxNumSkipHeadRows; } else if (parseSpec instanceof DelimitedParseSpec) { final Integer maxNumSkipHeadRows = ((DelimitedParseSpec) parseSpec).getMaxNumSkipHeadRows(); this.maxNumSkipHeadRows = maxNumSkipHeadRows == null ? DEFAULT_NUM_SKIP_HEAD_ROWS : maxNumSkipHeadRows; } else { maxNumSkipHeadRows = DEFAULT_NUM_SKIP_HEAD_ROWS; } }</code><technical_language>Hmm, of a do this instanceof. In #4198 strategy is for parser return null for rows want skip. work too</technical_language>

Target:
public FileIteratingFirehose( Iterator<LineIterator> lineIterators, StringInputRowParser parser ) { this.lineIterators = lineIterators; this.parser = parser; }
Source:
<code>public Collection<BuildTarget<?>> computeDependencies(BuildTargetRegistry targetRegistry, TargetOutputIndex outputIndex) { <START> return Collections.emptyList(); <END> }</code><technical_language>ContainerUtil</technical_language>

Target:
public Collection<BuildTarget<?>> computeDependencies(BuildTargetRegistry targetRegistry, TargetOutputIndex outputIndex) { return ContainerUtil.emptyList(); }
Source:
<code>public void testConnectionWithCustomSchema() throws Exception { Connection fooConn = DriverManager.getConnection(String.format("crate://%s/foo", hostAndPort)); assertThat(fooConn.getSchema(), is("foo")); Statement statement = fooConn.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); ResultSet resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); Connection barConnection = DriverManager.getConnection(String.format("crate://%s/bar", hostAndPort)); assertThat(barConnection.getSchema(), is("bar")); statement = barConnection.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); <START> assertThat(resultSet.getLong(1), is(1L)); <END> }</code><technical_language>ensure a call information_schema.tables tables exist, doc.t created</technical_language>

Target:
public void testConnectionWithCustomSchema() throws Exception { Connection fooConn = DriverManager.getConnection(String.format("crate://%s/foo", hostAndPort)); assertThat(fooConn.getSchema(), is("foo")); Statement statement = fooConn.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); ResultSet resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); Connection barConnection = DriverManager.getConnection(String.format("crate://%s/bar", hostAndPort)); assertThat(barConnection.getSchema(), is("bar")); statement = barConnection.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); resultSet = statement.executeQuery( "select collect_set(schema_name) from information_schema.tables where table_name = 't'"); resultSet.next(); Object[] objects = (Object[]) resultSet.getObject(1); String[] schemas = Arrays.copyOf(objects, objects.length, String[].class); assertThat(schemas, Matchers.arrayContainingInAnyOrder("foo", "bar")); }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (o == null || getClass() != o.getClass()) return false; AccessModel that = (AccessModel) o; return Objects.equal(perRepositoryAuthorities, that.perRepositoryAuthorities) && Objects.equal(perRepositoryPaths, that.perRepositoryPaths); }</code><technical_language>![MAJOR](<LINK_2> 'Severity: MAJOR') Missing curly brace. [![rule](<LINK_3>](<LINK_1> ![MAJOR](<LINK_2> 'Severity: MAJOR') statement is allowed line, 2 statements this line. [![rule](<LINK_3>](<LINK_0></technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AccessModel that = (AccessModel) o; return Objects.equal(urlToPrivilegesMap, that.urlToPrivilegesMap); }
Source:
<code>public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException { int PERMISSIONS_MASK = 07777; int MAX_SUPPORTED_MODE = 0b111111111; mode = mode & PERMISSIONS_MASK; if ((mode & MAX_SUPPORTED_MODE) != mode) { throw new IOException("Invalid mode: " + mode); } PosixFilePermission[] allPermissions = PosixFilePermission.values(); <START> Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); <END> for (int i = 0; i < allPermissions.length; i++) { if ((mode & 1) == 1) { result.add(allPermissions[allPermissions.length - i - 1]); } mode >>= 1; } return result; }</code><technical_language>Is covered tests? <LINK_0> is explicit, I aware some modifications return a non-modifyable set (performance tweaks)</technical_language>

Target:
public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException { int PERMISSIONS_MASK = 07777; int MAX_SUPPORTED_MODE = 0777; mode = mode & PERMISSIONS_MASK; if ((mode & MAX_SUPPORTED_MODE) != mode) { throw new IOException("Invalid mode: " + mode); } PosixFilePermission[] allPermissions = PosixFilePermission.values(); Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); for (int i = 0; i < allPermissions.length; i++) { if ((mode & 1) == 1) { result.add(allPermissions[allPermissions.length - i - 1]); } mode >>= 1; } return result; }
Source:
<code><START> public static Properties loadProperties(Class<?> clazz, String resource) { <END> return loadProperties(clazz.getResourceAsStream(resource)); }</code><technical_language>I do this anywhere, remove</technical_language>

Target:
private static Properties loadProperties(Class<?> clazz, String resource) { return loadProperties(clazz.getResourceAsStream(resource)); }