auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testDeleteByIdAndPartitionKey() { final Mono<Void> deleteMono = repository.deleteById(DOMAIN_1.getNumber(), new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(deleteMono).verifyComplete(); Mono<LongIdDomainPartition> findIdMono = this.repository.findById(ID_1, new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); <START> StepVerifier.create(findIdMono).verifyComplete(); <END> }</code><technical_language>here, expectNextCount = 0</technical_language>

Target:
public void testDeleteByIdAndPartitionKey() { final Mono<Void> deleteMono = repository.deleteById(DOMAIN_1.getNumber(), new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(deleteMono).verifyComplete(); Mono<LongIdDomainPartition> findIdMono = this.repository.findById(ID_1, new PartitionKey(entityInformation.getPartitionKeyFieldValue(DOMAIN_1))); StepVerifier.create(findIdMono).expectNextCount(0).verifyComplete(); }
Source:
<code><START> GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { <END> super(parameters); }</code><technical_language>is package private</technical_language>

Target:
public GetAllSupportedNetworkFiltersByVersionQuery(VersionQueryParameters parameters) { super(parameters); }
Source:
<code>public double getPercent() { <START> final double extent = this.max - (double) this.min; <END> if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }</code><technical_language>here, extent integer</technical_language>

Target:
public double getPercent() { final int extent = this.max - this.min; if (extent == 0.) { return 0.; } return (this.current - this.min) * 100. / extent; }
Source:
<code>public T build() { <START> return builderFunction.build(this); <END> }</code><technical_language>If Function<ClientBuilderImpl, T> for build function type, instead of a custom interface, this method return builderFunction.apply(this);</technical_language>

Target:
public T build() { return builderFunction.apply(this); }
Source:
<code>public GraphInfo<?> getGraphInfo() { final DefaultGraphInfo graphInfo = new DefaultGraphInfo(TOPOLOGY_NAMESPACE, SimpleVertex.class); graphInfo.setLabel("Application Graph"); <START> graphInfo.setDescription("This Topology Provider displays the hierarchy of TODO."); END> return graphInfo; }</code><technical_language>This Topology Provider displays defined Applications calculated states. Source <LINK_1> refer implementation <LINK_0></technical_language>

Target:
public GraphInfo<?> getGraphInfo() { final DefaultGraphInfo graphInfo = new DefaultGraphInfo(TOPOLOGY_NAMESPACE, ApplicationVertex.class); graphInfo.setLabel(GRAPH_LABEL); graphInfo.setDescription(GRAPH_DESCRIPTION); return graphInfo; }
Source:
<code>public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException { ByteBuffer byteBuffer; <START> if (Platform.OS_WIN32.equals(Platform.getOS())) { <END> byteBuffer = ByteBuffer.allocate((int) size); fc.read(byteBuffer, position); } else { byteBuffer = fc.map(mode, position, size); } return byteBuffer; }</code><technical_language>this cached? I hope TMF migrate, I this is a fix slow Linux</technical_language>

Target:
public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException { ByteBuffer byteBuffer; if (IS_WIN32) { byteBuffer = ByteBuffer.allocate((int) size); fc.read(byteBuffer, position); } else { byteBuffer = fc.map(mode, position, size); } return byteBuffer; }
Source:
<code>public List<ArticleRelationship> getRelationshipsTo(ArticleIdentifier targetId) { return (List<ArticleRelationship>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT ar " + <START> "FROM VersionedArticleRelationship ar " + <END> "WHERE ar.targetArticle.doi = :doi "); query.setParameter("doi", targetId.getDoiName()); return query.list(); }); }</code><technical_language>this ArticleRelationship</technical_language>

Target:
public List<ArticleRelationship> getRelationshipsTo(ArticleIdentifier targetId) { return (List<ArticleRelationship>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT ar " + "FROM ArticleRelationship ar " + "WHERE ar.targetArticle.doi = :doi "); query.setParameter("doi", targetId.getDoiName()); return query.list(); }); }
Source:
<code>public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); Stat returnStat = null; if ( backgrounding.inBackground() ) { OperationAndData<String> operationAndData = new OperationAndData<String>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); if ( createParentContainersIfNeeded || createParentsIfNeeded ) { <START> CreateBuilderImpl.backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData(), backgrounding, client.getAclProvider(), createParentContainersIfNeeded); <END> } else { client.processBackgroundOperation(operationAndData, null); } } else { returnStat = pathInForeground(path); } return returnStat; }</code><technical_language>ExistsBuilder ability set ACL provider for parent containers well, provide option of creating parent containers</technical_language>

Target:
public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); Stat returnStat = null; if ( backgrounding.inBackground() ) { OperationAndData<String> operationAndData = new OperationAndData<String>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); if ( createParentContainersIfNeeded || createParentsIfNeeded ) { CreateBuilderImpl.backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData(), backgrounding, acling.getACLProviderForParents(), createParentContainersIfNeeded); } else { client.processBackgroundOperation(operationAndData, null); } } else { returnStat = pathInForeground(path); } return returnStat; }
Source:
<code>public void releaseSlotFor(LocalAssignment assignment, int port) throws IOException { PortAndAssignment pna = new PortAndAssignmentImpl(port, assignment); final String topologyId = assignment.get_topology_id(); LOG.debug("Releasing slot for {}", topologyId, port); String topoJarKey = ConfigUtils.masterStormJarKey(topologyId); String topoCodeKey = ConfigUtils.masterStormCodeKey(topologyId); String topoConfKey = ConfigUtils.masterStormConfKey(topologyId); LocallyCachedBlob topoJar = topologyBlobs.get(topoJarKey); if (topoJar != null) { topoJar.removeReference(pna); } LocallyCachedBlob topoCode = topologyBlobs.get(topoCodeKey); if (topoCode != null) { topoCode.removeReference(pna); } LocallyCachedBlob topoConfBlob = topologyBlobs.get(topoConfKey); if (topoConfBlob != null) { topoConfBlob.removeReference(pna); } List<LocalResource> localResources = null; try { localResources = getLocalResources(pna); } catch (FileNotFoundException fnfException) { LOG.warn("Local base blobs have not been downloaded yet. " + "DownloadExecService is too busy", fnfException); return; } catch (IOException ioException) { LOG.error("Unable to read local conf file. ", ioException); throw ioException; } <START> <END> for (LocalResource lr : localResources) { try { removeBlobReference(lr.getBlobName(), pna, lr.shouldUncompress()); } catch (Exception e) { throw new IOException(e); } } }</code><technical_language>add pna this message IOException error? is side effect of releasing this if a race condition? localizer updating this file continually</technical_language>

