auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); final String type; if (!rec.getReadUnmappedFlag()) { <START> if(referenceIndex != rec.getReferenceIndex() || gc == null || refBases == null){ <END> final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex=rec.getReferenceIndex(); } final String group; if (this.readGroup != null) { type = this.readGroup; group = "Read Group"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.library != null) { type = this.library; group = "Library"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.sample != null) { type = this.sample; group = "Sample"; addRead(gcData.get(type), rec, group, gc, refBases); } else { type = allReads; group = "All Reads"; addRead(gcData.get(type), rec, group, gc, refBases); } } else { for (final Map.Entry<String, GcObject> entry : gcData.entrySet()) { final GcObject gcCur = entry.getValue(); if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++gcCur.totalClusters; } } }</code><technical_language>good point</technical_language>

Target:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); final String type; if (!rec.getReadUnmappedFlag()) { if(referenceIndex != rec.getReferenceIndex() || gc == null){ final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex=rec.getReferenceIndex(); } final String group; if (this.readGroup != null) { type = this.readGroup; group = "Read Group"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.library != null) { type = this.library; group = "Library"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.sample != null) { type = this.sample; group = "Sample"; addRead(gcData.get(type), rec, group, gc, refBases); } else { type = allReads; group = "All Reads"; addRead(gcData.get(type), rec, group, gc, refBases); } } else { for (final Map.Entry<String, GcObject> entry : gcData.entrySet()) { final GcObject gcCur = entry.getValue(); if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++gcCur.totalClusters; } } }
Source:
<code>private Diagram doTransformation(final String fileName, final String raw) { final Metadata metadata = createMetadata(); final Graph<DefinitionSet, ?> graph = marshalling.unmarshall(metadata, raw); final Node<Definition<BPMNDiagram>, ?> diagramNode = GraphUtils.getFirstNode((Graph<?, Node>) graph, BPMNDiagramImpl.class); if (null == diagramNode) { throw new RuntimeException("No BPMN Diagram can be found."); } <START> diagramNode.getContent().getDefinition().getDiagramSet().getName().setValue(fileName); <END> diagramNode.getContent().getDefinition().getDiagramSet().getId().setValue(fileName); final String title = diagramNode.getContent().getDefinition().getDiagramSet().getName().getValue(); metadata.setTitle(title); final Diagram diagram = diagramFactory.build(title, metadata, graph); updateClientMetadata(diagram); return diagram; }</code><technical_language>create a variable for DiagramSet set name id</technical_language>

Target:
private Diagram doTransformation(final String fileName, final String raw) { final Metadata metadata = createMetadata(); final Graph<DefinitionSet, ?> graph = marshalling.unmarshall(metadata, raw); final Node<Definition<BPMNDiagram>, ?> diagramNode = GraphUtils.getFirstNode((Graph<?, Node>) graph, BPMNDiagramImpl.class); if (null == diagramNode) { throw new RuntimeException("No BPMN Diagram can be found."); } final BaseDiagramSet diagramSet = diagramNode.getContent().getDefinition().getDiagramSet(); if (diagramSet.getName().getValue().isEmpty()) { diagramSet.getName().setValue(fileName); } if (diagramSet.getId().getValue().isEmpty()) { diagramSet.getId().setValue(fileName); } final String title = diagramNode.getContent().getDefinition().getDiagramSet().getName().getValue(); metadata.setTitle(title); final Diagram diagram = diagramFactory.build(title, metadata, graph); updateClientMetadata(diagram); return diagram; }
Source:
<code>private static Context buildWithApplicationContext(ApplicationContainerContext applicationContainerContext, ApplicationTaskContext applicationTaskContext) { return new ContextImpl(mock(JobContext.class), mock(ContainerContext.class), mock(TaskContext.class), applicationContainerContext, applicationTaskContext); <START> ======= <END> return new ContextImpl(null, null, null, applicationContainerContext, null); }</code><technical_language>resolve this merge conflict</technical_language>

Target:
private static Context buildWithApplicationContext(ApplicationContainerContext applicationContainerContext, ApplicationTaskContext applicationTaskContext) { return new ContextImpl(mock(JobContext.class), mock(ContainerContext.class), mock(TaskContext.class), Optional.ofNullable(applicationContainerContext), Optional.ofNullable(applicationTaskContext)); }
Source:
<code>public void run() { if (Misc.isNPCIncludingVillagers(player)) { return; } if (!player.isOnline()) { mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + " - player logged out"); return; } PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), player.getUniqueId(), true); if (profile.isLoaded()) { new ApplySuccessfulProfile(new McMMOPlayer(player, profile)).runTask(mcMMO.p); <START> Bukkit.getScheduler().runTask(mcMMO.p, () -> { <END> EventUtils.callPlayerProfileLoadEvent(player, profile); }); return; } if (attempt >= 3) { mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); mcMMO.p.getServer().broadcast(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), Server.BROADCAST_CHANNEL_ADMINISTRATIVE); player.sendMessage(LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)).split("\n")); } attempt++; new PlayerProfileLoadingTask(player, attempt).runTaskLaterAsynchronously(mcMMO.p, (100 + (attempt * 100))); }</code><technical_language>is this a task exactly</technical_language>

