auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public VoltTable[] run( String targetStream, int pkey ) { if (targetStream.equals("S_ALLOW_NULLS_REPL")) { } else if (targetStream.equals("S_ALLOW_NULLS")) { voltQueueSQL(i_insert_select_part); } else { assert(false); <START> throw new RuntimeException("Don't call this."); <END> } return voltExecuteSQL(); }</code><technical_language>get throw statement</technical_language>

Target:
public VoltTable[] run( String targetStream, int pkey ) { if (targetStream.equals("S_ALLOW_NULLS_REPL")) { } else if (targetStream.equals("S_ALLOW_NULLS")) { voltQueueSQL(i_insert_select_part); } else { throw new RuntimeException("Don't call this."); } return voltExecuteSQL(); }
Source:
<code><START> public AnnotationBasedTestInjectorManager(Class<?> classUnderTest) { <END> getModulesForTestClass(classUnderTest); getMocksForTestClass(classUnderTest); getSpiesForTargetKeys(Elements.getElements(modulesForTestClass)); testCompositeConfig = new TestCompositeConfig(classLevelOverrides, methodLevelOverrides); overrideModules.add(new ArchaiusTestConfigOverrideModule(testCompositeConfig)); injector = createInjector(modulesForTestClass, overrideModules); }</code><technical_language>method names { getModulesForTestClass, getMocksForTestClass getSpiesForTargetKeys } void return type; 'get' methods return a type. prefix method names 'construct' 'inspect' instead, method name matches function</technical_language>

Target:
public AnnotationBasedTestInjectorManager(Class<?> classUnderTest) { inspectModulesForTestClass(classUnderTest); inspectMocksForTestClass(classUnderTest); inspectSpiesForTargetKeys(Elements.getElements(modulesForTestClass)); testCompositeConfig = new TestCompositeConfig(classLevelOverrides, methodLevelOverrides); overrideModules.add(new ArchaiusTestConfigOverrideModule(testCompositeConfig)); injector = createInjector(modulesForTestClass, overrideModules); }
Source:
<code>public void tearDown() throws Exception { if (workspaceServiceClient.exists(WORKSPACE_NAME, adminTestUser.getName())) { workspaceServiceClient.stop(WORKSPACE_NAME, adminTestUser.getName()); <START> workspaceServiceClient.delete(WORKSPACE_NAME, adminTestUser.getName()); <END> } org.delete(); }</code><technical_language>workspaceServiceClient.delete(WORKSPACE_NAME, adminTestUser.getName()) is enough this method checks existence of workspace stops deletion</technical_language>

Target:
public void tearDown() throws Exception { workspaceServiceClient.delete(WORKSPACE_NAME, adminTestUser.getName()); org.delete(); }
Source:
<code>public ArrayList<String> loadVarScope() { File file = new File(scopefile); Scanner input = null; try { input = new Scanner(file); <START> } <END> catch (FileNotFoundException e) { e.printStackTrace(); } if (input != null) { while (input.hasNext()) { String nextLine = input.nextLine(); if (null == nextLine) break; if (!nextLine.equals("")) scope.add(nextLine); } input.close(); } return getScope(); }</code><technical_language>indentation problem. brace do line up</technical_language>

Target:
public ArrayList<String> loadVarScope() { File file = new File(scopefile); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } while (input.hasNext()) { String nextLine = input.nextLine(); if (null == nextLine) break; if (!nextLine.equals("")) scope.add(nextLine); } input.close(); return getScope(); }
Source:
<code>IkeDeletePayload(boolean critical, byte[] payloadBody) throws IkeException { super(PAYLOAD_TYPE_DELETE, critical); ByteBuffer inputBuffer = ByteBuffer.wrap(payloadBody); protocolId = Byte.toUnsignedInt(inputBuffer.get()); spiSize = inputBuffer.get(); numSpi = Short.toUnsignedInt(inputBuffer.getShort()); spisToDelete = new int[numSpi]; switch (protocolId) { case PROTOCOL_ID_IKE: if (spiSize != SPI_LEN_NOT_INCLUDED || numSpi != 0 || inputBuffer.remaining() != 0) { throw new InvalidSyntaxException("Invalid Delete IKE Payload."); } break; case PROTOCOL_ID_ESP: if (spiSize == <START> SPI_LEN_NOT_INCLUDED <END> || numSpi == 0 || inputBuffer.remaining() != SPI_LEN_IPSEC * numSpi) { throw new InvalidSyntaxException("Invalid Delete Child Payload."); } for (int i = 0; i < numSpi; i++) { spisToDelete[i] = inputBuffer.getInt(); } break; default: throw new InvalidSyntaxException("Unrecognized protocol in Delete Payload."); } }</code><technical_language>this SPI_LEN_IPSEC? I considered "valid" for this check, fail input buffer read? protocolId = PROTOCOL_ID_ESP spiSize = 1 numSpi = 4 inputBuffer.remaining() = 4</technical_language>

Target:
IkeDeletePayload(boolean critical, byte[] payloadBody) throws IkeException { super(PAYLOAD_TYPE_DELETE, critical); ByteBuffer inputBuffer = ByteBuffer.wrap(payloadBody); protocolId = Byte.toUnsignedInt(inputBuffer.get()); spiSize = inputBuffer.get(); numSpi = Short.toUnsignedInt(inputBuffer.getShort()); spisToDelete = new int[numSpi]; switch (protocolId) { case PROTOCOL_ID_IKE: if (spiSize != SPI_LEN_NOT_INCLUDED || numSpi != 0 || inputBuffer.remaining() != 0) { throw new InvalidSyntaxException("Invalid Delete IKE Payload."); } break; case PROTOCOL_ID_ESP: if (spiSize != SPI_LEN_IPSEC || numSpi == 0 || inputBuffer.remaining() != SPI_LEN_IPSEC * numSpi) { throw new InvalidSyntaxException("Invalid Delete Child Payload."); } for (int i = 0; i < numSpi; i++) { spisToDelete[i] = inputBuffer.getInt(); } break; default: throw new InvalidSyntaxException("Unrecognized protocol in Delete Payload."); } }
Source:
<code>public T store(T o) throws RiakException { final Mutation<T> mutation = mutationProducer.produce(o); final StoreObject<T> so = bucket.store(o) .withConverter(converter) .withMutator(mutation) .withResolver(resolver) .withRetrier(retrier); if (fetchMeta.getR() != null) { so.r(fetchMeta.getR()); } if (storeMeta.hasW()) { so.w(storeMeta.getW()); } if (storeMeta.hasDw()) { so.dw(storeMeta.getDw()); } if (fetchMeta.hasPr()) { so.pr(fetchMeta.getPr()); } if (storeMeta.hasPw()) { so.pw(storeMeta.getPw()); } if (fetchMeta.hasBasicQuorum()) { so.basicQuorum(fetchMeta.getBasicQuorum()); } if (fetchMeta.hasNotFoundOk()) { so.notFoundOK(fetchMeta.getNotFoundOK()); } if (storeMeta.hasIfNotModified()) { so.ifNotModified(storeMeta.isIfNotModified()); } <START> if (storeMeta.hasIfNonMatch()) { <END> so.ifNonMatch(storeMeta.isIfNonMatch()); } if (fetchMeta.hasReturnDeletedVClock()) { so.returnDeletedVClock(fetchMeta.getReturnDeletedVClock()); } if (storeMeta.hasReturnBody()) { so.returnBody(storeMeta.getReturnBody()); } return so.execute(); }</code><technical_language>I count 28 instances of [Ii]fNonMatch</technical_language>

