auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPhoneStateChangeAsExpected() throws Exception { if (!mShouldTestTelecom) { return; } setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE); Uri testNumber = createTestNumber(); addAndVerifyNewIncomingCall(testNumber, null); TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); CountDownLatch count = new CountDownLatch(1); Executor executor = (Runnable command)->count.countDown(); PhoneStateListener listener = new PhoneStateListener(executor); telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); count.await(TIMEOUT, TimeUnit.MILLISECONDS); Thread.sleep(TIMEOUT); assertEquals(TelephonyManager.CALL_STATE_RINGING, telephonyManager.getCallState()); }

Target:
public void testPhoneStateChangeAsExpected() throws Exception { if (!mShouldTestTelecom) { return; } setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE); Uri testNumber = createTestNumber(); addAndVerifyNewIncomingCall(testNumber, null); TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); CountDownLatch count = new CountDownLatch(1); Executor executor = (Runnable command)->count.countDown(); PhoneStateListener listener = new PhoneStateListener(executor); telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); count.await(TestUtils.WAIT_FOR_PHONE_STATE_LISTENER_REGISTERED_TIMEOUT_S, TimeUnit.SECONDS); Thread.sleep(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS); assertEquals(TelephonyManager.CALL_STATE_RINGING, telephonyManager.getCallState()); }
Source:
public void onDraw(Canvas canvas) { for (int i = viewPort.x; i < (viewPort.x + NUM_SQUARES_IN_ROW); i++) { for (int j = viewPort.y; j < (viewPort.y + NUM_SQUARES_IN_COLUMN); j++) { Sector sector = sectors[i][j]; if (globalGameData.getHumanPlayer().isVisible(sector)) { paint.setColor(Color.BLACK); } else { paint.setColor(THE_UNDISCOVERED_COUNTRY); } int x = (sector.getX() - viewPort.x) * SQUARE_SIZE; int y = (sector.getY() - viewPort.y) * SQUARE_SIZE; r.left = x; r.top = y; r.right = x + (SQUARE_SIZE); r.bottom = y + (SQUARE_SIZE); canvas.drawRect(r, paint); drawWormhole(sector, canvas); drawSystem(sector, canvas); drawShip(canvas, sector); } } drawGrid(canvas); for (Object s : globalGameData.getHumanPlayer().getDiscoveredSectors()) { drawSystem((Sector) s, canvas); drawSystemLabel(canvas, (Sector) s); } drawTopLeftInformation(canvas); }

Target:
public void onDraw(Canvas canvas) { for (int i = viewPort.x; i < globalGameData.galaxySizeX; i++) { for (int j = viewPort.y; j < globalGameData.galaxySizeY; j++) { try { Sector sector = sectors[i][j]; if (globalGameData.getHumanPlayer().isVisible(sector)) { paint.setColor(Color.BLACK); } else { paint.setColor(THE_UNDISCOVERED_COUNTRY); } int x = (sector.getX() - viewPort.x) * SQUARE_SIZE; int y = (sector.getY() - viewPort.y) * SQUARE_SIZE; r.left = x; r.top = y; r.right = x + (SQUARE_SIZE); r.bottom = y + (SQUARE_SIZE); canvas.drawRect(r, paint); drawWormhole(sector, canvas); drawSystem(sector, canvas); drawShip(canvas, sector); } catch (ArrayIndexOutOfBoundsException e) { } } } drawGrid(canvas); for (Object s : globalGameData.getHumanPlayer().getDiscoveredSectors()) { drawSystem((Sector) s, canvas); drawSystemLabel(canvas, (Sector) s); } drawTopLeftInformation(canvas); }
Source:
public String evaluate(AbstractBuild<?, ?> build, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException { if (StringUtils.isEmpty(format)) { format = showPaths ? FORMAT_DEFAULT_VALUE_WITH_PATHS : FORMAT_DEFAULT_VALUE; } DateFormat dateFormatter; if (StringUtils.isEmpty(dateFormat)) { dateFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); } else { dateFormatter = new SimpleDateFormat(dateFormat); } StringBuffer buf = new StringBuffer(); if (!build.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : build.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } if (showDependencies) { Run<?,?> previousRun = ExtendedEmailPublisher.getPreviousRun(build, listener); if (previousRun != null && previousRun instanceof AbstractBuild) { for (Entry<AbstractProject, DependencyChange> e : build.getDependencyChanges((AbstractBuild)previousRun).entrySet()) { buf.append("\n=======================\n"); buf.append("\nChanges in ").append(e.getKey().getName()) .append(":\n"); for (AbstractBuild<?, ?> b : e.getValue().getBuilds()) { if (!b.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : b.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } } } } } return buf.toString(); }

Target:
public String evaluate(AbstractBuild<?, ?> build, TaskListener listener, String macroName) throws MacroEvaluationException, IOException, InterruptedException { if (StringUtils.isEmpty(format)) { format = showPaths ? FORMAT_DEFAULT_VALUE_WITH_PATHS : FORMAT_DEFAULT_VALUE; } DateFormat dateFormatter; if (StringUtils.isEmpty(dateFormat)) { dateFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); } else { dateFormatter = new SimpleDateFormat(dateFormat); } StringBuffer buf = new StringBuffer(); if (!build.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : build.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } if (showDependencies) { Run<?,?> previousRun = ExtendedEmailPublisher.getPreviousRun(build, listener); if (previousRun instanceof AbstractBuild) { for (Entry<AbstractProject, DependencyChange> e : build.getDependencyChanges((AbstractBuild)previousRun).entrySet()) { buf.append("\n=======================\n"); buf.append("\nChanges in ").append(e.getKey().getName()) .append(":\n"); for (AbstractBuild<?, ?> b : e.getValue().getBuilds()) { if (!b.getChangeSet().isEmptySet()) { for (ChangeLogSet.Entry entry : b.getChangeSet()) { Util.printf(buf, format, new ChangesSincePrintfSpec(entry, pathFormat, dateFormatter)); } } else { buf.append(def); } } } } } return buf.toString(); }
Source:
public void verifySwiping (PerformTouchAction touchAction, String direction, int attempts) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; boolean imageChanged = false; int startX = 70; int endX = 20; int duration = 300; int waitAfter = 5000; if (direction == "right") { int temp = startX; startX = endX; endX = temp; } else { direction = "left"; } for (int i = 0; i < attempts; ++i) { touchAction.swipeFromPointToPoint(startX, 50, endX, 50, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { imageChanged = true; break; } } if (imageChanged) { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " works", true); } else { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " doesn't work", false); } }