Target:
public void run() { if (Misc.isNPCIncludingVillagers(player)) { return; } if (!player.isOnline()) { mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + " - player logged out"); return; } PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), player.getUniqueId(), true); if (profile.isLoaded()) { new ApplySuccessfulProfile(new McMMOPlayer(player, profile)).runTask(mcMMO.p); EventUtils.callPlayerProfileLoadEvent(player, profile); return; } if (attempt >= 3) { mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); mcMMO.p.getServer().broadcast(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), Server.BROADCAST_CHANNEL_ADMINISTRATIVE); player.sendMessage(LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)).split("\n")); } attempt++; new PlayerProfileLoadingTask(player, attempt).runTaskLaterAsynchronously(mcMMO.p, (100 + (attempt * 100))); }
Source:
<code>public void trackValuePropModalView(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final SegmentEvent aEvent = new SegmentEvent(); aEvent.data.putValue(Keys.COURSE_ID, courseId); <START> if (assignmentId != null) { <END> aEvent.data.putValue(Keys.ASSIGNMENT_ID, assignmentId); } aEvent.data.putValue(Keys.SCREEN_NAME, screenName); trackSegmentEvent(Events.VALUE_PROP_MODAL_VIEW, aEvent.properties); }</code><technical_language>condition replaced !TextUtils.isEmpty(assignmentId)</technical_language>

Target:
public void trackValuePropModalView(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final SegmentEvent aEvent = new SegmentEvent(); aEvent.data.putValue(Keys.COURSE_ID, courseId); if (TextUtils.isEmpty(assignmentId)) { aEvent.data.putValue(Keys.ASSIGNMENT_ID, assignmentId); } aEvent.data.putValue(Keys.SCREEN_NAME, screenName); trackSegmentEvent(Events.VALUE_PROP_MODAL_VIEW, aEvent.properties); }
Source:
<code>public static ImmutableList<Class<?>> findEntityClassesFromDirectory(String pckg) { Builder<Class<?>> builder = ImmutableList.<Class<?>>builder(); PackageNamesScanner scanner = new PackageNamesScanner(new String[] {pckg}, true); @SuppressWarnings("unchecked") final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class); while (scanner.hasNext()) { <START> final String next = scanner.next(); <END> if (asl.accept(next)) { final InputStream in = scanner.open(); try { asl.process(next, in); } catch (IOException e) { throw new RuntimeException("AnnotationAcceptingListener failed to process scanned resource: " + next); } finally { try { in.close(); } catch (IOException ex) { throw new RuntimeException("Error closing resource stream", ex); } } } } for (Class<?> clazz : asl.getAnnotatedClasses()) { builder.add(clazz); } return builder.build(); }</code><technical_language>spacing</technical_language>

Target:
public static ImmutableList<Class<?>> findEntityClassesFromDirectory(String pckg) { @SuppressWarnings("unchecked") final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class); final PackageNamesScanner scanner = new PackageNamesScanner(new String[]{pckg}, true); while (scanner.hasNext()) { final String next = scanner.next(); if (asl.accept(next)) { try (final InputStream in = scanner.open()) { asl.process(next, in); } catch (IOException e) { throw new RuntimeException("AnnotationAcceptingListener failed to process scanned resource: " + next); } } } final Builder<Class<?>> builder = ImmutableList.builder(); for (Class<?> clazz : asl.getAnnotatedClasses()) { builder.add(clazz); } return builder.build(); }
Source:
<code>private boolean handleArrayNode(ArrayNode array, Collection<Object> collection, Class<?> componentType, ObjectMapper mapper) throws Exception { Assert.notNull(array, "ArrayNode must not be null!"); Assert.notNull(collection, "Source collection must not be null!"); Assert.notNull(mapper, "ObjectMapper must not be null!"); Iterator<Object> value = collection.iterator(); boolean nestedObjectFound = false; for (JsonNode jsonNode : array) { if (!value.hasNext()) { if (componentType != null) { collection.add(mapper.treeToValue(jsonNode, componentType)); <START> } <END> return nestedObjectFound; } Object next = value.next(); if (ArrayNode.class.isInstance(jsonNode)) { final Collection<Object> nestedCollection = asCollection(next); final Iterator<Object> iterator = nestedCollection.iterator(); return handleArrayNode(array, nestedCollection, iterator.hasNext() ? iterator.next().getClass() : null, mapper); } if (ObjectNode.class.isInstance(jsonNode)) { nestedObjectFound = true; doMerge((ObjectNode) jsonNode, next, mapper); } } while (value.hasNext()) { value.next(); value.remove(); } return nestedObjectFound; }</code><technical_language>I extend algorithm this work if *one* more item provided. get added iteration is stopped subsequent incoming elements ignored, right? I guess trigger a continue if more elements in array resorting eventual return if maxed out array elements. I kind of wondering invert processing here: iterating existing elements first, removing items if max out array resort adding left in array that</technical_language>

