auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean shouldPersist(Metric metric) throws Exception { boolean areStringMetricsDropped = Configuration.getInstance().getBooleanProperty(CoreConfig.STRING_METRICS_DROPPED); if(areStringMetricsDropped) { return false; } else { String currentValue = String.valueOf(metric.getMetricValue()); final String lastValue = AstyanaxReader.getInstance().getLastStringValue(metric.getLocator()); return lastValue == null || !currentValue.equals(lastValue); } }

Target:
public boolean shouldPersist(Metric metric) throws Exception { if (areStringMetricsDropped) { return false; } else { String currentValue = String.valueOf(metric.getMetricValue()); final String lastValue = AstyanaxReader.getInstance().getLastStringValue(metric.getLocator()); return lastValue == null || !currentValue.equals(lastValue); } }
Source:
private String getUnit(Metric metric) { return metric.getUnit(); }

Target:
private static String getUnit(Metric metric) { return metric.getUnit(); }
Source:
public <C> Builder<A, C> withFunction(AsyncFunction<B, C> function) { Preconditions.checkNotNull(function); ArrayList<AsyncFunction<?, ?>> copy = new ArrayList<AsyncFunction<?, ?>>(this.functions); return new Builder<A, C>(copy); }

Target:
public <C> Builder<A, C> withFunction(AsyncFunction<B, C> function) { Preconditions.checkNotNull(function); ArrayList<AsyncFunction<?, ?>> copy = new ArrayList<AsyncFunction<?, ?>>(this.functions); copy.add(function); return new Builder<A, C>(copy); }
Source:
public boolean areTTLsForced() { final Configuration config = Configuration.getInstance(); return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); }

Target:
public boolean areTTLsForced() { return ARE_TTLS_FORCED; }
Source:
public static final boolean areTTLsForced() { final Configuration config = Configuration.getInstance(); return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); }

Target:
public boolean areTTLsForced() { return ARE_TTLS_FORCED; }
Source:
public static void main(String[] args) throws Exception { String[] preLoadClasses = { "javax.servlet.Filter", "javax.servlet.DispatcherType", }; for (String className : preLoadClasses) { Class.forName(className); } new IngestApplication().run(args); }

Target:
public static void main(String[] args) throws Exception { new IngestApplication().run(args); }
Source:
public void update(long when, int shard) { Long current = updates.get(shard); if (current == null) { updates.put(shard, when); } else { if (when > current) { updates.put(shard, when); } } }

Target:
public void update(long when, int shard) { updates.put(shard, when); }
Source:
public void decrementReadCounter(long count) { readCounter.addAndGet((-1) * count); owner.interrupt(); }

Target:
public void decrementReadCounter(long count) { readCounter.addAndGet(-count); owner.interrupt(); }
Source:
public long getAge() { return (System.nanoTime() - timestamp) / 1000; }

Target:
public long getAge() { return System.currentTimeMillis() - timestamp; }
Source:
public synchronized void start() { fileUploader = new DoneFileUploader(); if (uploaderThread != null) { throw new RuntimeException("StorageManager is already started"); } uploaderThread = new Thread(fileUploader, "StorageManager uploader"); uploaderThread.start(); log.info("Storage Manager fully started"); }

Target:
public synchronized void start() { if (uploaderThread != null) { throw new RuntimeException("StorageManager is already started"); } fileUploader = new DoneFileUploader(); uploaderThread = new Thread(fileUploader, "StorageManager uploader"); uploaderThread.start(); }
Source:
public boolean equals(Object obj) { if (!(obj instanceof CounterRollup) || obj == null) return false; CounterRollup other = (CounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate; }

Target:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof CounterRollup)) return false; CounterRollup other = (CounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate; }
Source:
public boolean equals(Object obj) { return obj instanceof Locator && obj.hashCode() == this.hashCode(); }

Target:
public boolean equals(Object obj) { return obj != null && obj instanceof Locator && obj.hashCode() == this.hashCode(); }
Source:
public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override public void call(T... arg) { Emitter.this.off(event, this); fn.call(arg); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; }

Target:
public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override public void call(T... args) { Emitter.this.off(event, this); fn.call(args); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; }
Source:
public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", intValue); case LONG: return String.format("%d (long)", longValue); case DOUBLE: return String.format("%s (double)", doubleValue); default: return "ERROR"; } }

Target:
public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", intValue); case LONG: return String.format("%d (long)", longValue); case DOUBLE: return String.format("%s (double)", doubleValue); default: return super.toString(); } }
Source:
public void start() { synchronized (running) { if (running.get()) return; else { running.set(true); run(); } } }