Target:
public void verifySwiping (PerformTouchAction touchAction, String direction, int attempts) { String currentImageSrc = getCurrentImagePath(); String nextImageSrc; boolean imageChanged = false; int startX = 70; int endX = 20; int duration = 300; int waitAfter = 5000; int centerY = 50; if ("right".equals(direction)) { int temp = startX; startX = endX; endX = temp; } else { direction = "left"; } for (int i = 0; i < attempts; ++i) { touchAction.swipeFromPointToPoint(startX, centerY, endX, centerY, duration, waitAfter); nextImageSrc = getCurrentImagePath(); if (!nextImageSrc.contains(currentImageSrc)) { imageChanged = true; break; } } if (imageChanged) { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " works", true); } else { PageObjectLogging.log("verifySwiping", "Swiping to " + direction + " doesn't work", false); } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); searchEditText = (EditText) findViewById(R.id.searchEditText); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(count>2 ) showResults(s.toString()); } @Override public void afterTextChanged(Editable s) }); messageView = (TextView) findViewById(R.id.search_area); warningView = (TextView) findViewById(R.id.search_warning); buttonGetTranslations = (Button) findViewById(R.id.btnGetTranslations); buttonGetTranslations.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent; if (downloadArabicSearchDb) { downloadArabicSearchDb(); return; } else { intent = new Intent(getApplicationContext(), TranslationManagerActivity.class); } startActivity(intent); finish(); } }); handleIntent(getIntent()); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); searchEditText = (EditText) findViewById(R.id.searchEditText); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (count > 2) { showResults(s.toString()); } } @Override public void afterTextChanged(Editable s) { } }); messageView = (TextView) findViewById(R.id.search_area); warningView = (TextView) findViewById(R.id.search_warning); buttonGetTranslations = (Button) findViewById(R.id.btnGetTranslations); buttonGetTranslations.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent; if (downloadArabicSearchDb) { downloadArabicSearchDb(); return; } else { intent = new Intent(getApplicationContext(), TranslationManagerActivity.class); } startActivity(intent); finish(); } }); handleIntent(getIntent()); }
Source:
public static byte[] encode(Message msg) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { GZIPOutputStream zip = new GZIPOutputStream(bytes); ObjectOutputStream output = new ObjectOutputStream(zip); output.writeObject(msg); output.flush(); zip.finish(); } catch (IOException e) { throw bomb(e); } return bytes.toByteArray(); }

Target:
public static byte[] encode(Message msg) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { GZIPOutputStream zip = new GZIPOutputStream(bytes); ObjectOutputStream output = new ObjectOutputStream(zip); try { output.writeObject(msg); } finally { output.close(); } } catch (IOException e) { throw bomb(e); } return bytes.toByteArray(); }
Source:
public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node), "Plan testing framework error: shapeMatches returned false in detailMatches in %s", this.getClass().getName()); ExchangeNode exchangeNode = (ExchangeNode) node; if (!orderBy.isEmpty()) { if (!exchangeNode.getOrderingScheme().isPresent()) { return NO_MATCH; } for (int i = 0; i < orderBy.size(); ++i) { Ordering ordering = orderBy.get(i); Symbol symbol = Symbol.from(symbolAliases.get(ordering.getField())); OrderingScheme orderingScheme = exchangeNode.getOrderingScheme().get(); if (!symbol.equals(orderingScheme.getOrderBy().get(i))) { return NO_MATCH; } if (!ordering.getSortOrder().equals(orderingScheme.getOrdering(symbol))) { return NO_MATCH; } } } return MatchResult.match(); }

Target:
public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) { checkState(shapeMatches(node), "Plan testing framework error: shapeMatches returned false in detailMatches in %s", this.getClass().getName()); ExchangeNode exchangeNode = (ExchangeNode) node; if (!orderBy.isEmpty()) { if (!exchangeNode.getOrderingScheme().isPresent()) { return NO_MATCH; } if (!orderingSchemeMatches(orderBy, exchangeNode.getOrderingScheme().get(), symbolAliases)) { return NO_MATCH; } } return MatchResult.match(); }
Source:
public boolean processMessage(Object msg) { if (msg instanceof DatagramPacket) { DatagramPacket packet = (DatagramPacket) msg; ByteBuf buffer = packet.content(); if (!buffer.isDirect()) { ByteBuf ioBuffer = UnixChannelUtil.ioBuffer(allocator, buffer.readableBytes()); ioBuffer.writeBytes(buffer, buffer.readerIndex(), buffer.readableBytes()); if (add(ioBuffer, packet.recipient())) { buffers[idx++] = ioBuffer; return true; } else { ioBuffer.release(); return false; } } else { return add(buffer, packet.recipient()); } } return false; }

Target:
public boolean processMessage(Object msg) { if (msg instanceof DatagramPacket) { DatagramPacket packet = (DatagramPacket) msg; ByteBuf buffer = packet.content(); if (!buffer.isDirect()) { return processNonDirectPacket(buffer, packet.recipient()); } return add(buffer, packet.recipient()); } return false; }
Source:
public void shouldRecordChannelConnect() throws Exception { try (Recording recording = new Recording()) { recording.setSettings(Map.of("io.netty.channel.Connect#threshold", "0ms")); recording.start(); EmbeddedChannel channel = new EmbeddedChannel(new JfrChannelHandler()); channel.connect(new InetSocketAddress(80)).await(); recording.stop(); final Path tempFile = Files.createTempFile(JFrChannelHandlerTest.class.getSimpleName(), ".jfr"); recording.dump(tempFile); final List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(tempFile); boolean hasConnectEvent = false; for (RecordedEvent event : recordedEvents) { if ("io.netty.channel.Connect".equals(event.getEventType().getName())) { hasConnectEvent = true; break; } } assertTrue("Expected a connect event", hasConnectEvent); } }

