auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void loadBanner(Context context, CustomEventBannerListener listener, Map<String, Object> localExtras, Map<String, String> serverExtras) { if (context == null) { Log.e(LOG_TAG, "Context cannot be null."); listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } if (listener == null) { Log.e(LOG_TAG, "CustomEventBannerListener cannot be null."); return; } if (!(context instanceof Activity)) { Log.e(LOG_TAG, "Ad can be rendered only in Activity context."); listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } if (!extrasAreValid(serverExtras)) { listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } mContext = context; mListener = listener; mLayout = new FrameLayout(context); String apiKey = serverExtras.get(FlurryAgentWrapper.PARAM_API_KEY); mAdSpaceName = serverExtras.get(FlurryAgentWrapper.PARAM_AD_SPACE_NAME); FlurryAgentWrapper.getInstance().startSession(context, apiKey, null); Log.d(LOG_TAG, "fetch Flurry Ad (" + mAdSpaceName + ") -- " + mLayout.toString()); mBanner = new FlurryAdBanner(mContext, mLayout, mAdSpaceName); mBanner.setListener(new FlurryMopubBannerListener()); mBanner.fetchAd(); }

Target:
protected void loadBanner(Context context, CustomEventBannerListener listener, Map<String, Object> localExtras, Map<String, String> serverExtras) { if (context == null) { Log.e(LOG_TAG, "Context cannot be null."); listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } if (listener == null) { Log.e(LOG_TAG, "CustomEventBannerListener cannot be null."); return; } if (!(context instanceof Activity)) { Log.e(LOG_TAG, "Ad can be rendered only in Activity context."); listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } if (!validateExtras(serverExtras)) { Log.e(LOG_TAG, "Failed banner ad fetch: Missing required server extras" + " [FLURRY_APIKEY and/or FLURRY_ADSPACE]."); listener.onBannerFailed(ADAPTER_CONFIGURATION_ERROR); return; } mContext = context; mListener = listener; mLayout = new FrameLayout(context); String apiKey = serverExtras.get(FlurryAgentWrapper.PARAM_API_KEY); mAdSpaceName = serverExtras.get(FlurryAgentWrapper.PARAM_AD_SPACE_NAME); FlurryAgentWrapper.getInstance().startSession(context, apiKey, null); Log.d(LOG_TAG, "Fetching Flurry ad, ad unit name:" + mAdSpaceName); mBanner = new FlurryAdBanner(mContext, mLayout, mAdSpaceName); mBanner.setListener(new FlurryMopubBannerListener()); mBanner.fetchAd(); }
Source:
private LinkedList<IncludedStructuralElement> determineIncludedStructuralElementPathToChildRecursive( IncludedStructuralElement includedStructuralElement, int number) { if (!Objects.isNull(includedStructuralElement.getLink())) { try { if (ServiceManager.getProcessService() .processIdFromUri(includedStructuralElement.getLink().getUri()) == number) { LinkedList<IncludedStructuralElement> linkedIncludedStructuralElements = new LinkedList<>(); linkedIncludedStructuralElements.add(includedStructuralElement); return linkedIncludedStructuralElements; } } catch (IllegalArgumentException | ClassCastException | SecurityException e) { logger.catching(Level.TRACE, e); } } for (IncludedStructuralElement includedStructuralElementChild : includedStructuralElement.getChildren()) { LinkedList<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive( includedStructuralElementChild, number); if (Objects.nonNull(includedStructuralElementList)) { includedStructuralElementList.addFirst(includedStructuralElementChild); return includedStructuralElementList; } } return null; }

Target:
private static List<IncludedStructuralElement> determineIncludedStructuralElementPathToChildRecursive( IncludedStructuralElement includedStructuralElement, int number) { if (Objects.nonNull(includedStructuralElement.getLink())) { try { if (ServiceManager.getProcessService() .processIdFromUri(includedStructuralElement.getLink().getUri()) == number) { LinkedList<IncludedStructuralElement> linkedIncludedStructuralElements = new LinkedList<>(); linkedIncludedStructuralElements.add(includedStructuralElement); return linkedIncludedStructuralElements; } } catch (IllegalArgumentException | ClassCastException | SecurityException e) { logger.catching(Level.TRACE, e); } } for (IncludedStructuralElement includedStructuralElementChild : includedStructuralElement.getChildren()) { List<IncludedStructuralElement> includedStructuralElementList = determineIncludedStructuralElementPathToChildRecursive( includedStructuralElementChild, number); if (!includedStructuralElementList.isEmpty()) { includedStructuralElementList.add(0, includedStructuralElement); return includedStructuralElementList; } } return Collections.emptyList(); }
Source:
public Optional<ResistanceCalculator> getResistanceCalculator() { return Optional.of(((ExplosionBridge) this).bridge$getResistanceCalculator()); }

Target:
public Optional<ResistanceCalculator> getResistanceCalculator() { return Optional.ofNullable(((ExplosionBridge) this).bridge$getResistanceCalculator()); }
Source:
public RtuDevice(final String deviceIdentification) { super(deviceIdentification); this.lastCommunicationTime = new GregorianCalendar(2001, 0, 1).getTime(); }

Target:
public RtuDevice(final String deviceIdentification) { super(deviceIdentification); }
Source:
private void postProcessClean() throws IOException { unregisterOp(OP_WRITE); for (; ; ) { State state = scheduled.get(); if (state == State.RESCHEDULE) { if (!scheduled.compareAndSet(State.RESCHEDULE, State.SCHEDULED)) { continue; } owner().addTaskAndWakeup(this); return; } if (!scheduled.compareAndSet(state, State.UNSCHEDULED)) { continue; } if (writeQueue.isEmpty() && priorityWriteQueue.isEmpty()) { return; } if (scheduled.compareAndSet(State.UNSCHEDULED, State.SCHEDULED)) { if (Thread.currentThread().getClass() == NioThread.class) { owner().addTask(this); } else { owner().addTaskAndWakeup(this); } } return; } }