Target:
public T store(T o) throws RiakException { final Mutation<T> mutation = mutationProducer.produce(o); final StoreObject<T> so = bucket.store(o) .withConverter(converter) .withMutator(mutation) .withResolver(resolver) .withRetrier(retrier); if (fetchMeta.getR() != null) { so.r(fetchMeta.getR()); } if (storeMeta.hasW()) { so.w(storeMeta.getW()); } if (storeMeta.hasDw()) { so.dw(storeMeta.getDw()); } if (fetchMeta.hasPr()) { so.pr(fetchMeta.getPr()); } if (storeMeta.hasPw()) { so.pw(storeMeta.getPw()); } if (fetchMeta.hasBasicQuorum()) { so.basicQuorum(fetchMeta.getBasicQuorum()); } if (fetchMeta.hasNotFoundOk()) { so.notFoundOK(fetchMeta.getNotFoundOK()); } if (storeMeta.hasIfNotModified()) { so.ifNotModified(storeMeta.isIfNotModified()); } if (storeMeta.hasIfNoneMatch()) { so.ifNoneMatch(storeMeta.isIfNoneMatch()); } if (fetchMeta.hasReturnDeletedVClock()) { so.returnDeletedVClock(fetchMeta.getReturnDeletedVClock()); } if (storeMeta.hasReturnBody()) { so.returnBody(storeMeta.getReturnBody()); } return so.execute(); }
Source:
<code>public void initialize(TransformContext context) throws Exception { super.initialize(context); <START> init(null, context.getFailureCollector()); <END> }</code><technical_language>if errors this point, exception needs thrown. This ignore errors, a confusing error in transform. call context.getFailureCollector().getOrThrowException() this line</technical_language>

Target:
public void initialize(TransformContext context) throws Exception { super.initialize(context); FailureCollector collector = context.getFailureCollector(); init(null, collector); collector.getOrThrowException(); }
Source:
<code>public String toString(Schema schema) { Iterable<String> strings = Iterables.transform(set, new ToString<T>(schema)); <START> return Joiner.on(',').join(Sets.newTreeSet(strings)); <END> }</code><technical_language>clear here. Generally, a LinkedHashMap LinkedHashSet preserve order. If somewhere, I is a bug fixed. URIs normalized needed, avoid annoyance. I do in this case, I wanted sure</technical_language>

Target:
public String toString(Schema schema) { return Joiner.on(',').join( Iterables.transform(set, new ToString<T>(schema))); }
Source:
<code>@Override public void onPositiveClicked(@NonNull String instanceTag) { switch (instanceTag) { <START> case TAG_ADD_SITE_ICON_DIALOG: <END> ActivityLauncher.showPhotoPickerForResult(getActivity(), MediaBrowserType.SITE_ICON_PICKER, getSelectedSite()); break; case TAG_CHANGE_SITE_ICON_DIALOG: ActivityLauncher.showPhotoPickerForResult(getActivity(), MediaBrowserType.SITE_ICON_PICKER, getSelectedSite()); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }</code><technical_language>TAG_ADD_SITE_ICON_DIALOG TAG_CHANGE_SITE_ICON_DIALOG do consolidate this. case TAG_ADD_SITE_ICON_DIALOG: case TAG_CHANGE_SITE_ICON_DIALOG: ActivityLauncher.showPhotoPickerForResult(getActivity(), MediaBrowserType.SITE_ICON_PICKER, getSelectedSite()); break;</technical_language>

Target:
public void onPositiveClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_ADD_SITE_ICON_DIALOG: case TAG_CHANGE_SITE_ICON_DIALOG: ActivityLauncher.showPhotoPickerForResult(getActivity(), MediaBrowserType.SITE_ICON_PICKER, getSelectedSite()); break; case TAG_EDIT_SITE_ICON_PERMISSIONS_DIALOG: break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }
Source:
<code>public final void setAdapterFactory(AdapterFactory adapterFactory) { this.adapterFactory = adapterFactory; <START> clearCache(); setEnabled(editingDomain != null && updateSelection(getStructuredSelection())); <END> }</code><technical_language>AdapterFactory is for tooltips do need this. Objections</technical_language>

Target:
public final void setAdapterFactory(AdapterFactory adapterFactory) { this.adapterFactory = adapterFactory; if (adapterFactory != null) { contextualizeTooltip(); } }
Source:
<code>private ConjureGetFreshTimestampsResponse makeTimestampsRequest() { return conjureTimelockService.getFreshTimestamps( <START> AuthHeader.valueOf("Bearer unused"), CLIENT, ConjureGetFreshTimestampsRequest.of(10)); <END> }</code><technical_language>Lets this 13+ response sense</technical_language>