Target:
public void shouldRecordChannelConnect() throws Exception { try (Recording recording = new Recording()) { recording.enable("io.netty.channel.Connect").withoutThreshold(); recording.start(); EmbeddedChannel channel = new EmbeddedChannel(new JfrChannelHandler()); channel.connect(new InetSocketAddress(80)).await(); recording.stop(); final Path tempFile = Files.createTempFile(JFrChannelHandlerTest.class.getSimpleName(), ".jfr"); recording.dump(tempFile); final List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(tempFile); boolean hasConnectEvent = false; for (RecordedEvent event : recordedEvents) { if ("io.netty.channel.Connect".equals(event.getEventType().getName())) { hasConnectEvent = true; break; } } assertTrue("Expected a connect event", hasConnectEvent); } }
Source:
public void close() { Channel rawChannel = rawChannel(); if ( rawChannel.isOpen() ) { messageLogger.serverEvent( "CLOSE" ); try { rawChannel.close().sync(); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } }

Target:
public void close() { Channel rawChannel = rawChannel(); if ( rawChannel.isOpen() ) { messageLogger.serverEvent( "CLOSE" ); rawChannel.close().syncUninterruptibly(); } }
Source:
public static CtfTmfEventType get(CtfTmfTrace trace, String eventName) { String path = CONTEXT_ID; if (trace != null) { path = trace.getPath(); } return (CtfTmfEventType) TmfEventTypeManager.getInstance().getType(CONTEXT_ID + "/" + path, eventName); }

Target:
public static CtfTmfEventType get(CtfTmfTrace trace, String eventName) { return (CtfTmfEventType) TmfEventTypeManager.getInstance().getType(computeContextName(trace), eventName); }
Source:
public static final boolean isKQueueAvailable() { try { return Env.isMacOs() && KQueue.isAvailable(); } catch (java.lang.NoClassDefFoundError e) { logger.debug(e.getMessage(), e); ActiveMQClientLogger.LOGGER.unableToCheckKQueueAvailability(e); return false; } }

Target:
public static final boolean isKQueueAvailable() { try { return Env.isMacOs() && KQueue.isAvailable(); } catch (Throwable e) { ActiveMQClientLogger.LOGGER.unableToCheckKQueueAvailability(e); return false; } }
Source:
public void testUnsetDataDirAtClusterLevelBeforeActivate() { assertThat( invokeConfigTool("unset", "-s", "localhost:" + getNodePort(), "-c", "data-dirs.main"), is(successful())); activateCluster(); }

Target:
public void testUnsetDataDirAtClusterLevelBeforeActivate() throws IOException, SanskritException { invokeConfigTool("unset", "-s", "localhost:" + getNodePort(), "-c", "data-dirs.main"); activateCluster(); assertChanges(3); }
Source:
private static boolean isJavaFxAvailable() { if (System.getProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY) != null) { return false; } try { @SuppressWarnings("unused") javafx.embed.swing.JFXPanel unused = new javafx.embed.swing.JFXPanel(); return true; } catch (Throwable e) { LOGGER.warn("Unable to use JavaFX: " + e.getMessage()); System.setProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY, "true"); if (LOGGER.isDebugEnabled()) { LOGGER.warn(e); } } return false; }

Target:
private static boolean isJavaFxAvailable() { if (System.getProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY) != null) { return false; } try { @SuppressWarnings("unused") javafx.embed.swing.JFXPanel unused = new javafx.embed.swing.JFXPanel(); return true; } catch (Throwable e) { LOGGER.warn("Unable to use JavaFX: " + e.getMessage()); LOGGER.debug(e); System.setProperty(ZAP_JAVAFX_INIT_FAILED_SYSTEM_PROPERTY, "true"); } return false; }
Source:
ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = checkNotNull(outdatedBoxesFilter, "outdatedBoxesFilter"); this.cliFactory = checkNotNull(cliFactory, "cliFactory"); this.boxToImage = checkNotNull(boxToImage, "boxToImage"); }

Target:
ImageSupplier(Function<Collection<B>, Collection<B>> outdatedBoxesFilter, VagrantBoxApiFacade.Factory<B> cliFactory, Function<B, Image> boxToImage) { this.outdatedBoxesFilter = outdatedBoxesFilter; this.cliFactory = cliFactory; this.boxToImage = boxToImage; }
Source:
public void testThreadLeakWhenClientCanNotStartDueToAuthenticationError() { try { Hazelcast.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.getGroupConfig().setName("invalid cluster"); HazelcastClient.newHazelcastClient(config); Assert.fail(); } finally { Hazelcast.shutdownAll(); } }

Target:
public void testThreadLeakWhenClientCanNotStartDueToAuthenticationError() { Hazelcast.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.getGroupConfig().setName("invalid cluster"); Set<Thread> testStartThreads = getThreads(); try { HazelcastClient.newHazelcastClient(config); } finally { Hazelcast.shutdownAll(); assertHazelcastThreadShutdown(testStartThreads); } }
Source:
private void runMigrations() { for (Map.Entry<String, Configuration.DatastoreConfig> entry : _configuration.getDatastores().entrySet()) { final String dbName = entry.getKey(); final Configuration.DatastoreConfig config = entry.getValue(); final String directory = config.getDirectory(); if (!Strings.isNullOrEmpty(directory)) { final URL resource = _environment.resource(directory); if (resource != null) { LOGGER.info("Running migrations for Cassandra database " + dbName); try { final scala.collection.immutable.Map<String, Object> replication = JavaConverters.mapAsScalaMapConverter( config.getReplication()).asScala().toMap(Predef.conforms()); final File file = new File(resource.toURI()); final Registry registry = Registry.fromDirectory(file); final Migrator migrator = new CassandraMigrator(registry); final Session session = _injector.getInstance(Key.get(Session.class, Names.named(dbName))); session.init(); migrator.initialize(session, config.getKeyspace(), new ReplicationOptions(replication)); session.execute("USE " + config.getKeyspace()); migrator.migrate(session, Option.<Date>none().asScala()); } catch (final URISyntaxException e) { LOGGER.error("Unable to run migrations at " + resource, e); } } else { LOGGER.info("Found no migrations in directory " + directory + " for Cassandra database " + dbName); } } } }

