auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!operation.hasDefined(CommonAttributes.JGROUPS_CLUSTER.getName()) && operation.hasDefined(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName())) { operation.get(CommonAttributes.JGROUPS_CLUSTER.getName()).set(operation.get(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName())); operation.remove(CommonAttributes.LEGACY_JGROUPS_CLUSTER.getName()); } if (operation.hasDefined(JGROUPS_CLUSTER.getName())) { if (operation.hasDefined(JGROUPS_CHANNEL_FACTORY.getName()) && !operation.hasDefined(JGROUPS_CHANNEL.getName())) { String channel = operation.get(JGROUPS_CLUSTER.getName()).asString(); operation.get(JGROUPS_CHANNEL.getName()).set(channel); PathAddress channelAddress = context.getCurrentAddress().getParent().getParent().getParent().append(ModelDescriptionConstants.SUBSYSTEM, "jgroups").append("channel", channel); ModelNode addChannelOperation = Util.createAddOperation(channelAddress); addChannelOperation.get("stack").set(operation.get(JGROUPS_CHANNEL_FACTORY.getName())); <START> System.out.println("Executing " + addChannelOperation); <END> context.addStep(addChannelOperation, AddIfAbsentStepHandler.INSTANCE, OperationContext.Stage.MODEL); } } super.execute(context, operation); }</code><technical_language>removed</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { CommonAttributes.renameChannelToCluster(operation); if (operation.hasDefined(JGROUPS_CLUSTER.getName())) { if (operation.hasDefined(JGROUPS_CHANNEL_FACTORY.getName()) && !operation.hasDefined(JGROUPS_CHANNEL.getName())) { String channel = operation.get(JGROUPS_CLUSTER.getName()).asString(); operation.get(JGROUPS_CHANNEL.getName()).set(channel); PathAddress channelAddress = context.getCurrentAddress().getParent().getParent().getParent().append(ModelDescriptionConstants.SUBSYSTEM, "jgroups").append("channel", channel); ModelNode addChannelOperation = Util.createAddOperation(channelAddress); addChannelOperation.get("stack").set(operation.get(JGROUPS_CHANNEL_FACTORY.getName())); context.addStep(addChannelOperation, AddIfAbsentStepHandler.INSTANCE, OperationContext.Stage.MODEL); } } super.execute(context, operation); }
Source:
<code>public void dispose() { menuManager.dispose(); if (toolbarManager != null) { <START> ((ToolBarManager) toolbarManager).dispose(); <END> } super.dispose(); }</code><technical_language>removed if field right type</technical_language>

Target:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { toolbarManager.dispose(); } super.dispose(); }
Source:
<code>public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA).isEqualTo(factory.fromString("59959303159920881837560881824507314222")); <START> assertThat(tokenA).isEqualTo(tokenB); <END> }</code><technical_language>Trivial: chained isEqualTo calls</technical_language>

Target:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA) .isEqualTo(factory.fromString("59959303159920881837560881824507314222")) .isEqualTo(tokenB); }
Source:
<code>protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { <START> setReturnValue(new ArrayList<>()); <END> return; } VM vm = DbFacade.getInstance().getVmDao().get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { setReturnValue(new ArrayList<>()); return; } List<Disk> filteredDiskList = new ArrayList<Disk>(); for (Disk disk : diskList) { if (DiskValidator.isDiskInterfaceSupportedByOs(disk.getDiskInterface(), vm.getOs(), vm.getVdsGroupCompatibilityVersion())) { filteredDiskList.add(disk); } } setReturnValue(filteredDiskList); }</code><technical_language>Actually, a new ArrayList<> better. result serializable for GWT compatibility, want enforce a dependency DAO layer</technical_language>

Target:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { setReturnValue(new ArrayList<>()); return; } VM vm = DbFacade.getInstance().getVmDao().get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { setReturnValue(new ArrayList<>()); return; } List<Disk> filteredDiskList = new ArrayList<>(); for (Disk disk : diskList) { if (DiskValidator.isDiskInterfaceSupportedByOs(disk.getDiskInterface(), vm.getOs(), vm.getVdsGroupCompatibilityVersion())) { filteredDiskList.add(disk); } } setReturnValue(filteredDiskList); }
Source:
<code>static HttpHeaders getHeaders(StripeRequest request) { Map<String, List<String>> headerMap = new HashMap<>(request.headers().map()); headerMap.put("User-Agent", Arrays.asList(buildUserAgentString())); <START> headerMap.put("X-Stripe-Client-User-Agent", Arrays.asList(buildXStripeClientUserAgentString())); <END> return HttpHeaders.of(headerMap); }</code><technical_language>calling out strikes a weird HttpHeaders build a set of headers, instead manipulate a Map create HttpHeaders. I based PR description supposed a safety feature prevent reuse of HttpHeaders object, limitation feels a over-restrictive IMO</technical_language>