Target:
public void releaseSlotFor(LocalAssignment assignment, int port) throws IOException { PortAndAssignment pna = new PortAndAssignmentImpl(port, assignment); final String topologyId = assignment.get_topology_id(); LOG.debug("Releasing slot for {}", topologyId, port); String topoJarKey = ConfigUtils.masterStormJarKey(topologyId); String topoCodeKey = ConfigUtils.masterStormCodeKey(topologyId); String topoConfKey = ConfigUtils.masterStormConfKey(topologyId); LocallyCachedBlob topoJar = topologyBlobs.get(topoJarKey); if (topoJar != null) { topoJar.removeReference(pna); } LocallyCachedBlob topoCode = topologyBlobs.get(topoCodeKey); if (topoCode != null) { topoCode.removeReference(pna); } LocallyCachedBlob topoConfBlob = topologyBlobs.get(topoConfKey); if (topoConfBlob != null) { topoConfBlob.removeReference(pna); } List<LocalResource> localResources; try { localResources = getLocalResources(pna); } catch (IOException e) { LOG.info("Port and assignment info: {}", pna); if (e instanceof FileNotFoundException) { localResourceFileNotFoundWhenReleasingSlot.mark(); LOG.warn("Local base blobs have not been downloaded yet. ", e); return; } else { LOG.error("Unable to read local file. ", e); throw e; } } for (LocalResource lr : localResources) { removeBlobReference(lr.getBlobName(), pna, lr.shouldUncompress()); } }
Source:
<code><START> public void test_named_parameters() throws Throwable { <END> Class<?> moduleClass = compileAndLoadGoloModule(SRC, "namedparameters-function-calls.golo"); Method createPost = moduleClass.getMethod("create_post", Object.class, Object.class, Object.class); GoloFunction annotatation = createPost.getAnnotation(GoloFunction.class); assertThat(annotatation, is(notNullValue())); assertThat(Arrays.asList(annotatation.parameters()), containsInAnyOrder("author", "title", "content")); Method createPostOk = moduleClass.getMethod("create_post_ok"); String result = (String) createPostOk.invoke(null); assertThat(result, is("John Awesome Post Lorem Ipsum")); Method createPostWithInvalidArgumentName = moduleClass.getMethod("create_post_with_invalid_argument_name"); try { createPostWithInvalidArgumentName.invoke(null); fail("Exception should have been thrown"); } catch (InvocationTargetException e) { assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertThat(iae.getMessage(), is("Argument name foo not in parameter names used in declaration: create_post[author, title, content]")); } Method csvBuilder = moduleClass.getMethod("csv_builder"); result = (String) csvBuilder.invoke(null); assertThat(result, is("a,b,c")); }</code><technical_language>I create a new enum entry specifically for problem, throw a GoloCompilationException</technical_language>

Target:
public void test_named_parameters() throws Throwable { Class<?> moduleClass = compileAndLoadGoloModule(SRC, "namedparameters-function-calls.golo"); Method createPostOk = moduleClass.getMethod("create_post_ok"); String result = (String) createPostOk.invoke(null); assertThat(result, is("John Awesome Post Lorem Ipsum")); Method createPostWithInvalidArgumentName = moduleClass.getMethod("create_post_with_invalid_argument_name"); try { createPostWithInvalidArgumentName.invoke(null); fail("Exception should have been thrown"); } catch (InvocationTargetException e) { assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertThat(iae.getMessage(), is("Argument name foo not in parameter names used in declaration: create_post[author, title, content]")); } Method csvBuilder = moduleClass.getMethod("csv_builder"); result = (String) csvBuilder.invoke(null); assertThat(result, is("a,b,c")); try { compileAndLoadGoloModule(SRC, "failure-function-call-with-named-and-unamed-args.golo"); fail("A GoloCompilationException was expected"); } catch (GoloCompilationException e) { assertThat(e.getProblems().size(), is(1)); Problem problem = e.getProblems().get(0); assertThat(problem.getType(), is(INCOMPLETE_NAMED_ARGUMENTS_USAGE)); } Method golo_decoratored = moduleClass.getMethod("golo_decoratored"); result = (String) golo_decoratored.invoke(null); assertThat(result, is("<Golo>")); Method golo_augmentation_varargs = moduleClass.getMethod("golo_augmentation_varargs"); result = (String) golo_augmentation_varargs.invoke(null); assertThat(result, is("abc")); }
Source:
<code>protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
<code>public void setPriority(int priority) { if (NICE_VALUES.length != (1 + Thread.MAX_PRIORITY - Thread.MIN_PRIORITY)) { throw new <START> AssertionError("NICE_VALUES[] length is not correct"); <END> } if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { throw new IllegalArgumentException("Priority out of range: " + priority); } Process.setThreadPriority(NICE_VALUES[priority - Thread.MIN_PRIORITY]); }</code><technical_language>quoting offending value: "Unexpected NICE_VALUES.length=" + NICE_VALUES.length</technical_language>