Target:
private void runMigrations() { for (final Map.Entry<String, Configuration.DatastoreConfig> entry : _configuration.getDatastores().entrySet()) { final String dbName = entry.getKey(); final Configuration.DatastoreConfig config = entry.getValue(); final Path directory = config.getDirectory(); @Nullable final URL resource = _environment.resource(directory.toString()); if (resource != null) { LOGGER.info() .setMessage("Running migrations for Cassandra database") .addData("database", dbName) .log(); try { final scala.collection.immutable.Map<String, Object> replication = JavaConverters.<String, Object>mapAsScalaMapConverter( MAPPER.convertValue(config.getReplication(), MAP_TYPE_REFERENCE)) .asScala() .toMap(Predef.conforms()); final File file = new File(resource.toURI()); final Registry registry = Registry.fromDirectory(file); final Migrator migrator = new CassandraMigrator(registry); final Session session = _injector.getInstance(Key.get(Session.class, Names.named(dbName))); session.init(); migrator.initialize(session, config.getKeyspace(), new ReplicationOptions(replication)); session.execute("USE " + config.getKeyspace()); migrator.migrate(session, Option.<Date>none().asScala()); } catch (final URISyntaxException e) { LOGGER.error() .setMessage("Unable to run migrations") .addData("resource", resource) .setThrowable(e) .log(); } } else { LOGGER.info() .setMessage("Could not find migrations directory") .addData("directory", directory) .addData("database" , dbName) .log(); } } }
Source:
private void refreshSnapshotsInCluster(VDSGroup cluster) { if (!supportsGlusterSnapshotFeature(cluster)) { return; } final VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { return; } VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeSnapshotInfo, new GlusterVolumeSnapshotVDSParameters(upServer.getId(), null, cluster.getId())); try { addOrUpdateSnapshots(cluster.getId(), (ArrayList<GlusterVolumeSnapshotEntity>) returnValue.getReturnValue()); } catch (VdcBLLException e) { throw e; } }

Target:
private void refreshSnapshotsInCluster(VDSGroup cluster) { if (!supportsGlusterSnapshotFeature(cluster)) { return; } final VDS upServer = getClusterUtils().getRandomUpServer(cluster.getId()); if (upServer == null) { return; } try { List<GlusterVolumeSnapshotEntity> snapshotsList = (ArrayList<GlusterVolumeSnapshotEntity>) runVdsCommand(VDSCommandType.GetGlusterVolumeSnapshotInfo, new GlusterVolumeSnapshotVDSParameters(upServer.getId(), null, cluster.getId())).getReturnValue(); addOrUpdateSnapshots(cluster.getId(), snapshotsList); } catch (VdcBLLException e) { throw e; } }
Source:
public static CassandraKeyValueService createForTesting(CassandraKeyValueServiceConfig config) { try { MetricsManager metricsManager = MetricsManagers.createForTests(); Optional<CqlClientManager> cqlClientManager = config.cqlClientManager(); CassandraClientPool clientPool = CassandraClientPoolImpl.createImplForTest(metricsManager, config, CassandraClientPoolImpl.StartupChecks.RUN, new Blacklist(config)); Optional<CqlClient> cqlClient = config.servers() .visit((thriftServers, maybeCqlServers) -> maybeCqlServers .map(servers -> cqlClientManager .map(manager -> manager.createCqlClient(config, servers)) .orElseGet(() -> CqlClientImpl.create(config, servers)))); return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, cqlClient, CassandraMutationTimestampProviders.legacyModeForTestsOnly(), LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }

Target:
public static CassandraKeyValueService createForTesting(CassandraKeyValueServiceConfig config) { MetricsManager metricsManager = MetricsManagers.createForTests(); CassandraClientPool clientPool = CassandraClientPoolImpl.createImplForTest(metricsManager, config, CassandraClientPoolImpl.StartupChecks.RUN, new Blacklist(config)); return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, CassandraMutationTimestampProviders.legacyModeForTestsOnly(), LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }
Source:
public void actionUpdateAttributeTypes(AttributeType typeNew) { if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { if (attribute.equals(model.getSelectedAttribute())) { for (int k = 0; k < COMBO1_TYPES.length; k++) { if (typeNew == COMBO1_TYPES[k]) { cmbType.select(k); break; } } } actionAttributeTypeChanged(attribute, typeNew); } } } } }