Target:
static HttpHeaders getHeaders(StripeRequest request) { Map<String, List<String>> userAgentHeadersMap = new HashMap<>(); userAgentHeadersMap.put("User-Agent", Arrays.asList(buildUserAgentString())); userAgentHeadersMap.put( "X-Stripe-Client-User-Agent", Arrays.asList(buildXStripeClientUserAgentString())); return request.headers().withAdditionalHeaders(userAgentHeadersMap); }
Source:
<code>Field getField(ColumnIdent path, Operation operation) throws UnsupportedOperationException, ColumnUnknownException; <START> QualifiedName getQualifiedName(); <END> List<Symbol> outputs(); WhereClause where(); List<Symbol> groupBy(); @Nullable HavingClause having(); @Nullable OrderBy orderBy(); @Nullable Symbol limit(); @Nullable Symbol offset(); boolean hasAggregates(); @Override default void visitSymbols(Consumer<? super Symbol> consumer) { for (Symbol output : outputs()) { consumer.accept(output); } where().accept(consumer); for (Symbol groupKey : groupBy()) { consumer.accept(groupKey); } HavingClause having = having(); if (having != null) { having.accept(consumer); } OrderBy orderBy = orderBy(); if (orderBy != null) { orderBy.accept(consumer); } Symbol limit = limit(); if (limit != null) { consumer.accept(limit); } Symbol offset = offset(); if (offset != null) { consumer.accept(offset); } }</code><technical_language>added Nonull annotation, a statement implements AnalyzedRelation fields</technical_language>

Target:
Field getField(ColumnIdent path, Operation operation) throws UnsupportedOperationException, ColumnUnknownException; @Nonnull List<Field> fields(); QualifiedName getQualifiedName(); List<Symbol> outputs(); WhereClause where(); List<Symbol> groupBy(); @Nullable HavingClause having(); @Nullable OrderBy orderBy(); @Nullable Symbol limit(); @Nullable Symbol offset(); boolean hasAggregates(); @Override default void visitSymbols(Consumer<? super Symbol> consumer) { for (Symbol output : outputs()) { consumer.accept(output); } where().accept(consumer); for (Symbol groupKey : groupBy()) { consumer.accept(groupKey); } HavingClause having = having(); if (having != null) { having.accept(consumer); } OrderBy orderBy = orderBy(); if (orderBy != null) { orderBy.accept(consumer); } Symbol limit = limit(); if (limit != null) { consumer.accept(limit); } Symbol offset = offset(); if (offset != null) { consumer.accept(offset); } }
Source:
<code>private void saveUUID(String uuid) { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.getParentFile().exists()) { if (!eclipseUUIDFile.getParentFile().mkdirs()) return; } <START> OutputStream os = null; <END> try { os = new BufferedOutputStream(new FileOutputStream(eclipseUUIDFile)); Properties prop = new Properties(); prop.setProperty(PROP_UUID, uuid); prop.setProperty("version", "1"); prop.store(os, ""); } catch (IOException e) { return; } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } } }</code><technical_language>core.runtime is 1.7 a try-with</technical_language>

Target:
private void saveUUID(String uuid) { File eclipseUUIDFile = new File(System.getProperty("user.home") + UUID_PATH); if (!eclipseUUIDFile.getParentFile().exists()) { if (!eclipseUUIDFile.getParentFile().mkdirs()) return; } try (OutputStream os = new BufferedOutputStream(new FileOutputStream(eclipseUUIDFile))){ Properties prop = new Properties(); prop.setProperty(PROP_UUID, uuid); prop.setProperty("version", "1"); prop.store(os, ""); } catch (IOException e) { return; } }
Source:
<code>public void close() { final int usages = referencing.dropReference(); <START> if (usages > 0) { <END> lock.unlock(); } }</code><technical_language>I this introduces a bug in case "close" finds reference in use. In case "close" call unlock fail ReentrantLock requires unlock called thread called lock (I think). In general wold if thread called lock beginning of "try-with-resource" caller of "unlock"</technical_language>