Target:
private boolean handleArrayNode(ArrayNode array, Collection<Object> collection, Class<?> componentType, ObjectMapper mapper) throws Exception { Assert.notNull(array, "ArrayNode must not be null!"); Assert.notNull(collection, "Source collection must not be null!"); Assert.notNull(mapper, "ObjectMapper must not be null!"); Iterator<Object> value = new ArrayList<Object>(collection).iterator(); boolean nestedObjectFound = false; for (JsonNode jsonNode : array) { if (!value.hasNext()) { if (componentType != null) { collection.add(mapper.treeToValue(jsonNode, componentType)); continue; } } Object next = value.next(); if (ArrayNode.class.isInstance(jsonNode)) { Collection<Object> nestedCollection = asCollection(next); Iterator<Object> iterator = nestedCollection.iterator(); return handleArrayNode(array, nestedCollection, iterator.hasNext() ? iterator.next().getClass() : null, mapper); } if (ObjectNode.class.isInstance(jsonNode)) { nestedObjectFound = true; doMerge((ObjectNode) jsonNode, next, mapper); } } while (value.hasNext()) { collection.remove(value.next()); } return nestedObjectFound; }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RepartitionTopicConfig that = (RepartitionTopicConfig) o; return Objects.equals(name, that.name) && Objects.equals(topicConfigs, that.topicConfigs) && <START> Objects.equals(numberOfPartitions, that.numberOfPartitions); <END> }</code><technical_language>If add this equals, *must* add hashCode well, _should_ add toString()</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RepartitionTopicConfig that = (RepartitionTopicConfig) o; return Objects.equals(name, that.name) && Objects.equals(topicConfigs, that.topicConfigs) && Objects.equals(enforceNumberOfPartitions, that.enforceNumberOfPartitions); }
Source:
<code>private double calculatePressureDrag(FlightConfiguration configuration, FlightConditions conditions, Map<RocketComponent, AerodynamicForces> map, WarningSet warnings) { double stagnation, base, total; double radius = 0; if (calcMap == null) buildCalcMap(configuration); stagnation = calculateStagnationCD(conditions.getMach()); base = calculateBaseCD(conditions.getMach()); total = 0; final InstanceMap imap = configuration.getActiveInstances(); for(Map.Entry<RocketComponent, ArrayList<InstanceContext>> entry: imap.entrySet() ) { final RocketComponent c = entry.getKey(); if (!c.isAerodynamic()) continue; final ArrayList<InstanceContext> contextList = entry.getValue(); for(InstanceContext context: contextList ) { double cd = calcMap.get(c).calculatePressureDragForce(conditions, stagnation, base, warnings); total += cd; if (map != null) { map.get(c).setPressureCD(cd); } <START> if(c.isCDOverridden()) continue; <END> if (c instanceof SymmetricComponent) { SymmetricComponent s = (SymmetricComponent) c; if (radius < s.getForeRadius()) { double area = Math.PI * (pow2(s.getForeRadius()) - pow2(radius)); cd = stagnation * area / conditions.getRefArea(); total += cd; if (map != null) { map.get(c).setPressureCD(map.get(c).getPressureCD() + cd); } } radius = s.getAftRadius(); } } } return total; }</code><technical_language>nit: while a style nut, I find styles consistent I continue next line. I realize this is carry indentation change, code is touched - worthwhile consistent</technical_language>