Target:
public void actionUpdateAttributeTypes(AttributeType typeNew) { if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { if (attribute.equals(this.attribute)) { for (int k = 0; k < COMBO1_TYPES.length; k++) { if (typeNew == COMBO1_TYPES[k]) { cmbType.select(k); break; } } } actionAttributeTypeChanged(attribute, typeNew); } } } } }
Source:
public ProcessResult processFiles(Content dataSource, Path moduleOutputPath, AbstractFile iLeappFile) { try { List<String> iLeappTsvOutputFiles = findTsvFiles(moduleOutputPath); if (!iLeappTsvOutputFiles.isEmpty()) { processiLeappFiles(iLeappTsvOutputFiles, iLeappFile); } } catch (IOException | IngestModuleException ex) { logger.log(Level.SEVERE, String.format("Error trying to process iLeapp output files in directory %s. ", moduleOutputPath.toString()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }

Target:
public ProcessResult processFiles(Content dataSource, Path moduleOutputPath, AbstractFile iLeappFile) { try { List<String> iLeappTsvOutputFiles = findTsvFiles(moduleOutputPath); processiLeappFiles(iLeappTsvOutputFiles, iLeappFile); } catch (IOException | IngestModuleException ex) { logger.log(Level.SEVERE, String.format("Error trying to process iLeapp output files in directory %s. ", moduleOutputPath.toString()), ex); return ProcessResult.ERROR; } return ProcessResult.OK; }
Source:
public static ConsoleNote readFrom(DataInputStream in) throws IOException, ClassNotFoundException { try { byte[] preamble = new byte[PREAMBLE.length]; in.readFully(preamble); if (!Arrays.equals(preamble,PREAMBLE)) return null; DataInputStream decoded = new DataInputStream(new UnbufferedBase64InputStream(in)); int macSz = - decoded.readInt(); byte[] mac; int sz; if (macSz > 0) { mac = new byte[macSz]; decoded.readFully(mac); sz = decoded.readInt(); if (sz < 0) { throw new IOException("Corrupt stream"); } } else { mac = null; sz = - macSz; } byte[] buf = new byte[sz]; decoded.readFully(buf); byte[] postamble = new byte[POSTAMBLE.length]; in.readFully(postamble); if (!Arrays.equals(postamble,POSTAMBLE)) return null; if (!INSECURE) { if (mac == null) { throw new IOException("Refusing to deserialize unsigned note from an old log."); } else if (!MAC.checkMac(buf, mac)) { throw new IOException("MAC mismatch"); } } Jenkins jenkins = Jenkins.get(); try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(new ByteArrayInputStream(buf)), jenkins.pluginManager.uberClassLoader, ClassFilter.DEFAULT)) { return (ConsoleNote) ois.readObject(); } } catch (Error e) { throw new IOException(e); } }

Target:
public static ConsoleNote readFrom(DataInputStream in) throws IOException, ClassNotFoundException { try { byte[] preamble = new byte[PREAMBLE.length]; in.readFully(preamble); if (!Arrays.equals(preamble,PREAMBLE)) return null; DataInputStream decoded = new DataInputStream(new UnbufferedBase64InputStream(in)); int macSz = - decoded.readInt(); byte[] mac; int sz; if (macSz > 0) { mac = new byte[macSz]; decoded.readFully(mac); sz = decoded.readInt(); if (sz < 0) { throw new IOException("Corrupt stream"); } } else { mac = null; sz = - macSz; } byte[] buf = new byte[sz]; decoded.readFully(buf); byte[] postamble = new byte[POSTAMBLE.length]; in.readFully(postamble); if (!Arrays.equals(postamble,POSTAMBLE)) return null; if (!INSECURE) { if (mac == null) { throw new IOException("Refusing to deserialize unsigned note from an old log."); } else if (!MAC.checkMac(buf, mac)) { throw new IOException("MAC mismatch"); } } Jenkins jenkins = Jenkins.getInstanceOrNull(); try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(new ByteArrayInputStream(buf)), jenkins != null ? jenkins.pluginManager.uberClassLoader : ConsoleNote.class.getClassLoader(), ClassFilter.DEFAULT)) { return (ConsoleNote) ois.readObject(); } } catch (Error e) { throw new IOException(e); } }
Source:
public static URL url(String protocol, String host, int port, String path) throws IllegalArgumentException { if ((80 == port && "http".equals(protocol)) || (443 == port && "https".equals(protocol))) { port = -1; } try { return new URL(protocol, host, port, path); } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
public static URL url(String protocol, String host, int port, String path) throws IllegalArgumentException { if ((DEFAULT_HTTP_PORT == port && "http".equals(protocol)) || (DEFAULT_HTTPS_PORT == port && "https".equals(protocol))) { port = -1; } try { return new URL(protocol, host, port, path); } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
public static Topup retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, instanceURL(Topup.class, id), null, Topup.class, options); }

Target:
public static Topup retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, null, options); }
Source:
public @Nullable DataRadioStation getBestNameMatch(String query) { DataRadioStation bestStation = null; query = query.toUpperCase(); double smallesDistance = Double.MAX_VALUE; for (DataRadioStation station : listStations) { Cosine distMeasure = new Cosine(); double distance = distMeasure.distance(station.Name.toUpperCase(), query); if (distance < smallesDistance) { bestStation = station; smallesDistance = distance; } } return bestStation; }

Target:
public @Nullable DataRadioStation getBestNameMatch(String query) { DataRadioStation bestStation = null; query = query.toUpperCase(); double smallesDistance = Double.MAX_VALUE; Cosine distMeasure = new Cosine(); for (DataRadioStation station : listStations) { double distance = distMeasure.distance(station.Name.toUpperCase(), query); if (distance < smallesDistance) { bestStation = station; smallesDistance = distance; } } return bestStation; }
Source:
public static int calculateBlockSizeInBytes(long breakerLimit, int shardsUsedOnNode) { int blockSize = Math.min((int) (breakerLimit * BREAKER_LIMIT_PERCENTAGE), MAX_BLOCK_SIZE_IN_BYTES); return Math.max(100, blockSize / Math.max(shardsUsedOnNode, 1)); }

Target:
public static int calculateBlockSizeInBytes(long breakerLimit, int shardsUsedOnNode) { int blockSize = Math.min((int) (breakerLimit * BREAKER_LIMIT_PERCENTAGE), MAX_BLOCK_SIZE_IN_BYTES); return blockSize / Math.max(shardsUsedOnNode, 1); }
Source:
public String[] transform(final InputRow inputRow) { String subtractedString = inputRow.getValue(baseColumn); for (final InputColumn<?> inputColumn : substringColumns) { if (inputColumn.getDataType() == List.class) { final List<?> list = (List) inputRow.getValue(inputColumn); for (final Object element : list) { subtractedString = subtract(subtractedString, element); } } else { subtractedString = subtract(subtractedString, inputRow.getValue(inputColumn)); } } return new String[] { subtractedString }; }