Target:
private ConjureGetFreshTimestampsResponse makeTimestampsRequest() { return conjureTimelockService.getFreshTimestamps( AuthHeader.valueOf("Bearer unused"), CLIENT, ConjureGetFreshTimestampsRequest.of(96)); }
Source:
<code>protected void executeCommand() { boolean succeeded = false; try { Guid vmId = getParameters().getVmId(); List<VmNumaNode> vmNumaNodes = getParameters().getVmNumaNodeList(); <START> if (vmNumaNodes != null && vmNumaNodes.size() > 0) { <END> Guid vdsId = getVm().getDedicatedVmForVds(); List<VdsNumaNode> vdsNumaNodes = new ArrayList<>(); if (vdsId != null) { vdsNumaNodes = getVdsNumaNodeDao().getAllVdsNumaNodeByVdsId(vdsId); } List<VdsNumaNode> nodes = new ArrayList<>(); for (VmNumaNode vmNumaNode : vmNumaNodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vmNumaNode.getVdsNumaNodeList()) { int index = pair.getSecond().getSecond(); for (VdsNumaNode vdsNumaNode : vdsNumaNodes) { if (vdsNumaNode.getIndex() == index) { pair.setFirst(vdsNumaNode.getId()); pair.getSecond().setFirst(true); break; } } } nodes.add(vmNumaNode); } getVmNumaNodeDao().massSaveNumaNode(nodes, null, vmId); setActionReturnValue(nodes.get(0).getId()); } succeeded = true; } finally { setSucceeded(succeeded); } }</code><technical_language>checked in cando action</technical_language>

Target:
protected void executeCommand() { Guid vmId = getParameters().getVmId(); List<VmNumaNode> vmNumaNodes = getParameters().getVmNumaNodeList(); Guid vdsId = getVm().getDedicatedVmForVds(); List<VdsNumaNode> vdsNumaNodes = new ArrayList<>(); if (vdsId != null) { vdsNumaNodes = getVdsNumaNodeDao().getAllVdsNumaNodeByVdsId(vdsId); } List<VdsNumaNode> nodes = new ArrayList<>(); for (VmNumaNode vmNumaNode : vmNumaNodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vmNumaNode.getVdsNumaNodeList()) { int index = pair.getSecond().getSecond(); for (VdsNumaNode vdsNumaNode : vdsNumaNodes) { if (vdsNumaNode.getIndex() == index) { pair.setFirst(vdsNumaNode.getId()); pair.getSecond().setFirst(true); break; } } } nodes.add(vmNumaNode); } getVmNumaNodeDao().massSaveNumaNode(nodes, null, vmId); setActionReturnValue(nodes.get(0).getId()); setSucceeded(true); }
Source:
<code>int getAddIndex(final WiresShape wiresShape, final WiresContainer container) { Node parent = WiresUtils.getNode(getCanvasHandler(), container); if (parent.getInEdges().size() == 0) { final double shapeX = wiresShape.getComputedLocation().getX(); final List<WiresShape> children = container.getChildShapes().toList().stream() .filter(s -> !((WiresShapeView) s).getUUID().equals(((WiresShapeView) wiresShape).getUUID())) .collect(Collectors.toList()); int targetIndex = children.size(); for (int idx = 0; idx < children.size(); idx++) { final WiresShape child = children.get(idx); if (shapeX < child.getComputedLocation().getX()) { targetIndex = idx; break; } } return targetIndex; } <START> if (state.getOriginalParent().isPresent()) { <END> if (state.getOriginalParent().get().equals(container)) { return parent.getOutEdges().size() - 1; } } return parent.getOutEdges().size(); }</code><technical_language>a suggestion this block: suggestion return state.getOriginalParent() .filter(container::equals) .map(p -> parent.getOutEdges().size() - 1) .orElse(parent.getOutEdges().size());</technical_language>

Target:
int getAddIndex(final WiresShape wiresShape, final WiresContainer container) { Node parent = WiresUtils.getNode(getCanvasHandler(), container); if (parent.getInEdges().size() == 0) { final double shapeX = wiresShape.getComputedLocation().getX(); final List<WiresShape> children = container.getChildShapes().toList().stream() .filter(s -> !((WiresShapeView) s).getUUID().equals(((WiresShapeView) wiresShape).getUUID())) .collect(Collectors.toList()); int targetIndex = children.size(); for (int idx = 0; idx < children.size(); idx++) { final WiresShape child = children.get(idx); if (shapeX < child.getComputedLocation().getX()) { targetIndex = idx; break; } } return targetIndex; } return state.getOriginalParent() .filter(container::equals) .map(p -> parent.getOutEdges().size() -1) .orElse(parent.getOutEdges().size()); }
Source:
<code>public static Object sleepFor(Object payload, long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { currentThread().interrupt(); <START> return payload; <END> } return payload; }</code><technical_language>remove "return payload" in catch</technical_language>

Target:
public static Object sleepFor(Object payload, long millis) { try { sleep(millis); } catch (InterruptedException e) { currentThread().interrupt(); } return payload; }
Source:
<code>public static String[][] to2DStringArray(Collection coll) { String[][] arr2D = new String[coll.size()][]; Iterator it = coll.iterator(); int i = 0; for (;it.hasNext();i++) { arr2D[i] = new String[]{ (String) it.next()}; } <START> return arr2D; <END> }</code><technical_language>change this</technical_language>

Target:
public static String[][] to2DStringArray(Collection coll) { return (String[][]) coll.toArray( new String[coll.size()][] ); }
Source:
<code>private CacheKey fillKey(CacheKey key, Event event) { key.setTenantId(event.getTenantId()); <START> key.setDataId(event.getId()); <END> return key; }</code><technical_language>key.setDataId(event.getId()); -> key.setDataId(event.getDataId()); This issue culprit for failing itest profile. I test cluster profile check if is green also</technical_language>

Target:
private CacheKey fillKey(CacheKey key, Event event) { key.setTenantId(event.getTenantId()); key.setDataId(event.getDataId()); return key; }
Source:
<code>public Scope enter() { GroovyInterceptor sandbox = new SandboxInterceptor(whitelist()); ApprovalContext _context = context != null ? context : ApprovalContext.create(); sandbox.register(); ScriptApproval.pushRegistrationCallback(x -> { if (ExtensionList.lookup(RootAction.class).get(ScriptApproval.class) == null) { return; } String signature = x.getSignature(); <START> if (signature != null && !StaticWhitelist.isPermanentlyBlacklisted(signature)) { <END> ScriptApproval.get().accessRejected(x, _context); } if (listener != null) { ScriptApprovalNote.print(listener, x); } }); return () -> { sandbox.unregister(); ScriptApproval.popRegistrationCallback(); }; }</code><technical_language>Uh, what? No. need call accessRejected signature == null (that "unclassified" error)</technical_language>