Target:
private void postProcessClean() throws IOException { unregisterOp(OP_WRITE); for (; ; ) { State state = scheduled.get(); if (state == State.RESCHEDULE) { scheduled.set(State.SCHEDULED); owner().addTaskAndWakeup(this); return; } if (!scheduled.compareAndSet(state, State.UNSCHEDULED)) { continue; } if (writeQueue.isEmpty() && priorityWriteQueue.isEmpty()) { return; } if (scheduled.compareAndSet(State.UNSCHEDULED, State.SCHEDULED)) { if (Thread.currentThread().getClass() == NioThread.class) { owner().addTask(this); } else { owner().addTaskAndWakeup(this); } } return; } }
Source:
public JsonPattern(JsonPattern other) { pattern = new ArrayList<Integer>(other.pattern); }

Target:
public JsonPattern(JsonPattern other) { this(new ArrayList<Integer>(other.pattern)); }
Source:
public void testConnectionException() throws Exception { ImapMailReceiver mailReceiver = new ImapMailReceiver("imap:foo"); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(mailReceiver); final List<ImapIdleExceptionEvent> events = new ArrayList<ImapIdleExceptionEvent>(); final CountDownLatch latch = new CountDownLatch(1); adapter.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { events.add((ImapIdleExceptionEvent) event); latch.countDown(); } }); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); adapter.setTaskScheduler(taskScheduler); adapter.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(1, events.size()); assertEquals("ImapIdleExceptionEvent [exception=Failure in 'idle' task. Will resubmit.]", events.get(0).toString()); }

Target:
public void testConnectionException() throws Exception { ImapMailReceiver mailReceiver = new ImapMailReceiver("imap:foo"); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(mailReceiver); final AtomicReference<ImapIdleExceptionEvent> theEvent = new AtomicReference<ImapIdleExceptionEvent>(); final CountDownLatch latch = new CountDownLatch(1); adapter.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { assertNull("only one event expected", theEvent.get()); theEvent.set((ImapIdleExceptionEvent) event); latch.countDown(); } }); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); adapter.setTaskScheduler(taskScheduler); adapter.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(theEvent.get().toString().endsWith("cause=java.lang.IllegalStateException: Failure in 'idle' task. Will resubmit.]")); }
Source:
private static File getAndroidStudioLocalMavenRepoPath() { return null; }

Target:
private static File getAndroidStudioLocalMavenRepoPath() { File androidHomePath = DefaultSdks.getDefaultAndroidHome(); if (androidHomePath != null) { File repoPath = new File(androidHomePath, FileUtil.join("gradle", "m2repository")); if (repoPath.isDirectory()) { return repoPath; } } return null; }
Source:
public Thread newThread(Runnable r) { Thread t = new Thread(this.group, r, "cucumber-runner-thread-" + this.threadNumber.getAndIncrement(), 0L); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != 5) { t.setPriority(5); } return t; }

Target:
public Thread newThread(Runnable r) { return new Thread(r, namePrefix + this.threadNumber.getAndIncrement()); }
Source:
default float getHeightFactor(ITimeEvent event) { StateItem stateItem = null; if (event instanceof TimeEvent) { int status = ((TimeEvent) event).getValue(); StateItem[] stateTable = getStateTable(); if (status >= 0 && status < stateTable.length) { stateItem = stateTable[status]; } } return stateItem != null ? stateItem.getHeightFactor() : 1.0f; }

Target:
default float getHeightFactor(ITimeEvent event) { StateItem stateItem = null; if (event instanceof TimeEvent) { int index = getStateTableIndex(event); StateItem[] stateTable = getStateTable(); if (index >= 0 && index < stateTable.length) { stateItem = stateTable[index]; } } return stateItem != null ? (float) stateItem.getStyleMap().getOrDefault(ITimeEventStyle.HEIGHT_FACTOR(), 1.0f) : 1.0f; }
Source:
public void visit(NodeList n, Void arg) { if (configuration.isOrderImports() && n.size() > 0 && n.get(0) instanceof ImportDeclaration) { NodeList<ImportDeclaration> modifiableList = new NodeList<>(n); modifiableList.sort( comparingInt((ImportDeclaration left) -> left.isStatic() ? 0 : 1) .thenComparing(NodeWithName::getNameAsString)); for (Object node : modifiableList) { ((Node) node).accept(this, arg); } } else { for (Object node : n) { ((Node) node).accept(this, arg); } } }

Target:
public void visit(NodeList n, Void arg) { if (configuration.isOrderImports() && n.size() > 0 && n.get(0) instanceof ImportDeclaration) { NodeList<ImportDeclaration> modifiableList = new NodeList<>(n); modifiableList.sort( comparingInt((ImportDeclaration i) -> i.isStatic() ? 0 : 1) .thenComparing(NodeWithName::getNameAsString)); for (Object node : modifiableList) { ((Node) node).accept(this, arg); } } else { for (Object node : n) { ((Node) node).accept(this, arg); } } }
Source:
IExtension getExtension() { return !element.isValid() ? null : element.getDeclaringExtension(); }

Target:
IExtension getExtension() { return declaringExtension; }
Source:
public boolean updateRigidBody(EntityRef entity) { LocationComponent location = entity.getComponent(LocationComponent.class); BulletRigidBody rigidBody = entityRigidBodies.get(entity); if (location == null) { logger.warn("Updating rigid body of entity that has no " + "LocationComponent?! Nothing is done, except log this" + " warning instead."); return false; } else if (rigidBody != null) { float scale = location.getWorldScale(); if (Math.abs(rigidBody.rb.getCollisionShape().getLocalScaling(new Vector3f()).x - scale) > BulletGlobals.SIMD_EPSILON) { removeRigidBody(rigidBody); newRigidBody(entity); } updateKinematicSettings(entity.getComponent(RigidBodyComponent.class), rigidBody); return true; } else { logger.warn("Updating a non-existing rigid body. Creating a new one " + "instead, also logging this warning since it should not " + "happen. Entity: " + entity); newRigidBody(entity); return false; } }