Target:
public void setPriority(int priority) { if (NICE_VALUES.length != (1 + Thread.MAX_PRIORITY - Thread.MIN_PRIORITY)) { throw new AssertionError("Unexpected NICE_VALUES.length=" + NICE_VALUES.length); } if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { throw new IllegalArgumentException("Priority out of range: " + priority); } Process.setThreadPriority(NICE_VALUES[priority - Thread.MIN_PRIORITY]); }
Source:
<code>private static List<Policy> parse(String policyString) { List<Policy> list = new LinkedList<Policy>(); String[] policies = policyString.split(" and "); for (String policy : policies) { policy = policy.trim(); String name; String[] args = null; int i = policy.indexOf('('); if (i == -1) { name = policy.trim(); } else { name = policy.substring(0, i).trim(); args = policy.substring(i + 1, policy.length() - 1).split(","); for (int j = 0; j < args.length; j++) { args[j] = args[j].trim(); } } if (name.equals(Length.NAME)) { list.add(new Length(args)); } else if (name.equals(Digits.NAME)) { list.add(new Digits(args)); } else if (name.equals(LowerCase.NAME)) { list.add(new LowerCase(args)); } else if (name.equals(UpperCase.NAME)) { list.add(new UpperCase(args)); } else if (name.equals(SpecialChars.NAME)) { list.add(new SpecialChars(args)); } else if (name.equals(NotUsername.NAME)) { list.add(new NotUsername(args)); } else if (name.equals(HashIterations.NAME)) { list.add(new HashIterations(args)); } else if (name.equals(RegexPatterns.NAME)) { for (String regexPattern : args) { Pattern.compile(regexPattern); } list.add(new RegexPatterns(args)); <START> } else if (name.equals(ExpiredPasswords.NAME)) { <END> list.add(new ExpiredPasswords(args)); } } return list; }</code><technical_language>I ExpiredPasswords is correct name for this policy</technical_language>

Target:
private static List<Policy> parse(String policyString) { List<Policy> list = new LinkedList<Policy>(); String[] policies = policyString.split(" and "); for (String policy : policies) { policy = policy.trim(); String name; String[] args = null; int i = policy.indexOf('('); if (i == -1) { name = policy.trim(); } else { name = policy.substring(0, i).trim(); args = policy.substring(i + 1, policy.length() - 1).split(","); for (int j = 0; j < args.length; j++) { args[j] = args[j].trim(); } } if (name.equals(Length.NAME)) { list.add(new Length(args)); } else if (name.equals(Digits.NAME)) { list.add(new Digits(args)); } else if (name.equals(LowerCase.NAME)) { list.add(new LowerCase(args)); } else if (name.equals(UpperCase.NAME)) { list.add(new UpperCase(args)); } else if (name.equals(SpecialChars.NAME)) { list.add(new SpecialChars(args)); } else if (name.equals(NotUsername.NAME)) { list.add(new NotUsername(args)); } else if (name.equals(HashIterations.NAME)) { list.add(new HashIterations(args)); } else if (name.equals(RegexPatterns.NAME)) { for (String regexPattern : args) { Pattern.compile(regexPattern); } list.add(new RegexPatterns(args)); } else if (name.equals(PasswordHistory.NAME)) { list.add(new PasswordHistory(args)); } } return list; }
Source:
<code>protected OperatingMode determineOperatingMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { <START> Thread.sleep(1200); <END> boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (InvalidOperatingModeException e1) { } catch (XBeeException e1) { } catch (InterruptedException e2) { } } catch (InvalidOperatingModeException e) { } return OperatingMode.UNKNOWN; }</code><technical_language>Move this time a constant</technical_language>

Target:
protected OperatingMode determineOperatingMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { if (e.getErrorCode() == XBeeException.CONNECTION_TIMEOUT) { operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (InvalidOperatingModeException e1) { } catch (XBeeException e1) { } catch (InterruptedException e2) { } } } catch (InvalidOperatingModeException e) { } return OperatingMode.UNKNOWN; }
Source:
<code>public ZkCoordinator( SegmentLoadDropHandler loadDropHandler, ObjectMapper jsonMapper, ZkPathsConfig zkPaths, DruidServerMetadata me, CuratorFramework curator, SegmentLoaderConfig config ) { this.dataSegmentChangeHandler = loadDropHandler; this.jsonMapper = jsonMapper; this.zkPaths = zkPaths; this.me = me; this.curator = curator; <START> this.loadSegmentService = Executors.newFixedThreadPool( <END> config.getNumLoadingThreads(), new ThreadFactoryBuilder().setNameFormat( "ZKCoordinator-LoadSegment--%d").build() ); }</code><technical_language>Execs.multiThreaded. shorter, daemon threads automatically, preferred block JVM shutdown</technical_language>