Target:
public synchronized void start() { if (running.get()) return; else { run(); // running.get == true now. } }
Source:
public Collection<PhysicalAddress> fetchClusterMembers(String clusterName) { //If no DAO has been set just return an empty list if (pingDao == null) { log.info("No PingDao set, returning empty set for current cluster members"); return Collections.emptyList(); } //Add our address to the store getAndSavePhysicalAddress(clusterName); //Get the current cluster members final Map<Address, PhysicalAddress> existing_mbrs = pingDao.getAddresses(clusterName); //Return current members return existing_mbrs.values(); }

Target:
public Collection<PhysicalAddress> fetchClusterMembers(String clusterName) { //If no DAO has been set just return an empty list if (pingDao == null) { log.info("No PingDao set, returning empty set for current cluster members"); return Collections.emptyList(); } //Get the current cluster members final Map<Address, PhysicalAddress> existing_mbrs = pingDao.getAddresses(clusterName); //Add our address to the store getAndSavePhysicalAddress(clusterName); //Return current members return existing_mbrs.values(); }
Source:
public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) throws Exception { try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:///" + mainDirectory)); } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }

Target:
public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) { try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:///" + mainDirectory)); } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }
Source:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { // @processing-role processRoleStack.pop(); final DitaClass cls = classes.pop(); if ((cls == null || !cls.isValid()) && !ELEMENT_NAME_DITA.equals(localName)) { return; } getContentHandler().endElement(uri, localName, qName); }

Target:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { // @processing-role processRoleStack.pop(); classes.pop(); getContentHandler().endElement(uri, localName, qName); }
Source:
final void removeFirst() { Node head = get(); Node next = head.get(); size--; // can't just move the head because it would retain the very first value // can't null out the head's value because of late replayers would see null Node newHead = new Node(null); Node newNext = next.get(); newHead.set(newNext); setFirst(newHead); if (newNext == null) { tail = newHead; } }

Target:
final void removeFirst() { Node head = get(); Node next = head.get(); size--; // can't just move the head because it would retain the very first value // can't null out the head's value because of late replayers would see null setFirst(next); }
Source:
@Override public Object call() { return null; // null scalar is interpreted as being empty }

Target:
public Object call() { return null; // null scalar is interpreted as being empty }
Source:
public void unsubscribe() { if (once.compareAndSet(false, true)) { // unsubscribe should be idempotent, so only do this once // Release the worker _after_ the previous action (if any) has completed threadWorker.schedule(new Action0() { @Override public void call() { pool.release(threadWorker); } }); } innerSubscription.unsubscribe(); }

Target:
public void unsubscribe() { if (once.compareAndSet(false, true)) { // unsubscribe should be idempotent, so only do this once // Release the worker _after_ the previous action (if any) has completed threadWorker.schedule(this); } innerSubscription.unsubscribe(); }
Source:
public void onError(Throwable e) { error = e; List<Throwable> errors = null; for (PublishSubjectProducer<T> pp : getAndSet(TERMINATED)) { try { pp.onError(e); } catch (Throwable ex) { if (errors == null) { errors = new ArrayList<Throwable>(); } errors.add(ex); } } Exceptions.throwIfAny(errors); }

Target:
public void onError(Throwable e) { error = e; List<Throwable> errors = null; for (PublishSubjectProducer<T> pp : getAndSet(TERMINATED)) { try { pp.onError(e); } catch (Throwable ex) { if (errors == null) { errors = new ArrayList<Throwable>(1); } errors.add(ex); } } Exceptions.throwIfAny(errors); }
Source:
public void onError(Throwable e) { long r = get(); if (r != Long.MIN_VALUE) { actual.onError(e); } }

Target:
public void onError(Throwable e) { if (get() != Long.MIN_VALUE) { actual.onError(e); } }
Source:
public Subscriber<? super T> call(final Subscriber<? super T> child) { return new Subscriber<T>(child) { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { // ignore element } }; }

Target:
public Subscriber<? super T> call(final Subscriber<? super T> child) { Subscriber<T> parent = new Subscriber<T>() { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { // ignore element } }; child.add(parent); return parent; }
Source:
void requestMore(long n) { if (n > 0) { // CAS loop to atomically change state given that onCompleted() // or another requestMore() may be acting concurrently while (true) { //read the value of state and then try state transitions //only if the value of state does not change in the meantime //(in another requestMore() or onCompleted()). If the value // has changed and we expect to do a transition still then // we loop and try again. final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, REQUESTED_NOT_COMPLETED)) { request(Long.MAX_VALUE); return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else // already requested so we exit return; } } }

Target:
void requestMore(long n) { if (n > 0) { // CAS loop to atomically change state given that onCompleted() // or another requestMore() may be acting concurrently while (true) { // read the value of state and then try state transitions // only if the value of state does not change in the // meantime (in another requestMore() or onCompleted()). If // the value has changed and we expect to do a transition // still then we loop and try again. final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, REQUESTED_NOT_COMPLETED)) { return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else // already requested so we exit return; } } }
Source:
protected String render (Object item) { //do nothing by default return null; }

Target:
protected String render (Object item) throws InterruptedException { //do nothing by default return null; }
Source:
private boolean isSelected() { if (selection.choice.get() == this) { // fast-path return true; } else { if (selection.choice.compareAndSet(null, this)) { selection.unsubscribeOthers(this); return true; } else { // we lost so unsubscribe ... and force cleanup again due to possible race conditions unsubscribe(); selection.unsubscribeLosers(); return false; } } }

Target:
private boolean isSelected() { if (selection.choice.get() == this) { // fast-path return true; } else { if (selection.choice.compareAndSet(null, this)) { selection.unsubscribeOthers(this); return true; } else { // we lost so unsubscribe ... and force cleanup again due to possible race conditions selection.unsubscribeLosers(); return false; } } }
Source:
public void unsubscribe() { if (unsubscribed) { return; } unsubscribed = true; // we will only get here once unsubscribeFromAll(subscriptions); }

Target:
public void unsubscribe() { if (unsubscribed) { return; } unsubscribed = true; // we will only get here once unsubscribeFromAll(subscriptions); subscriptions = null; }
Source:
public void unsubscribe() { synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { unsubscribed = true; } } // we will only get here once unsubscribeFromAll(subscriptions); }

Target:
public void unsubscribe() { synchronized (this) { if (unsubscribed) { return; } unsubscribed = true; } // we will only get here once unsubscribeFromAll(subscriptions); }
Source:
private void closeTestingServerSocket(ServerSocket serverSocket) throws IOException { serverSocket.close(); while (!serverSocket.isClosed()) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }

Target:
private void closeTestingServerSocket(ServerSocket serverSocket) throws IOException { serverSocket.close(); while (!serverSocket.isClosed()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.debug(e.toString()); } } }
Source:
protected void showMessage(String message) { System.out.print(message); }

Target:
protected void showMessage(String message) { System.out.println(message); }
Source:
protected Function<String, Set<SpotInstanceRequest>> spotInstancesByIdInRegion(final Multimap<String,String> idsByRegions) { return new Function<String, Set<SpotInstanceRequest>>() { @Override public Set<SpotInstanceRequest> apply(String from) { return client.getSpotInstanceServices() .describeSpotInstanceRequestsInRegion(from, Iterables.toArray(idsByRegions.get(from), String.class)); } }; }

Target:
protected Function<String, Set<SpotInstanceRequest>> spotInstancesByIdInRegion(final Multimap<String,String> idsByRegions) { return new Function<String, Set<SpotInstanceRequest>>() { @Override public Set<SpotInstanceRequest> apply(String from) { return client.getSpotInstanceServices() .describeSpotInstanceRequestsInRegion(from, toArray(idsByRegions.get(from), String.class)); } }; }
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); WebDriverLog log = (WebDriverLog) session.getLogManager().getLog(type); List<LogEntry> entries = (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries()); return createResponse(entries); }

Target:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); List<LogEntry> entries = session.getLogManager().getLog(type); return createResponse(entries); }
Source:
public void close() throws ResourceException { try { super.close(); } catch (Exception e) { e.printStackTrace(); } LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); //$NON-NLS-1$ }

Target:
public void close() { super.close(); LogManager.logDetail(LogConstants.CTX_CONNECTOR, CassandraManagedConnectionFactory.UTIL.getString("shutting_down")); //$NON-NLS-1$ }
Source:
public static void deleteEPerson(UUID uuid) throws SQLException, IOException { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); EPerson ePerson = ePersonService.find(c, uuid); if (ePerson != null) { try { ePersonService.delete(c, ePerson); } catch (AuthorizeException e) { // cannot occur, just wrap it to make the compiler happy throw new RuntimeException(e.getMessage(), e); } } c.complete(); } }

Target:
public static void deleteEPerson(UUID uuid) throws SQLException, IOException { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); EPerson ePerson = ePersonService.find(c, uuid); if (ePerson != null) { try { ePersonService.delete(c, ePerson); } catch (AuthorizeException e) { // cannot occur, just wrap it to make the compiler happy throw new RuntimeException(e); } } c.complete(); } }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != RelationshipMetadataValue.class) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (! (obj instanceof RelationshipMetadataValue)) { return false; } final RelationshipMetadataValue other = (RelationshipMetadataValue) obj; if (this.isUseForPlace() != other.isUseForPlace()) { return false; } return super.equals(obj); }
Source:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { // now add them to the destination object List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy = resourcePolicyService.create(c); policy = srp.copyToDSpaceObject(policy,dest); resourcePolicyService.update(c,policy); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }

Target:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { // now add them to the destination object List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy =resourcePolicyService.copyToDSpaceObject(c,srp,dest); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }
Source:
public static void _destroyKernel() { if (kernel != null) { // cleanup the kernel try { kernel.destroy(); } catch (Exception e) { // keep going } kernel.destroy(); } // must null things out or JUnit will not clean them up kernel = null; }

Target:
public static void _destroyKernel() { if (kernel != null) { // cleanup the kernel kernel.destroy(); } // must null things out or JUnit will not clean them up kernel = null; }
Source:
public static String format(Date date, boolean init) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.'000Z'"); if (!init) sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.'999Z'"); // We indicate that the returned date is in Zulu time (UTC) so we have // to set the time zone of sdf correct. sdf.setTimeZone(TimeZone.getTimeZone("ZULU")); String ret = sdf.format(date); return ret; }

Target:
public static String format(Date date, boolean init) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.'000Z'"); if (!init) { sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.'999Z'"); } // We indicate that the returned date is in Zulu time (UTC) so we have // to set the time zone of sdf correct. sdf.setTimeZone(TimeZone.getTimeZone("ZULU")); String ret = sdf.format(date); return ret; }
Source:
public boolean hasSeqNo() { return this.seqNo != null && SequenceNumbers.isAssignedSeqNo(this.seqNo); }

Target:
public boolean hasSeqNo() { return this.seqNo != null; }
Source:
public T doWith(@Nullable Document document) { if (document == null) { return null; } T materializedEntity = reader.read(type, document); return maybeCallbackAfterConvert(materializedEntity, document, index); }

Target:
public T doWith(@Nullable Document document) { if (document == null) { return null; } T entity = reader.read(type, document); return maybeCallbackAfterConvert(entity, document, index); }
Source:
float getScore() { return score; }

Target:
public float getScore() { return score; }
Source:
public void shouldSupportSortOnStandardFieldWithCriteria() { final List<String> sortedIds = repository.findAllByNameOrderByText("Salt").stream() // .map(it -> it.id).collect(Collectors.toList()); assertThat(sortedIds).containsExactly("4", "5"); }

Target:
public void shouldSupportSortOnStandardFieldWithCriteria() { List<String> sortedIds = repository.findAllByNameOrderByText("Salt").stream() // .map(it -> it.id).collect(Collectors.toList()); assertThat(sortedIds).containsExactly("4", "5"); }
Source:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "Vimal's testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); //now delete the folder created fileService.deleteFolder(folder.getFileId()); }

Target:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); //now delete the folder created fileService.deleteFolder(folder.getFileId()); }
Source:
public static int getItemBurnTime(ItemStack stack) { if (stack.isEmpty()) { return 0; } else { Item item = stack.getItem(); int base = stack.getBurnTime(); //I changed the original logic here. Previously every time ForgeEventFactory#getItemBurnTime was called, now the result is cahced aswell. return getBurnTimes().computeIfAbsent(item, i -> net.minecraftforge.event.ForgeEventFactory.getItemBurnTime(stack, base == -1 ? getVanillaBurnTimes().getOrDefault(i, 0) : base)); } }

Target:
public static int getItemBurnTime(ItemStack stack) { if (stack.isEmpty()) { return 0; } else { Item item = stack.getItem(); int base = stack.getBurnTime(); return net.minecraftforge.event.ForgeEventFactory.getItemBurnTime(stack, base == -1 ? getBurnTimes().getOrDefault(item, 0) : base); } }
Source:
public static void invalidate() { burnTimes = null; vanillaBurnTimes = null; }

Target:
public static void invalidate() { burnTimes = null; }
Source:
public static Map<DataFixer, Pair<Integer, Integer>> getFixVersionsNoVanilla(NBTTagCompound nbttagcompound, boolean useLatestOtherwiseN1) { return getFixVersionsNoVanilla(nbttagcompound, (useLatestOtherwiseN1 ? -2492 : -1)); }

Target:
public static Map<DataFixer, Pair<Integer, Integer>> getFixVersionsNoVanilla(NBTTagCompound nbttagcompound, boolean useLatestOtherwiseN1) { return getFixVersionsNoVanilla(nbttagcompound, -1, useLatestOtherwiseN1); }
Source:
public void write(PacketBuffer buffer) { this.getBlocks().write(buffer); this.getItems().write(buffer); this.getFluids().write(buffer); //we might wind up sending more data than vanilla needs (and therefore produce excessive Network traffic...) //TODO Check if connected to vanilla client and if so don't write ForgeTag Data writeForgeTags(buffer); }

Target:
public void write(PacketBuffer buffer) { this.getBlocks().write(buffer); this.getItems().write(buffer); this.getFluids().write(buffer); //we might wind up sending more data than vanilla needs (and therefore produce excessive Network traffic...) //writeForgeTags(buffer); }
Source:
public Predicate<IResourceType> get() { if (this.currentPredicate == null) // TODO configs || !ForgeMod.selectiveResourceReloadEnabled) { return ReloadRequirements.all(); } return this.currentPredicate; }

Target:
public Predicate<IResourceType> get() { if (this.currentPredicate == null && false) // TODO configs || !ForgeMod.selectiveResourceReloadEnabled) { return ReloadRequirements.all(); } return this.currentPredicate; }
Source:
private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, String[] validValuesDisplay, String langKey) { Property prop = this.get(category, name, defaultValue); prop.setValidValues(validValues); if (validValuesDisplay != null) prop.setValidValuesDisplay(validValuesDisplay); prop.setLanguageKey(langKey); prop.setComment(comment + " [default: " + defaultValue + "]"); return prop.getStringList(); }

Target:
private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, String[] validValuesDisplay, String langKey) { Property prop = this.get(category, name, defaultValue); prop.setValidValues(validValues); prop.setValidValuesDisplay(validValuesDisplay); prop.setLanguageKey(langKey); prop.setComment(comment + " [default: " + defaultValue + "]"); return prop.getStringList(); }
Source:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); return filled > 0 ? filled : 0; }

Target:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); return Math.max(filled, 0); }
Source:
public int fill(FluidStack resource, boolean doFill) { // NOTE: "Filling" means placement in this context! if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); BlockDynamicLiquid block = BlockLiquid.getFlowingBlock(material); world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }

Target:
public int fill(FluidStack resource, boolean doFill) { // NOTE: "Filling" means placement in this context! if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); BlockLiquid block = BlockLiquid.getFlowingBlock(material); world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }
Source:
public GuiTab(String name, ResourceLocation icon, Class<? extends GuiContainer> clazz) { this.name = name; this.iconResLoc = icon; // Make sure the vanilla tab doesnt get duplicated if (GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB) == false) { GuiTab.VANILLA_INVENTORY_TAB.addTo(clazz); } }

Target:
public GuiTab(String name, ResourceLocation icon, Class<? extends GuiContainer> clazz) { this.name = name; this.iconResLoc = icon; // Make sure the vanilla tab doesnt get duplicated if (!GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB)) { // GuiTab.VANILLA_INVENTORY_TAB.addTo(clazz); } }
Source:
PhpCfgBlock(Set<PhpCfgBlock> successors, @Nullable PhpCfgBlock syntacticSuccessor) { this.successors = ImmutableSet.copyOf(successors); this.syntacticSuccessor = syntacticSuccessor; }

Target:
private PhpCfgBlock(Set<PhpCfgBlock> successors, @Nullable PhpCfgBlock syntacticSuccessor) { this.successors = ImmutableSet.copyOf(successors); this.syntacticSuccessor = syntacticSuccessor; }
Source:
private static boolean hasMoreThanOneStatement(ForEachStatementTree forEach) { if (forEach.statements().size() > 1) { return true; } StatementTree body = forEach.statements().get(0); if (body.is(Tree.Kind.BLOCK)) { return ((BlockTree) body).statements().size() > 1; } return false; }

Target:
private static boolean hasMoreThanOneStatement(ForEachStatementTree forEach) { if (forEach.statements().size() > 1) { return true; } if (forEach.statements().isEmpty()) { // just to be sure // will never happen in this rule, because we are hooked on jumps inside loops return false; } StatementTree body = forEach.statements().get(0); if (body.is(Tree.Kind.BLOCK)) { return ((BlockTree) body).statements().size() > 1; } return false; }
Source:
public void visitClassPropertyDeclaration(ClassPropertyDeclarationTree tree) { if (tree.hasModifiers("private")) { tree.declarations().forEach(varDec -> privateProperties.add(varDec.identifier().text())); } // don't enter inside class property declarations }

Target:
public void visitClassPropertyDeclaration(ClassPropertyDeclarationTree tree) { // don't enter inside class property declarations }
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (!(obj instanceof BaseEntity)) { // This entity has a different type return false; } if (getId() == null) { // This entity has not been persisted return super.equals(obj); } BaseEntity other = (BaseEntity) obj; return getId().equals(other.getId()); }

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (!(obj.getClass().equals(getClass()))) { // This entity has a different type return false; } if (getId() == null) { // This entity has not been persisted return super.equals(obj); } BaseEntity other = (BaseEntity) obj; return getId().equals(other.getId()); }
Source:
void setUserCancel(boolean isUserCancel) { synchronized (this) { this.isUserCancel = isUserCancel; } }

Target:
void setUserCancel(boolean isUserCancel) { this.isUserCancel = isUserCancel; }
Source:
public static DnsPrefetcher getDnsPrefetcher() { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); synchronized (dnsPrefetcher) { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); } } } return dnsPrefetcher; }

Target:
public static DnsPrefetcher getDnsPrefetcher() { if (dnsPrefetcher == null) { synchronized (DnsPrefetcher.class) { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); } } } return dnsPrefetcher; }
Source:
public List<InetAddress> getInetAddressByHost(String host) { if (mConcurrentHashMap != null) { return mConcurrentHashMap.get(host); } return null; }

Target:
public List<InetAddress> getInetAddressByHost(String host) { return mConcurrentHashMap.get(host); }
Source:
private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }

Target:
private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }
Source:
public void close() throws Exception { // empty arrays have no buffer at all if (released || isEmpty()) return; if (!closeable()) throw new ND4JIllegalStateException("Can't release this INDArray"); data.close(); released = true; }

Target:
public void close() { // empty arrays have no buffer at all if (released || isEmpty()) return; if (!closeable()) throw new ND4JIllegalStateException("Can't release this INDArray"); data.close(); released = true; }
Source:
private void initOptionsIfNeeded() { //setup the status object to be used for all tensorflow calls if(status == null) { status = TF_NewStatus(); } if (options == null) { options = TF_NewSessionOptions(); if(protoBufConfigProto != null) { BytePointer bytePointer = new BytePointer(protoBufConfigProto.toByteArray()); TF_SetConfig(options,bytePointer,bytePointer.getStringBytes().length,status); if (TF_GetCode(status) != TF_OK) { throw new RuntimeException("ERROR: Unable to set value configuration:" + TF_Message(status).getString()); } } } }

Target:
private void initOptionsIfNeeded() { //setup the status object to be used for all tensorflow calls if(status == null) { status = TF_NewStatus(); } if (options == null) { options = TF_NewSessionOptions(); if(protoBufConfigProto != null) { BytePointer bytePointer = new BytePointer(protoBufConfigProto.toByteArray()); TF_SetConfig(options,bytePointer,bytePointer.getStringBytes().length,status); if (TF_GetCode(status) != TF_OK) { throw new IllegalStateException("ERROR: Unable to set value configuration:" + TF_Message(status).getString()); } } } }
Source:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is // called in AsyncLabelAwareIterator.reset(). if (thread != null) thread.join(); } catch (InterruptedException e) { } buffer.clear(); }

Target:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is // called in AsyncLabelAwareIterator.reset(). if (thread != null) thread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } buffer.clear(); }
Source:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); // if(params != null) // return params; List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams; if(layer instanceof BasePretrainNetwork) layerParams = ((BasePretrainNetwork) layer).paramsBackprop(); else layerParams = layer.params(); if(layerParams != null) params.add(layerParams); //may be null: subsampling etc layers } return Nd4j.toFlattened('f', params); }

Target:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); // if(params != null) // return params; List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams = layer.params(); if(layerParams != null) params.add(layerParams); //may be null: subsampling etc layers } return Nd4j.toFlattened('f', params); }
Source:
public void addWall(Coordinate coordinate) { if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); // a wall may overwrite a square this.squares.remove(coordinate); }

Target:
public void addWall(Coordinate coordinate) { if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); // a wall may overwrite a square this.squares.remove(coordinate); }
Source:
public Grid(Map<Coordinate, ASquare> grid, Map<IPlayer, Coordinate> players) { if (grid == null || players == null) throw new IllegalArgumentException("Grid could not be created!"); this.grid = grid; this.players = players; }

Target:
Grid(Map<Coordinate, ASquare> grid, Map<IPlayer, Coordinate> players) { if (grid == null || players == null) throw new IllegalArgumentException("Grid could not be created!"); this.grid = grid; this.players = players; }
Source:
public void toSchemaOrgTest() throws IOException, URISyntaxException { FullBeanImpl bean = MockFullBean.mock(); String output = SchemaOrgUtils.toSchemaOrg(bean); Assert.assertNotNull(output); //Used for testing purposes, use the following call to update the expected output whenever the serialization is updated // writeToFile(output); InputStream stream = getClass().getResourceAsStream(FULL_BEAN_FILE); String expectedOutput = IOUtils.toString(stream, StandardCharsets.UTF_8); //we cannot string compare until the ordering of properties is implemented //still, a fast indication that the output was changed will be indicated through the length of the string System.out.println(output); assertEquals(expectedOutput.length(), output.length()); }

Target:
public void toSchemaOrgTest() throws IOException, URISyntaxException { FullBeanImpl bean = MockFullBean.mock(); String output = SchemaOrgUtils.toSchemaOrg(bean); Assert.assertNotNull(output); //Used for testing purposes, use the following call to update the expected output whenever the serialization is updated //writeToFile(output); try (InputStream stream = getClass().getResourceAsStream(FULL_BEAN_FILE)) { String expectedOutput = IOUtils.toString(stream, StandardCharsets.UTF_8); //we cannot string compare until the ordering of properties is implemented //still, a fast indication that the output was changed will be indicated through the length of the string assertEquals(expectedOutput.length(), output.length()); } }
Source:
protected EntityMetadata retrieveMetadata(Path injectionPath, String entityName, String entityVersion) { EntityMetadata emd = metadataMap.get(entityName); if (emd != null) { String defaultVersion = emd.getEntityInfo().getDefaultVersion(); if (!isValidReference(entityVersion, requestVersion, defaultVersion)) { throw Error.get(CrudConstants.ERR_METADATA_APPEARS_TWICE, entityName + ":" + entityVersion + " and " + requestVersion); } } return metadataMap.get(entityName); }

Target:
protected EntityMetadata retrieveMetadata(Path injectionPath, String entityName, String entityVersion) { return metadataMap.get(entityName); }
Source:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { if (in.readBoolean()) { // see writeTo lengthLimit = Integer.MAX_VALUE; } else { lengthLimit = in.readInt(); } } else { lengthLimit = Integer.MAX_VALUE; } }

Target:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { lengthLimit = in.readInt(); } else { lengthLimit = Integer.MAX_VALUE; } }
Source:
public ByteBuf allocate(int capacity) { accountBytes.accept(capacity); // TODO: should we hold onto the buffers and release them as well? // contract would require it, but there is no resource behind it that must be released return Unpooled.wrappedBuffer(new byte[capacity]); }

Target:
public ByteBuf allocate(int capacity) { accountBytes.accept(capacity); // We don't track the ByteBuf instance to release it later because it is not necessary for on-heap buffers. return Unpooled.buffer(capacity); }
Source:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { return unboundAnalyze(rewriteShowTransaction(), analysis, ParamTypeHints.EMPTY); }

Target:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { return unboundAnalyze(rewriteShowTransaction(), analysis); }
Source:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } // Tables created with CrateDB < 4.0 don't have any positional information stored inside the meta data so // we must fallback to old behaviour which uses a simple increased iterating based var. Integer position = ref.position(); if (position == null) { position = ordinal.intValue(); } ordinal++; return new ColumnContext(tableInfo, ref, position); }

Target:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } // Tables created with CrateDB < 4.0 don't have any positional information stored inside the meta data so // we must fallback to old behaviour which uses a simple increased iterating based var. Integer position = ref.position(); if (position == null) { position = ordinal; } ordinal++; return new ColumnContext(tableInfo, ref, position); }
Source:
public static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) { return new EngineSearcherTotalHitsMatcher(query, totalHits); }

Target:
static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) { return new EngineSearcherTotalHitsMatcher(query, totalHits); }
Source:
public static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) { return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits); }

Target:
static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) { return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits); }
Source:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("can't be larger than 5gb")); final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); }

Target:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("can't be larger than 5gb")); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); }
Source:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { // check if other document IDs are allowed boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { // create and add doc IDs List<IdentificationDocument> idDocs = new ArrayList<IdentificationDocument>(); IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }

Target:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { // check if other document IDs are allowed boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { // create and add doc IDs List<IdentificationDocument> idDocs = new ArrayList<>(); IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }
Source:
public Boolean deleteLoanRepayment(String accountId, String repaymentId) throws MambuApiException { // Example: GET endpoint "/api/loans/{LOAN_ID}/repayments/{REPAYMENT_ID} // Available since Mambu 4.3 if (accountId == null && repaymentId == null) { throw new IllegalArgumentException("Account ID and Repayment ID must not be null!"); } return serviceExecutor.deleteOwnedEntity(MambuEntityType.LOAN_ACCOUNT, accountId, MambuEntityType.REPAYMENTS, repaymentId); }

Target:
public Boolean deleteLoanRepayment(String accountId, String repaymentId) throws MambuApiException { // Example: GET endpoint "/api/loans/{LOAN_ID}/repayments/{REPAYMENT_ID} // Available since Mambu 4.3 if (accountId == null || repaymentId == null) { throw new IllegalArgumentException("Account ID and Repayment ID must not be null!"); } return serviceExecutor.deleteOwnedEntity(MambuEntityType.LOAN_ACCOUNT, accountId, MambuEntityType.REPAYMENTS, repaymentId); }
Source:
public boolean updateClientCustomField(String clientId, String customFieldId, String fieldValue) throws MambuApiException { // Execute request for PATCH API to update custom field value for a client. See MBU-6661 // e.g. PATCH "{ "value": "10" }" /host/api/clients/clientId/custominformation/customFieldId // Make ParamsMap with JSON request for Update API ParamsMap params = ServiceHelper.makeParamsForUpdateCustomField(clientId, customFieldId, fieldValue); return serviceExecutor.execute(updateClientCustomField, clientId, customFieldId, params); }

Target:
public boolean updateClientCustomField(String clientId, String customFieldId, String fieldValue) throws MambuApiException { // Execute request for PATCH API to update custom field value for a client. See MBU-6661 // e.g. PATCH "{ "value": "10" }" /host/api/clients/clientId/custominformation/customFieldId // Make ParamsMap with JSON request for Update API ParamsMap params = ServiceHelper.makeParamsForUpdateCustomField(customFieldId, fieldValue); return serviceExecutor.execute(updateClientCustomField, clientId, customFieldId, params); }
Source:
public boolean deleteTasks(String taskId) throws MambuApiException { // create the api call String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); // On success the response is: returnCode: 0
returnStatus: SUCCESS // An exception can be thrown: E.g, ({"returnCode":980,"returnStatus":"INVALID_TASK_ID"}) // Parse the response. (Though, as no exception was thrown here, must be a "SUCCESS" response) boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) deletionStatus = true; return deletionStatus; }

Target:
public boolean deleteTasks(String taskId) throws MambuApiException { // create the api call String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); // On success the response is: returnCode: 0
returnStatus: SUCCESS // An exception can be thrown: E.g. ({"returnCode":980,"returnStatus":"INVALID_TASK_ID"}) // Parse the response. (Though, as no exception was thrown here, must be a "SUCCESS" response) boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) { deletionStatus = true; } return deletionStatus; }
Source:
private EVCacheClient selectClient(List<EVCacheClient> clients) { if (clients == null) { if (log.isDebugEnabled()) log.debug("clients is null returning null!!!"); return null; } if (clients.size() == 1) { return clients.get(0); // Frequently used scenario } // Get absolute value of current val to ensure correctness even at 9 quintillion+ requests final long currentVal = Math.abs(numberOfModOps.incrementAndGet()); // make sure to truncate after the mod. This allows up to 2^31 clients. final int index = (int) (currentVal % clients.size()); return clients.get(index); }

Target:
private EVCacheClient selectClient(List<EVCacheClient> clients) { if (clients == null) { if (log.isDebugEnabled()) log.debug("clients is null returning null!!!"); return null; } if (clients.size() == 1) { return clients.get(0); // Frequently used scenario } final long currentVal = numberOfModOps.incrementAndGet(); // Get absolute value of current val to ensure correctness even at 9 quintillion+ requests // make sure to truncate after the mod. This allows up to 2^31 clients. final int index = Math.abs((int) (currentVal % clients.size())); return clients.get(index); }