Target:
public Scope enter() { GroovyInterceptor sandbox = new SandboxInterceptor(whitelist()); ApprovalContext _context = context != null ? context : ApprovalContext.create(); sandbox.register(); ScriptApproval.pushRegistrationCallback(x -> { if (ExtensionList.lookup(RootAction.class).get(ScriptApproval.class) == null) { return; } String signature = x.getSignature(); if (!StaticWhitelist.isPermanentlyBlacklisted(signature)) { ScriptApproval.get().accessRejected(x, _context); } if (listener != null) { ScriptApprovalNote.print(listener, x); } }); return () -> { sandbox.unregister(); ScriptApproval.popRegistrationCallback(); }; }
Source:
<code>public void process(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) { Optional<Person> optionalPerson = ingestPerson(paPerson); Person person; if (!optionalPerson.isPresent()) { return; <START> } else { <END> person = optionalPerson.get(); } Optional<Person> existing = personResolver.person(person.getCanonicalUri()); if (!existing.isPresent()) { personWriter.createOrUpdatePerson(person); } else { merge(existing.get(), person); personWriter.createOrUpdatePerson(existing.get()); } }</code><technical_language>else is unnecessary if branch a return</technical_language>

Target:
public void process(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) { Optional<Person> optionalPerson = ingestPerson(paPerson); Person person; if (!optionalPerson.isPresent()) { return; } person = optionalPerson.get(); Optional<Person> existing = personResolver.person(person.getCanonicalUri()); if (!existing.isPresent()) { personWriter.createOrUpdatePerson(person); } else { merge(existing.get(), person); personWriter.createOrUpdatePerson(existing.get()); } }
Source:
<code>public void activate(boolean redo) { if (SageConstants.ENFORCE_EMBEDDED_RESTRICTIONS && Sage.EMBEDDED && (!System.getProperty("java.version").startsWith("phoneme_advanced") || System.getProperty("os.name").indexOf("Linux") == -1 || System.getProperty("os.version").indexOf("sigma") == -1) && Math.random() < 0.05) System.exit(0); active = true; if (!comp.hasFreshlyLoadedContext() && !redo) comp.reloadAttributeContext(); Catbert.processUISpecificHook("BeforeMenuLoad", new Object[]{Boolean.valueOf(redo)}, uiMgr, false); if (!active) { comp.unfreshAttributeContext(); return; } comp.setMenuLoadedState(true); comp.evaluateTree(true, false); comp.evaluateTree(false, true); comp.recalculateDynamicFonts(); comp.invalidateAll(); if (comp.getWidth() > 0 && comp.getHeight() > 0) comp.doLayout(); if ((comp.hasFocusableChildren() || uiMgr.allowHiddenFocus()) && (!redo || !comp.doesHierarchyHaveFocus())) { Catbert.processUISpecificHook("MenuNeedsDefaultFocus", new Object[]{Boolean.valueOf(redo)}, uiMgr, false); if (!comp.doesHierarchyHaveFocus()) { if (!comp.checkForcedFocus()) comp.setDefaultFocus(); } } multipleTextInputs = comp.getNumTextInputs(0) > 1; <START> uiMgr.getRootPanel().getRenderEngine().setMenuHint(widg.getName(), null, comp.getNumTextInputs(0)>0); <END> }</code><technical_language>This optimized getNumTextInputs is called is stored reused set multipleTextInputs hint properly</technical_language>

Target:
public void activate(boolean redo) { if (SageConstants.ENFORCE_EMBEDDED_RESTRICTIONS && Sage.EMBEDDED && (!System.getProperty("java.version").startsWith("phoneme_advanced") || System.getProperty("os.name").indexOf("Linux") == -1 || System.getProperty("os.version").indexOf("sigma") == -1) && Math.random() < 0.05) System.exit(0); active = true; if (!comp.hasFreshlyLoadedContext() && !redo) comp.reloadAttributeContext(); Catbert.processUISpecificHook("BeforeMenuLoad", new Object[]{Boolean.valueOf(redo)}, uiMgr, false); if (!active) { comp.unfreshAttributeContext(); return; } comp.setMenuLoadedState(true); comp.evaluateTree(true, false); comp.evaluateTree(false, true); comp.recalculateDynamicFonts(); comp.invalidateAll(); if (comp.getWidth() > 0 && comp.getHeight() > 0) comp.doLayout(); if ((comp.hasFocusableChildren() || uiMgr.allowHiddenFocus()) && (!redo || !comp.doesHierarchyHaveFocus())) { Catbert.processUISpecificHook("MenuNeedsDefaultFocus", new Object[]{Boolean.valueOf(redo)}, uiMgr, false); if (!comp.doesHierarchyHaveFocus()) { if (!comp.checkForcedFocus()) comp.setDefaultFocus(); } } int numTextInputs=comp.getNumTextInputs(0); multipleTextInputs = numTextInputs > 1; uiMgr.getRootPanel().getRenderEngine().setMenuHint(widg.getName(), null, numTextInputs>0); }
Source:
<code>public TemplateStore getCodeTemplateStore() { if (fCodeTemplateStore == null) { Promise<TemplateStore> p= <START> getTemplateStoreInitializer().getTemplateStore(); <END> try { fCodeTemplateStore= p.getValue(); } catch (InvocationTargetException | InterruptedException e) { fCodeTemplateStore= getTemplateStoreInitializer().loadTemplateStore(); log(e); } } return fCodeTemplateStore; }</code><technical_language>please extract a variable below</technical_language>

Target:
public TemplateStore getCodeTemplateStore() { if (fCodeTemplateStore == null) { TemplateStoreInitializer initializer= getTemplateStoreInitializer(); Promise<TemplateStore> p= initializer.getTemplateStore(); try { fCodeTemplateStore= p.getValue(); } catch (InvocationTargetException e) { fCodeTemplateStore= initializer.loadTemplateStore(); log(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); fCodeTemplateStore= initializer.loadTemplateStore(); log(e); } } return fCodeTemplateStore; }
Source:
<code>public RegisteredService findServiceByName(final String name) { if (StringUtils.isBlank(name)) { return null; } var service = services.asMap().values().stream() .filter(r -> r.getName().equals(name)) .findFirst() .orElse(null); if (service == null) { <START> LOGGER.trace("The service with name is not found in the cache, try to find it from [{}]", <END> name, serviceRegistry.getName()); service = serviceRegistry.findServiceByExactServiceName(name); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in and populated to the cache ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); }</code><technical_language>suggestion LOGGER.trace("The service name is in cache, try find [{}]",</technical_language>

Target:
public RegisteredService findServiceByName(final String name) { if (StringUtils.isBlank(name)) { return null; } var service = getService(name, 0); if (service == null) { LOGGER.trace("The service with name is not found in the cache; trying to find it from [{}]", name, serviceRegistry.getName()); service = serviceRegistry.findServiceByExactServiceName(name); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in and populated to the cache ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); }
Source:
<code>public DBObject getFieldsObject() { <START> BasicDBObject projection = (BasicDBObject) getOptions().getProjection(); <END> if (projection == null || projection.size() == 0) { return null; } final MappedClass mc = ds.getMapper().getMappedClass(clazz); Entity entityAnnotation = mc.getEntityAnnotation(); final BasicDBObject fieldsFilter = copy(projection); if (includeFields && entityAnnotation != null && !entityAnnotation.noClassnameStored()) { fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1); } return fieldsFilter; }</code><technical_language>Unsafe cast BasicDBObject. projection.keySet().size() next line avoid cast</technical_language>