Target:
public ZkCoordinator( SegmentLoadDropHandler loadDropHandler, ObjectMapper jsonMapper, ZkPathsConfig zkPaths, DruidServerMetadata me, CuratorFramework curator, SegmentLoaderConfig config ) { this.dataSegmentChangeHandler = loadDropHandler; this.jsonMapper = jsonMapper; this.zkPaths = zkPaths; this.me = me; this.curator = curator; this.segmentLoadUnloadService = Execs.multiThreaded( config.getNumLoadingThreads(), "ZKCoordinator--%d" ); }
Source:
<code>private static Object readArrayTillTheEnd(final StringTokenizer tokenizer) { final JSONArray result = new JSONArray(); final char possibleEnd = tokenizer.nextUnskippable(); if (possibleEnd == ']') { return result; } tokenizer.back(); boolean finished = false; while (!finished) { result.put(parse(tokenizer)); final char separator = tokenizer.nextUnskippable(); if (separator == ']') { finished = true; } else if (separator != ',') { <START> throw syntaxError("Unexpected separator " + separator, tokenizer); <END> } } return result; }</code><technical_language>please put separator in single quotes</technical_language>

Target:
private static Object readArrayTillTheEnd(final StringTokenizer tokenizer) { final JSONArray result = new JSONArray(); final char possibleEnd = tokenizer.nextUnskippable(); if (possibleEnd == ']') { return result; } tokenizer.back(); boolean finished = false; while (!finished) { result.put(parse(tokenizer)); final char separator = tokenizer.nextUnskippable(); if (separator == ']') { finished = true; } else if (separator != ',') { throw syntaxError("Unexpected separator '" + separator + "'", tokenizer); } } return result; }
Source:
<code>public Iterable<SingleServerAppliance> listImages() { GenericQueryOptions options = new GenericQueryOptions(); <START> options.options(0, 0, null, Types.OSImageType.Minimal.toString(), null); <END> List<ServerAppliance> list = api.serverApplianceApi().list(options); List<SingleServerAppliance> results = new ArrayList<SingleServerAppliance>(); for (ServerAppliance appliance : list) { List<SingleServerAppliance.AvailableDataCenters> availableDatacenters = new ArrayList<SingleServerAppliance.AvailableDataCenters>(); for (String dcId : appliance.availableDataCenters()) { availableDatacenters.add(SingleServerAppliance.AvailableDataCenters.create(dcId, "")); } results.add(SingleServerAppliance.create(appliance.id(), appliance.name(), availableDatacenters, appliance.osInstallationBase(), appliance.osFamily(), appliance.os(), appliance.osVersion(), appliance.osArchitecture(), appliance.osImageType(), appliance.minHddSize(), appliance.type(), appliance.state(), appliance.version(), appliance.categories(), appliance.eulaUrl())); } return results; }</code><technical_language>Minimal</technical_language>

Target:
public Iterable<SingleServerAppliance> listImages() { GenericQueryOptions options = new GenericQueryOptions(); options.options(0, 0, null, null, null); List<ServerAppliance> list = api.serverApplianceApi().list(options); List<SingleServerAppliance> results = new ArrayList<SingleServerAppliance>(); for (ServerAppliance appliance : list) { List<SingleServerAppliance.AvailableDataCenters> availableDatacenters = new ArrayList<SingleServerAppliance.AvailableDataCenters>(); for (String dcId : appliance.availableDataCenters()) { availableDatacenters.add(SingleServerAppliance.AvailableDataCenters.create(dcId, "")); } results.add(SingleServerAppliance.builder() .id(appliance.id()) .name(appliance.name()) .availableDataCenters(availableDatacenters) .osInstallationBase(appliance.osInstallationBase()) .osFamily(appliance.osFamily()) .os(appliance.os()) .osVersion(appliance.osVersion()) .osArchitecture(appliance.osArchitecture()) .osImageType(appliance.osImageType()) .minHddSize(appliance.minHddSize()) .type(appliance.type()) .state(appliance.state()) .version(appliance.version()) .categories(appliance.categories()) .eulaUrl(appliance.eulaUrl()) .build()); } return results; }
Source:
<code>private Optional<PinotExpression> handleDateOrTimestampBinaryExpression(String operator, List<RowExpression> arguments, Function<VariableReferenceExpression, Selection> context) { String leftDefinition = arguments.get(0).accept(this, context).getDefinition(); String rightDefinition = arguments.get(1).accept(this, context).getDefinition(); <START> Optional<String> left = handleTimeValueCast(arguments.get(1), arguments.get(0), leftDefinition); <END> Optional<String> right = handleTimeValueCast(arguments.get(0), arguments.get(1), rightDefinition); if (left.isPresent() && right.isPresent()) { return Optional.of(derived(format("(%s %s %s)", left.get(), operator, right.get()))); } else { return Optional.empty(); } }</code><technical_language>a bit weird "left" arguments end. I wondering if simpler read changing order of arguments to: Optional<String> left = handleTimeValueCast(arguments.get(0), leftDefinition, arguments.get(1));</technical_language>

Target:
private Optional<PinotExpression> handleDateOrTimestampBinaryExpression(String operator, List<RowExpression> arguments, Function<VariableReferenceExpression, Selection> context) { Optional<String> left = handleTimeValueCast(context, arguments.get(1), arguments.get(0)); Optional<String> right = handleTimeValueCast(context, arguments.get(0), arguments.get(1)); if (left.isPresent() && right.isPresent()) { return Optional.of(derived(format("(%s %s %s)", left.get(), operator, right.get()))); } else { return Optional.empty(); } }
Source:
<code>public static Route fromLearned(org.midonet.midolman.layer3.Route from) { Route route = new Route(); <START> route.id = new UUID(0xffffffffffffffffL, 0xffffffffffffffffL); <END> route.dstNetworkAddr = IPv4Addr.apply(from.dstNetworkAddr).toString(); route.dstNetworkLength = from.dstNetworkLength; route.srcNetworkAddr = IPv4Addr.apply(from.srcNetworkLength).toString(); route.srcNetworkLength = from.srcNetworkLength; route.nextHopGateway = IPv4Addr.apply(from.nextHopGateway).toString(); route.weight = from.weight; route.routerId = from.routerId; route.nextHopPort = from.nextHopPort; route.type = NextHop.Normal; route.learned = true; return route; }</code><technical_language>this stored in ZK ZOOM? If case, is this supposed a unique instance</technical_language>