Target:
public String[] transform(final InputRow inputRow) { String subtractedString = inputRow.getValue(baseColumn); for (final InputColumn<?> inputColumn : substringColumns) { final Object value = inputRow.getValue(inputColumn); if (value instanceof List) { for (final Object element : (List<?>) value) { subtractedString = subtract(subtractedString, element); } } else { subtractedString = subtract(subtractedString, value); } } return new String[] { subtractedString }; }
Source:
public Builder setIdentity(PrivateKey privateKey, Certificate[] certificateChain, CertificateType... certificateTypes) { if (privateKey == null) { throw new NullPointerException("The private key must not be null"); } else if (certificateChain == null) { throw new NullPointerException("The certificate chain must not be null"); } else if (certificateChain.length < 1) { throw new IllegalArgumentException("The certificate chain must not be empty"); } else { config.privateKey = privateKey; config.certChain = toX509Certificates(certificateChain); config.publicKey = config.certChain[0].getPublicKey(); if (certificateTypes == null || certificateTypes.length == 0) { config.identityCertificateTypes = new ArrayList<>(1); config.identityCertificateTypes.add(CertificateType.X_509); } else { config.identityCertificateTypes = Arrays.asList(certificateTypes); if (!config.identityCertificateTypes.contains(CertificateType.X_509)) { config.certChain = null; } } return this; } }

Target:
public Builder setIdentity(PrivateKey privateKey, Certificate[] certificateChain, CertificateType... certificateTypes) { if (certificateTypes == null) { return setIdentity(privateKey, certificateChain, (List<CertificateType>) null); } else { return setIdentity(privateKey, certificateChain, Arrays.asList(certificateTypes)); } }
Source:
protected void readExternalData(byte protoVer, ObjectInput in) throws IOException { int len = in.readInt(); keys = new String[len]; valBytesArray = new byte[len][]; for (int i = 0; i < len; i++) { keys[i] = U.readString(in); valBytesArray[i] = U.readByteArray(in); } }

Target:
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException { int len = in.readInt(); keys = new String[len]; valBytesArr = new byte[len][]; for (int i = 0; i < len; i++) { keys[i] = U.readString(in); valBytesArr[i] = U.readByteArray(in); } }
Source:
void close() throws Exception { final ErrorHandler errorHandler = mock(ErrorHandler.class); final CountedErrorHandler countedErrorHandler = mock(CountedErrorHandler.class); final MediaDriver driver = mock(MediaDriver.class); when(driver.context()).thenReturn(new MediaDriver.Context().errorHandler(errorHandler)); final AssertionError driverException = new AssertionError("driver"); throwOnClose(driver, driverException); final Archive archive = mock(Archive.class); when(archive.context()).thenReturn(new Archive.Context().countedErrorHandler(countedErrorHandler)); final ArithmeticException archiveException = new ArithmeticException("archive"); throwOnClose(archive, archiveException); final ClusterBackup clusterBackup = mock(ClusterBackup.class); final BatchUpdateException clusterBackupException = new BatchUpdateException(); throwOnClose(clusterBackup, clusterBackupException); final ClusterBackupMediaDriver clusterBackupMediaDriver = new ClusterBackupMediaDriver(driver, archive, clusterBackup); final AssertionError ex = assertThrows(AssertionError.class, clusterBackupMediaDriver::close); assertSame(driverException, ex); final InOrder inOrder = inOrder(errorHandler, countedErrorHandler); inOrder.verify(countedErrorHandler).onError(clusterBackupException); inOrder.verify(errorHandler).onError(archiveException); inOrder.verifyNoMoreInteractions(); }

Target:
void close() throws Exception { final ErrorHandler errorHandler = mock(ErrorHandler.class); final CountedErrorHandler countedErrorHandler = mock(CountedErrorHandler.class); final MediaDriver driver = mock(MediaDriver.class); when(driver.context()).thenReturn(new MediaDriver.Context().errorHandler(errorHandler)); final AssertionError driverException = new AssertionError("driver"); throwOnClose(driver, driverException); final Archive archive = mock(Archive.class); when(archive.context()).thenReturn(new Archive.Context().countedErrorHandler(countedErrorHandler)); final ArithmeticException archiveException = new ArithmeticException("archive"); throwOnClose(archive, archiveException); final ClusterBackup clusterBackup = mock(ClusterBackup.class); final IllegalStateException clusterBackupException = new IllegalStateException(); throwOnClose(clusterBackup, clusterBackupException); final ClusterBackupMediaDriver clusterBackupMediaDriver = new ClusterBackupMediaDriver(driver, archive, clusterBackup); final AssertionError ex = assertThrows(AssertionError.class, clusterBackupMediaDriver::close); assertSame(driverException, ex); final InOrder inOrder = inOrder(errorHandler, countedErrorHandler); inOrder.verify(countedErrorHandler).onError(clusterBackupException); inOrder.verify(errorHandler).onError(archiveException); inOrder.verifyNoMoreInteractions(); }
Source:
public static <V extends Persistable & Versionable> PaxosStateLog<V> createWithMigration( PaxosStorageParameters params, Persistable.Hydrator<V> hydrator, LegacyOperationMarkers legacyOperationMarkers, OptionalLong migrateFrom) { String logDirectory = params.fileBasedLogDirectory() .orElseThrow(() -> new SafeIllegalStateException("We currently need to have file-based storage")); NamespaceAndUseCase namespaceUseCase = params.namespaceAndUseCase(); PaxosStateLogMigrator.MigrationContext<V> migrationContext = ImmutableMigrationContext.<V>builder() .sourceLog(new PaxosStateLogImpl<>(logDirectory)) .destinationLog(SqlitePaxosStateLog.create(namespaceUseCase, params.sqliteDataSource())) .hydrator(hydrator) .migrationState(SqlitePaxosStateLogMigrationState.create(namespaceUseCase, params.sqliteDataSource())) .migrateFrom(migrateFrom) .build(); Instant start = Instant.now(); log.info("Starting migration for namespace and use case {}.", SafeArg.of("namespaceAndUseCase", params.namespaceAndUseCase())); long cutoff = PaxosStateLogMigrator.migrateAndReturnCutoff(migrationContext); log.info("Migration for namespace and use case took {}.", SafeArg.of("namespaceAndUseCase", params.namespaceAndUseCase()), SafeArg.of("duration", Duration.between(start, Instant.now()))); SplittingParameters<V> splittingParameters = ImmutableSplittingParameters.<V>builder() .legacyLog(migrationContext.sourceLog()) .currentLog(migrationContext.destinationLog()) .cutoffInclusive(cutoff) .legacyOperationMarkers(legacyOperationMarkers) .build(); return SplittingPaxosStateLog.create(splittingParameters); }