Target:
public DBObject getFieldsObject() { DBObject projection = getOptions().getProjection(); if (projection == null || projection.keySet().size() == 0) { return null; } final MappedClass mc = ds.getMapper().getMappedClass(clazz); Entity entityAnnotation = mc.getEntityAnnotation(); final BasicDBObject fieldsFilter = copy(projection); if (includeFields && entityAnnotation != null && !entityAnnotation.noClassnameStored()) { fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1); } return fieldsFilter; }
Source:
<code>public void testSegmentMetadataUnionQuery() { System.out.println(); SegmentAnalysis expected = new SegmentAnalysis( QueryRunnerTestHelper.segmentId, Lists.newArrayList(new Interval("2011-01-12T00:00:00.000Z/2011-04-15T00:00:00.001Z")), ImmutableMap.of( "placement", new ColumnAnalysis( ValueType.STRING.toString(), false, mmap ? 43524 : 43056, 1, "preferred", "preferred", null ) ), mmap ? 287928 : 291020, <START> 4836, <END> null, null ); SegmentMetadataQuery query = new Druids.SegmentMetadataQueryBuilder() .dataSource(QueryRunnerTestHelper.unionDataSource) .intervals(QueryRunnerTestHelper.fullOnInterval) .toInclude(new ListColumnIncluderator(Lists.newArrayList("placement"))) .build(); List result = Sequences.toList(runner.run(query, Maps.newHashMap()), Lists.<SegmentAnalysis>newArrayList()); System.out.println(result); TestHelper.assertExpectedObjects(ImmutableList.of(expected), result, "failed SegmentMetadata union query"); }</code><technical_language>Is this right for union dataSource? (hard non-union test compare to)</technical_language>

Target:
public void testSegmentMetadataUnionQuery() { SegmentAnalysis expected = new SegmentAnalysis( QueryRunnerTestHelper.segmentId, Lists.newArrayList(new Interval("2011-01-12T00:00:00.000Z/2011-04-15T00:00:00.001Z")), ImmutableMap.of( "placement", new ColumnAnalysis( ValueType.STRING.toString(), false, mmap ? 43524 : 43056, 1, "preferred", "preferred", null ) ), mmap ? 287928 : 291020, 4836, null, null ); SegmentMetadataQuery query = new Druids.SegmentMetadataQueryBuilder() .dataSource(QueryRunnerTestHelper.unionDataSource) .intervals(QueryRunnerTestHelper.fullOnInterval) .toInclude(new ListColumnIncluderator(Lists.newArrayList("placement"))) .build(); List result = Sequences.toList(runner.run(query, Maps.newHashMap()), Lists.<SegmentAnalysis>newArrayList()); TestHelper.assertExpectedObjects(ImmutableList.of(expected), result, "failed SegmentMetadata union query"); }
Source:
<code>protected void writeProperties(ElasticsearchPersistentEntity<?> entity, PersistentPropertyAccessor<?> accessor, Map<String, Object> sink) { for (ElasticsearchPersistentProperty property : entity) { if (!property.isWritable()) { continue; } Object value = accessor.getProperty(property); if (value == null) { continue; } if (!conversions.isSimpleType(value.getClass())) { writeProperty(property, value, sink); } else { sink.put(property.getFieldName(), getWriteSimpleValue(value)); <START> } <END> } }</code><technical_language>a isSimpleType( ) calls. Do want consolidate methods</technical_language>

Target:
protected void writeProperties(ElasticsearchPersistentEntity<?> entity, PersistentPropertyAccessor<?> accessor, Map<String, Object> sink) { for (ElasticsearchPersistentProperty property : entity) { if (!property.isWritable()) { continue; } Object value = accessor.getProperty(property); if (value == null) { continue; } if (!isSimpleType(value)) { writeProperty(property, value, sink); } else { sink.put(property.getFieldName(), getWriteSimpleValue(value)); } } }
Source:
<code>Allele toSymbolicAltAllele() { <START> if (this.equals(StructuralVariantType.BND)) <END> throw new UnsupportedOperationException("BND type does not have angle bracketed alt allele"); return Allele.create("<" + name() + ">", false); }</code><technical_language>Add curly braces if statement body</technical_language>

Target:
Allele toSymbolicAltAllele() { if (this.equals(StructuralVariantType.BND)) { throw new UnsupportedOperationException("BND type does not have angle bracketed alt allele"); } return Allele.create("<" + name() + ">", false); }
Source:
<code>public void slicesOfLongSeries() { Series series = new Series("918493904243"); List<List<Integer>> expected = Arrays.asList(Arrays.asList(9, 1, 8, 4, 9), Arrays.asList(1, 8, 4, 9, 3), Arrays.asList(8, 4, 9, 3, 9), Arrays.asList(4, 9, 3, 9, 0), Arrays.asList(9, 3, 9, 0, 4), <START> Arrays.asList(3, 9, 0, 4, 2), Arrays.asList(9, 0, 4, 2, 4), Arrays.asList(0, 4, 2, 4, 3)); <END> List<List<Integer>> actual = series.slices(5); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }</code><technical_language>a minor thing; is long for line a bit more readable put argument a new line: myVariable = someFunction( argument1, argument2, argument3 ); easy argument function takes accidentally miss</technical_language>