Target:
public boolean updateRigidBody(EntityRef entity) { LocationComponent location = entity.getComponent(LocationComponent.class); BulletRigidBody rigidBody = entityRigidBodies.get(entity); if (location == null) { logger.warn("Updating rigid body of entity that has no " + "LocationComponent?! Nothing is done, except log this" + " warning instead. Entity: {}", entity); return false; } else if (rigidBody != null) { float scale = location.getWorldScale(); if (Math.abs(rigidBody.rb.getCollisionShape().getLocalScaling(new Vector3f()).x - scale) > BulletGlobals.SIMD_EPSILON) { removeRigidBody(rigidBody); newRigidBody(entity); } updateKinematicSettings(entity.getComponent(RigidBodyComponent.class), rigidBody); return true; } else { newRigidBody(entity); return false; } }
Source:
private static boolean isAssignmentEqualsSized(@NotNull GoAssignmentStatement assignment) { List<GoExpression> expressions = assignment.getExpressionList(); return assignment.getLeftHandExprList().getExpressionList().size() == expressions.size() && expressions.stream().allMatch(e -> GoInspectionUtil.getExpressionResultCount(e) == 1); }

Target:
private static boolean isAssignmentEqualsSized(@NotNull GoAssignmentStatement assignment) { return getLeftHandElements(assignment).size() == assignment.getExpressionList().size(); }
Source:
public void leaveCritical() { final long now = System.nanoTime(); assert TIME_ENTER_UPDATER.get(this) <= now : "Must call enterCritical first"; TIME_LEFT_UPDATER.lazySet(this, now); }

Target:
public void leaveCritical() { TIME_LEFT_UPDATER.lazySet(this, System.nanoTime()); }
Source:
private static boolean isValidSnappyStream(File f) throws IOException { FileInputStream fis = null; byte[] byteArray = new byte[SnappyCodec.MAGIC_LEN]; try { fis = new FileInputStream(f); fis.read(byteArray, 0, SnappyCodec.MAGIC_LEN); ByteBuffer bb = ByteBuffer.wrap(byteArray); byte[] magicHeader = new byte[SnappyCodec.MAGIC_LEN]; bb.get(magicHeader, 0, SnappyCodec.MAGIC_LEN); return Arrays.equals(magicHeader, SnappyCodec.getMagicHeader()); } catch (FileNotFoundException e) { LOG.error("Unable to open file " + f.getName() + " : ", e); return false; } finally { if (fis != null) { fis.close(); } } }

Target:
private static boolean isValidSnappyStream(File f) throws IOException { byte[] byteArray = new byte[SnappyCodec.MAGIC_LEN]; try (FileInputStream fis = new FileInputStream(f)) { if (SnappyCodec.MAGIC_LEN != fis.read(byteArray, 0, SnappyCodec.MAGIC_LEN)) { LOG.error("Read incorrect number of bytes from " + f.getName()); return false; } ByteBuffer bb = ByteBuffer.wrap(byteArray); byte[] magicHeader = new byte[SnappyCodec.MAGIC_LEN]; bb.get(magicHeader, 0, SnappyCodec.MAGIC_LEN); return Arrays.equals(magicHeader, SnappyCodec.getMagicHeader()); } catch (FileNotFoundException e) { LOG.error("Unable to open file " + f.getName() + " : ", e); return false; } }
Source:
public static Policy policy(SqlKind kind) { return getPolicy(kind); }

Target:
public static Policy policy(SqlKind kind) { return MAP.getOrDefault(kind, Policy.AS_IS); }
Source:
public void executeCommand() { cmd = spy(createTestCommand(volumeWithRebalanceTask)); prepareMocks(cmd); mockBackend(true, null); assertTrue(cmd.canDoAction()); cmd.executeCommand(); verify(cmd).endStepJob(); verify(cmd).clearVolumeTaskAndReleaseLock(); }

Target:
public void executeCommand() { cmd = spy(createTestCommand(volumeWithRebalanceTask)); prepareMocks(cmd); mockBackend(true, null); assertTrue(cmd.canDoAction()); cmd.executeCommand(); verify(cmd).endStepJob(); verify(cmd).clearVolumeTaskAndReleaseLock(); assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_VOLUME_REBALANCE_STOP); }
Source:
public void sendBroadCast() throws Exception { byte[] data = discoveryRequest.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), 8002); getSendSocket().send(packet); logger.info("Discovery package sent!" + packet.getAddress() + ":" + packet.getPort()); byte[] response = new byte[discoveryResponse.length()]; DatagramPacket responsePacket = new DatagramPacket(response, response.length); getSendSocket().receive(responsePacket); logger.info("Discovery response received!" + responsePacket.getAddress() + ":" + responsePacket.getPort()); String responseData = new String(responsePacket.getData()).trim(); if (responseData.equals(discoveryResponse)) { logger.info("Found server!" + responsePacket.getAddress() + ":" + responsePacket.getPort()); } }