Target:
public static Route fromLearned(org.midonet.midolman.layer3.Route from) { Route route = new Route(); route.id = NO_ID; route.dstNetworkAddr = IPv4Addr.apply(from.dstNetworkAddr).toString(); route.dstNetworkLength = from.dstNetworkLength; route.srcNetworkAddr = IPv4Addr.apply(from.srcNetworkAddr).toString(); route.srcNetworkLength = from.srcNetworkLength; route.nextHopGateway = IPv4Addr.apply(from.nextHopGateway).toString(); route.weight = from.weight; route.routerId = from.routerId; route.nextHopPort = from.nextHopPort; route.type = NextHop.Normal; route.learned = true; return route; }
Source:
<code>protected File getAbsoluteFile( String bundleName, String relativePath ) { String absolutePath = this.managedResourcesFolder.getAbsolutePath(); <START> absolutePath += "/" + bundleName; <END> absolutePath += ( relativePath.startsWith( "/" ) ? "" : "/" ) + relativePath .replace( MANAGED_RESOURCES_DIR, "" ); return new File( absolutePath ); }</code><technical_language>File separator</technical_language>

Target:
protected File getAbsoluteFile( String bundleName, String relativePath ) { return Paths.get( this.managedResourcesFolder.getPath(), bundleName, relativePath.replace( MANAGED_RESOURCES_DIR, "" ) ) .toFile(); }
Source:
<code>public Models getModels() { if (!mModels.getLoaded()) { loadModels(); } <START> while (!mModels.getLoaded()) { <END> try { Timber.d("Waiting for models"); new Exception().printStackTrace(); TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } } return mModels; }</code><technical_language>I guess missing point of a Future... This loop is unnecessary, call .get() task block thread joined</technical_language>

Target:
public Models getModels() { if (futureLoadingModel == null) { loadModels(); } try { futureLoadingModel.get(); } catch (ExecutionException | InterruptedException e) { return mModels.load(loadColumn("models")); } return mModels; }
Source:
<code>public void initialized() { initialized = true; if (gerritPushTargetPanels.size() == 1) { String branchName; try { String gitReviewFilePath = StringUtils.join( new String[]{ProjectManager.getInstance().getOpenProjects()[0].getBasePath(), GITREVIEW_FILENAME}, File.separator); Properties properties = new Properties(); properties.load(new FileInputStream(gitReviewFilePath)); branchName = properties.getProperty("defaultbranch"); <START> } catch (IOException e) { <END> branchName = gerritPushTargetPanels.values().iterator().next(); } if (branchName == null) { branchName = gerritPushTargetPanels.values().iterator().next(); } branchTextField.setText(branchName); } SwingUtilities.invokeLater(new Runnable() { public void run() { initDestinationBranch(); } }); }</code><technical_language>I checking if file exists a bit nicer instead of catching exception. Also, catch block empty, do branchName assignment is empty a lines below. Please extract this reading code a new method</technical_language>

Target:
public void initialized() { initialized = true; if (gerritPushTargetPanels.size() == 1) { String branchName = gerritPushTargetPanels.values().iterator().next(); Optional<String> gitReviewBranchName = getGitReviewBranchName(); branchTextField.setText(gitReviewBranchName.or(branchName)); } SwingUtilities.invokeLater(new Runnable() { public void run() { initDestinationBranch(); } }); }
Source:
<code>public static WebArchive appDeployment1() { WebArchive war = ShrinkWrap.create(WebArchive.class, EJB_SECURITY + ".war"); war.addClasses(BasicAuthenticationMechanismPicketboxRemovedTestCase.class, SecuredEJB.class, SecuredEJBServlet.class); war.setWebXML(Utils.getResource("org/jboss/as/test/integration/web/security/authentication/deployment/web.xml")); war.addAsWebInfResource(Utils.getResource("org/jboss/as/test/integration/web/security/authentication/deployment/jboss-web.xml"), "jboss-web.xml"); <START> war.addAsWebInfResource(Utils.getResource("org/jboss/as/test/integration/web/security/authentication/deployment/beans.xml"), "beans.xml"); <END> war.addAsResource(BasicAuthenticationMechanismPicketboxRemovedTestCase.class.getPackage(), "jboss-ejb-client.properties", "jboss-ejb-client.properties"); return war; }</code><technical_language>need test for a specific successes condition (i.e. check invoke a secured EJB return a result). check output for a specific exception name call done. server completely broken throwing a exception this test pass</technical_language>