Target:
public void slicesOfLongSeries() { Series series = new Series("918493904243"); List<List<String>> expected = Arrays.asList( Arrays.asList("9", "1", "8", "4", "9"), Arrays.asList("1", "8", "4", "9", "3"), Arrays.asList("8", "4", "9", "3", "9"), Arrays.asList("4", "9", "3", "9", "0"), Arrays.asList("9", "3", "9", "0", "4"), Arrays.asList("3", "9", "0", "4", "2"), Arrays.asList("9", "0", "4", "2", "4"), Arrays.asList("0", "4", "2", "4", "3") ); List<List<String>> actual = series.slices(5); assertEquals(expected, actual); }
Source:
<code>public void requestsAreIdempotentDuringAcquisitionPhase() { LockToken currentHolder = lockSynchronously(REQUEST_1, LOCK_A); <START> AsyncResult<LeasableLockToken> tokenResult = lock(REQUEST_2, LOCK_A); <END> AsyncResult<LeasableLockToken> duplicateResult = lock(REQUEST_2, LOCK_A); service.unlock(currentHolder); assertThat(tokenResult.isCompletedSuccessfully()).isTrue(); assertThat(duplicateResult.isCompletedSuccessfully()).isTrue(); assertThat(tokenResult.get()).isEqualTo(duplicateResult.get()); }</code><technical_language>noted before; I do some tests validate some stuff do leasing; a lock a lease, lease times sense, lease duration sense, etc</technical_language>

Target:
public void requestsAreIdempotentDuringAcquisitionPhase() { LockToken currentHolder = lockSynchronously(REQUEST_1, LOCK_A); AsyncResult<Leased<LockToken>> tokenResult = lock(REQUEST_2, LOCK_A); AsyncResult<Leased<LockToken>> duplicateResult = lock(REQUEST_2, LOCK_A); service.unlock(currentHolder); assertThat(tokenResult.isCompletedSuccessfully()).isTrue(); assertThat(duplicateResult.isCompletedSuccessfully()).isTrue(); assertThat(tokenResult.get().value()).isEqualTo(duplicateResult.get().value()); }
Source:
<code>public DynamicTableSource createDynamicTableSource(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); ReadableConfig tableOptions = helper.getOptions(); DecodingFormat<DeserializationSchema<RowData>> decodingFormat = helper.discoverDecodingFormat( DeserializationFormatFactory.class, FactoryUtil.FORMAT); Optional<String> topic = tableOptions.getOptional(TOPIC); Optional<String> pattern = tableOptions.getOptional(TOPIC_PATTERN); helper.validateExcept(PROPERTIES_PREFIX); validateTableOptions(tableOptions); DataType producedDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType(); final StartupOptions startupOptions = getStartupOptions(tableOptions); final Properties properties = getKafkaProperties(context.getCatalogTable().getOptions()); properties.setProperty(FlinkKafkaConsumerBase.KEY_PARTITION_DISCOVERY_INTERVAL_MILLIS, String.valueOf(tableOptions .getOptional(SCAN_TOPIC_PARTITION_DISCOVERY) .map(val -> val.toMillis()) .orElse(FlinkKafkaConsumerBase.PARTITION_DISCOVERY_DISABLED))); return createKafkaTableSource( producedDataType, <START> topic.map(value -> Arrays .stream(value.split(",")) .map(String::trim) .collect(Collectors.toList())) .orElse(null), pattern.map(value -> Pattern.compile(value)).orElse(null), <END> properties, decodingFormat, startupOptions.startupMode, startupOptions.specificOffsets, startupOptions.startupTimestampMillis); }</code><technical_language>I suggest add static util methods List<String> getTopics(ReadableConfig) Pattern getTopicPattern(ReadableConfig) in KafkaOptions</technical_language>

Target:
public DynamicTableSource createDynamicTableSource(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); ReadableConfig tableOptions = helper.getOptions(); DecodingFormat<DeserializationSchema<RowData>> decodingFormat = helper.discoverDecodingFormat( DeserializationFormatFactory.class, FactoryUtil.FORMAT); helper.validateExcept(PROPERTIES_PREFIX); validateTableSourceOptions(tableOptions); DataType producedDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType(); final StartupOptions startupOptions = getStartupOptions(tableOptions); final Properties properties = getKafkaProperties(context.getCatalogTable().getOptions()); properties.setProperty(FlinkKafkaConsumerBase.KEY_PARTITION_DISCOVERY_INTERVAL_MILLIS, String.valueOf(tableOptions .getOptional(SCAN_TOPIC_PARTITION_DISCOVERY) .map(Duration::toMillis) .orElse(FlinkKafkaConsumerBase.PARTITION_DISCOVERY_DISABLED))); return createKafkaTableSource( producedDataType, KafkaOptions.getSourceTopics(tableOptions), KafkaOptions.getSourceTopicPattern(tableOptions), properties, decodingFormat, startupOptions.startupMode, startupOptions.specificOffsets, startupOptions.startupTimestampMillis); }
Source:
<code>private Set<IGroupMember> primGetAllMembers(Set<IGroupMember> rslt) throws GroupsException { final Set<IGroupMember> members = getChildren(); <START> for (IGroupMember gm : members) { <END> rslt.add(gm); if (gm.isGroup()) { ((EntityGroupImpl) gm).primGetAllMembers(rslt); } } return rslt; }</code><technical_language>This assignment removed</technical_language>

Target:
private Set<IGroupMember> primGetAllMembers(Set<IGroupMember> rslt) throws GroupsException { for (IGroupMember gm : getChildren()) { rslt.add(gm); if (gm.isGroup()) { ((EntityGroupImpl) gm).primGetAllMembers(rslt); } } return rslt; }
Source:
<code><START> protected Class<?> loadRepositoryInterface(RepositoryConfiguration<?> configuration, ResourceLoader loader) { <END> String repositoryInterface = configuration.getRepositoryInterface(); ClassLoader classLoader = loader.getClassLoader(); try { return org.springframework.util.ClassUtils.forName(repositoryInterface, classLoader); } catch (ClassNotFoundException | LinkageError e) { LOGGER.warn(String.format(CLASS_LOADING_ERROR, getModuleName(), repositoryInterface, classLoader), e); } return null; }</code><technical_language>reason need this protected</technical_language>

Target:
private Class<?> loadRepositoryInterface(RepositoryConfiguration<?> configuration, ResourceLoader loader) { String repositoryInterface = configuration.getRepositoryInterface(); ClassLoader classLoader = loader.getClassLoader(); try { return org.springframework.util.ClassUtils.forName(repositoryInterface, classLoader); } catch (ClassNotFoundException | LinkageError e) { LOGGER.warn(String.format(CLASS_LOADING_ERROR, getModuleName(), repositoryInterface, classLoader), e); } return null; }
Source:
<code>public Schema<ChangeData> getSchema() { <START> return null; <END> }</code><technical_language>Hm, I if this lead lurking NPEs? more sense throw UnsupportedOperationException? is calls this method stores result</technical_language>