Target:
public void sendBroadCast() throws Exception { byte[] data = discoveryRequest.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), 8002); getSendSocket().send(packet); logger.info("Discovery package sent!" + packet.getAddress() + ":" + packet.getPort()); byte[] response = new byte[discoveryResponse.length()]; DatagramPacket responsePacket = new DatagramPacket(response, response.length); getSendSocket().receive(responsePacket); logger.info("Discovery response received!" + responsePacket.getAddress() + ":" + responsePacket.getPort()); String responseData = new String(responsePacket.getData(), StandardCharsets.UTF_8); if (responseData.equals(discoveryResponse)) { logger.info("Found server!" + responsePacket.getAddress() + ":" + responsePacket.getPort()); } }
Source:
public void shouldDecorateFutureAndReturnSuccess() throws Exception { CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName"); final Future<String> future = executor.submit(() -> "Hello World"); CircuitBreakerFuture<String> decoratedFuture = new CircuitBreakerFuture<>(circuitBreaker, future); String value = decoratedFuture.get(); assertThat(value).isEqualTo("Hello World"); assertThat(circuitBreaker.getMetrics().getNumberOfBufferedCalls()).isEqualTo(1); assertThat(circuitBreaker.getMetrics().getNumberOfFailedCalls()).isEqualTo(0); assertThat(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1); assertThat(circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()).isEqualTo(0); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); }

Target:
public void shouldDecorateFutureAndReturnSuccess() throws Exception { CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName"); final Future<String> future = mock(Future.class); when(future.get()).thenReturn("Hello World"); CircuitBreakerFuture<String> decoratedFuture = new CircuitBreakerFuture<>(circuitBreaker, future); String value = decoratedFuture.get(); assertThat(value).isEqualTo("Hello World"); assertThat(circuitBreaker.getMetrics().getNumberOfBufferedCalls()).isEqualTo(1); assertThat(circuitBreaker.getMetrics().getNumberOfFailedCalls()).isEqualTo(0); assertThat(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1); assertThat(circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()).isEqualTo(0); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); then(future).should().get(); }
Source:
public void testAcceptWhenIsNotExpectedClass() { when(rule.getId()).thenReturn("SomeOtherClass"); boolean actual = check.accepts(rule, context); assertFalse(actual); }

Target:
public void testAcceptWhenIsNotExpectedClass() { when(rule.getId()).thenReturn("SomeOtherClass"); final boolean actual = check.accepts(rule, context); assertFalse(actual); }
Source:
@Override public void lockInterruptibly() throws IgniteException { ctx.kernalContext().gateway().readLock(); try { try { sync.acquireInterruptibly(); } catch (InterruptedException e) { throw new IgniteInterruptedException(e); } } finally { ctx.kernalContext().gateway().readUnlock(); } }

Target:
@Override public void lockInterruptibly() throws IgniteException { ctx.kernalContext().gateway().readLock(); try { sync.acquireInterruptibly(); } catch (InterruptedException e) { throw new IgniteInterruptedException(e); } finally { ctx.kernalContext().gateway().readUnlock(); } }
Source:
private ConfigurationImpl() { this.validationBootstrapParameters = new ValidationBootstrapParameters(); TypeResolutionHelper typeResolutionHelper = new TypeResolutionHelper(); ClassLoader classLoader = getClass().getClassLoader(); if ( isJavaFxInClasspath( classLoader ) ) { JavaFXPropertyValueUnwrapper jfxUnwrapper = createJavaFXUnwrapperClass( typeResolutionHelper, classLoader ); validatedValueHandlers.add( jfxUnwrapper ); } if ( Version.getJavaRelease() >= 8 ) { validatedValueHandlers.add( new OptionalValueUnwrapper( typeResolutionHelper ) ); } this.defaultResourceBundleLocator = new PlatformResourceBundleLocator( ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES ); this.defaultTraversableResolver = new DefaultTraversableResolver(); this.defaultConstraintValidatorFactory = new ConstraintValidatorFactoryImpl(); this.defaultParameterNameProvider = new DefaultParameterNameProvider(); this.defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); this.defaultConstraintDefinitionContributor = new ServiceLoaderBasedConstraintDefinitionContributor( typeResolutionHelper ); this.addConstraintDefinitionContributor( defaultConstraintDefinitionContributor ); }

Target:
private ConfigurationImpl() { this.validationBootstrapParameters = new ValidationBootstrapParameters(); TypeResolutionHelper typeResolutionHelper = new TypeResolutionHelper(); if ( isJavaFxInClasspath() ) { validatedValueHandlers.add( createJavaFXUnwrapperClass( typeResolutionHelper ) ); } if ( Version.getJavaRelease() >= 8 ) { validatedValueHandlers.add( new OptionalValueUnwrapper( typeResolutionHelper ) ); } this.defaultResourceBundleLocator = new PlatformResourceBundleLocator( ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES ); this.defaultTraversableResolver = new DefaultTraversableResolver(); this.defaultConstraintValidatorFactory = new ConstraintValidatorFactoryImpl(); this.defaultParameterNameProvider = new DefaultParameterNameProvider(); this.defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); this.defaultConstraintDefinitionContributor = new ServiceLoaderBasedConstraintDefinitionContributor( typeResolutionHelper ); this.addConstraintDefinitionContributor( defaultConstraintDefinitionContributor ); }
Source:
public void shouldNotBlockInCloseForZeroDuration() throws InterruptedException { try (final KafkaStreams streams = new KafkaStreams(new StreamsBuilder().build(), props, supplier, time)) { final Thread th = new Thread(() -> streams.close(Duration.ofMillis(0L))); th.start(); th.join(30_000L); assertFalse(th.isAlive()); } }

Target:
public void shouldNotBlockInCloseForZeroDuration() { try (final KafkaStreams streams = new KafkaStreams(new StreamsBuilder().build(), props, supplier, time)) { assertFalse(streams.close(Duration.ZERO)); } }
Source:
public MapCanvas build() { if (this.canvas == null) { return SpongeEmptyCanvas.INSTANCE; } return this.canvas; }