Target:
private double calculatePressureDrag(FlightConfiguration configuration, FlightConditions conditions, Map<RocketComponent, AerodynamicForces> map, WarningSet warnings) { double stagnation, base, total; if (calcMap == null) buildCalcMap(configuration); stagnation = calculateStagnationCD(conditions.getMach()); base = calculateBaseCD(conditions.getMach()); total = 0; final InstanceMap imap = configuration.getActiveInstances(); for(Map.Entry<RocketComponent, ArrayList<InstanceContext>> entry: imap.entrySet() ) { final RocketComponent c = entry.getKey(); if (!c.isAerodynamic()) continue; final ArrayList<InstanceContext> contextList = entry.getValue(); for(InstanceContext context: contextList ) { double cd = calcMap.get(c).calculatePressureDragForce(conditions, stagnation, base, warnings); total += cd; if (map != null) { map.get(c).setPressureCD(cd); } if(c.isCDOverridden()) continue; if (c instanceof SymmetricComponent) { SymmetricComponent s = (SymmetricComponent) c; double radius = 0; final SymmetricComponent prevComponent = s.getPreviousSymmetricComponent(); if (prevComponent != null) radius = prevComponent.getAftRadius(); if (radius < s.getForeRadius()) { double area = Math.PI * (pow2(s.getForeRadius()) - pow2(radius)); cd = stagnation * area / conditions.getRefArea(); total += cd; if (map != null) { map.get(c).setPressureCD(map.get(c).getPressureCD() + cd); } } } } } return total; }
Source:
<code>public void run() { LOGGER.info(() -> "[TimeGraphView:BuildThreadStart] uid=" + fUniqueDebuggingId + ", trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } <START> LOGGER.info(() -> "[TimeGraphView:BuildThreadEnd]"); END> }</code><technical_language>do match end start? start prints trace, for views, loggerName in console output</technical_language>

Target:
public void run() { LOGGER.info(() -> "[TimeGraphView:BuildThreadStart] viewId=" + getViewId() + ", trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } LOGGER.info(() -> "[TimeGraphView:BuildThreadEnd]"); }
Source:
<code>public void checkSpecificAccessControl() { <START> if (!userInfo.isInstructor && !userInfo.isAdmin) { <END> throw new UnauthorizedAccessException("Instructor or Admin privilege is required to access this resource."); } }</code><technical_language>admin is allowed here, is meaningless execute() process need instructor info</technical_language>

Target:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } }
Source:
<code>Object getEvent(int i, DateTime timestamp) { Map<String, Object> event = new HashMap<>(); event.put("page", "Gypsy Danger"); event.put("language", "en"); event.put("user", "nuclear"); event.put("unpatrolled", "true"); event.put("newPage", "true"); event.put("robot", "false"); event.put("anonymous", "false"); event.put("namespace", "article"); <START> event.put("continent", "North Americ"); <END> event.put("country", "United States"); event.put("region", "Bay Area"); event.put("city", "San Francisco"); event.put("timestamp", DATE_TIME_FORMATTER.print(timestamp)); event.put("added", i); event.put("deleted", 0); event.put("delta", i); return event; }</code><technical_language>North Americ -> North America</technical_language>

Target:
Object getEvent(int i, DateTime timestamp) { Map<String, Object> event = new HashMap<>(); event.put("page", "Gypsy Danger"); event.put("language", "en"); event.put("user", "nuclear"); event.put("unpatrolled", "true"); event.put("newPage", "true"); event.put("robot", "false"); event.put("anonymous", "false"); event.put("namespace", "article"); event.put("continent", "North America"); event.put("country", "United States"); event.put("region", "Bay Area"); event.put("city", "San Francisco"); event.put("timestamp", DATE_TIME_FORMATTER.print(timestamp)); event.put("added", i); event.put("deleted", 0); event.put("delta", i); return event; }
Source:
<code><START> public IOpResponse execute(ThirdPartyLoginParams params) throws Exception { <END> final Rp rp = getRp(); String authorizationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint(); String state = getStateService().generateState(); String nonce = getStateService().generateNonce(); String clientId = getConfigurationService().getConfiguration().getEncodeClientIdInAuthorizationUrl() ? Utils.encode(rp.getClientId()) : rp.getClientId(); String redirectUri = rp.getRedirectUri(); authorizationEndpoint += "?response_type=" + Utils.joinAndUrlEncode(rp.getResponseTypes()); authorizationEndpoint += "&client_id=" + clientId; authorizationEndpoint += "&redirect_uri=" + redirectUri; authorizationEndpoint += "&scope=" + Utils.joinAndUrlEncode(rp.getScope()); authorizationEndpoint += "&state=" + state; authorizationEndpoint += "&nonce=" + nonce; return new GetAuthorizationUrlResponse(authorizationEndpoint); }</code><technical_language>validate target_link_uri . Spec: RPs verify of target_link_uri prevent open redirector external sites. in current state oxd perform redirect authorization. able improve in 5.0 (later) implement this: <LINK_0> Anyway, lets perform validation implementing it</technical_language>

Target:
public IOpResponse execute(ThirdPartyLoginParams params) throws Exception { final Rp rp = getRp(); if (Strings.isNullOrEmpty(params.getIss())) { LOG.error("'iss' is empty or not specified in parameter."); throw new HttpException(ErrorResponseCode.BAD_REQUEST_NO_ISSUER); } if (!Strings.isNullOrEmpty(params.getTargetLinkUri()) && !rp.getRedirectUris().stream().anyMatch(uri -> getHost(uri) == getHost(params.getTargetLinkUri()))) { LOG.error("The hostname of `target_link_uri` should match with the hostname of `redirect_uri` of RP."); throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_TARGET_URI); } String authorizationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint(); String state = getStateService().generateState(); String nonce = getStateService().generateNonce(); String clientId = getConfigurationService().getConfiguration().getEncodeClientIdInAuthorizationUrl() ? Utils.encode(rp.getClientId()) : rp.getClientId(); String redirectUri = rp.getRedirectUri(); authorizationEndpoint += "?response_type=" + Utils.joinAndUrlEncode(rp.getResponseTypes()); authorizationEndpoint += "&client_id=" + clientId; authorizationEndpoint += "&redirect_uri=" + redirectUri; authorizationEndpoint += "&scope=" + Utils.joinAndUrlEncode(rp.getScope()); authorizationEndpoint += "&state=" + state; authorizationEndpoint += "&nonce=" + nonce; return new GetAuthorizationUrlResponse(authorizationEndpoint); }
Source:
<code>Bitmap loadConstrainedBitmap(Uri uri) throws FileNotFoundException { if (uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to getScaledBitmap"); } BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; loadBitmap(uri, opt); int w = opt.outWidth; int h = opt.outHeight; if (w <= 0 || h <= 0) { return null; } int imageSide = Math.max(w, h); int sampleSize = 1; while (imageSide > MAX_PRINT_SIZE) { imageSide >>>= 1; sampleSize <<= 1; } if (sampleSize <= 0 || 0 >= (Math.min(w, h) / sampleSize)) { return null; } BitmapFactory.Options decodeOptions; synchronized (mLock) { mDecodeOptions = new BitmapFactory.Options(); mDecodeOptions.inMutable = true; mDecodeOptions.inSampleSize = sampleSize; <START> mDecodeOptions.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB); <END> decodeOptions = mDecodeOptions; } try { return loadBitmap(uri, decodeOptions); } finally { synchronized (mLock) { mDecodeOptions = null; } } }</code><technical_language>this API if this is available. wrap this is a check for Build.SDK_INT</technical_language>

Target:
Bitmap loadConstrainedBitmap(Uri uri) throws FileNotFoundException { if (uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to getScaledBitmap"); } BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; loadBitmap(uri, opt); int w = opt.outWidth; int h = opt.outHeight; if (w <= 0 || h <= 0) { return null; } int imageSide = Math.max(w, h); int sampleSize = 1; while (imageSide > MAX_PRINT_SIZE) { imageSide >>>= 1; sampleSize <<= 1; } if (sampleSize <= 0 || 0 >= (Math.min(w, h) / sampleSize)) { return null; } BitmapFactory.Options decodeOptions; synchronized (mLock) { mDecodeOptions = new BitmapFactory.Options(); mDecodeOptions.inMutable = true; mDecodeOptions.inSampleSize = sampleSize; if (Build.VERSION.SDK_INT >= 26) { mDecodeOptions.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB); } decodeOptions = mDecodeOptions; } try { return loadBitmap(uri, decodeOptions); } finally { synchronized (mLock) { mDecodeOptions = null; } } }
Source:
<code>public void testTrimRetryServerEpochChange() throws Exception{ final int nEntries = 5; final long initEpoch = 0; final long finalEpoch = 1; Map<String, String> testMap = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<SMRMap<String, String>>() { }) .setStreamName("test") .open(); <START> testMap.put("k1", "1"); <END> testMap.put("k2", "2"); testMap.put("k3", "3"); testMap.put("k4", "4"); testMap.put("k5", "5"); MultiCheckpointWriter mcw = new MultiCheckpointWriter(); mcw.addMap((SMRMap) testMap); Token checkpointAddress = mcw.appendCheckpoints(getRuntime(), "author"); assertThat(checkpointAddress).isEqualTo(new Token(initEpoch, nEntries - 1)); Layout l = new Layout(getLayoutServer(0).getCurrentLayout()); l.setEpoch(l.getEpoch() + 1); getDefaultRuntime().getLayoutView().getRuntimeLayout(l).sealMinServerSet(); getDefaultRuntime().getLayoutView().updateLayout(l, 1L); boolean exceptionCaught = false; try { getDefaultRuntime().getAddressSpaceView().prefixTrim(new Token(finalEpoch, nEntries - 1)); } catch (Exception e) { exceptionCaught = true; assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseInstanceOf(WrongEpochException.class); } assertThat(exceptionCaught).isFalse(); Token trimMark = getDefaultRuntime().getAddressSpaceView().getTrimMark(); assertThat(trimMark).isEqualTo(new Token(finalEpoch, nEntries)); }</code><technical_language>I omit writing, exercise AddressSpaceview::prefixTrim</technical_language>

Target:
public void testTrimRetryServerEpochChange() throws Exception{ Map<String, String> testMap = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<SMRMap<String, String>>() { }) .setStreamName("test") .open(); Layout l = new Layout(getLayoutServer(0).getCurrentLayout()); final long finalEpoch = l.getEpoch() + 1; l.setEpoch(finalEpoch); getDefaultRuntime().getLayoutView().getRuntimeLayout(l).sealMinServerSet(); getDefaultRuntime().getLayoutView().updateLayout(l, 1L); boolean exceptionCaught = false; try { getDefaultRuntime().getAddressSpaceView().prefixTrim(new Token(finalEpoch, Address.NON_ADDRESS)); } catch (Exception e) { exceptionCaught = true; assertThat(e) .isInstanceOf(WrongEpochException.class); } assertThat(exceptionCaught).isFalse(); Token trimMark = getDefaultRuntime().getAddressSpaceView().getTrimMark(); assertThat(trimMark).isEqualTo(new Token(finalEpoch, 0L)); }
Source:
<code>public void dispose() { <START> LogManager.logInfo("Disposing", this); END> fWindow= null; }</code><technical_language>is this logging buying ? Do need of it</technical_language>

Target:
public void dispose() { fWindow= null; }
Source:
<code>private int pingIsAlive( ) { try { final HttpClient client = HttpClientManager.getInstance().createDefaultClient(); final URIBuilder uriBuilder = new URIBuilder() <START> .setScheme( HTTP_SCHEME ) <END> .setHost( WN_HOST ) .setPort( WN_PORT ) .setPath( IS_ALIVE_ENDPOINT ); final URI pingIsAliveURI = uriBuilder.build(); final HttpGet pingIsAlive = new HttpGet( pingIsAliveURI.toString() ); final HttpResponse response = client.execute( pingIsAlive ); return response.getStatusLine().getStatusCode(); } catch ( URISyntaxException | IOException e ) { logger.error( e.getMessage() ); } return HttpStatus.SC_INTERNAL_SERVER_ERROR; }</code><technical_language>add a debug statement is checking if server is</technical_language>

Target:
private int pingIsAlive( ) { if ( logger.isDebugEnabled() ) { logger.debug( " Checking is alive endpoint..." ); } try { final HttpClient client = HttpClientManager.getInstance().createDefaultClient(); final URIBuilder uriBuilder = new URIBuilder() .setScheme( HTTP_SCHEME ) .setHost( WN_HOST ) .setPort( WN_PORT ) .setPath( IS_ALIVE_ENDPOINT ); final URI pingIsAliveURI = uriBuilder.build(); final HttpGet pingIsAlive = new HttpGet( pingIsAliveURI.toString() ); final HttpResponse response = client.execute( pingIsAlive ); return response.getStatusLine().getStatusCode(); } catch ( URISyntaxException | IOException e ) { logger.error( e.getMessage() ); } return HttpStatus.SC_INTERNAL_SERVER_ERROR; }
Source:
<code>Bubble(int x, int y, int id, int radius) { this.x = x; this.y = y; this.id = id; <START> this.radius = radius; <END> }</code><technical_language>fields final</technical_language>

Target:
Bubble(int x, int y, int id, int radius) { super(x,y,id); this.radius = radius; }
Source:
<code>public void testAddIgnoredFile() throws Exception { <START> assertTrue(new File(db.getWorkTree(), "sub").mkdir()); <END> File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File ignoreFile = new File(db.getWorkTree(), ".gitignore"); FileUtils.createNewFile(ignoreFile); writer = new PrintWriter(ignoreFile); writer.print("sub/b.txt"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]", indexState(CONTENT)); }</code><technical_language>FileUtils.mkdirs</technical_language>

Target:
public void testAddIgnoredFile() throws Exception { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File ignoreFile = new File(db.getWorkTree(), ".gitignore"); FileUtils.createNewFile(ignoreFile); writer = new PrintWriter(ignoreFile); writer.print("sub/b.txt"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]", indexState(CONTENT)); }
Source:
<code>private boolean isCourseArchived(CourseAttributes course, String googleId) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, googleId); boolean isCourseArchived = (instructor.isArchived != null)? instructor.isArchived : <START> course.isArchived; <END> return isCourseArchived; }</code><technical_language>This condition is duplicated in CoursesLogic. abstract a static method in CoursesLogic</technical_language>

Target:
private boolean isCourseArchived(CourseAttributes course, String googleId) { return logic.isCourseArchived(course.id, googleId); }
Source:
<code>public List<UserCertificationBodyMapDTO> getByUserId(Long userId) { Query query = entityManager.createQuery( <START> "from UserCertificationBodyMapEntity ucbm " + "join fetch ucbm.certificationBody cb " <END> + "join fetch ucbm.user u " + "where (ucbm.deleted != true) AND (u.id = :userId) ", UserCertificationBodyMapEntity.class); query.setParameter("userId", userId); List<UserCertificationBodyMapEntity> result = query.getResultList(); List<UserCertificationBodyMapDTO> dtos = new ArrayList<UserCertificationBodyMapDTO>(); for (UserCertificationBodyMapEntity entity : result) { dtos.add(new UserCertificationBodyMapDTO(entity)); } return dtos; }</code><technical_language>If a user ACB permissions this return? Null? checking if matters for this is used. I do a left join if straight join is more correct fine</technical_language>

Target:
public List<UserCertificationBodyMapDTO> getByUserId(Long userId) { Query query = entityManager.createQuery( "from UserCertificationBodyMapEntity ucbm " + "join fetch ucbm.certificationBody cb " + "join fetch ucbm.user u " + "where (ucbm.deleted != true) AND (u.id = :userId) ", UserCertificationBodyMapEntity.class); query.setParameter("userId", userId); List<UserCertificationBodyMapEntity> result = query.getResultList(); List<UserCertificationBodyMapDTO> dtos = new ArrayList<UserCertificationBodyMapDTO>(); if (result != null) { for (UserCertificationBodyMapEntity entity : result) { dtos.add(new UserCertificationBodyMapDTO(entity)); } } return dtos; }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (o == null || getClass() != o.getClass()) return false; ClassLoaderModel that = (ClassLoaderModel) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }</code><technical_language>please add {}</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassLoaderModel that = (ClassLoaderModel) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }
Source:
<code>public String edit() { <START> logger.debug("Edit"); <END> try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); for (Category cat : resCategories) { this.getCategoryCodes().add(cat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); this.setMetadata(resource.getMetadata()); } catch (Throwable t) { logger.error("error in edit", t); return FAILURE; } return SUCCESS; }</code><technical_language>This needs some context. "Edit in multiple resource action for id ...."</technical_language>