Target:
public static WebArchive appDeployment1() { WebArchive war = ShrinkWrap.create(WebArchive.class, EJB_SECURITY + ".war"); war.addClasses(BasicAuthenticationMechanismPicketboxRemovedTestCase.class, SecuredEJB.class, SecuredEJBServlet.class); war.addAsWebInfResource(BasicAuthenticationMechanismPicketboxRemovedTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml"); war.addAsWebInfResource(BasicAuthenticationMechanismPicketboxRemovedTestCase.class.getPackage(), "web.xml", "web.xml"); return war; }
Source:
<code>protected HashMap<Guid, AsyncTaskStatus> ParseTaskStatusList(XmlRpcStruct taskStatusList) { HashMap<Guid, AsyncTaskStatus> result = new HashMap<Guid, AsyncTaskStatus>( taskStatusList.getCount()); for (Map.Entry<String, ?> entry : taskStatusList.getEntries()) { try { Guid taskGuid = new Guid(entry.getKey().toString()); <START> Map<String, Object> xrsTaskStatusAsMAp = (Map<String, Object>) entry.getValue(); <END> XmlRpcStruct xrsTaskStatus = (xrsTaskStatusAsMAp == null) ? null : new XmlRpcStruct(xrsTaskStatusAsMAp); if (xrsTaskStatus == null) { log.errorFormat("Task ID {0} has no task data", entry.getKey().toString()); } else { TaskStatusForXmlRpc tempVar = new TaskStatusForXmlRpc(); tempVar.mCode = Integer.parseInt(xrsTaskStatus.getItem("code").toString()); tempVar.mMessage = xrsTaskStatus.getItem("message").toString(); tempVar.mTaskResult = xrsTaskStatus.getItem("taskResult").toString(); tempVar.mTaskState = xrsTaskStatus.getItem("taskState").toString(); TaskStatusForXmlRpc taskStatus = tempVar; AsyncTaskStatus task = ParseTaskStatus(taskStatus); result.put(taskGuid, task); } } catch (RuntimeException exp) { log.error( String.format( "HSMGetAllTasksStatusesVDSCommand: Error while parsing task status from list. key: %1$s, value: %2$s - ignoring.", entry.getKey().toString(), entry.getValue().toString()), exp); } } return result; }</code><technical_language>please clean ugly assignment of xrsTaskStatus</technical_language>

Target:
protected HashMap<Guid, AsyncTaskStatus> ParseTaskStatusList(XmlRpcStruct taskStatusList) { HashMap<Guid, AsyncTaskStatus> result = new HashMap<Guid, AsyncTaskStatus>( taskStatusList.getCount()); for (Map.Entry<String, ?> entry : taskStatusList.getEntries()) { try { Guid taskGuid = new Guid(entry.getKey().toString()); Map<String, Object> xrsTaskStatusAsMAp = (Map<String, Object>) entry.getValue(); if (xrsTaskStatusAsMAp == null) { log.errorFormat("Task ID {0} has no task data", entry.getKey().toString()); } else { XmlRpcStruct xrsTaskStatus = new XmlRpcStruct(xrsTaskStatusAsMAp); TaskStatusForXmlRpc tempVar = new TaskStatusForXmlRpc(); tempVar.mCode = Integer.parseInt(xrsTaskStatus.getItem("code").toString()); tempVar.mMessage = xrsTaskStatus.getItem("message").toString(); tempVar.mTaskResult = xrsTaskStatus.getItem("taskResult").toString(); tempVar.mTaskState = xrsTaskStatus.getItem("taskState").toString(); TaskStatusForXmlRpc taskStatus = tempVar; AsyncTaskStatus task = ParseTaskStatus(taskStatus); result.put(taskGuid, task); } } catch (RuntimeException exp) { log.error( String.format( "HSMGetAllTasksStatusesVDSCommand: Error while parsing task status from list. key: %1$s, value: %2$s - ignoring.", entry.getKey().toString(), entry.getValue().toString()), exp); } } return result; }
Source:
<code>public void testCheckVariantExistsDoesExist() throws URISyntaxException { <START> testCheckVariantExistsHelper("20:71822:C:G"); <END> }</code><technical_language>asserts removed</technical_language>

Target:
public void testCheckVariantExistsDoesExist() throws URISyntaxException { assertTrue(testCheckVariantExistsHelper("20:71822:C:G")); }
Source:
<code>public static Color getSWTColor(ColorByDefinition colorByDefinition) { Color color = colorByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return color; } RGB colorFromDefinition = provider.getColor(colorByDefinition.getSymbolicName()); if (colorFromDefinition != null && !colorFromDefinition.equals(color.getRGB())) { <START> color = new Color(color.getDevice(), colorFromDefinition); <END> } return color; }</code><technical_language>This resource needs managed disposed appropriate. org.eclipse.jface.resource.LocalResourceManager. change org.eclipse.e4.ui.internal.css.swt.definition.IColorAndFontProvider interface responsible for managing resource, if done</technical_language>

Target:
public static Color getSWTColor(ColorByDefinition colorByDefinition) { Color color = colorByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return color; } RGB colorFromDefinition = provider.getColor(colorByDefinition.getSymbolicName()); if (colorFromDefinition != null && !colorFromDefinition.equals(color.getRGB())) { Device device = color.getDevice(); color.dispose(); color = new Color(device, colorFromDefinition); colorByDefinition.setResource(color); } colorByDefinition.setValid(true); return color; }
Source:
<code>private TypeSpec createUnbinderClass() { ClassName targetClassName = ClassName.bestGuess(targetClass); MethodSpec unbinderConstructor = MethodSpec.constructorBuilder() .addParameter(targetClassName, "target") .addStatement("this.$1N = $1N", "target") .build(); TypeSpec.Builder result = TypeSpec.classBuilder(unbinderBinding.getUnbinderClassName().simpleName()) .addSuperinterface(UNBINDER) .addModifiers(PRIVATE, STATIC, FINAL) <START> .addField(targetClassName, "target", PRIVATE) <END> .addMethod(unbinderConstructor); MethodSpec.Builder unbindMethod = MethodSpec.methodBuilder("unbind") .addAnnotation(Override.class) .addModifiers(PUBLIC); for (ViewBindings bindings : viewIdMap.values()) { addFieldAndUnbindStatement(result, unbindMethod, bindings); for (FieldViewBinding fieldBinding : bindings.getFieldBindings()) { unbindMethod.addStatement("target.$L = null", fieldBinding.getName()); } } for (FieldCollectionViewBinding fieldCollectionBinding : collectionBindings.keySet()) { unbindMethod.addStatement("target.$L = null", fieldCollectionBinding.getName()); } unbindMethod.addStatement("target.$L = null", unbinderBinding.getUnbinderFieldName()); unbindMethod.addStatement("target = null"); result.addMethod(unbindMethod.build()); return result.build(); }</code><technical_language>+FINAL</technical_language>