Target:
public MapCanvas build() { if (this.canvas == null) { return SpongeEmptyCanvas.INSTANCE; } return new SpongeMapByteCanvas(canvas.clone()); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.car_list); StoreConfig storeConfig = new StoreConfig(); storeConfig.setContext(getApplicationContext()); storeConfig.setType(StoreTypes.SQL); storeConfig.setKlass(Car.class); idGenerator = new IncrementalIdGenerator(readLastSQLStoreIdFromSharedPreference()); storeConfig.setIdGenerator(idGenerator); DataManager dataManager = new DataManager(); store = (SQLStore<Car>) dataManager.store("myStorage", storeConfig); store.open(new Callback<SQLStore<Car>>() { @Override public void onSuccess(SQLStore<Car> data) { updateDisplayCars(); } @Override public void onFailure(Exception e) { Toast.makeText(HowToUseSQLStorage.this, getString(R.string.error_open_database), Toast.LENGTH_SHORT).show(); } }); ListView listview = getListView(); listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { final Car car = (Car) adapterView.getItemAtPosition(position); AlertDialog.Builder builder = new AlertDialog.Builder(HowToUseSQLStorage.this) .setTitle(getString(R.string.delete_confirmation)) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { store.remove(car.getId()); updateDisplayCars(); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.create().show(); return false; } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.car_list); idGenerator = new IncrementalIdGenerator(readLastSQLStoreIdFromSharedPreference()); StoreConfig storeConfig = buildStoreConfig(); DataManager dataManager = new DataManager(); store = (SQLStore<Car>) dataManager.store("myStorage", storeConfig); store.open(new Callback<SQLStore<Car>>() { @Override public void onSuccess(SQLStore<Car> data) { updateDisplayCars(); } @Override public void onFailure(Exception e) { Toast.makeText(HowToUseSQLStorage.this, getString(R.string.error_open_database), Toast.LENGTH_SHORT).show(); } }); ListView listview = getListView(); listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { final Car car = (Car) adapterView.getItemAtPosition(position); AlertDialog.Builder builder = new AlertDialog.Builder(HowToUseSQLStorage.this) .setTitle(getString(R.string.delete_confirmation)) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { remove(car); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.create().show(); return false; } }); }
Source:
private boolean isRequiredToUploadAtTime(TopicPartition topicPartition) throws Exception{ final String topic = topicPartition.getTopic(); final String topicFilter = mConfig.getKafkaTopicUploadAtMinuteMarkFilter(); if (topicFilter == null || topicFilter.isEmpty()){ return false; } if (topic.matches(topicFilter)){ if (DateTime.now().minuteOfHour().get() == mConfig.getUploadMinuteMark()){ return true; } } return false; }

Target:
private boolean isRequiredToUploadAtTime(TopicPartition topicPartition) throws Exception{ final String topic = topicPartition.getTopic(); if (mTopicFilter == null || mTopicFilter.isEmpty()){ return false; } if (topic.matches(mTopicFilter)){ if (DateTime.now().minuteOfHour().get() == mConfig.getUploadMinuteMark()){ return true; } } return false; }
Source:
public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; int dot = name.lastIndexOf('.'); this.packName = (dot < 0) ? name : name.substring(0, dot); this.sizeMap = new HashMap<String, Long>(); }

Target:
public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; int dot = name.lastIndexOf('.'); this.packName = (dot < 0) ? name : name.substring(0, dot); this.sizeMap = new HashMap<String, Long>(5); }
Source:
private void handleCommand(ChannelHandlerContext ctx, String payload, int requestId) throws IOException { if (this.loggedIn) { try { EventFactory.callEvent(new RemoteServerCommandEvent(commandSender, payload)); ; rconServer.getServer().dispatchCommand(commandSender, payload); sendMultiPacketResponse(ctx, requestId, ChatColor.stripColor(commandSender.getLog())); commandSender.clearLog(); } catch (CommandException e) { sendMultiPacketResponse(ctx, requestId, String.format("Error executing: %s (%s)", payload, e.getMessage())); } } else { ByteBuf buf = ctx.alloc().buffer(); createResponse(buf, -1, 2, ""); ctx.write(buf); } }

Target:
private void handleCommand(ChannelHandlerContext ctx, String payload, int requestId) throws IOException { if (this.loggedIn) { try { EventFactory.callEvent(new RemoteServerCommandEvent(commandSender, payload)); rconServer.getServer().dispatchCommand(commandSender, payload); String message = commandSender.getLog(); if (!rconServer.getServer().useRConColors()) { message = ChatColor.stripColor(message); } sendMultiPacketResponse(ctx, requestId, message); commandSender.clearLog(); } catch (CommandException e) { sendMultiPacketResponse(ctx, requestId, String.format("Error executing: %s (%s)", payload, e.getMessage())); } } else { ByteBuf buf = ctx.alloc().buffer(); createResponse(buf, -1, 2, ""); ctx.write(buf); } }
Source:
public ImmutableMap<String, ProcedureRunner> getPreparedUserProcedures(SiteProcedureConnection site) { long hsId = site.getCorrespondingSiteId(); ImmutableMap<String, ProcedureRunner> userProcs = m_catalogInfo.m_userProcsMap.get(hsId); if (userProcs == null) { hostLog.warn("look for MPI site: " + hsId + " in Map: " + m_catalogInfo.m_userProcsMap.keySet()); long siteId = CoreUtils.getSiteIdFromHSId(hsId); userProcs = m_catalogInfo.m_userProcsMap.get(siteId); if (userProcs == null) { hostLog.error("look for site id : " + siteId + " in Map: " + m_catalogInfo.m_userProcsMap.keySet()); } } for (ProcedureRunner runner: userProcs.values()) { runner.initSiteAndStats(site); } return userProcs; }

Target:
public ImmutableMap<String, ProcedureRunner> getPreparedUserProcedures(SiteProcedureConnection site) { long hsId = site.getCorrespondingSiteId(); ImmutableMap<String, ProcedureRunner> userProcs = m_catalogInfo.m_userProcsMap.get(hsId); if (userProcs == null) { hostLog.debug("look for MPI site: " + hsId + " in Map: " + m_catalogInfo.m_userProcsMap.keySet()); long siteId = CoreUtils.getSiteIdFromHSId(hsId); userProcs = m_catalogInfo.m_userProcsMap.get(siteId); if (userProcs == null) { throw new RuntimeException("look for site id : " + siteId + " in Map: " + m_catalogInfo.m_userProcsMap.keySet()); } } for (ProcedureRunner runner: userProcs.values()) { runner.initSiteAndStats(site); } return userProcs; }
Source:
public RecoveryDecorator get(Class<?> returnType) { return recoveryDecorator.stream().filter(it -> it.supports(returnType)) .findFirst() .orElse(defaultRecoveryDecorator); }

Target:
private RecoveryDecorator get(Class<?> returnType) { return recoveryDecorator.stream().filter(it -> it.supports(returnType)) .findFirst() .orElse(defaultRecoveryDecorator); }
Source:
private static boolean sameVisibilityNotPrivate(Symbol s1, Symbol s2) { return !s1.isPrivate() && ((JavaSymbol) s1).flags() == ((JavaSymbol) s2).flags(); }