Target:
public static <V extends Persistable & Versionable> PaxosStateLog<V> createWithMigration( PaxosStorageParameters params, Persistable.Hydrator<V> hydrator, LegacyOperationMarkers legacyOperationMarkers, OptionalLong migrateFrom) { String logDirectory = params.fileBasedLogDirectory() .orElseThrow(() -> new SafeIllegalStateException("We currently need to have file-based storage")); NamespaceAndUseCase namespaceUseCase = params.namespaceAndUseCase(); PaxosStateLogMigrator.MigrationContext<V> migrationContext = ImmutableMigrationContext.<V>builder() .sourceLog(PaxosStateLogImpl.createFileBacked(logDirectory)) .destinationLog(SqlitePaxosStateLog.create(namespaceUseCase, params.sqliteDataSource())) .hydrator(hydrator) .migrationState(SqlitePaxosStateLogMigrationState.create(namespaceUseCase, params.sqliteDataSource())) .migrateFrom(migrateFrom) .build(); log.info("Starting migration for namespace and use case if migration has not run before.", SafeArg.of("namespaceAndUseCase", params.namespaceAndUseCase())); long cutoff = PaxosStateLogMigrator.migrateAndReturnCutoff(migrationContext); SplittingParameters<V> splittingParameters = ImmutableSplittingParameters.<V>builder() .legacyLog(migrationContext.sourceLog()) .currentLog(migrationContext.destinationLog()) .cutoffInclusive(cutoff) .legacyOperationMarkers(legacyOperationMarkers) .build(); return SplittingPaxosStateLog.create(splittingParameters); }
Source:
public void testDecompressionSkip() { EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false, ALWAYS_SKIP)); byte[] payload = new byte[300]; random.nextBytes(payload); assertTrue(encoderChannel.writeOutbound(Unpooled.wrappedBuffer(payload))); ByteBuf compressedPayload = encoderChannel.readOutbound(); BinaryWebSocketFrame compressedBinaryFrame = new BinaryWebSocketFrame( true, WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedPayload); assertTrue(decoderChannel.writeInbound(compressedBinaryFrame)); BinaryWebSocketFrame inboundBinaryFrame = decoderChannel.readInbound(); assertNotNull(inboundBinaryFrame); assertNotNull(inboundBinaryFrame.content()); assertEquals(compressedPayload, inboundBinaryFrame.content()); assertEquals(5, inboundBinaryFrame.rsv()); assertTrue(inboundBinaryFrame.release()); assertTrue(encoderChannel.finish()); assertFalse(decoderChannel.finish()); }

Target:
public void testDecompressionSkip() { EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false, ALWAYS_SKIP)); byte[] payload = new byte[300]; random.nextBytes(payload); assertTrue(encoderChannel.writeOutbound(Unpooled.wrappedBuffer(payload))); ByteBuf compressedPayload = encoderChannel.readOutbound(); BinaryWebSocketFrame compressedBinaryFrame = new BinaryWebSocketFrame( true, WebSocketExtension.RSV1 | WebSocketExtension.RSV3, compressedPayload); assertTrue(decoderChannel.writeInbound(compressedBinaryFrame)); BinaryWebSocketFrame inboundBinaryFrame = decoderChannel.readInbound(); assertNotNull(inboundBinaryFrame); assertNotNull(inboundBinaryFrame.content()); assertEquals(compressedPayload, inboundBinaryFrame.content()); assertEquals(5, inboundBinaryFrame.rsv()); assertTrue(inboundBinaryFrame.release()); assertTrue(encoderChannel.finishAndReleaseAll()); assertFalse(decoderChannel.finish()); }
Source:
public RebalanceException(String message) { super(message); }

Target:
public RebalanceException(String message) { super(message, null, false, false); }
Source:
public String getFromExpression(ConversionContext conversionContext) { throw new IllegalStateException( "Not supported." ); }

Target:
public String getFromExpression(ConversionContext conversionContext) { return bigDecimal( conversionContext ) + ".valueOf( <SOURCE> )"; }
Source:
public ImmutableComputableGraph setValue(@Nonnull final String nodeKey, @Nonnull final Duplicable newValue) throws IllegalArgumentException, UnsupportedOperationException { assertNodeExists(Utils.nonNull(nodeKey, "The key of the node can not be null.")); CacheNode node = nodesMap.get(nodeKey); if (!node.isExternallyMutable()) { throw new UnsupportedOperationException("Can not explicitly set the value of a non-primitive cache node."); } final Map<String, CacheNode> updatedNodesMap = new HashMap<>(); updatedNodesMap.put(nodeKey, node.duplicateWithUpdatedValue(newValue)); final ImmutableComputableGraph out = duplicateWithUpdatedNodes( addDuplicateOfOutdatedDescendents(nodeKey, updatedNodesMap)); if (cacheAutoUpdate) { Map<String, Duplicable> accumulatedValues = out.accumulateEvaluationsForDepthSortedNodeList( cgs.getEvalStrategyByMutatedNode(nodeKey), true); return out.updateCachesFromAccumulatedValues(accumulatedValues); } else { return out; } }