Target:
public String edit() { logger.debug("Edit in multiple resource action for id {}", this.getResourceId() ); try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); for (Category cat : resCategories) { this.getCategoryCodes().add(cat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); this.setMetadata(resource.getMetadata()); } catch (Throwable t) { logger.error("error in edit", t); return FAILURE; } return SUCCESS; }
Source:
<code>private boolean initGlusterPeerProcess() { <START> Map<String, Pair<String, String>> exclusiveLocks = new HashMap<String, Pair<String, String>>(); <END> exclusiveLocks.put(getVds().getVdsGroupId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER, VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_OPERATION_INPROGRESS)); EngineLock lock = new EngineLock(exclusiveLocks, null); getLockManager().acquireLockWait(lock); try { glusterPeerListSucceeded = true; glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!getVdsId().equals(vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); Map<String, String> customLogValues = new HashMap<String, String>(); customLogValues.put("Server", upServer.getHostName()); if (glusterServers.size() == 0) { customLogValues.put("Command", "gluster peer status"); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().getHostName())) { customLogValues.put("Command", "gluster peer probe " + getVds().getHostName()); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } } } } return true; } finally { getLockManager().releaseLock(lock); } }</code><technical_language>of putting this logic a separate method for lock</technical_language>

Target:
private boolean initGlusterPeerProcess() { EngineLock lock = GlusterUtil.getInstance().acquireGlusterLockWait(getVds().getVdsGroupId()); try { glusterPeerListSucceeded = true; glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!getVdsId().equals(vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); Map<String, String> customLogValues = new HashMap<String, String>(); customLogValues.put("Server", upServer.getHostName()); if (glusterServers.size() == 0) { customLogValues.put("Command", "gluster peer status"); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().getHostName())) { customLogValues.put("Command", "gluster peer probe " + getVds().getHostName()); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } } } } return true; } finally { getLockManager().releaseLock(lock); } }
Source:
<code>private void appendPortsToConfig(File tempFile) throws IOException { for(CouchbasePort port: CouchbasePort.values()) { <START> if (! port.isBootstrap()) { <END> String config = String.format("{%s, %d}.\n", port.name, getMappedPort(port)); FileUtils.writeStringToFile(tempFile, config, "UTF-8", true); } } }</code><technical_language>code style: space</technical_language>