Target:
public void close() { referencing.dropReference(); lock.unlock(); }
Source:
<code>public static String getCssValueFromTheme(Display display, String value) { BundleContext context = FrameworkUtil.getBundle(E4ThemeColor.class).getBundleContext(); try { Object reference = MethodUtils.invokeMethod(context, "getServiceReference", "org.eclipse.e4.ui.css.swt.theme.IThemeManager"); if (reference != null) { Object iThemeManager = MethodUtils.invokeMethod(context, "getService", reference); if (iThemeManager != null) { final Object themeEngine = MethodUtils.invokeMethod(iThemeManager, "getEngineForDisplay", display); if (themeEngine != null) { Shell shell = display.getActiveShell(); if (shell == null) { shell = Iterables.find(Arrays.asList(display.getShells()), new Predicate<Shell>() { @Override public boolean apply(Shell input) { try { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", input); <START> if (shellStyle instanceof CSSStyleDeclaration) { <END> return true; } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { return false; } return false; } }, null); } if (shell != null) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", shell); if (shellStyle instanceof CSSStyleDeclaration) { CSSValue cssValue = ((CSSStyleDeclaration) shellStyle).getPropertyCSSValue(value); if (cssValue != null) { return cssValue.getCssText(); } } } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logOnce(e); return null; } return null; }</code><technical_language>return shellStyle instanceof CSSStyleDeclaration</technical_language>

Target:
public static String getCssValueFromTheme(Display display, String value) { BundleContext context = FrameworkUtil.getBundle(E4ThemeColor.class).getBundleContext(); try { Object reference = MethodUtils.invokeMethod(context, "getServiceReference", "org.eclipse.e4.ui.css.swt.theme.IThemeManager"); if (reference != null) { Object iThemeManager = MethodUtils.invokeMethod(context, "getService", reference); if (iThemeManager != null) { final Object themeEngine = MethodUtils.invokeMethod(iThemeManager, "getEngineForDisplay", display); if (themeEngine != null) { Shell shell = display.getActiveShell(); if (shell == null) { for (Shell input : display.getShells()) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", input); if (shellStyle instanceof CSSStyleDeclaration) { shell = input; break; } } } if (shell != null) { Object shellStyle = MethodUtils.invokeMethod(themeEngine, "getStyle", shell); if (shellStyle instanceof CSSStyleDeclaration) { CSSValue cssValue = ((CSSStyleDeclaration) shellStyle).getPropertyCSSValue(value); if (cssValue != null) { return cssValue.getCssText(); } } } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { logOnce(e); return null; } return null; }
Source:
<code>@Test public void overrideDoesNotCopyDefaultModifier() { TypeElement classElement = getElement(ExtendsIterableWithDefaultMethods.class); DeclaredType classType = (DeclaredType) classElement.asType(); List<ExecutableElement> methods = methodsIn(elements.getAllMembers(classElement)); ExecutableElement exec = findFirst(methods, "iterator"); <START> Assume.assumeTrue(Util.DEFAULT != null); <END> exec = findFirst(methods, "spliterator"); MethodSpec method = MethodSpec.overriding(exec, classType, types).build(); assertThat(method.toString()).isEqualTo("" + "@java.lang.Override\n" + "public java.util.Spliterator<java.lang.Object> spliterator() {\n" + "}\n"); }</code><technical_language>assumeNotNull? import static? (and possibly TruthJUnit.assume() instead: assume().that(Util.DEFAULT).isNotNull())</technical_language>

Target:
@Test public void overrideDoesNotCopyDefaultModifier() { TypeElement classElement = getElement(ExtendsIterableWithDefaultMethods.class); DeclaredType classType = (DeclaredType) classElement.asType(); List<ExecutableElement> methods = methodsIn(elements.getAllMembers(classElement)); ExecutableElement exec = findFirst(methods, "iterator"); assume().that(Util.DEFAULT).isNotNull(); exec = findFirst(methods, "spliterator"); MethodSpec method = MethodSpec.overriding(exec, classType, types).build(); assertThat(method.toString()).isEqualTo("" + "@java.lang.Override\n" + "public java.util.Spliterator<java.lang.Object> spliterator() {\n" + "}\n"); }
Source:
<code>static <T> Iterator<T> iteratorFrom(WorkProcessor<T> processor) { return new AbstractIterator<T>() { final Iterator<Optional<T>> yieldingIterator = yieldingIteratorFrom(processor); @Override protected T computeNext() { if (!yieldingIterator.hasNext()) { return endOfData(); } <START> Optional<T> elementOptional = yieldingIterator.next(); <END> if (!elementOptional.isPresent()) { throw new IllegalStateException("Work has yielded"); } return elementOptional.get(); } }; }</code><technical_language>call element next</technical_language>

Target:
static <T> Iterator<T> iteratorFrom(WorkProcessor<T> processor) { requireNonNull(processor, "processor is null"); return new AbstractIterator<T>() { final Iterator<Optional<T>> yieldingIterator = yieldingIteratorFrom(processor); @Override protected T computeNext() { if (!yieldingIterator.hasNext()) { return endOfData(); } return yieldingIterator.next() .orElseThrow(() -> new IllegalStateException("Cannot iterate over yielding WorkProcessor")); } }; }
Source:
<code>public ModelAndView membershipDetail() { ModelAndView modelAndView = new ModelAndView("/membership-give-edit"); modelAndView.addObject("userGroups", MembershipUserGroup.values()); <START> modelAndView.addObject("membershipLevels", Lists.newArrayList(0, 1, 2, 3, 4, 5)); <END> return modelAndView; }</code><technical_language>db find</technical_language>

Target:
public ModelAndView membershipDetail() { ModelAndView modelAndView = new ModelAndView("/membership-give-edit"); modelAndView.addObject("userGroups", MembershipUserGroup.values()); modelAndView.addObject("membershipLevels", Lists.newArrayList(userMembershipService.getAllLevels())); return modelAndView; }
Source:
<code>public CourseStudent update(CourseStudent courseStudent, Student student, CourseEnrolmentType courseEnrolmentType, CourseParticipationType participationType, Date enrolmentDate, Boolean lodging, CourseOptionality optionality) throws DuplicateCourseStudentException { EntityManager entityManager = getEntityManager(); List<CourseStudent> courseStudents = listByCourseAndStudent(courseStudent.getCourse(), student); if (!courseStudents.isEmpty()) { <START> for (CourseStudent cs : courseStudents) { <END> if (cs.getId() != courseStudent.getId()) throw new DuplicateCourseStudentException(); } } courseStudent.setStudent(student); courseStudent.setCourseEnrolmentType(courseEnrolmentType); courseStudent.setEnrolmentTime(enrolmentDate); courseStudent.setParticipationType(participationType); courseStudent.setLodging(lodging); courseStudent.setOptionality(optionality); entityManager.persist(courseStudent); courseStudentUpdatedEvent.fire(new CourseStudentUpdatedEvent(courseStudent.getId(), courseStudent.getCourse().getId(), courseStudent.getStudent().getId())); return courseStudent; }</code><technical_language>cs -> courseStudent</technical_language>

Target:
public CourseStudent update(CourseStudent courseStudent, Student student, CourseEnrolmentType courseEnrolmentType, CourseParticipationType participationType, Date enrolmentDate, Boolean lodging, CourseOptionality optionality) throws DuplicateCourseStudentException { EntityManager entityManager = getEntityManager(); List<CourseStudent> courseStudents = listByCourseAndStudent(courseStudent.getCourse(), student); if (!courseStudents.isEmpty()) { for (CourseStudent courseStudent2 : courseStudents) { if (courseStudent2.getId() != courseStudent.getId()) throw new DuplicateCourseStudentException(); } } courseStudent.setStudent(student); courseStudent.setCourseEnrolmentType(courseEnrolmentType); courseStudent.setEnrolmentTime(enrolmentDate); courseStudent.setParticipationType(participationType); courseStudent.setLodging(lodging); courseStudent.setOptionality(optionality); entityManager.persist(courseStudent); courseStudentUpdatedEvent.fire(new CourseStudentUpdatedEvent(courseStudent.getId(), courseStudent.getCourse().getId(), courseStudent.getStudent().getId())); return courseStudent; }
Source:
<code>public ComponentBuilder(ComponentBuilder original) { current = new TextComponent( original.getCurrent() ); for (BaseComponent baseComponent : original.getParts()) { <START> parts.add( new TextComponent( (TextComponent) baseComponent ) ); <END> } }</code><technical_language>if component is in fact a TextComponent</technical_language>

Target:
public ComponentBuilder(ComponentBuilder original) { current = new TextComponent( original.current ); for (BaseComponent baseComponent : original.parts) { parts.add( baseComponent.duplicate() ); } }
Source:
<code>public int compareTo(Location other) { if (equals(other)) { return 0; } <START> return Double.compare(toDouble(), other.toDouble()); <END> }</code><technical_language>INVALID relationship a valid location, IIRC bigger</technical_language>

Target:
public int compareTo(Location other) { return (other == INVALID) ? 0 : -1; }
Source:
<code>public void basic() { Assert.assertTrue(getClassPath(true).contains("\t")); Assert.assertTrue(getClassPath(true).contains("Java System Classloader")); Assert.assertTrue(getClassPath(true).contains("Level")); Assert.assertTrue(getClassPath(true).length() > getClassPath(false).length()); <START> Assert.assertFalse(getClassPath(false).contains("\t")); <END> Assert.assertFalse(getClassPath(false).contains("Java System Classloader")); Assert.assertFalse(getClassPath(false).contains("Level")); }</code><technical_language>sense ensure is white space</technical_language>

Target:
public void basic() { assertPattern(getClassPath(true), "(?s).*\\s+.*\\n$", true); Assert.assertTrue(getClassPath(true).contains("Java System Classloader")); Assert.assertTrue(getClassPath(true).contains("Level")); Assert.assertTrue(getClassPath(true).length() > getClassPath(false).length()); assertPattern(getClassPath(false), "(?s).*\\s+.*\\n$", false); Assert.assertFalse(getClassPath(false).contains("Java System Classloader")); Assert.assertFalse(getClassPath(false).contains("Level")); }
Source:
<code>public SerializedString toBytes(Codec<PlanFragment> codec) { requireNonNull(codec, "codec is null"); if (cachedSerialization == null) { cachedSerialization = new SerializedString(new String(codec.toBytes(this))); } <START> return cachedSerialization; <END> }</code><technical_language>benign data race ? question is if serialization request similar time, this serialize for task</technical_language>

Target:
public synchronized byte[] toBytes(Codec<PlanFragment> codec) { requireNonNull(codec, "codec is null"); if (cachedSerialization != null) { verify(codec == lastUsedCodec, "Only one Codec may be used to serialize PlanFragments"); } else { cachedSerialization = codec.toBytes(this); lastUsedCodec = codec; } return cachedSerialization; }
Source:
<code>public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { return Arrays.asList(create().select(INSTANCE.AGENT_ID) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .join(INSTANCE_HOST_MAP) .on(INSTANCE.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(HOST) .on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID)) .join(AGENT) .on(AGENT.ID.eq(HOST.AGENT_ID)) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) <START> .and(AGENT.STATE.eq(AgentConstants.STATE_ACTIVE)) <END> .orderBy(INSTANCE.AGENT_ID.asc()) .fetch().intoArray(INSTANCE.AGENT_ID)); }</code><technical_language>CommonStateConstants.ACTIVE</technical_language>

Target:
public List<Long> getAgentProvider(String providedServiceLabel, long accountId) { return Arrays.asList(create().select(INSTANCE.AGENT_ID) .from(INSTANCE) .join(INSTANCE_LABEL_MAP) .on(INSTANCE_LABEL_MAP.INSTANCE_ID.eq(INSTANCE.ID)) .join(LABEL) .on(LABEL.ID.eq(INSTANCE_LABEL_MAP.LABEL_ID).and(LABEL.KEY.eq(providedServiceLabel))) .join(INSTANCE_HOST_MAP) .on(INSTANCE.ID.eq(INSTANCE_HOST_MAP.INSTANCE_ID)) .join(HOST) .on(INSTANCE_HOST_MAP.HOST_ID.eq(HOST.ID)) .join(AGENT) .on(AGENT.ID.eq(HOST.AGENT_ID)) .where(INSTANCE.ACCOUNT_ID.eq(accountId) .and(INSTANCE.AGENT_ID.isNotNull()) .and(INSTANCE.STATE.eq(InstanceConstants.STATE_RUNNING)) .and(INSTANCE.HEALTH_STATE.in(HealthcheckConstants.HEALTH_STATE_HEALTHY, HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY))) .and(AGENT.STATE.eq(CommonStatesConstants.ACTIVE)) .orderBy(INSTANCE.AGENT_ID.asc()) .fetch().intoArray(INSTANCE.AGENT_ID)); }
Source:
<code><START> public C4Error getError() { <END> return error; }</code><technical_language>C4Error is private return CouchbaseLiteException instead. convert CouchbaseLiteException, CBLStatus.convertError() method. Please check handle null error well</technical_language>

Target:
public CouchbaseLiteException getError() { return error.getCode() != 0 ? CBLStatus.convertError(error) : null; }
Source:
<code>public String toString() { StringBuilder url = new StringBuilder(); url.append("http"); if (secure) { url.append("s"); } url.append("://"); url.append(host); if (port != 80 && port != 443) { <START> url.append(":"); <END> url.append(port); } url.append(path); return url.toString(); }</code><technical_language>omit port if matches protocol. java if (!(port == 80 && !secure) && !(port == 443 && secure)) {</technical_language>

Target:
public String toString() { StringBuilder url = new StringBuilder(); url.append("http"); if (secure) { url.append("s"); } url.append("://"); url.append(host); if (!(port == 80 && !secure) && !(port == 443 && secure)) { url.append(":"); url.append(port); } url.append(path); return url.toString(); }
Source:
<code>private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException { if (resp.has("items")) { JSONArray activities = resp.getJSONArray("items"); for (int i = 0; i < activities.length(); i++) { JSONObject item = activities.getJSONObject(i); SyncActivityItem ai = new SyncActivityItem(); String startTime = item.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { <START> ai.setStartTime(format.parse(startTime).getTime()/ONE_THOUSEND); <END> } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } Float time = Float.parseFloat(item.getString("duration")); ai.setDuration(time.longValue()); BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance"))); dist = dist.setScale(2, BigDecimal.ROUND_UP); ai.setDistance(dist.floatValue()); ai.setURI(REST_URL + item.getString("uri")); ai.setId((long) items.size()); String sport = item.getString("type"); if (SPORT_MAP.containsKey(sport)) { ai.setSport(SPORT_MAP.get(sport)); } else { ai.setSport(Sport.OTHER.getDbValue()); } items.add(ai); } } if (resp.has("next")) { return REST_URL + resp.getString("next"); } return null; }</code><technical_language>remove ONE_THOUSAND instead create a method convertSecondsToMillis()</technical_language>

Target:
private String parseForNext(JSONObject resp, List<SyncActivityItem> items) throws JSONException { if (resp.has("items")) { JSONArray activities = resp.getJSONArray("items"); for (int i = 0; i < activities.length(); i++) { JSONObject item = activities.getJSONObject(i); SyncActivityItem ai = new SyncActivityItem(); String startTime = item.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { ai.setStartTime(TimeUnit.MILLISECONDS.toSeconds(format.parse(startTime).getTime())); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } Float time = Float.parseFloat(item.getString("duration")); ai.setDuration(time.longValue()); BigDecimal dist = new BigDecimal(Float.parseFloat(item.getString("total_distance"))); dist = dist.setScale(2, BigDecimal.ROUND_UP); ai.setDistance(dist.floatValue()); ai.setURI(REST_URL + item.getString("uri")); ai.setId((long) items.size()); String sport = item.getString("type"); if (SPORT_MAP.containsKey(sport)) { ai.setSport(SPORT_MAP.get(sport)); } else { ai.setSport(Sport.OTHER.getDbValue()); } items.add(ai); } } if (resp.has("next")) { return REST_URL + resp.getString("next"); } return null; }
Source:
<code>public CoapObserveRelation observeAndWait(Request request, CoapHandler handler) { if (request.getOptions().hasObserve()) { Endpoint outEndpoint = getEffectiveEndpoint(request); CoapObserveRelation relation = new CoapObserveRelation(request, outEndpoint); request.addMessageObserver(new ObserveMessageObserverImpl(handler, relation)); CoapResponse response = synchronous(request, outEndpoint); if (response == null || !response.advanced().getOptions().hasObserve()) relation.setCanceled(true); relation.setCurrent(response); return relation; } else { <START> throw new IllegalStateException("please make sure that the request has observe option set."); <END> } }</code><technical_language>this is a problem provided parameter (request), throw IllegalArgumentException'</technical_language>

Target:
public CoapObserveRelation observeAndWait(Request request, CoapHandler handler) { if (request.getOptions().hasObserve()) { Endpoint outEndpoint = getEffectiveEndpoint(request); CoapObserveRelation relation = new CoapObserveRelation(request, outEndpoint); request.addMessageObserver(new ObserveMessageObserverImpl(handler, relation)); CoapResponse response = synchronous(request, outEndpoint); if (response == null || !response.advanced().getOptions().hasObserve()) relation.setCanceled(true); relation.setCurrent(response); return relation; } else { throw new IllegalArgumentException("please make sure that the request has observe option set."); } }
Source:
<code>public final void writeSelf(FileChannel fc) throws IOException { fRwl.readLock().lock(); try { final int blockSize = fConfig.getBlockSize(); ByteBuffer buffer = ByteBuffer.allocate(blockSize); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.clear(); buffer.put(getNodeType().toByte()); buffer.putLong(fNodeStart); buffer.putLong(fNodeEnd); buffer.putInt(fSequenceNumber); buffer.putInt(fParentSequenceNumber); buffer.putInt(fIntervals.size()); buffer.put((byte) 1); writeSpecificHeader(buffer); <START> fIntervals.forEach(i->i.writeInterval(buffer)); <END> while (buffer.position() < blockSize) { buffer.put((byte) 0); } buffer.position(blockSize); buffer.flip(); int res = fc.write(buffer); if (res != blockSize) { throw new IllegalStateException("Wrong size of block written: Actual: " + res + ", Expected: " + blockSize); } } finally { fRwl.readLock().unlock(); } fIsOnDisk = true; }</code><technical_language>changing this byte[] thing, this become: forEach( interval -> { byte[] array = interval.writeInterval() (or .serialize() w/e) buffer.putInt(array.length); buffer.put(array); }</technical_language>

Target:
public final void writeSelf(FileChannel fc) throws IOException { fRwl.readLock().lock(); try { final int blockSize = fConfig.getBlockSize(); ByteBuffer buffer = ByteBuffer.allocate(blockSize); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.clear(); buffer.put(getNodeType().toByte()); buffer.putLong(fNodeStart); buffer.putLong(fNodeEnd); buffer.putInt(fSequenceNumber); buffer.putInt(fParentSequenceNumber); buffer.putInt(fIntervals.size()); buffer.put((byte) 1); writeSpecificHeader(buffer); fIntervals.forEach(i->i.writeInterval(buffer)); while (buffer.position() < blockSize) { buffer.put((byte) 0); } buffer.flip(); int res = fc.write(buffer); if (res != blockSize) { throw new IllegalStateException("Wrong size of block written: Actual: " + res + ", Expected: " + blockSize); } } finally { fRwl.readLock().unlock(); } fIsOnDisk = true; }
Source:
<code>private static Map<String, FormatValidator> formatValidators(Map<String, FormatValidator> parent, FormatValidator... validators) { Map<String, FormatValidator> validatorMap = parent == null ? new HashMap<>() : new HashMap<>(parent); <START> for(FormatValidator validator : validators) <END> validatorMap.put(validator.formatName(), validator); return unmodifiableMap(validatorMap); }</code><technical_language>please add brackets here</technical_language>

Target:
private static Map<String, FormatValidator> formatValidators(Map<String, FormatValidator> parent, FormatValidator... validators) { Map<String, FormatValidator> validatorMap = (parent == null) ? new HashMap<>() : new HashMap<>(parent); for(FormatValidator validator : validators) { validatorMap.put(validator.formatName(), validator); } return unmodifiableMap(validatorMap); }
Source:
<code>public void registerClientInformation(final ClientInformation clientInformation) { <START> if (this.clientInformation != null) { <END> sensors.connectionsByClient.decrement(this.clientInformation); } this.clientInformation = clientInformation; sensors.connectionsByClient.increment(clientInformation); }</code><technical_language>If this exists, check if equal new information wanted register. If is, skip decrement metric + increment metric dance</technical_language>

Target:
public void registerClientInformation(final ClientInformation clientInformation) { if (this.clientInformation != null) { if (this.clientInformation.equals(clientInformation)) return; sensors.connectionsByClient.decrement(this.clientInformation); } this.clientInformation = clientInformation; sensors.connectionsByClient.increment(clientInformation); }
Source:
<code>public void destroyTicketGrantingTicket(final WebContext context, final HttpTGTProfile profile) { HttpURLConnection connection = null; try { final URL endpointURL = new URL(getAuthenticator().getCasRestUrl()); final URL deleteURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId()); connection = HttpUtils.openDeleteConnection(deleteURL); final int responseCode = connection.getResponseCode(); <START> if (responseCode != HTTP_STATUS_OK) { <END> throw new TechnicalException("TGT delete request for `" + profile + "` failed: " + HttpUtils.buildHttpErrorMessage(connection)); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }</code><technical_language>this constant here: <LINK_0></technical_language>

Target:
public void destroyTicketGrantingTicket(final WebContext context, final HttpTGTProfile profile) { HttpURLConnection connection = null; try { final URL endpointURL = new URL(getAuthenticator().getCasRestUrl()); final URL deleteURL = new URL(endpointURL, endpointURL.getPath() + "/" + profile.getTicketGrantingTicketId()); connection = HttpUtils.openDeleteConnection(deleteURL); final int responseCode = connection.getResponseCode(); if (responseCode != HttpConstants.OK) { throw new TechnicalException("TGT delete request for `" + profile + "` failed: " + HttpUtils.buildHttpErrorMessage(connection)); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }
Source:
<code>protected StopMachineDetails<Integer> suspendAnyProvisionedMachines() { @SuppressWarnings("unchecked") MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION); if (Iterables.isEmpty(entity().getLocations())) { log.debug("No machine decommissioning necessary for " + entity() + " - no locations"); return new StopMachineDetails<>("No machine suspend necessary - no locations", 0); } if (provisioner == null) { log.debug("No machine decommissioning necessary for " + entity() + " - did not provision"); return new StopMachineDetails<>("No machine suspend necessary - did not provision", 0); } Location machine = getLocation(null); if (!(machine instanceof MachineLocation)) { log.debug("No decommissioning necessary for " + entity() + " - not a machine location (" + machine + ")"); return new StopMachineDetails<>("No machine suspend necessary - not a machine (" + machine + ")", 0); } if (!(provisioner instanceof SuspendsMachines)) { log.debug("Location provisioner ({}) cannot suspend machines", provisioner); throw new UnsupportedOperationException("Location provisioner cannot suspend machines: " + provisioner); } clearEntityLocationAttributes(machine); try { <START> SuspendsMachines.class.cast(provisioner).suspendMachine(MachineLocation.class.cast(machine)); <END> } catch (Throwable t) { throw Exceptions.propagate(t); } return new StopMachineDetails<>("Suspended " + machine, 1); }</code><technical_language>advantage of calling .cast class school cast? I thought usage is instance of class in a variable (so dynamic)</technical_language>

Target:
protected StopMachineDetails<Integer> suspendAnyProvisionedMachines() { @SuppressWarnings("unchecked") MachineProvisioningLocation<MachineLocation> provisioner = entity().getAttribute(SoftwareProcess.PROVISIONING_LOCATION); if (Iterables.isEmpty(entity().getLocations())) { log.debug("No machine decommissioning necessary for " + entity() + " - no locations"); return new StopMachineDetails<>("No machine suspend necessary - no locations", 0); } if (provisioner == null) { log.debug("No machine decommissioning necessary for " + entity() + " - did not provision"); return new StopMachineDetails<>("No machine suspend necessary - did not provision", 0); } Location machine = getLocation(null); if (!(machine instanceof MachineLocation)) { log.debug("No decommissioning necessary for " + entity() + " - not a machine location (" + machine + ")"); return new StopMachineDetails<>("No machine suspend necessary - not a machine (" + machine + ")", 0); } if (!(provisioner instanceof SuspendsMachines)) { log.debug("Location provisioner ({}) cannot suspend machines", provisioner); throw new UnsupportedOperationException("Location provisioner cannot suspend machines: " + provisioner); } clearEntityLocationAttributes(machine); SuspendsMachines.class.cast(provisioner).suspendMachine(MachineLocation.class.cast(machine)); return new StopMachineDetails<>("Suspended " + machine, 1); }
Source:
<code>public String visitConstant(ConstantExpression literal, Void context) { <START> return format("%d", literal.hashCode()); <END> }</code><technical_language>This is dangerous, it? int32 hash collision is pretty high</technical_language>

Target:
public String visitConstant(ConstantExpression literal, Void context) { if (literal.getValue() instanceof Slice) { Slice slice = (Slice) literal.getValue(); if (slice.hasByteArray()) { return Slices.wrappedBuffer(Base64.getEncoder().encode(slice.toByteBuffer())).toStringUtf8(); } return Slices.wrappedBuffer(Base64.getEncoder().encode(slice.getBytes())).toStringUtf8(); } return literal.toString(); }
Source:
<code>public void scheduleDownload( LeaderLocator leaderLocator ) { if ( currentJob == null || currentJob.hasCompleted() ) { <START> synchronized ( this ) <END> { if ( currentJob == null || currentJob.hasCompleted() ) { currentJob = new PersistentSnapshotDownloader( leaderLocator, applicationProcess, downloader, log ); jobScheduler.schedule( downloadSnapshotGroup, currentJob ); } } } }</code><technical_language>entire function synchronized. This double-checking trick is unsafe unnecessary</technical_language>

Target:
public synchronized void scheduleDownload( LeaderLocator leaderLocator ) { if ( currentJob == null || currentJob.hasCompleted() ) { currentJob = new PersistentSnapshotDownloader( leaderLocator, applicationProcess, downloader, log, downloaderPauseStrategy ); jobScheduler.schedule( downloadSnapshot, currentJob ); } }
Source:
<code>public void clear(IntSet segments) { Connection conn = null; PreparedStatement ps = null; try { String sql = tableManager.getDeleteRowsSqlForSegments(segments.size()); conn = connectionFactory.getConnection(); ps = conn.prepareStatement(sql); int offset = 0; for (PrimitiveIterator.OfInt segIter = segments.iterator(); segIter.hasNext(); ) { ps.setInt(++offset, segIter.nextInt()); } int result = ps.executeUpdate(); if (log.isTraceEnabled()) { log.tracef("Successfully removed %d rows.", result); } } catch (SQLException ex) { log.failedClearingJdbcCacheStore(ex); <START> throw new PersistenceException("Failed clearing cache store", ex); <END> } finally { JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(conn); } }</code><technical_language>add failing segment values log/exception message</technical_language>

Target:
public void clear(IntSet segments) { Connection conn = null; PreparedStatement ps = null; try { String sql = tableManager.getDeleteRowsSqlForSegments(segments.size()); conn = connectionFactory.getConnection(); ps = conn.prepareStatement(sql); int offset = 0; for (PrimitiveIterator.OfInt segIter = segments.iterator(); segIter.hasNext(); ) { ps.setInt(++offset, segIter.nextInt()); } int result = ps.executeUpdate(); if (log.isTraceEnabled()) { log.tracef("Successfully removed %d rows.", result); } } catch (SQLException ex) { log.failedClearingJdbcCacheStore(ex); throw new PersistenceException("Failed clearing cache store when using segments " + segments, ex); } finally { JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(conn); } }
Source:
<code>private void migrateV1FilesToV2Location(FilePersistence filePersistence, Migration migration) { for (Migration.FileMetadata fileMetadata : migration.getFileMetadata()) { filePersistence.create(fileMetadata.newFileLocation(), fileMetadata.fileSize()); FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(fileMetadata.originalFileLocation().path())); byte[] bytes = new byte[RANDOMLY_CHOSEN_BUFFER_SIZE_THAT_SEEMS_TO_WORK]; int readLast = 0; while (readLast != -1) { readLast = inputStream.read(bytes); if (readLast != 0 && readLast != -1) { filePersistence.write(bytes, 0, readLast); <START> bytes = new byte[RANDOMLY_CHOSEN_BUFFER_SIZE_THAT_SEEMS_TO_WORK]; <END> } } } catch (IOException e) { Log.e(getClass().getSimpleName(), e.getMessage()); } finally { try { filePersistence.close(); if (inputStream != null) { inputStream.close(); } } catch (IOException e) { Log.e(getClass().getSimpleName(), e.getMessage()); } } } }</code><technical_language>I wrong, need recreate this time. content is overwritten in inputStream.read(bytes), writing freshest content (the new readLast bytes)</technical_language>

Target:
private void migrateV1FilesToV2Location(FilePersistence filePersistence, Migration migration) { for (Migration.FileMetadata fileMetadata : migration.getFileMetadata()) { filePersistence.create(fileMetadata.newFileLocation(), fileMetadata.fileSize()); FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(fileMetadata.originalFileLocation().path())); byte[] bytes = new byte[RANDOMLY_CHOSEN_BUFFER_SIZE_THAT_SEEMS_TO_WORK]; int readLast = 0; while (readLast != -1) { readLast = inputStream.read(bytes); if (readLast != 0 && readLast != -1) { filePersistence.write(bytes, 0, readLast); } } } catch (IOException e) { Logger.e(e.getMessage()); } finally { try { filePersistence.close(); if (inputStream != null) { inputStream.close(); } } catch (IOException e) { Logger.e(e.getMessage()); } } } }
Source:
<code>public void testWriteListener() throws Exception { applicationContext = new SpringApplicationBuilder() .sources(getConfigurations(BatchExecutionEventTests.ItemWriteEventsListenerBinding.class)) .build().run( getCommandLineParams("--spring.cloud.stream.bindings.item-write-events.destination=item-write-events-foobar")); assertTrue(itemWriteEventsLatch.await(1, TimeUnit.SECONDS)); <START> } <END></code><technical_language>Missing a test for skip listener..</technical_language>

Target:
public void testWriteListener() throws Exception { testListener("--spring.cloud.stream.bindings.item-write-events.destination=item-write-events-foobar", itemWriteEventsLatch, BatchExecutionEventTests.ItemWriteEventsListenerBinding.class); }
Source:
<code>public void testDownloadInMultipleThreads() throws IOException, InterruptedException { FileUtils.deleteDirectory(targetMavenDir); final CountDownLatch latch = new CountDownLatch(1); createThreadWithDownload(latch).start(); createThreadWithDownload(latch).start(); latch.countDown(); <START> downloadSWR300Alpha1(); <END> String expMsg = "Resolver: downloading Maven binaries from"; Matcher matcher = Pattern.compile(expMsg).matcher(systemOutRule.getLog()); assertThat(matcher.find()).as(String.format( "The log should contain one occurrence of message \"%s\" but none was found. For more information see the log", expMsg)) .isTrue(); assertThat(matcher.find()).as(String.format( "The log should contain only one occurrence of message \"%s\" but more than one was found. For more information see the log", expMsg)).isFalse(); }</code><technical_language>do actual download in threads? countDown in right place</technical_language>

Target:
public void testDownloadInMultipleThreads() throws IOException, InterruptedException { FileUtils.deleteDirectory(targetMavenDir); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch stopLatch = new CountDownLatch(3); createThreadWithDownload(startLatch, stopLatch).start(); createThreadWithDownload(startLatch, stopLatch).start(); createThreadWithDownload(startLatch, stopLatch).start(); startLatch.countDown(); stopLatch.await(20, TimeUnit.SECONDS); String expMsg = "Resolver: downloading Maven binaries from"; Matcher matcher = Pattern.compile(expMsg).matcher(systemOutRule.getLog()); assertThat(matcher.find()).as(String.format( "The log should contain one occurrence of message \"%s\" but none was found. For more information see the log", expMsg)) .isTrue(); assertThat(matcher.find()).as(String.format( "The log should contain only one occurrence of message \"%s\" but more than one was found. For more information see the log", expMsg)).isFalse(); }
Source:
<code>public void testProjectUpdatesRowType() { final RelBuilder builder = RelBuilder.create(RelBuilderTest.config().build()); final RelNode root = builder .scan("EMP") .project( builder.field("DEPTNO"), builder.field("SAL")) .build(); final RelDataType type1 = root.getRowType(); final RelNode rootWithCast = builder .scan("EMP") .project( builder.cast(builder.field("DEPTNO"), SqlTypeName.VARCHAR), builder.cast(builder.field("SAL"), SqlTypeName.VARCHAR)) <START> .build(); <END> final RelDataType type2 = rootWithCast.getRowType(); assertThat(type1, not(type2)); final RelNode rootWithCastViaRexShuttle = root.accept(new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef inputRef) { return builder.cast(inputRef, SqlTypeName.VARCHAR); } }); final RelDataType type3 = rootWithCastViaRexShuttle.getRowType(); assertThat(type2, is(type3)); }</code><technical_language>This assert is necessary</technical_language>

Target:
public void testProjectUpdatesRowType() { final RelBuilder builder = RelBuilder.create(RelBuilderTest.config().build()); final RelNode root = builder .scan("EMP") .project( builder.field("DEPTNO"), builder.field("SAL")) .build(); final RelNode rootWithCast = builder .scan("EMP") .project( builder.cast(builder.field("DEPTNO"), SqlTypeName.VARCHAR), builder.cast(builder.field("SAL"), SqlTypeName.VARCHAR)) .build(); final RelDataType type = rootWithCast.getRowType(); final RelNode rootWithCastViaRexShuttle = root.accept(new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef inputRef) { return builder.cast(inputRef, SqlTypeName.VARCHAR); } }); final RelDataType type2 = rootWithCastViaRexShuttle.getRowType(); assertThat(type, is(type2)); }
Source:
<code>public UnknownTypeJsonAccessor path(String dotSeparatedPath) { <START> String[] components = DOT_REGEX.split( dotSeparatedPath ); <END> String leaf = components[components.length - 1]; JsonObjectAccessor parent = this; for ( int i = 0; i < components.length - 1; i++ ) { parent = parent.property( components[i] ).asObject(); } return parent.property( leaf ); }</code><technical_language>Wondering if add a Contracts#assertNotNullNorEmpty() call for this method method above</technical_language>

Target:
public UnknownTypeJsonAccessor path(String dotSeparatedPath) { Contracts.assertNotNullNorEmpty( dotSeparatedPath, "dotSeparatedPath" ); String[] components = DOT_REGEX.split( dotSeparatedPath ); String leaf = components[components.length - 1]; JsonObjectAccessor parent = this; for ( int i = 0; i < components.length - 1; i++ ) { parent = parent.property( components[i] ).asObject(); } return parent.property( leaf ); }