Target:
private TypeSpec createUnbinderClass() { ClassName targetClassName = ClassName.bestGuess(targetClass); MethodSpec unbinderConstructor = MethodSpec.constructorBuilder() .addParameter(targetClassName, "target") .addStatement("this.$1N = $1N", "target") .build(); TypeSpec.Builder result = TypeSpec.classBuilder(unbinderBinding.getUnbinderClassName().simpleName()) .addSuperinterface(UNBINDER) .addModifiers(PRIVATE, STATIC, FINAL) .addField(targetClassName, "target", PRIVATE) .addMethod(unbinderConstructor); MethodSpec.Builder unbindMethod = MethodSpec.methodBuilder("unbind") .addAnnotation(Override.class) .addModifiers(PUBLIC); unbindMethod.addStatement("if (target == null) throw new $T($S)", IllegalStateException.class, "Bindings already cleared."); for (ViewBindings bindings : viewIdMap.values()) { addFieldAndUnbindStatement(result, unbindMethod, bindings); for (FieldViewBinding fieldBinding : bindings.getFieldBindings()) { unbindMethod.addStatement("target.$L = null", fieldBinding.getName()); } } for (FieldCollectionViewBinding fieldCollectionBinding : collectionBindings.keySet()) { unbindMethod.addStatement("target.$L = null", fieldCollectionBinding.getName()); } unbindMethod.addStatement("target.$L = null", unbinderBinding.getUnbinderFieldName()); unbindMethod.addStatement("target = null"); result.addMethod(unbindMethod.build()); return result.build(); }
Source:
<code>public void evaluate() throws Throwable { PackageManager pm = mContext.getPackageManager(); buildPackageList(SystemProperties.get(PACKAGE_PATH_PROPERTY), pm); if (mLoadPackages.isEmpty()) { throw new TestHelperException("No installed helper packages found"); } Log.d(LOG_TAG, "Helper search path: " + String.join(":", mSourceDirs)); mHelperManager = HelperManager.getInstance(mSourceDirs, mInstrumentation); for (String prefix : mPrefixes) { try { Pattern classMatch = Pattern.compile("^.*\\.\\Q" + prefix + "\\E[^.]*$"); mHelper = mHelperManager.get(mHelperClass, classMatch); break; } catch (TestHelperException e) { <START> Log.d( LOG_TAG, String.format( "No %s implementation found with prefix %s.", mHelperClass, prefix)); <END> } } mBase.evaluate(); }</code><technical_language>reduce this line</technical_language>

Target:
public void evaluate() throws Throwable { PackageManager pm = mContext.getPackageManager(); buildPackageList(SystemProperties.get(PACKAGE_PATH_PROPERTY), pm); if (mLoadPackages.isEmpty()) { throw new TestHelperException("No installed helper packages found"); } Log.d(LOG_TAG, "Helper search path: " + String.join(":", mSourceDirs)); mHelperManager = HelperManager.getInstance(mSourceDirs, mInstrumentation); for (String prefix : mPrefixes) { try { Pattern classMatch = Pattern.compile("^.*\\.\\Q" + prefix + "\\E[^.]*$"); mHelper = mHelperManager.get(mHelperClass, classMatch); break; } catch (TestHelperException e) { Log.d(LOG_TAG, String.format( "No %s implementation found with prefix %s.", mHelperClass, prefix), e); } } if (mHelper == null) { throw new TestHelperException("No implementation found for " + mHelperClass); } mBase.evaluate(); }
Source:
<code>public JedisSentinelPool(String masterName, Set<String> sentinels, final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, final String password, final int database, final String clientName, <START> final int sentinelConnectionTimeout, final int sentinelSoTimeout, final String sentinelPassword, <END> final String sentinelClientName) { this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, null, password, database, clientName, sentinelConnectionTimeout, sentinelSoTimeout, null, sentinelPassword, sentinelClientName, false, false, null, null, null); }</code><technical_language>This removes existing constructor. do that. Hint: this constructor, copy previous constructor earlier code paste this constructor</technical_language>

Target:
public JedisSentinelPool(String masterName, Set<String> sentinels, final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, final String password, final int database, final String clientName, final int sentinelConnectionTimeout, final int sentinelSoTimeout, final String sentinelPassword, final String sentinelClientName) { this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, null, password, database, clientName, sentinelConnectionTimeout, sentinelSoTimeout, null, sentinelPassword, sentinelClientName); }
Source:
<code>public void testCommit() throws SQLException, AuthorizeException, IOException { Context instance = new Context(); assertThat("HibernateDBConnection should exist", instance.getDBConnection(), notNullValue()); assertTrue("Context should be valid", instance.isValid()); assertTrue("Transaction should be open", instance.isTransactionAlive()); when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true); <START> String createdEmail = "myfakeemail@gmail.com"; <END> EPerson newUser = ePersonService.create(instance); newUser.setFirstName(instance, "Tim"); newUser.setLastName(instance, "Smith"); newUser.setEmail(createdEmail); newUser.setCanLogIn(true); newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage()); instance.commit(); assertThat("HibernateDBConnection should still be open", instance.getDBConnection(), notNullValue()); assertTrue("Context should still be valid", instance.isValid()); assertFalse("DB transaction should be closed", instance.isTransactionAlive()); newUser = instance.reloadEntity(newUser); assertEquals("New user should be created", newUser.getEmail(), createdEmail); String newEmail = "myrealemail@gmail.com"; newUser.setEmail(newEmail); instance.commit(); newUser = instance.reloadEntity(newUser); assertEquals("New email address should be saved", newUser.getEmail(), newEmail); ePersonService.delete(instance, newUser); cleanupContext(instance); }</code><technical_language>Small point: leery of testing real email domains, if localpart "should fake". myfakeemail@example.com guaranteed undeliverable, domain is reserved</technical_language>