Target:
public ImmutableComputableGraph setValue(@Nonnull final String nodeKey, @Nonnull final Duplicable newValue) throws IllegalArgumentException, UnsupportedOperationException { assertNodeExists(nodeKey); CacheNode node = nodesMap.get(nodeKey); if (!node.isExternallyComputable()) { throw new UnsupportedOperationException("Can not explicitly set the value of a non-primitive cache node."); } final Map<String, CacheNode> updatedNodesMap = new HashMap<>(); updatedNodesMap.put(nodeKey, node.duplicateWithUpdatedValue(newValue)); final ImmutableComputableGraph out = duplicateWithUpdatedNodes( addDuplicateOfOutdatedDescendents(nodeKey, updatedNodesMap)); if (cacheAutoUpdate) { Map<String, Duplicable> accumulatedValues = out.evaluateInTopologicalOrder( cgs.getTopologicalOrderForNodeMutation(nodeKey)); return out.updateCachesFromAccumulatedValues(accumulatedValues); } else { return out; } }
Source:
public URLDownload(URL source) { this.source = source; this.addHeader("User-Agent", URLDownload.USER_AGENT); if (source.toString().contains(Medra.API_URL)) { this.addHeader("Accept", Medra.CONTENT_TYPE_JSON); } }

Target:
public URLDownload(URL source) { this.source = source; this.addHeader("User-Agent", URLDownload.USER_AGENT); }
Source:
ListenableFuture<Void> setZoomPercentage(@FloatRange(from = 0f, to = 1f) float percentage) { synchronized (mActiveLock) { if (!mIsActive) { throw new IllegalStateException( "Camera is not active."); } float clampedPercentage = MathUtils.clamp(percentage, 0.0f, 1.0f); if (getMaxDigitalZoom() == MIN_ZOOM) { clampedPercentage = 0.0f; } float ratio = getRatioByPercentage(clampedPercentage); setLiveDataValue(mZoomPercentageLiveData, clampedPercentage); ListenableFuture<Void> result = setZoomRatioInternal(ratio, false); if (percentage > 1.0f || (percentage < 0f)) { synchronized (mCompleterLock) { mPendingZoomRatioCompleter = null; mPendingZoomCropRegion = null; } String outOfRangeDesc = "Requested zoomPercentage " + percentage + " is not within" + " valid range [0..1]"; result = Futures.immediateFailedFuture( new CameraControl.ArgumentOutOfRangeException(outOfRangeDesc)); Log.w(TAG, outOfRangeDesc); } return result; } }

Target:
ListenableFuture<Void> setZoomPercentage(@FloatRange(from = 0f, to = 1f) float percentage) { synchronized (mActiveLock) { if (!mIsActive) { return Futures.immediateFailedFuture( new OperationCanceledException("Camera is not active.")); } float clampedPercentage = MathUtils.clamp(percentage, 0.0f, 1.0f); if (getMaxDigitalZoom() == MIN_ZOOM) { clampedPercentage = 0.0f; } float ratio = getRatioByPercentage(clampedPercentage); setLiveDataValue(mZoomPercentageLiveData, clampedPercentage); ListenableFuture<Void> result = setZoomRatioInternal(ratio, false); if (percentage > 1.0f || (percentage < 0f)) { synchronized (mCompleterLock) { mPendingZoomRatioCompleter = null; mPendingZoomCropRegion = null; } String outOfRangeDesc = "Requested zoomPercentage " + percentage + " is not within" + " valid range [0..1]"; result = Futures.immediateFailedFuture( new CameraControl.ArgumentOutOfRangeException(outOfRangeDesc)); Log.w(TAG, outOfRangeDesc); } return result; } }
Source:
private static void deleteContestData(DSLContext ctx, long contestPK) { ctx.deleteFrom(CONTEST_TEAM_MEMBER) .where(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestPK)) .execute(); ctx.deleteFrom(CONTEST_TRANSLATION) .where(CONTEST_TRANSLATION.CONTEST_ID.eq(contestPK)) .execute(); ctx.deleteFrom(CONTEST_DISCUSSION) .where(CONTEST_DISCUSSION.CONTEST_ID.eq(contestPK)) .execute(); Long threadId = ctx.select(CONTEST.DISCUSSION_GROUP_ID) .from(CONTEST) .where(CONTEST.CONTEST_PK.eq(contestPK)) .fetchOne() .value1(); ctx.deleteFrom(COMMENT) .where(COMMENT.THREAD_ID.eq(threadId)) .execute(); ctx.deleteFrom(THREAD) .where(THREAD.THREAD_ID.eq(threadId)) .execute(); ctx.deleteFrom(ACTIVITY_SUBSCRIPTION) .where(ACTIVITY_SUBSCRIPTION.CLASS_NAME_ID.eq(ActivityEntryType.CONTEST.getPrimaryTypeId())) .and(ACTIVITY_SUBSCRIPTION.CLASS_PK.eq(contestPK)); ctx.deleteFrom(ACTIVITY_ENTRY) .where(ACTIVITY_ENTRY.PRIMARY_TYPE.eq(ActivityEntryType.CONTEST.getPrimaryTypeId())) .and(ACTIVITY_ENTRY.CLASS_PRIMARY_KEY.eq(contestPK)); }

Target:
private static void deleteContestData(DSLContext ctx, long contestPK) { ctx.deleteFrom(CONTEST_TEAM_MEMBER) .where(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestPK)) .execute(); ctx.deleteFrom(CONTEST_TRANSLATION) .where(CONTEST_TRANSLATION.CONTEST_ID.eq(contestPK)) .execute(); ctx.deleteFrom(CONTEST_DISCUSSION) .where(CONTEST_DISCUSSION.CONTEST_ID.eq(contestPK)) .execute(); Long threadId = ctx.select(CONTEST.DISCUSSION_GROUP_ID) .from(CONTEST) .where(CONTEST.CONTEST_PK.eq(contestPK)) .fetchOne() .into(Long.class); ThreadClientUtil.deleteThread(threadId); ActivitiesClientUtil.batchDelete(ActivityEntryType.CONTEST, Collections.singletonList(contestPK)); }