Target:
public Schema<ChangeData> getSchema() { throw new UnsupportedOperationException(); }
Source:
<code>public Timestamp fromLong(Long microsFromEpoch, Schema schema, LogicalType type) { <START> java.sql.Timestamp ts = new java.sql.Timestamp(microsFromEpoch / 1000); <END> int micros = (int) (microsFromEpoch - (microsFromEpoch / 1000000 * 1000000)); ts.setNanos(micros * 1000); return Timestamp.newBuilder() .setSeconds(ts.getTime() / 1000) .setNanos(ts.getNanos()) .build(); }</code><technical_language>do java.sql.Timestamp here? Protobuf Timestamp builders proper methods for creating timestamp longs, semantic of this long is for in Avro in Protobuf, I is needed create additional objects here</technical_language>

Target:
public Timestamp fromLong(Long microsFromEpoch, Schema schema, LogicalType type) throws IllegalArgumentException { return ProtoConversions.fromLong(microsFromEpoch, TimestampPrecise.Micros); }
Source:
<code>private static Map<String, String[]> getXdocsMap() { final String rootPath = getRootPath(); final File checks = new File(rootPath + "/" + PACKAGE_NAME); final String[] checksSubDirNames = checks.list((rootDir, pathname) -> { return !pathname.endsWith(SUFFIX_JAVA); }); final Map<String, String[]> checksNamesMap = new HashMap<>(); if (checksSubDirNames != null) { for (String dirName : checksSubDirNames) { final File dirFile = new File(rootPath + "/" + PACKAGE_NAME + "/" + dirName); final String[] fileNames = dirFile.list((rootDir, pathname) -> { return pathname.endsWith(SUFFIX_CHECK_JAVA); <START> }); <END> checksNamesMap.put(dirName, fileNames); } final String[] miscNames = checks.list((rootDir, pathname) -> { return pathname.endsWith(SUFFIX_CHECK_JAVA); }); checksNamesMap.put(MISC, miscNames); } return checksNamesMap; }</code><technical_language>(rootDir, pathname) -> { return pathname.endsWith(SUFFIX_CHECK_JAVA); } this predicate is duplicated 3 times (negation counts well), please a variable</technical_language>

Target:
private static Map<String, List<String>> getXdocsMap() throws IOException { final Map<String, List<String>> checksNamesMap = new HashMap<>(); final Set<Class<?>> checkSet = CheckUtil.getCheckstyleModules(); final Set<Class<?>> treeWalkerOrFileSetCheckSet = checkSet.stream() .filter(clazz -> { return AbstractCheck.class.isAssignableFrom(clazz) || AbstractFileSetCheck.class.isAssignableFrom(clazz); }) .collect(Collectors.toSet()); for (Class<?> check : treeWalkerOrFileSetCheckSet) { final String checkName = check.getSimpleName(); if (!checkName.equals(TREE_WORKER)) { String packageName = check.getPackage().getName(); packageName = packageName.substring(packageName.lastIndexOf('.') + 1); if (packageName.equals(CHECKS)) { packageName = MISC; } if (checksNamesMap.get(packageName) == null) { final List<String> arrayList = new ArrayList<>(); arrayList.add(checkName); checksNamesMap.put(packageName, arrayList); } else { checksNamesMap.get(packageName).add(checkName); } } } return checksNamesMap; }
Source:
<code>private void updateInputProperties(String instance, String property) { for (DenonBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { DenonBindingConfig cfg = provider.getConfig(itemName); if (cfg.getInstance().equals(instance)) { <START> if (cfg.getProperty().startsWith("SI") && !cfg.getProperty().equals(property)) { <END> updateIfChanged(cfg.getInstance(), cfg.getProperty(), OnOffType.OFF); } } } } }</code><technical_language>please extract "SI" a constant</technical_language>

Target:
private void updateInputProperties(String instance, String property) { for (DenonBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { DenonBindingConfig cfg = provider.getConfig(itemName); if (cfg.getInstance().equals(instance)) { if (cfg.getProperty().startsWith(SWITCH_INPUT) && !cfg.getProperty().equals(property)) { updateIfChanged(cfg.getInstance(), cfg.getProperty(), OnOffType.OFF); } } } } }
Source:
<code>public void testEncryptAndSignWithoutSignerSecretKey() throws Exception { String msg = "Test Message"; PGPEncryptAndSignInfo encryptAndSignInfo = new PGPEncryptAndSignInfo("Robert Plant <robert@cambridge.edu.uk>"); kbStrategy.setCredentialsAccessor(new FakeCredentialAccessor("Mule client <mule_client@mule.com>")); kbStrategy.initialise(); try { kbStrategy.encrypt(msg.getBytes(), encryptAndSignInfo); fail("CryptoFailureException should be triggered because signer private key is not present"); } catch (CryptoFailureException e) { <START> assertThat(e.getMessage(), startsWith("Crypto Failure: Signer private key not found for principal:")); <END> } }</code><technical_language>static field for beginning of reason for Exception? static field for String literal</technical_language>

Target:
public void testEncryptAndSignWithoutSignerSecretKey() throws Exception { String msg = "Test Message"; PGPEncryptAndSignInfo encryptAndSignInfo = new PGPEncryptAndSignInfo("Robert Plant <robert@cambridge.edu.uk>"); kbStrategy.setCredentialsAccessor(new FakeCredentialAccessor("Mule client <mule_client@mule.com>")); kbStrategy.initialise(); try { kbStrategy.encrypt(msg.getBytes(), encryptAndSignInfo); fail("CryptoFailureException should be triggered because signer private key is not present"); } catch (CryptoFailureException e) { assertThat(e.getMessage(), startsWith(EXPECTED_NO_SIGNER_PRIVATE_KEY_ERROR_MESSAGE)); } }
Source:
<code>public void renameInternal(Path src, Path dst, boolean overwrite) throws AccessControlException, FileAlreadyExistsException, FileNotFoundException, ParentNotDirectoryException, UnresolvedLinkException, IOException { Options.Rename renameOpt = Options.Rename.NONE; if (overwrite) { renameOpt = Options.Rename.OVERWRITE; } final Options.Rename opt = renameOpt; <START> renameInternal(src, dst, (s, d) -> getMyFs().rename(s, d, opt)); <END> }</code><technical_language>this, more elegant functional API. is nice for hadoop 3+. I fear lose elegance branch-2 (assuming do want a backport). If do, simply copying existing renameInternal a new signature is simplest</technical_language>