Target:
private void appendPortsToConfig(File tempFile) throws IOException { for (CouchbasePort port : CouchbasePort.values()) { if (!port.isDynamic()) { String config = String.format("{%s, %d}.\n", port.name, getMappedPort(port)); FileUtils.writeStringToFile(tempFile, config, "UTF-8", true); } } }
Source:
<code>public boolean equals(final Object o) { if (o instanceof DenseMatrix) { return breezeMatrix.equals(((DenseMatrix) o).breezeMatrix); } <START> if (o instanceof CSCMatrix) { <END> return breezeMatrix.equals(((CSCMatrix) o).getBreezeMatrix()); } return false; }</code><technical_language>Please else if. However, I wondering if result is false o is instance of CSCMatrix. tested this in scala console a DenseMatrix a CSCMatrix of elements. check this</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } else if (o instanceof DenseMatrix) { return breezeMatrix.equals(((DenseMatrix) o).breezeMatrix); } else if (o instanceof CSCMatrix) { return breezeMatrix.equals(((CSCMatrix) o).getBreezeMatrix()); } else { return false; } }
Source:
<code>public static void logS3GuardDisabled(Logger logger, String warnLevelStr, String bucket) throws UnsupportedOperationException, IllegalArgumentException { final DisabledWarnLevel warnLevel; try { <START> warnLevel = DisabledWarnLevel.valueOf(warnLevelStr); <END> } catch (IllegalArgumentException e) { throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr, e); } switch (warnLevel) { case SILENT: break; case INFORM: logger.info(DISABLED_LOG_MSG, bucket); break; case WARN: logger.warn(DISABLED_LOG_MSG, bucket); break; case FAIL: logger.error(DISABLED_LOG_MSG, bucket); throw new UnsupportedOperationException(DISABLED_LOG_MSG + bucket); default: throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr); } }</code><technical_language>warnLevel.toUpperCase(Locale.EN_US)</technical_language>