Target:
private static boolean sameVisibilityNotPrivate(Symbol s1, Symbol s2) { return bothPublic(s1, s2) || bothProtected(s1, s2) || bothPackageVisibility(s1, s2); }
Source:
<Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readChunk( FSDataInputStream source, long sourceOffset, RecoveredChannelStateHandler<Info, Context> stateHandler, Info channelInfo) throws IOException { if (source.getPos() != sourceOffset) { source.seek(sourceOffset); } int length = serializer.readLength(source); while (length > 0) { Tuple2<ChannelStateByteBuffer, Context> bufferWithContext = stateHandler.getBuffer(channelInfo); try { while (length > 0 && bufferWithContext.f0.isWritable()) { length -= serializer.readData(source, bufferWithContext.f0, length); } } catch (Exception e) { bufferWithContext.f0.recycle(); throw e; } stateHandler.recover(channelInfo, bufferWithContext.f1); } }

Target:
<Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readChunk( FSDataInputStream source, long sourceOffset, RecoveredChannelStateHandler<Info, Context> stateHandler, Info channelInfo) throws IOException, InterruptedException { if (source.getPos() != sourceOffset) { source.seek(sourceOffset); } int length = serializer.readLength(source); while (length > 0) { RecoveredChannelStateHandler.BufferWithContext<Context> bufferWithContext = stateHandler.getBuffer(channelInfo); try { while (length > 0 && bufferWithContext.buffer.isWritable()) { length -= serializer.readData(source, bufferWithContext.buffer, length); } } catch (Exception e) { bufferWithContext.buffer.recycle(); throw e; } stateHandler.recover(channelInfo, bufferWithContext.context); } }
Source:
public long incrementCounter(final String key, final long value) { long l = incAtomicLong(counterMap.get(key), value); LOG.debug("Incrementing counter by with final value {}", key, value, l); return l; }

Target:
public long incrementCounter(final String key, final long value) { AtomicLong counter = counterMap.get(key); if (counter == null) { LOG.debug("Ignoring counter increment for unknown counter {}", key); return 0; } if (value < 0) { LOG.debug("Ignoring negative increment value for counter {}", value, key); return counter.get(); } else { long l = incAtomicLong(counter, value); LOG.debug("Incrementing counter by with final value {}", key, value, l); return l; } }
Source:
public void testTextWrapBoundariesUpdates() { tested.refresh(); verify(textDecorator).setTextBoundaries(any()); }

Target:
public void testTextWrapBoundariesUpdates() { tested.refresh(); verify(textDecorator).setTextBoundaries(PATH.getBoundingBox()); }
Source:
protected Response performAction(VdcActionType task, VdcActionParametersBase params, Action action) { try { if (QueryHelper.hasMatrixParam(getUriInfo(), ASYNC_CONSTRAINT) || expectNonBlocking()) { getCurrent().get(MetaData.class).set("async", true); return performNonBlockingAction(task, params); } else { doAction(task, params); if (action!=null) { return Response.ok().entity(action).build(); } else { return Response.ok().build(); } } } catch (Exception e) { return handleError(Response.class, e, false); } }

Target:
protected Response performAction(VdcActionType task, VdcActionParametersBase params, Action action) { try { if (QueryHelper.hasMatrixParam(getUriInfo(), ASYNC_CONSTRAINT) || expectNonBlocking()) { getCurrent().get(MetaData.class).set("async", true); return performNonBlockingAction(task, params); } else { doAction(task, params); if (action!=null) { action.setStatus(StatusUtils.create(CreationStatus.COMPLETE)); return Response.ok().entity(action).build(); } else { return Response.ok().build(); } } } catch (Exception e) { return handleError(Response.class, e, false); } }
Source:
public static void instanceFieldTest2() { Foo f = new Foo(); int a = f.$inline$GetInstanceField(); if (a != 42) { throw new Error("Expected 42, got " + a); } f.iField = 43; a = f.$inline$GetInstanceField(); if (a != 43) { throw new Error("Expected 43, got " + a); } }

Target:
public static void instanceFieldTest2() { Foo f = new Foo(); int a = f.$inline$GetInstanceField(); f.iField = 43; a = f.$inline$GetInstanceField(); if (a != 43) { throw new Error("Expected 43, got " + a); } }
Source:
public void init() { jobNameLabel.addRequiredIndicator(); jobTypeLabel.addRequiredIndicator(); jobRetriesLabel.addRequiredIndicator(); jobRetriesInput.init(); jobRetriesInput.getElement().setType("number"); jobRetriesInput.getElement().setAttribute("min", "0"); jobRetriesInput.getElement().setDefaultValue("0"); myParametersGrid.setHeight("200px"); myParametersGrid.setEmptyTableWidget(new Label(constants.No_Parameters_added_yet())); initGridColumns(); initDateTimePicker(); Button button = GWT.create(Button.class); button.setText(Constants.INSTANCE.Add_Parameter()); button.addClickHandler(e -> addNewParameter()); advancedContent.add(myParametersGrid); advancedContent.add(button); inlineNotification.setType(InlineNotification.InlineNotificationType.DANGER); }

Target:
public void init() { jobNameLabel.addRequiredIndicator(); jobTypeLabel.addRequiredIndicator(); jobRetriesLabel.addRequiredIndicator(); jobRetriesInput.init(); jobRetriesInput.getElement().setAttribute("min", "0"); jobRetriesInput.getElement().setDefaultValue("0"); myParametersGrid.setHeight("200px"); myParametersGrid.setEmptyTableWidget(new Label(constants.No_Parameters_added_yet())); initGridColumns(); initDateTimePicker(); Button button = GWT.create(Button.class); button.setText(Constants.INSTANCE.Add_Parameter()); button.addClickHandler(e -> addNewParameter()); advancedContent.add(myParametersGrid); advancedContent.add(button); inlineNotification.setType(InlineNotification.InlineNotificationType.DANGER); }
Source:
private void updateWrittenAndUnread(AssignmentExpressionTree statementTree, String key, String variableName, Symbol variableSymbol) { Map<String, AssignmentExpressionTree> keysToAssignmentMap; if (writtenAndUnread.containsKey(variableName)) { keysToAssignmentMap = writtenAndUnread.get(variableName); } else { keysToAssignmentMap = new HashMap<>(); } keysToAssignmentMap.put(key, statementTree); namesToSymbols.put(variableName, variableSymbol); writtenAndUnread.put(variableName, keysToAssignmentMap); }