Target:
public void testCommit() throws SQLException, AuthorizeException, IOException { Context instance = new Context(); assertThat("HibernateDBConnection should exist", instance.getDBConnection(), notNullValue()); assertTrue("Context should be valid", instance.isValid()); assertTrue("Transaction should be open", instance.isTransactionAlive()); when(authorizeServiceSpy.isAdmin(instance)).thenReturn(true); String createdEmail = "myfakeemail@example.com"; EPerson newUser = ePersonService.create(instance); newUser.setFirstName(instance, "Tim"); newUser.setLastName(instance, "Smith"); newUser.setEmail(createdEmail); newUser.setCanLogIn(true); newUser.setLanguage(instance, I18nUtil.getDefaultLocale().getLanguage()); instance.commit(); assertThat("HibernateDBConnection should still be open", instance.getDBConnection(), notNullValue()); assertTrue("Context should still be valid", instance.isValid()); assertFalse("DB transaction should be closed", instance.isTransactionAlive()); newUser = instance.reloadEntity(newUser); assertEquals("New user should be created", newUser.getEmail(), createdEmail); String newEmail = "myrealemail@example.com"; newUser.setEmail(newEmail); instance.commit(); newUser = instance.reloadEntity(newUser); assertEquals("New email address should be saved", newUser.getEmail(), newEmail); ePersonService.delete(instance, newUser); cleanupContext(instance); }
Source:
<code>public void processEntity(Entity entity, float deltaTime) { timeRunning+=deltaTime; ViewPortComponent ViewPortComponent = viewPortMapper.get(entity); Camera camera = ViewPortComponent.viewPort.getCamera(); batch.setProjectionMatrix(camera.combined); batch.begin(); drawRecursively(entity, 1f); batch.end(); if (!drawOnly) { if (rayHandler != null) { rayHandler.setCulling(false); OrthographicCamera orthoCamera = (OrthographicCamera) camera; camera.combined.scl(1f / PhysicsBodyLoader.getScale()); rayHandler.setCombinedMatrix(orthoCamera); rayHandler.updateAndRender(); } <START> if (world != null && isPhysicsOn) { <END> doPhysicsStep(deltaTime); } } }</code><technical_language>This Physics system</technical_language>

Target:
public void processEntity(Entity entity, float deltaTime) { timeRunning+=deltaTime; ViewPortComponent ViewPortComponent = viewPortMapper.get(entity); Camera camera = ViewPortComponent.viewPort.getCamera(); camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); drawRecursively(entity, 1f); batch.end(); if (rayHandler != null) { rayHandler.setCulling(false); OrthographicCamera orthoCamera = (OrthographicCamera) camera; camera.combined.scl(1f / PhysicsBodyLoader.getScale()); rayHandler.setCombinedMatrix(orthoCamera); rayHandler.updateAndRender(); } }
Source:
<code>private Icon makeMarkerIcon(boolean isActive) { Bitmap bmp = Bitmap.createBitmap(MAP_PLACE_ICON_SIZE, MAP_PLACE_ICON_SIZE, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); paint.setAntiAlias(true); Drawable d; <START> if (isActive) { <END> paint.setColor(getResources().getColor(R.color.blue_liberal)); int circleSize = bmp.getWidth() / 2; canvas.drawCircle(circleSize, circleSize, circleSize, paint); Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_place_dark); Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, MAP_PLACE_ICON_SIZE, MAP_PLACE_ICON_SIZE, true)); d = DrawableCompat.wrap(d).mutate(); DrawableCompat.setTint(d, getResources().getColor(R.color.blue_liberal)); } else { paint.setColor(getResources().getColor(R.color.green_progressive)); int circleSize = bmp.getWidth() / 2; canvas.drawCircle(circleSize, circleSize, circleSize / 2, paint); d = new BitmapDrawable(getResources(), bmp); } return new Icon(d); }</code><technical_language>active markers positioned properly. If I click a dot, I intuitively location of interest is located center of it. active marker a pointer, point center was. In future, animating transition active inactive states</technical_language>

Target:
private Icon makeMarkerIcon(boolean isActive) { int iconSize = (int) getResources().getDimension(R.dimen.map_marker_icon_size); Bitmap bmp = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); paint.setAntiAlias(true); Drawable d; if (isActive) { paint.setColor(getResources().getColor(R.color.blue_liberal)); int circleSize = bmp.getWidth() / 2; canvas.drawCircle(circleSize, circleSize, circleSize, paint); Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.ic_place_dark); Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, iconSize, iconSize, true)); d = DrawableCompat.wrap(d).mutate(); DrawableCompat.setTint(d, getResources().getColor(R.color.blue_liberal)); } else { paint.setColor(getResources().getColor(R.color.green_progressive)); int circleSize = bmp.getWidth() / 2; canvas.drawCircle(circleSize, circleSize, circleSize / 2, paint); d = new BitmapDrawable(getResources(), bmp); } return new Icon(d); }