Target:
public static void logS3GuardDisabled(Logger logger, String warnLevelStr, String bucket) throws UnsupportedOperationException, IllegalArgumentException { final DisabledWarnLevel warnLevel; try { warnLevel = DisabledWarnLevel.valueOf(warnLevelStr.toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr, e); } switch (warnLevel) { case SILENT: logger.debug(DISABLED_LOG_MSG, bucket); break; case INFORM: logger.info(DISABLED_LOG_MSG, bucket); break; case WARN: logger.warn(DISABLED_LOG_MSG, bucket); break; case FAIL: logger.error(DISABLED_LOG_MSG, bucket); throw new UnsupportedOperationException(DISABLED_LOG_MSG + bucket); default: throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr); } }
Source:
<code><START> void exec(String[] cmdArray, final BluetoothProcessListener listener) { <END> logger.debug("Executing: {}", Arrays.toString(cmdArray)); Consumer<CommandStatus> callback = status -> logger.debug("Command ended with exit value {}", status.getExitStatus().getExitValue()); Command command = new Command(String.join(" ", cmdArray)); command.setOutputStream(this.outputStream); command.setErrorStream(this.errorStream); this.executorService.execute(command, callback); this.futureInputGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess Input Stream Gobbler"); try { readInputStreamFully(this.readOutputStream, listener); } catch (IOException | KuraException e) { logger.error("Process input stream failed", e); } }); this.futureErrorGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess ErrorStream Gobbler"); try { readErrorStreamFully(this.readErrorStream, listener); } catch (IOException | KuraException e) { logger.error("Process error stream failed", e); } }); }</code><technical_language>exec merged/optimized execSnoop</technical_language>