Target:
private void updateWrittenAndUnread(AssignmentExpressionTree statementTree, String key, String variableName, Symbol variableSymbol) { writtenAndUnread.computeIfAbsent(variableName, k -> new HashMap<>()).put(key, statementTree); namesToSymbols.put(variableName, variableSymbol); }
Source:
private Locale languageLocale(String languageCode) { if (TextUtils.isEmpty(languageCode)) return Locale.getDefault(); if (languageCode.length() > 2) { return new Locale(languageCode.substring(0, 2), languageCode.substring(3)); } return new Locale(languageCode); }

Target:
private Locale languageLocale(String languageCode) { if (TextUtils.isEmpty(languageCode)) return Locale.getDefault(); if (languageCode.length() > NO_REGION_LANG_CODE_LEN) { return new Locale(languageCode.substring(0, NO_REGION_LANG_CODE_LEN), languageCode.substring(REGION_SUBSTRING_INDEX)); } return new Locale(languageCode); }
Source:
public String getGuid() { return String.valueOf(id); }

Target:
public String getGuid() { return id; }
Source:
private static void setNot(Attributes atts, ITmfFilterTreeNode node) { String value = atts.getValue(TmfFilterContainsNode.NOT_ATTR); if (Boolean.TRUE.toString().equalsIgnoreCase(value)) { ((TmfFilterTreeNode) node).setNot(true); } }

Target:
private static void setNot(Attributes atts, ITmfFilterTreeNode node) { String value = atts.getValue(TmfFilterTreeNode.NOT_ATTRIBUTE); if (Boolean.TRUE.toString().equalsIgnoreCase(value)) { ((TmfFilterTreeNode) node).setNot(true); } }
Source:
public int hashCode() { int result = _syncType != null ? _syncType.hashCode() : 0; result = 31 * result + (_nuageVspCmsId != null ? _nuageVspCmsId.hashCode() : 0); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_syncType != null ? _syncType.hashCode() : 0); result = 31 * result + (_nuageVspCmsId != null ? _nuageVspCmsId.hashCode() : 0); return result; }
Source:
public PackagedProgram getPackagedProgram() throws FlinkException { try { if (PackagedProgramUtils.isPython(jobClassName) || PackagedProgramUtils.isPython(programArguments)){ String pythonJobClassName = PackagedProgramUtils.PYTHON_DRIVER_CLASS_NAME; File pythonJarFile = new File(PackagedProgramUtils.getPythonJar().getPath()); return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setArguments(programArguments) .setJarFile(pythonJarFile) .setEntryPointClassName(pythonJobClassName) .build(); } if (jarFile != null) { return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setArguments(programArguments) .setJarFile(jarFile) .setEntryPointClassName(jobClassName) .build(); } final String entryClass = getJobClassNameOrScanClassPath(); return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setEntryPointClassName(entryClass) .setArguments(programArguments) .build(); } catch (ProgramInvocationException e) { throw new FlinkException("Could not load the provided entrypoint class.", e); } }

Target:
public PackagedProgram getPackagedProgram() throws FlinkException { try { if (PackagedProgramUtils.isPython(jobClassName) || PackagedProgramUtils.isPython(programArguments)){ String pythonJobClassName = PackagedProgramUtils.getPythonDriverClassName(); File pythonJarFile = new File(PackagedProgramUtils.getPythonJar().getPath()); return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setArguments(programArguments) .setJarFile(pythonJarFile) .setEntryPointClassName(pythonJobClassName) .build(); } if (jarFile != null) { return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setArguments(programArguments) .setJarFile(jarFile) .setEntryPointClassName(jobClassName) .build(); } final String entryClass = getJobClassNameOrScanClassPath(); return PackagedProgram.newBuilder() .setUserClassPaths(new ArrayList<>(userClassPaths)) .setEntryPointClassName(entryClass) .setArguments(programArguments) .build(); } catch (ProgramInvocationException e) { throw new FlinkException("Could not load the provided entrypoint class.", e); } }
Source:
public final Optional<SslConfiguration> getSslConfiguration(String serviceName) { checkArgument(!Strings.isNullOrEmpty(serviceName)); Optional<ServiceConfiguration> maybeServiceConfig = getServiceConfiguration(serviceName); if (!maybeServiceConfig.isPresent()) { return defaultSecurity(); } return maybeServiceConfig.get().security().or(defaultSecurity()); }

Target:
public final Optional<SslConfiguration> getSslConfiguration(String serviceName) { ServiceConfiguration serviceConfig = Preconditions.checkNotNull( getServices().get(serviceName), "Unable to find the configuration for " + serviceName + "."); return serviceConfig.security(); }
Source:
public boolean include( Artifact artifact ) { for ( Exclusion exclusion : exclusions ) { if ( "*".equals( exclusion.getGroupId() ) && "*".equals( exclusion.getArtifactId() ) ) { return false; } if ( "*".equals( exclusion.getGroupId() ) ) { return !exclusion.getArtifactId().equals( artifact.getArtifactId() ); } if ( "*".equals( exclusion.getArtifactId() ) ) { return !exclusion.getGroupId().equals( artifact.getGroupId() ); } if ( exclusion.getGroupId().equals( artifact.getGroupId() ) && exclusion.getArtifactId().equals( artifact.getArtifactId() ) ) { return false; } } return true; }