Target:
public void renameInternal(Path src, Path dst, boolean overwrite) throws AccessControlException, FileAlreadyExistsException, FileNotFoundException, ParentNotDirectoryException, UnresolvedLinkException, IOException { Options.Rename renameOpt = Options.Rename.NONE; if (overwrite) { renameOpt = Options.Rename.OVERWRITE; } if (isDirectory(src)) { getMyFs().rename(src, dst, renameOpt); } else { getMyFs().rename(src, dst, renameOpt); Path checkFile = getChecksumFile(src); if (exists(checkFile)) { if (isDirectory(dst)) { getMyFs().rename(checkFile, dst, renameOpt); } else { getMyFs().rename(checkFile, getChecksumFile(dst), renameOpt); } } } }
Source:
<code>public static boolean setSchedulerLocation( Config runtime, String schedulerEndpoint, IScheduler scheduler) { Scheduler.SchedulerLocation.Builder builder = Scheduler.SchedulerLocation.newBuilder() .setTopologyName(Runtime.topologyName(runtime)) .setHttpEndpoint(schedulerEndpoint); List<String> jobLinks = scheduler.getJobLinks(); if (jobLinks != null) { builder.addAllJobPageLink(jobLinks); } Scheduler.SchedulerLocation location = builder.build(); <START> LOG.log(Level.INFO, "Setting Scheduler locations:\n{0}", location); <END> SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Boolean result = statemgr.setSchedulerLocation(location, Runtime.topologyName(runtime)); if (result == null || !result) { LOG.severe("Failed to set Scheduler location"); return false; } return true; }</code><technical_language>Inserting line breaks in log entries pains reading logs. remove \n</technical_language>

Target:
public static boolean setSchedulerLocation( Config runtime, String schedulerEndpoint, IScheduler scheduler) { Scheduler.SchedulerLocation.Builder builder = Scheduler.SchedulerLocation.newBuilder() .setTopologyName(Runtime.topologyName(runtime)) .setHttpEndpoint(schedulerEndpoint); List<String> jobLinks = scheduler.getJobLinks(); if (jobLinks != null) { builder.addAllJobPageLink(jobLinks); } Scheduler.SchedulerLocation location = builder.build(); LOG.log(Level.INFO, "Setting Scheduler locations: {0}", location); SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); Boolean result = statemgr.setSchedulerLocation(location, Runtime.topologyName(runtime)); if (result == null || !result) { LOG.severe("Failed to set Scheduler location"); return false; } return true; }
Source:
<code>private void updateRecord(final AccessRecord record, final String file, final int line, final UpdateRecordCallback callback) { List<Runnable> tasks = new ArrayList<Runnable>(); <START> MetricCollection metricCollection = new MetricCollection(); <END> for (final Metric<AccessRecord, ?> metric : metricCollection) { if (!ignoreMetrics.contains(metric.getName())) { tasks.add(new Runnable() { @Override public void run() { try { metric.write(record); } catch (Throwable e){ callback.handle(new WriteRecordResult(false, metric.getName(), file, line)); } } }); } } for (Runnable task : tasks) { threadPool.submit(task); } }</code><technical_language>if assemble this collection loop for records of a file? declare Iterable. easier a unmodifiable list a for-each loop</technical_language>

Target:
private void updateRecord(final AccessRecord record, final String file, final int line, final UpdateRecordCallback callback) { List<Runnable> tasks = new ArrayList<Runnable>(); for (final Metric<AccessRecord, ?> metric : metricCollection) { if (!ignoreMetrics.contains(metric.getName())) { tasks.add(new Runnable() { @Override public void run() { try { metric.write(record); } catch (Throwable e){ callback.handle(new WriteRecordResult(false, metric.getName(), file, line)); } } }); } } for (Runnable task : tasks) { threadPool.submit(task); } }
Source:
<code>public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } <START> QueryTraverser queryTraverser = newQueryTraversal(parameters); <END> Map<QueryVisitorFieldEnvironment, Integer> valuesByParent = new LinkedHashMap<>(); queryTraverser.visitPostOrder(new QueryVisitorStub() { @Override public void visitField(QueryVisitorFieldEnvironment env) { int childsComplexity = valuesByParent.getOrDefault(env, 0); int value = calculateComplexity(env, childsComplexity); valuesByParent.compute(env.getParentEnvironment(), (key, oldValue) -> ofNullable(oldValue).orElse(0) + value ); } }); int totalComplexity = valuesByParent.getOrDefault(null, 0); log.debug("Query complexity: {}", totalComplexity); if (totalComplexity > maxComplexity) { QueryComplexityInfo queryComplexityInfo = QueryComplexityInfo.newQueryComplexityInfo() .complexity(totalComplexity) .build(); boolean throwAbortException = maxQueryComplexityExceededFunction.apply(queryComplexityInfo); if (throwAbortException) { throw mkAbortException(totalComplexity, maxComplexity); } } }); }</code><technical_language>newQueryTraversal needs renamed newQueryTraverer</technical_language>

Target:
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraverser queryTraverser = newQueryTraverser(parameters); Map<QueryVisitorFieldEnvironment, Integer> valuesByParent = new LinkedHashMap<>(); queryTraverser.visitPostOrder(new QueryVisitorStub() { @Override public void visitField(QueryVisitorFieldEnvironment env) { int childsComplexity = valuesByParent.getOrDefault(env, 0); int value = calculateComplexity(env, childsComplexity); valuesByParent.compute(env.getParentEnvironment(), (key, oldValue) -> ofNullable(oldValue).orElse(0) + value ); } }); int totalComplexity = valuesByParent.getOrDefault(null, 0); log.debug("Query complexity: {}", totalComplexity); if (totalComplexity > maxComplexity) { QueryComplexityInfo queryComplexityInfo = QueryComplexityInfo.newQueryComplexityInfo() .complexity(totalComplexity) .build(); boolean throwAbortException = maxQueryComplexityExceededFunction.apply(queryComplexityInfo); if (throwAbortException) { throw mkAbortException(totalComplexity, maxComplexity); } } }); }