Target:
void exec(String[] cmdArray, final BluetoothProcessListener listener) { if (logger.isDebugEnabled()) { logger.debug("Executing: {}", Arrays.toString(cmdArray)); } Consumer<CommandStatus> callback = status -> logger.debug("Command ended with exit value {}", status.getExitStatus().getExitValue()); Command command = new Command(cmdArray); command.setOutputStream(this.outputStream); command.setErrorStream(this.errorStream); this.executorService.execute(command, callback); this.futureInputGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess Input Stream Gobbler"); try { readInputStreamFully(this.readOutputStream, listener); } catch (IOException | KuraException e) { logger.error("Process input stream failed", e); } }); this.futureErrorGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess ErrorStream Gobbler"); try { readErrorStreamFully(this.readErrorStream, listener); } catch (IOException | KuraException e) { logger.error("Process error stream failed", e); } }); }
Source:
<code>private void showTagsDialog() { String[] tagList = new String[mTags.size()]; int current = -1; for (int i = 0; i < mTags.size(); i++) { tagList[i] = mTags.get(i).getName(); <START> if (mTags.get(i).getCommit().getSha() == mSelectedRef) { <END> current = i; } } AlertDialog.Builder builder = UiUtils.createDialogBuilder(this); builder.setCancelable(true); builder.setTitle(R.string.repo_tags); builder.setSingleChoiceItems(tagList, current, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedRef = mTags.get(which).getCommit().getSha(); mSelectBranchTag = mTags.get(which).getName(); } }); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { refreshFragment(); } }); builder.show(); }</code><technical_language>equals(), ==</technical_language>

Target:
private void showTagsDialog() { String[] tagList = new String[mTags.size()]; int current = -1; for (int i = 0; i < mTags.size(); i++) { tagList[i] = mTags.get(i).getName(); if (mTags.get(i).getCommit().getSha().equals(mSelectedRef)) { current = i; } } AlertDialog.Builder builder = UiUtils.createDialogBuilder(this); builder.setCancelable(true); builder.setTitle(R.string.repo_tags); builder.setSingleChoiceItems(tagList, current, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedRef = mTags.get(which).getCommit().getSha(); mSelectBranchTag = mTags.get(which).getName(); } }); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { refreshFragment(); } }); builder.show(); }
Source:
<code>public HttpServerRequest streamPriorityHandler(Handler<StreamPriority> handler) { <START> streamPriorityHandler = handler; <END> return this; }</code><technical_language>wrap in synchronized (conn) block</technical_language>

Target:
public HttpServerRequest streamPriorityHandler(Handler<StreamPriority> handler) { synchronized (conn) { streamPriorityHandler = handler; } return this; }
Source:
<code>public boolean emit(U update) { <START> return true; <END> }</code><technical_language>return false is client connected anymore</technical_language>

Target:
public boolean emit(U update) { return false; }
Source:
<code>public final FieldArray clone() { int size = size(); FieldArray clone = new FieldArray(size); System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size); for (int i = 0; i < <START> mData.length; i++) <END> { if (mData[i] != null) { clone.mData[i] = mData[i].clone(); } } clone.mSize = mSize; return clone; }</code><technical_language>size</technical_language>

Target:
public final FieldArray clone() { int size = size(); FieldArray clone = new FieldArray(size); System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size); for (int i = 0; i < size; i++) { if (mData[i] != null) { clone.mData[i] = mData[i].clone(); } } clone.mSize = size; return clone; }
Source:
<code>private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); <START> if (unmanagedControllers.size() == 1) { <END> removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); return; } }</code><technical_language>this method is called collection of unmanaged devices is empty (#794) is reach is more 1 (#823) - this check redundant, right</technical_language>

Target:
private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); if (unmanagedControllers.size() != 1) { return; } removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); }