Target:
public boolean include( Artifact artifact ) { for ( Exclusion exclusion : exclusions ) { if ( WILDCARD.equals( exclusion.getGroupId() ) && WILDCARD.equals( exclusion.getArtifactId() ) ) { return false; } if ( WILDCARD.equals( exclusion.getGroupId() ) ) { return !exclusion.getArtifactId().equals( artifact.getArtifactId() ); } if ( WILDCARD.equals( exclusion.getArtifactId() ) ) { return !exclusion.getGroupId().equals( artifact.getGroupId() ); } if ( exclusion.getGroupId().equals( artifact.getGroupId() ) && exclusion.getArtifactId().equals( artifact.getArtifactId() ) ) { return false; } } return true; }
Source:
public void setup() { metadata = createTestMetadataManager(); domainTranslator = new RowExpressionDomainTranslator(metadata); columnExtractor = new SubfieldExtractor(new FunctionResolution(metadata.getFunctionManager()), new NoopExpressionOptimizer(), TestingSession.SESSION); }

Target:
public void setup() { metadata = createTestMetadataManager(); domainTranslator = new RowExpressionDomainTranslator(metadata); columnExtractor = new SubfieldExtractor( new FunctionResolution(metadata.getFunctionManager()), (rowExpression, level, session) -> rowExpression, TestingSession.SESSION); }
Source:
public void perform(Run build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { TestResultAction action = parseAndAttach(this, null, build, workspace, launcher, listener); if (action != null && action.getResult().getFailCount() > 0) build.setResult(Result.UNSTABLE); }

Target:
public void perform(Run build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { TestResultAction action = parseAndAttach(this, null, null, build, workspace, launcher, listener); if (action != null && action.getResult().getFailCount() > 0) build.setResult(Result.UNSTABLE); }
Source:
public void putCheckpoint(String replicatorIdentifier, String sequence) { logger.entering(this.getClass().getCanonicalName(),"putCheckpoint",new Object[]{replicatorIdentifier,sequence}); String checkpointDocumentId = getCheckpointDocumentId(replicatorIdentifier); BasicDocumentRevision doc = dbCore.getLocalDocument(checkpointDocumentId); Map<String, String> checkpointDoc = new HashMap<String, String>(); checkpointDoc.put("lastSequence", sequence); byte[] json = JSONUtils.serializeAsBytes(checkpointDoc); if(doc == null) { dbCore.createLocalDocument(checkpointDocumentId, DocumentBodyFactory.create(json)); } else { dbCore.updateLocalDocument(doc.getId(), doc.getRevision(), DocumentBodyFactory.create(json)); } }

Target:
public void putCheckpoint(String replicatorIdentifier, String sequence) { logger.entering("DatastoreWrapper","putCheckpoint",new Object[]{replicatorIdentifier,sequence}); String checkpointDocumentId = getCheckpointDocumentId(replicatorIdentifier); BasicDocumentRevision doc = dbCore.getLocalDocument(checkpointDocumentId); Map<String, String> checkpointDoc = new HashMap<String, String>(); checkpointDoc.put("lastSequence", sequence); byte[] json = JSONUtils.serializeAsBytes(checkpointDoc); if(doc == null) { dbCore.createLocalDocument(checkpointDocumentId, DocumentBodyFactory.create(json)); } else { dbCore.updateLocalDocument(doc.getId(), doc.getRevision(), DocumentBodyFactory.create(json)); } }
Source:
private AdColonyAppOptions buildAppOptions(MediationAdRequest adRequest, Bundle networkExtras) { AdColonyAppOptions options; if (appOptions != null) { options = appOptions; } else { options = new AdColonyAppOptions(); } if (networkExtras != null) { String userId = networkExtras.getString("user_id"); if (userId != null) { options.setUserID(userId); } } if (adRequest != null) { if (adRequest.isTesting()) { options.setTestModeEnabled(true); } AdColonyUserMetadata userMetadata = new AdColonyUserMetadata(); int genderVal = adRequest.getGender(); if (genderVal == AdRequest.GENDER_FEMALE) { userMetadata.setUserGender(AdColonyUserMetadata.USER_FEMALE); } else if (genderVal == AdRequest.GENDER_MALE) { userMetadata.setUserGender(AdColonyUserMetadata.USER_MALE); } Location location = adRequest.getLocation(); if (location != null) { userMetadata.setUserLocation(location); } Date birthday = adRequest.getBirthday(); if (birthday != null) { long currentTime = System.currentTimeMillis(); long birthdayTime = birthday.getTime(); long diff = currentTime - birthdayTime; if (diff > 0) { long day = (1000 * 60 * 60 * 24); long yearsPassed = diff / day / 365; userMetadata.setUserAge((int) yearsPassed); } } options.setUserMetadata(userMetadata); } return options; }

Target:
private AdColonyAppOptions buildAppOptions(MediationAdRequest adRequest, Bundle networkExtras) { AdColonyAppOptions options = AdColonyMediationAdapter.getAppOptions(); if (networkExtras != null) { String userId = networkExtras.getString("user_id"); if (userId != null) { options.setUserID(userId); } } if (adRequest != null) { if (adRequest.isTesting()) { options.setTestModeEnabled(true); } AdColonyUserMetadata userMetadata = new AdColonyUserMetadata(); int genderVal = adRequest.getGender(); if (genderVal == AdRequest.GENDER_FEMALE) { userMetadata.setUserGender(AdColonyUserMetadata.USER_FEMALE); } else if (genderVal == AdRequest.GENDER_MALE) { userMetadata.setUserGender(AdColonyUserMetadata.USER_MALE); } Location location = adRequest.getLocation(); if (location != null) { userMetadata.setUserLocation(location); } Date birthday = adRequest.getBirthday(); if (birthday != null) { long currentTime = System.currentTimeMillis(); long birthdayTime = birthday.getTime(); long diff = currentTime - birthdayTime; if (diff > 0) { long day = (1000 * 60 * 60 * 24); long yearsPassed = diff / day / 365; userMetadata.setUserAge((int) yearsPassed); } } options.setUserMetadata(userMetadata); } return options; }