code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void setNotificationEvents(java.util.Collection<String> notificationEvents) {
if (notificationEvents == null) {
this.notificationEvents = null;
return;
}
this.notificationEvents = new com.amazonaws.internal.SdkInternalList<String>(notificationEvents);
} } | public class class_name {
public void setNotificationEvents(java.util.Collection<String> notificationEvents) {
if (notificationEvents == null) {
this.notificationEvents = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.notificationEvents = new com.amazonaws.internal.SdkInternalList<String>(notificationEvents);
} } |
public class class_name {
public static void waitForJobCompletion(
Bigquery bigquery, String projectId, JobReference jobReference, Progressable progressable)
throws IOException, InterruptedException {
Sleeper sleeper = Sleeper.DEFAULT;
BackOff pollBackOff =
new ExponentialBackOff.Builder()
.setMaxIntervalMillis(POLL_WAIT_INTERVAL_MAX_MILLIS)
.setInitialIntervalMillis(POLL_WAIT_INITIAL_MILLIS)
.setMaxElapsedTimeMillis(POLL_WAIT_MAX_ELAPSED_MILLIS)
.build();
// Get starting time.
long startTime = System.currentTimeMillis();
long elapsedTime = 0;
boolean notDone = true;
// While job is incomplete continue to poll.
while (notDone) {
BackOff operationBackOff = new ExponentialBackOff.Builder().build();
Get get =
bigquery
.jobs()
.get(projectId, jobReference.getJobId())
.setLocation(jobReference.getLocation());
Job pollJob =
ResilientOperation.retry(
ResilientOperation.getGoogleRequestCallable(get),
operationBackOff,
RetryDeterminer.RATE_LIMIT_ERRORS,
IOException.class,
sleeper);
elapsedTime = System.currentTimeMillis() - startTime;
logger.atFine().log(
"Job status (%s ms) %s: %s",
elapsedTime, jobReference.getJobId(), pollJob.getStatus().getState());
if (pollJob.getStatus().getState().equals("DONE")) {
notDone = false;
if (pollJob.getStatus().getErrorResult() != null) {
throw new IOException(
"Error during BigQuery job execution: " + pollJob.getStatus().getErrorResult());
}
} else {
long millisToWait = pollBackOff.nextBackOffMillis();
if (millisToWait == BackOff.STOP) {
throw new IOException(
String.format(
"Job %s failed to complete after %s millis.",
jobReference.getJobId(), elapsedTime));
}
// Pause execution for the configured duration before polling job status again.
Thread.sleep(millisToWait);
// Call progress to ensure task doesn't time out.
progressable.progress();
}
}
} } | public class class_name {
public static void waitForJobCompletion(
Bigquery bigquery, String projectId, JobReference jobReference, Progressable progressable)
throws IOException, InterruptedException {
Sleeper sleeper = Sleeper.DEFAULT;
BackOff pollBackOff =
new ExponentialBackOff.Builder()
.setMaxIntervalMillis(POLL_WAIT_INTERVAL_MAX_MILLIS)
.setInitialIntervalMillis(POLL_WAIT_INITIAL_MILLIS)
.setMaxElapsedTimeMillis(POLL_WAIT_MAX_ELAPSED_MILLIS)
.build();
// Get starting time.
long startTime = System.currentTimeMillis();
long elapsedTime = 0;
boolean notDone = true;
// While job is incomplete continue to poll.
while (notDone) {
BackOff operationBackOff = new ExponentialBackOff.Builder().build();
Get get =
bigquery
.jobs()
.get(projectId, jobReference.getJobId())
.setLocation(jobReference.getLocation());
Job pollJob =
ResilientOperation.retry(
ResilientOperation.getGoogleRequestCallable(get),
operationBackOff,
RetryDeterminer.RATE_LIMIT_ERRORS,
IOException.class,
sleeper);
elapsedTime = System.currentTimeMillis() - startTime;
logger.atFine().log(
"Job status (%s ms) %s: %s",
elapsedTime, jobReference.getJobId(), pollJob.getStatus().getState());
if (pollJob.getStatus().getState().equals("DONE")) {
notDone = false; // depends on control dependency: [if], data = [none]
if (pollJob.getStatus().getErrorResult() != null) {
throw new IOException(
"Error during BigQuery job execution: " + pollJob.getStatus().getErrorResult());
}
} else {
long millisToWait = pollBackOff.nextBackOffMillis();
if (millisToWait == BackOff.STOP) {
throw new IOException(
String.format(
"Job %s failed to complete after %s millis.",
jobReference.getJobId(), elapsedTime));
}
// Pause execution for the configured duration before polling job status again.
Thread.sleep(millisToWait); // depends on control dependency: [if], data = [none]
// Call progress to ensure task doesn't time out.
progressable.progress(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Bitmap onStackBlur(Bitmap original, int radius) {
Bitmap bitmap = checkSource(original, radius);
// Return this none blur
if (radius == 1) {
return bitmap;
}
//Jni BitMap Blur
nativeStackBlurBitmap(bitmap, radius);
return (bitmap);
} } | public class class_name {
public static Bitmap onStackBlur(Bitmap original, int radius) {
Bitmap bitmap = checkSource(original, radius);
// Return this none blur
if (radius == 1) {
return bitmap; // depends on control dependency: [if], data = [none]
}
//Jni BitMap Blur
nativeStackBlurBitmap(bitmap, radius);
return (bitmap);
} } |
public class class_name {
public void updateNoDraw() {
if (autoUpdate) {
long now = getTime();
long delta = now - lastUpdate;
if (firstUpdate) {
delta = 0;
firstUpdate = false;
}
lastUpdate = now;
nextFrame(delta);
}
} } | public class class_name {
public void updateNoDraw() {
if (autoUpdate) {
long now = getTime();
long delta = now - lastUpdate;
if (firstUpdate) {
delta = 0;
// depends on control dependency: [if], data = [none]
firstUpdate = false;
// depends on control dependency: [if], data = [none]
}
lastUpdate = now;
// depends on control dependency: [if], data = [none]
nextFrame(delta);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected boolean estimate( Quadrilateral_F64 cornersPixels ,
Quadrilateral_F64 cornersNorm ,
Se3_F64 foundFiducialToCamera ) {
// put it into a list to simplify algorithms
listObs.clear();
listObs.add( cornersPixels.a );
listObs.add( cornersPixels.b );
listObs.add( cornersPixels.c );
listObs.add( cornersPixels.d );
// convert observations into normalized image coordinates which P3P requires
points.get(0).observation.set(cornersNorm.a);
points.get(1).observation.set(cornersNorm.b);
points.get(2).observation.set(cornersNorm.c);
points.get(3).observation.set(cornersNorm.d);
// estimate pose using all permutations
bestError = Double.MAX_VALUE;
estimateP3P(0);
estimateP3P(1);
estimateP3P(2);
estimateP3P(3);
if( bestError == Double.MAX_VALUE )
return false;
// refine the best estimate
inputP3P.clear();
for( int i = 0; i < 4; i++ ) {
inputP3P.add( points.get(i) );
}
// got poor or horrible solution the first way, let's try it with EPNP
// and see if it does better
if( bestError > 2 ) {
if (epnp.process(inputP3P, foundEPNP)) {
if( foundEPNP.T.z > 0 ) {
double error = computeErrors(foundEPNP);
// System.out.println(" error EPNP = "+error);
if (error < bestError) {
bestPose.set(foundEPNP);
}
}
}
}
if( !refine.fitModel(inputP3P,bestPose,foundFiducialToCamera) ) {
// us the previous estimate instead
foundFiducialToCamera.set(bestPose);
return true;
}
return true;
} } | public class class_name {
protected boolean estimate( Quadrilateral_F64 cornersPixels ,
Quadrilateral_F64 cornersNorm ,
Se3_F64 foundFiducialToCamera ) {
// put it into a list to simplify algorithms
listObs.clear();
listObs.add( cornersPixels.a );
listObs.add( cornersPixels.b );
listObs.add( cornersPixels.c );
listObs.add( cornersPixels.d );
// convert observations into normalized image coordinates which P3P requires
points.get(0).observation.set(cornersNorm.a);
points.get(1).observation.set(cornersNorm.b);
points.get(2).observation.set(cornersNorm.c);
points.get(3).observation.set(cornersNorm.d);
// estimate pose using all permutations
bestError = Double.MAX_VALUE;
estimateP3P(0);
estimateP3P(1);
estimateP3P(2);
estimateP3P(3);
if( bestError == Double.MAX_VALUE )
return false;
// refine the best estimate
inputP3P.clear();
for( int i = 0; i < 4; i++ ) {
inputP3P.add( points.get(i) ); // depends on control dependency: [for], data = [i]
}
// got poor or horrible solution the first way, let's try it with EPNP
// and see if it does better
if( bestError > 2 ) {
if (epnp.process(inputP3P, foundEPNP)) {
if( foundEPNP.T.z > 0 ) {
double error = computeErrors(foundEPNP);
// System.out.println(" error EPNP = "+error);
if (error < bestError) {
bestPose.set(foundEPNP); // depends on control dependency: [if], data = [none]
}
}
}
}
if( !refine.fitModel(inputP3P,bestPose,foundFiducialToCamera) ) {
// us the previous estimate instead
foundFiducialToCamera.set(bestPose); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private static String readArrayProperty(String ref, TypeDef source, Property property) {
TypeRef typeRef = property.getTypeRef();
if (typeRef instanceof ClassRef) {
//TODO: This needs further breakdown, to cover edge cases.
return readObjectArrayProperty(ref, source, property);
}
if (typeRef instanceof PrimitiveRef) {
return readPrimitiveArrayProperty(ref, source, property);
}
throw new IllegalStateException("Property should be either an object or a primitive.");
} } | public class class_name {
private static String readArrayProperty(String ref, TypeDef source, Property property) {
TypeRef typeRef = property.getTypeRef();
if (typeRef instanceof ClassRef) {
//TODO: This needs further breakdown, to cover edge cases.
return readObjectArrayProperty(ref, source, property); // depends on control dependency: [if], data = [none]
}
if (typeRef instanceof PrimitiveRef) {
return readPrimitiveArrayProperty(ref, source, property); // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Property should be either an object or a primitive.");
} } |
public class class_name {
public static String qsub(String input) {
final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
cmdLine.addArgument(input);
final OutputStream out = new ByteArrayOutputStream();
final OutputStream err = new ByteArrayOutputStream();
DefaultExecuteResultHandler resultHandler;
try {
resultHandler = execute(cmdLine, null, out, err);
resultHandler.waitFor(DEFAULT_TIMEOUT);
} catch (ExecuteException e) {
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
} catch (IOException e) {
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
} catch (InterruptedException e) {
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
}
final int exitValue = resultHandler.getExitValue();
LOGGER.info("qsub exit value: " + exitValue);
LOGGER.fine("qsub output: " + out.toString());
if (exitValue != 0)
throw new PBSException("Failed to submit job script " + input + ". Error output: " + err.toString());
String jobId = out.toString();
return jobId.trim();
} } | public class class_name {
public static String qsub(String input) {
final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
cmdLine.addArgument(input);
final OutputStream out = new ByteArrayOutputStream();
final OutputStream err = new ByteArrayOutputStream();
DefaultExecuteResultHandler resultHandler;
try {
resultHandler = execute(cmdLine, null, out, err); // depends on control dependency: [try], data = [none]
resultHandler.waitFor(DEFAULT_TIMEOUT); // depends on control dependency: [try], data = [none]
} catch (ExecuteException e) {
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
} catch (InterruptedException e) { // depends on control dependency: [catch], data = [none]
throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
final int exitValue = resultHandler.getExitValue();
LOGGER.info("qsub exit value: " + exitValue);
LOGGER.fine("qsub output: " + out.toString());
if (exitValue != 0)
throw new PBSException("Failed to submit job script " + input + ". Error output: " + err.toString());
String jobId = out.toString();
return jobId.trim();
} } |
public class class_name {
public void register() {
try {
objectName = consObjectName(domain, type, keysString);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(this, objectName);
} catch (Exception e) {
objectName = null;
throw new RuntimeException(e);
}
} } | public class class_name {
public void register() {
try {
objectName = consObjectName(domain, type, keysString);
// depends on control dependency: [try], data = [none]
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(this, objectName);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
objectName = null;
throw new RuntimeException(e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
public T validator(String ... validatorNames) {
Assert.notNull(applicationContext, "Citrus application context is not initialized!");
for (String validatorName : validatorNames) {
getAction().addValidator(applicationContext.getBean(validatorName, MessageValidator.class));
}
return self;
} } | public class class_name {
@SuppressWarnings("unchecked")
public T validator(String ... validatorNames) {
Assert.notNull(applicationContext, "Citrus application context is not initialized!");
for (String validatorName : validatorNames) {
getAction().addValidator(applicationContext.getBean(validatorName, MessageValidator.class)); // depends on control dependency: [for], data = [validatorName]
}
return self;
} } |
public class class_name {
private Lock createLock(boolean writer) {
final int pid = getPID();
final String baseLock;
if (!writer) {
baseLock = READER_LOCK_PREFIX + pid + LOCK_EXTENSION;
} else {
baseLock = WRITER_LOCK_PREFIX + pid + LOCK_EXTENSION;
}
int i = 0;
while (locks.containsKey(baseLock + (++i))) {
// no logic needed
}
final String lockName = baseLock + i;
final Lock lock = new Lock(lockName);
final File lockFile = new File(lockPath, lockName);
try {
if (!lockFile.createNewFile()) {
throw new IllegalStateException("could not create lock");
}
} catch (IOException e) {
throw new IllegalStateException("could not create lock", e);
}
locks.put(lockName, lock);
return lock;
} } | public class class_name {
private Lock createLock(boolean writer) {
final int pid = getPID();
final String baseLock;
if (!writer) {
baseLock = READER_LOCK_PREFIX + pid + LOCK_EXTENSION; // depends on control dependency: [if], data = [none]
} else {
baseLock = WRITER_LOCK_PREFIX + pid + LOCK_EXTENSION; // depends on control dependency: [if], data = [none]
}
int i = 0;
while (locks.containsKey(baseLock + (++i))) {
// no logic needed
}
final String lockName = baseLock + i;
final Lock lock = new Lock(lockName);
final File lockFile = new File(lockPath, lockName);
try {
if (!lockFile.createNewFile()) {
throw new IllegalStateException("could not create lock");
}
} catch (IOException e) {
throw new IllegalStateException("could not create lock", e);
} // depends on control dependency: [catch], data = [none]
locks.put(lockName, lock);
return lock;
} } |
public class class_name {
private void initializePresets() {
if (gobblinPresets == null) {
synchronized (GobblinHadoopJob.class) {
if (gobblinPresets == null) {
gobblinPresets = Maps.newHashMap();
String gobblinPresetDirName = getSysProps()
.getString(GobblinConstants.GOBBLIN_PRESET_DIR_KEY);
File gobblinPresetDir = new File(gobblinPresetDirName);
File[] presetFiles = gobblinPresetDir.listFiles();
if (presetFiles == null) {
return;
}
File commonPropertiesFile = new File(gobblinPresetDir,
GOBBLIN_PRESET_COMMON_PROPERTIES_FILE_NAME);
if (!commonPropertiesFile.exists()) {
throw new IllegalStateException("Gobbline preset common properties file is missing "
+ commonPropertiesFile.getAbsolutePath());
}
for (File f : presetFiles) {
if (GOBBLIN_PRESET_COMMON_PROPERTIES_FILE_NAME
.equals(f.getName())) { //Don't load common one itself.
continue;
}
if (f.isFile()) {
Properties prop = new Properties();
try (InputStream commonIs = new BufferedInputStream(
new FileInputStream(commonPropertiesFile));
InputStream presetIs = new BufferedInputStream(new FileInputStream(f))) {
prop.load(commonIs);
prop.load(presetIs);
String presetName = f.getName().substring(0,
f.getName().lastIndexOf('.')); //remove extension from the file name
gobblinPresets.put(GobblinPresets.fromName(presetName), prop);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
} } | public class class_name {
private void initializePresets() {
if (gobblinPresets == null) {
synchronized (GobblinHadoopJob.class) { // depends on control dependency: [if], data = [none]
if (gobblinPresets == null) {
gobblinPresets = Maps.newHashMap(); // depends on control dependency: [if], data = [none]
String gobblinPresetDirName = getSysProps()
.getString(GobblinConstants.GOBBLIN_PRESET_DIR_KEY);
File gobblinPresetDir = new File(gobblinPresetDirName);
File[] presetFiles = gobblinPresetDir.listFiles();
if (presetFiles == null) {
return; // depends on control dependency: [if], data = [none]
}
File commonPropertiesFile = new File(gobblinPresetDir,
GOBBLIN_PRESET_COMMON_PROPERTIES_FILE_NAME);
if (!commonPropertiesFile.exists()) {
throw new IllegalStateException("Gobbline preset common properties file is missing "
+ commonPropertiesFile.getAbsolutePath());
}
for (File f : presetFiles) {
if (GOBBLIN_PRESET_COMMON_PROPERTIES_FILE_NAME
.equals(f.getName())) { //Don't load common one itself.
continue;
}
if (f.isFile()) {
Properties prop = new Properties();
try (InputStream commonIs = new BufferedInputStream(
new FileInputStream(commonPropertiesFile));
InputStream presetIs = new BufferedInputStream(new FileInputStream(f))) {
prop.load(commonIs);
prop.load(presetIs); // depends on control dependency: [if], data = [none]
String presetName = f.getName().substring(0,
f.getName().lastIndexOf('.')); //remove extension from the file name
gobblinPresets.put(GobblinPresets.fromName(presetName), prop); // depends on control dependency: [if], data = [none]
} catch (IOException e) { // depends on control dependency: [for], data = [none]
throw new RuntimeException(e);
}
}
}
}
}
}
} } |
public class class_name {
private String addRemChars(String pstrSrc)
{
int intLen = 2;
int intPos = 0;
int intPrev = 0;
String strLeft = null;
String strRight = null;
if (pstrSrc == null) return null;
while (intPos >= 0)
{
intLen = 2;
intPos = pstrSrc.indexOf("\r\n", intPrev);
if (intPos < 0)
{
intLen = 1;
intPos = pstrSrc.indexOf("\n", intPrev);
if (intPos < 0) intPos = pstrSrc.indexOf("\r", intPrev);
}
if (intPos == 0)
{
pstrSrc = ";\r\n" + pstrSrc.substring(intPos + intLen);
intPrev = intPos + intLen + 1;
}
else if (intPos > 0)
{
strLeft = pstrSrc.substring(0, intPos);
strRight = pstrSrc.substring(intPos + intLen);
if (strRight == null)
pstrSrc = strLeft;
else if (strRight.length() == 0)
pstrSrc = strLeft;
else
pstrSrc = strLeft + "\r\n;" + strRight;
intPrev = intPos + intLen + 1;
}
}
if (!pstrSrc.substring(0, 1).equals(";"))
pstrSrc = ";" + pstrSrc;
pstrSrc = pstrSrc + "\r\n";
return pstrSrc;
} } | public class class_name {
private String addRemChars(String pstrSrc)
{
int intLen = 2;
int intPos = 0;
int intPrev = 0;
String strLeft = null;
String strRight = null;
if (pstrSrc == null) return null;
while (intPos >= 0)
{
intLen = 2;
// depends on control dependency: [while], data = [none]
intPos = pstrSrc.indexOf("\r\n", intPrev);
// depends on control dependency: [while], data = [none]
if (intPos < 0)
{
intLen = 1;
// depends on control dependency: [if], data = [none]
intPos = pstrSrc.indexOf("\n", intPrev);
// depends on control dependency: [if], data = [none]
if (intPos < 0) intPos = pstrSrc.indexOf("\r", intPrev);
}
if (intPos == 0)
{
pstrSrc = ";\r\n" + pstrSrc.substring(intPos + intLen);
// depends on control dependency: [if], data = [(intPos]
intPrev = intPos + intLen + 1;
// depends on control dependency: [if], data = [none]
}
else if (intPos > 0)
{
strLeft = pstrSrc.substring(0, intPos);
// depends on control dependency: [if], data = [none]
strRight = pstrSrc.substring(intPos + intLen);
// depends on control dependency: [if], data = [(intPos]
if (strRight == null)
pstrSrc = strLeft;
else if (strRight.length() == 0)
pstrSrc = strLeft;
else
pstrSrc = strLeft + "\r\n;" + strRight;
// depends on control dependency: [if], data = [none]
intPrev = intPos + intLen + 1;
// depends on control dependency: [if], data = [none]
}
}
if (!pstrSrc.substring(0, 1).equals(";"))
pstrSrc = ";" + pstrSrc;
pstrSrc = pstrSrc + "\r\n";
return pstrSrc;
} } |
public class class_name {
public int addSoundtrack(OggAudioHeaders audio) {
if (w == null) {
throw new IllegalStateException("Not in write mode");
}
// If it doesn't have a sid yet, get it one
OggPacketWriter aw = null;
if (audio.getSid() == -1) {
aw = ogg.getPacketWriter();
// TODO How to tell the OggAudioHeaders the new SID?
} else {
aw = ogg.getPacketWriter(audio.getSid());
}
int audioSid = aw.getSid();
// If we have a skeleton, tell it about the new stream
if (skeleton != null) {
SkeletonFisbone bone = skeleton.addBoneForStream(audioSid);
bone.setContentType(audio.getType().mimetype);
// TODO Populate the rest of the bone as best we can
}
// Record the new audio stream
soundtracks.put(audioSid, (OggAudioStreamHeaders)audio);
soundtrackWriters.put((OggAudioStreamHeaders)audio, aw);
// Report the sid
return audioSid;
} } | public class class_name {
public int addSoundtrack(OggAudioHeaders audio) {
if (w == null) {
throw new IllegalStateException("Not in write mode");
}
// If it doesn't have a sid yet, get it one
OggPacketWriter aw = null;
if (audio.getSid() == -1) {
aw = ogg.getPacketWriter(); // depends on control dependency: [if], data = [none]
// TODO How to tell the OggAudioHeaders the new SID?
} else {
aw = ogg.getPacketWriter(audio.getSid()); // depends on control dependency: [if], data = [(audio.getSid()]
}
int audioSid = aw.getSid();
// If we have a skeleton, tell it about the new stream
if (skeleton != null) {
SkeletonFisbone bone = skeleton.addBoneForStream(audioSid);
bone.setContentType(audio.getType().mimetype); // depends on control dependency: [if], data = [none]
// TODO Populate the rest of the bone as best we can
}
// Record the new audio stream
soundtracks.put(audioSid, (OggAudioStreamHeaders)audio);
soundtrackWriters.put((OggAudioStreamHeaders)audio, aw);
// Report the sid
return audioSid;
} } |
public class class_name {
public void createMaxArtifactDetailsTable() {
maxArtifactDetailsTable = createArtifactDetailsTable();
maxArtifactDetailsTable.setId(UIComponentIdProvider.UPLOAD_ARTIFACT_DETAILS_TABLE_MAX);
maxArtifactDetailsTable.setContainerDataSource(artifactDetailsTable.getContainerDataSource());
addGeneratedColumn(maxArtifactDetailsTable);
if (!readOnly) {
addGeneratedColumnButton(maxArtifactDetailsTable);
}
setTableColumnDetails(maxArtifactDetailsTable);
} } | public class class_name {
public void createMaxArtifactDetailsTable() {
maxArtifactDetailsTable = createArtifactDetailsTable();
maxArtifactDetailsTable.setId(UIComponentIdProvider.UPLOAD_ARTIFACT_DETAILS_TABLE_MAX);
maxArtifactDetailsTable.setContainerDataSource(artifactDetailsTable.getContainerDataSource());
addGeneratedColumn(maxArtifactDetailsTable);
if (!readOnly) {
addGeneratedColumnButton(maxArtifactDetailsTable); // depends on control dependency: [if], data = [none]
}
setTableColumnDetails(maxArtifactDetailsTable);
} } |
public class class_name {
@Override
public void run()
{
/* Wait for connections... */
while (true)
{
// Accept requests from clients.
try
{
clientSocket = serverSocket.accept();
/* Create a process for the communication and start it */
final AbstractClientHandler clientHandler = newClientHandler(clientSocket);
final Thread thread = new Thread(clientHandler);
thread.start();
}
catch (final IOException e)
{
/*
* Log the error of the server if IO fails. Something bad has happened
*/
logger.error("Could not accept " + e);
}
}
} } | public class class_name {
@Override
public void run()
{
/* Wait for connections... */
while (true)
{
// Accept requests from clients.
try
{
clientSocket = serverSocket.accept(); // depends on control dependency: [try], data = [none]
/* Create a process for the communication and start it */
final AbstractClientHandler clientHandler = newClientHandler(clientSocket);
final Thread thread = new Thread(clientHandler);
thread.start(); // depends on control dependency: [try], data = [none]
}
catch (final IOException e)
{
/*
* Log the error of the server if IO fails. Something bad has happened
*/
logger.error("Could not accept " + e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public Map<String, String> getImageAttributes(Map<String, String> attributes) {
for (Entry<Attribute, I_CmsFormWidget> entry : m_fields.entrySet()) {
String val = entry.getValue().getFormValueAsString();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(val)) {
continue;
}
attributes.put(entry.getKey().name(), val);
// put the same value in 'alt' and 'title' attribute
if (entry.getKey() == Attribute.alt) {
attributes.put(Attribute.title.name(), val);
}
}
return attributes;
} } | public class class_name {
public Map<String, String> getImageAttributes(Map<String, String> attributes) {
for (Entry<Attribute, I_CmsFormWidget> entry : m_fields.entrySet()) {
String val = entry.getValue().getFormValueAsString();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(val)) {
continue;
}
attributes.put(entry.getKey().name(), val); // depends on control dependency: [for], data = [entry]
// put the same value in 'alt' and 'title' attribute
if (entry.getKey() == Attribute.alt) {
attributes.put(Attribute.title.name(), val); // depends on control dependency: [if], data = [none]
}
}
return attributes;
} } |
public class class_name {
public static SecureRandom getSecureRandom() {
// we use double checked locking to minimize synchronization
// works because we use a volatile reference
SecureRandom r = secureRandom;
if (r == null) {
synchronized (LOCK) {
r = secureRandom;
if (r == null) {
r = new SecureRandom();
secureRandom = r;
}
}
}
return r;
} } | public class class_name {
public static SecureRandom getSecureRandom() {
// we use double checked locking to minimize synchronization
// works because we use a volatile reference
SecureRandom r = secureRandom;
if (r == null) {
synchronized (LOCK) { // depends on control dependency: [if], data = [none]
r = secureRandom;
if (r == null) {
r = new SecureRandom(); // depends on control dependency: [if], data = [none]
secureRandom = r; // depends on control dependency: [if], data = [none]
}
}
}
return r;
} } |
public class class_name {
protected Object getContextAttribute(String name)
{
if (ServletHandler.__J_S_CONTEXT_TEMPDIR.equals(name))
{
// Initialize temporary directory
Object t = getHttpContext().getAttribute(ServletHandler.__J_S_CONTEXT_TEMPDIR);
if (t instanceof File)
return (File)t;
return getHttpContext().getTempDirectory();
}
if (_attributes.containsKey(name))
return _attributes.get(name);
return getHttpContext().getAttribute(name);
} } | public class class_name {
protected Object getContextAttribute(String name)
{
if (ServletHandler.__J_S_CONTEXT_TEMPDIR.equals(name))
{
// Initialize temporary directory
Object t = getHttpContext().getAttribute(ServletHandler.__J_S_CONTEXT_TEMPDIR);
if (t instanceof File)
return (File)t;
return getHttpContext().getTempDirectory(); // depends on control dependency: [if], data = [none]
}
if (_attributes.containsKey(name))
return _attributes.get(name);
return getHttpContext().getAttribute(name);
} } |
public class class_name {
String
rrToString() {
InetAddress addr;
try {
addr = InetAddress.getByAddress(null, address);
} catch (UnknownHostException e) {
return null;
}
if (addr.getAddress().length == 4) {
// Deal with Java's broken handling of mapped IPv4 addresses.
StringBuffer sb = new StringBuffer("0:0:0:0:0:ffff:");
int high = ((address[12] & 0xFF) << 8) + (address[13] & 0xFF);
int low = ((address[14] & 0xFF) << 8) + (address[15] & 0xFF);
sb.append(Integer.toHexString(high));
sb.append(':');
sb.append(Integer.toHexString(low));
return sb.toString();
}
return addr.getHostAddress();
} } | public class class_name {
String
rrToString() {
InetAddress addr;
try {
addr = InetAddress.getByAddress(null, address); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
return null;
} // depends on control dependency: [catch], data = [none]
if (addr.getAddress().length == 4) {
// Deal with Java's broken handling of mapped IPv4 addresses.
StringBuffer sb = new StringBuffer("0:0:0:0:0:ffff:");
int high = ((address[12] & 0xFF) << 8) + (address[13] & 0xFF);
int low = ((address[14] & 0xFF) << 8) + (address[15] & 0xFF);
sb.append(Integer.toHexString(high)); // depends on control dependency: [if], data = [none]
sb.append(':'); // depends on control dependency: [if], data = [none]
sb.append(Integer.toHexString(low)); // depends on control dependency: [if], data = [none]
return sb.toString(); // depends on control dependency: [if], data = [none]
}
return addr.getHostAddress();
} } |
public class class_name {
public String encode(Iterable<? extends Cookie> cookies) {
if (cookies == null) {
throw new NullPointerException("cookies");
}
Iterator<? extends Cookie> cookiesIt = cookies.iterator();
if (!cookiesIt.hasNext()) {
return null;
}
StringBuilder buf = new StringBuilder();
while (cookiesIt.hasNext()) {
Cookie c = cookiesIt.next();
if (c == null) {
break;
}
encode(buf, c);
}
return stripTrailingSeparatorOrNull(buf);
} } | public class class_name {
public String encode(Iterable<? extends Cookie> cookies) {
if (cookies == null) {
throw new NullPointerException("cookies");
}
Iterator<? extends Cookie> cookiesIt = cookies.iterator();
if (!cookiesIt.hasNext()) {
return null; // depends on control dependency: [if], data = [none]
}
StringBuilder buf = new StringBuilder();
while (cookiesIt.hasNext()) {
Cookie c = cookiesIt.next();
if (c == null) {
break;
}
encode(buf, c); // depends on control dependency: [while], data = [none]
}
return stripTrailingSeparatorOrNull(buf);
} } |
public class class_name {
private void updateDomainAxisRange()
{
int count = dataSet.getSeries(0).getItemCount();
if (count < SHOW_FIXED_GENERATIONS)
{
domainAxis.setRangeWithMargins(0, SHOW_FIXED_GENERATIONS);
}
else if (allDataButton.isSelected())
{
domainAxis.setRangeWithMargins(0, Math.max(SHOW_FIXED_GENERATIONS, count));
}
else
{
domainAxis.setRangeWithMargins(count - SHOW_FIXED_GENERATIONS, count);
}
} } | public class class_name {
private void updateDomainAxisRange()
{
int count = dataSet.getSeries(0).getItemCount();
if (count < SHOW_FIXED_GENERATIONS)
{
domainAxis.setRangeWithMargins(0, SHOW_FIXED_GENERATIONS); // depends on control dependency: [if], data = [SHOW_FIXED_GENERATIONS)]
}
else if (allDataButton.isSelected())
{
domainAxis.setRangeWithMargins(0, Math.max(SHOW_FIXED_GENERATIONS, count)); // depends on control dependency: [if], data = [none]
}
else
{
domainAxis.setRangeWithMargins(count - SHOW_FIXED_GENERATIONS, count); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void completeCommittingTransaction(TransactionId transactionId) {
// Change ownership of the transaction to the local node and then commit it.
completeTransaction(
transactionId,
TransactionState.COMMITTING,
info -> new TransactionInfo(localMemberId, TransactionState.COMMITTING, info.participants),
info -> info.state == TransactionState.COMMITTING && info.coordinator.equals(localMemberId),
(id, transactional) -> transactional.commit(id))
.whenComplete((result, error) -> {
if (error != null) {
error = Throwables.getRootCause(error);
if (error instanceof TransactionException) {
LOGGER.warn("Failed to complete transaction", error);
} else {
LOGGER.warn("Failed to commit transaction " + transactionId);
}
}
});
} } | public class class_name {
private void completeCommittingTransaction(TransactionId transactionId) {
// Change ownership of the transaction to the local node and then commit it.
completeTransaction(
transactionId,
TransactionState.COMMITTING,
info -> new TransactionInfo(localMemberId, TransactionState.COMMITTING, info.participants),
info -> info.state == TransactionState.COMMITTING && info.coordinator.equals(localMemberId),
(id, transactional) -> transactional.commit(id))
.whenComplete((result, error) -> {
if (error != null) {
error = Throwables.getRootCause(error);
if (error instanceof TransactionException) {
LOGGER.warn("Failed to complete transaction", error); // depends on control dependency: [if], data = [none]
} else {
LOGGER.warn("Failed to commit transaction " + transactionId); // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
public boolean sendKeepAlive()
{
idleStrategy.reset();
int attempts = SEND_ATTEMPTS;
while (true)
{
final long result = publication.offer(keepaliveMsgBuffer, 0, keepaliveMsgBuffer.capacity(), null);
if (result > 0)
{
return true;
}
if (result == Publication.NOT_CONNECTED || result == Publication.CLOSED)
{
return false;
}
if (result == Publication.MAX_POSITION_EXCEEDED)
{
throw new ClusterException("unexpected publication state: " + result);
}
if (--attempts <= 0)
{
break;
}
idleStrategy.idle();
}
return false;
} } | public class class_name {
public boolean sendKeepAlive()
{
idleStrategy.reset();
int attempts = SEND_ATTEMPTS;
while (true)
{
final long result = publication.offer(keepaliveMsgBuffer, 0, keepaliveMsgBuffer.capacity(), null);
if (result > 0)
{
return true; // depends on control dependency: [if], data = [none]
}
if (result == Publication.NOT_CONNECTED || result == Publication.CLOSED)
{
return false; // depends on control dependency: [if], data = [none]
}
if (result == Publication.MAX_POSITION_EXCEEDED)
{
throw new ClusterException("unexpected publication state: " + result);
}
if (--attempts <= 0)
{
break;
}
idleStrategy.idle(); // depends on control dependency: [while], data = [none]
}
return false;
} } |
public class class_name {
@Override
public IResource newResource(URI uri) {
final String sourceMethod = "newResource"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{uri});
}
Mutable<URI> uriRef = new MutableObject<URI>(uri);
IResourceFactory factory = getResourceFactory(uriRef);
IResource result;
if (factory != null) {
result = factory.newResource(uriRef.getValue());
} else {
result = new NotFoundResource(uriRef.getValue());
}
result = runConverters(result);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, result);
}
return result;
} } | public class class_name {
@Override
public IResource newResource(URI uri) {
final String sourceMethod = "newResource"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{uri});
// depends on control dependency: [if], data = [none]
}
Mutable<URI> uriRef = new MutableObject<URI>(uri);
IResourceFactory factory = getResourceFactory(uriRef);
IResource result;
if (factory != null) {
result = factory.newResource(uriRef.getValue());
// depends on control dependency: [if], data = [none]
} else {
result = new NotFoundResource(uriRef.getValue());
// depends on control dependency: [if], data = [none]
}
result = runConverters(result);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, result);
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public static Channel forProcess(String name, ExecutorService execService, InputStream in, OutputStream out, OutputStream header, final Proc proc) throws IOException {
ChannelBuilder cb = new ChannelBuilder(name,execService) {
@Override
public Channel build(CommandTransport transport) throws IOException {
return new Channel(this,transport) {
/**
* Kill the process when the channel is severed.
*/
@Override
public synchronized void terminate(IOException e) {
super.terminate(e);
try {
proc.kill();
} catch (IOException x) {
// we are already in the error recovery mode, so just record it and move on
LOGGER.log(Level.INFO, "Failed to terminate the severed connection",x);
} catch (InterruptedException x) {
// process the interrupt later
Thread.currentThread().interrupt();
}
}
@Override
public synchronized void join() throws InterruptedException {
super.join();
// wait for the child process to complete, too
try {
proc.join();
} catch (IOException e) {
throw new IOError(e);
}
}
};
}
};
cb.withHeaderStream(header);
for (ChannelConfigurator cc : ChannelConfigurator.all()) {
cc.onChannelBuilding(cb,null); // TODO: what to pass as a context?
}
return cb.build(in,out);
} } | public class class_name {
public static Channel forProcess(String name, ExecutorService execService, InputStream in, OutputStream out, OutputStream header, final Proc proc) throws IOException {
ChannelBuilder cb = new ChannelBuilder(name,execService) {
@Override
public Channel build(CommandTransport transport) throws IOException {
return new Channel(this,transport) {
/**
* Kill the process when the channel is severed.
*/
@Override
public synchronized void terminate(IOException e) {
super.terminate(e);
try {
proc.kill(); // depends on control dependency: [try], data = [none]
} catch (IOException x) {
// we are already in the error recovery mode, so just record it and move on
LOGGER.log(Level.INFO, "Failed to terminate the severed connection",x);
} catch (InterruptedException x) { // depends on control dependency: [catch], data = [none]
// process the interrupt later
Thread.currentThread().interrupt();
} // depends on control dependency: [catch], data = [none]
}
@Override
public synchronized void join() throws InterruptedException {
super.join();
// wait for the child process to complete, too
try {
proc.join(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new IOError(e);
} // depends on control dependency: [catch], data = [none]
}
};
}
};
cb.withHeaderStream(header);
for (ChannelConfigurator cc : ChannelConfigurator.all()) {
cc.onChannelBuilding(cb,null); // TODO: what to pass as a context?
}
return cb.build(in,out);
} } |
public class class_name {
public static void reconfigureMonitor(MonitoringPluginConfig config) {
for (GenericMonitor monitor : MONITORS) {
if (monitor.config == config) {
monitor.stop();
monitor.setup();
}
}
} } | public class class_name {
public static void reconfigureMonitor(MonitoringPluginConfig config) {
for (GenericMonitor monitor : MONITORS) {
if (monitor.config == config) {
monitor.stop(); // depends on control dependency: [if], data = [none]
monitor.setup(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private Provider doLoadProvider() {
return AccessController.doPrivileged(new PrivilegedAction<Provider>() {
public Provider run() {
// if (debug != null) {
// debug.println("Loading provider: " + ProviderConfig.this);
// }
try {
// First try with the boot classloader.
return initProvider(className, Object.class.getClassLoader());
} catch (Exception e1) {
// If that fails, try with the system classloader.
try {
return initProvider(className, ClassLoader.getSystemClassLoader());
} catch (Exception e) {
Throwable t;
if (e instanceof InvocationTargetException) {
t = ((InvocationTargetException)e).getCause();
} else {
t = e;
}
// if (debug != null) {
// debug.println("Error loading provider " + ProviderConfig.this);
// t.printStackTrace();
// }
// provider indicates fatal error, pass through exception
if (t instanceof ProviderException) {
throw (ProviderException)t;
}
// provider indicates that loading should not be retried
if (t instanceof UnsupportedOperationException) {
disableLoad();
}
return null;
}
}
}
});
} } | public class class_name {
private Provider doLoadProvider() {
return AccessController.doPrivileged(new PrivilegedAction<Provider>() {
public Provider run() {
// if (debug != null) {
// debug.println("Loading provider: " + ProviderConfig.this);
// }
try {
// First try with the boot classloader.
return initProvider(className, Object.class.getClassLoader()); // depends on control dependency: [try], data = [none]
} catch (Exception e1) {
// If that fails, try with the system classloader.
try {
return initProvider(className, ClassLoader.getSystemClassLoader()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
Throwable t;
if (e instanceof InvocationTargetException) {
t = ((InvocationTargetException)e).getCause(); // depends on control dependency: [if], data = [none]
} else {
t = e; // depends on control dependency: [if], data = [none]
}
// if (debug != null) {
// debug.println("Error loading provider " + ProviderConfig.this);
// t.printStackTrace();
// }
// provider indicates fatal error, pass through exception
if (t instanceof ProviderException) {
throw (ProviderException)t;
}
// provider indicates that loading should not be retried
if (t instanceof UnsupportedOperationException) {
disableLoad(); // depends on control dependency: [if], data = [none]
}
return null;
} // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
protected boolean trigger(final ServletRequest pRequest) {
// If triggerParams not set, assume always trigger
if (triggerParams == null) {
return true;
}
// Trigger only for certain request parameters
for (String triggerParam : triggerParams) {
if (pRequest.getParameter(triggerParam) != null) {
return true;
}
}
// Didn't trigger
return false;
} } | public class class_name {
protected boolean trigger(final ServletRequest pRequest) {
// If triggerParams not set, assume always trigger
if (triggerParams == null) {
return true;
// depends on control dependency: [if], data = [none]
}
// Trigger only for certain request parameters
for (String triggerParam : triggerParams) {
if (pRequest.getParameter(triggerParam) != null) {
return true;
// depends on control dependency: [if], data = [none]
}
}
// Didn't trigger
return false;
} } |
public class class_name {
public void marshall(BatchDeleteImportDataRequest batchDeleteImportDataRequest, ProtocolMarshaller protocolMarshaller) {
if (batchDeleteImportDataRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchDeleteImportDataRequest.getImportTaskIds(), IMPORTTASKIDS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchDeleteImportDataRequest batchDeleteImportDataRequest, ProtocolMarshaller protocolMarshaller) {
if (batchDeleteImportDataRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchDeleteImportDataRequest.getImportTaskIds(), IMPORTTASKIDS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String getRealm(String sUrl) throws IOException, ModuleException
{
AuthorizationHandler ah = AuthorizationInfo.getAuthHandler();
try
{
URL url = new URL(sUrl);
HTTPConnection connection = new HTTPConnection(url);
connection.removeModule(CookieModule.class);
AuthorizationInfo.setAuthHandler(null);
HTTPResponse resp = connection.Get(url.getFile());
String authHeader = resp.getHeader("WWW-Authenticate");
if (authHeader == null)
{
return null;
}
String realm = authHeader.split("=")[1];
realm = realm.substring(1, realm.length() - 1);
return realm;
}
finally
{
AuthorizationInfo.setAuthHandler(ah);
}
} } | public class class_name {
private String getRealm(String sUrl) throws IOException, ModuleException
{
AuthorizationHandler ah = AuthorizationInfo.getAuthHandler();
try
{
URL url = new URL(sUrl);
HTTPConnection connection = new HTTPConnection(url);
connection.removeModule(CookieModule.class);
AuthorizationInfo.setAuthHandler(null);
HTTPResponse resp = connection.Get(url.getFile());
String authHeader = resp.getHeader("WWW-Authenticate");
if (authHeader == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
String realm = authHeader.split("=")[1];
realm = realm.substring(1, realm.length() - 1);
return realm;
}
finally
{
AuthorizationInfo.setAuthHandler(ah);
}
} } |
public class class_name {
private static void wait(Object lock, int timeout)
{
try {
lock.wait(timeout);
}
catch(InterruptedException unused) {
Thread.currentThread().interrupt();
}
} } | public class class_name {
private static void wait(Object lock, int timeout)
{
try {
lock.wait(timeout);
// depends on control dependency: [try], data = [none]
}
catch(InterruptedException unused) {
Thread.currentThread().interrupt();
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String decode(Geometry geometry, float scale) {
if (geometry == null) {
return "";
}
if (geometry instanceof LinearRing) {
return decodeLinearRing((LinearRing) geometry);
} else if (geometry instanceof LineString) {
return decodeLineString((LineString) geometry);
} else if (geometry instanceof Polygon) {
return decodePolygon((Polygon) geometry);
} else if (geometry instanceof MultiPolygon) {
return decodeMultiPolygon((MultiPolygon) geometry);
} else if (geometry instanceof MultiLineString) {
return decodeMultiLineString((MultiLineString) geometry);
}
return "";
} } | public class class_name {
public static String decode(Geometry geometry, float scale) {
if (geometry == null) {
return ""; // depends on control dependency: [if], data = [none]
}
if (geometry instanceof LinearRing) {
return decodeLinearRing((LinearRing) geometry); // depends on control dependency: [if], data = [none]
} else if (geometry instanceof LineString) {
return decodeLineString((LineString) geometry); // depends on control dependency: [if], data = [none]
} else if (geometry instanceof Polygon) {
return decodePolygon((Polygon) geometry); // depends on control dependency: [if], data = [none]
} else if (geometry instanceof MultiPolygon) {
return decodeMultiPolygon((MultiPolygon) geometry); // depends on control dependency: [if], data = [none]
} else if (geometry instanceof MultiLineString) {
return decodeMultiLineString((MultiLineString) geometry); // depends on control dependency: [if], data = [none]
}
return "";
} } |
public class class_name {
public static String channelToString(SocketAddress local1, SocketAddress remote1) {
try {
InetSocketAddress local = (InetSocketAddress) local1;
InetSocketAddress remote = (InetSocketAddress) remote1;
return toAddressString(local) + " -> " + toAddressString(remote);
} catch (Exception e) {
return local1 + "->" + remote1;
}
} } | public class class_name {
public static String channelToString(SocketAddress local1, SocketAddress remote1) {
try {
InetSocketAddress local = (InetSocketAddress) local1;
InetSocketAddress remote = (InetSocketAddress) remote1;
return toAddressString(local) + " -> " + toAddressString(remote); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return local1 + "->" + remote1;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public YearMonthDay withChronologyRetainFields(Chronology newChronology) {
newChronology = DateTimeUtils.getChronology(newChronology);
newChronology = newChronology.withUTC();
if (newChronology == getChronology()) {
return this;
} else {
YearMonthDay newYearMonthDay = new YearMonthDay(this, newChronology);
newChronology.validate(newYearMonthDay, getValues());
return newYearMonthDay;
}
} } | public class class_name {
public YearMonthDay withChronologyRetainFields(Chronology newChronology) {
newChronology = DateTimeUtils.getChronology(newChronology);
newChronology = newChronology.withUTC();
if (newChronology == getChronology()) {
return this; // depends on control dependency: [if], data = [none]
} else {
YearMonthDay newYearMonthDay = new YearMonthDay(this, newChronology);
newChronology.validate(newYearMonthDay, getValues()); // depends on control dependency: [if], data = [none]
return newYearMonthDay; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected boolean writeFile(QualifiedName name, ExtraLanguageAppendable appendable, IExtraLanguageGeneratorContext context) {
final ExtraLanguageAppendable fileAppendable = createAppendable(null, context);
generateFileHeader(name, fileAppendable, context);
final ImportManager importManager = appendable.getImportManager();
if (importManager != null && !importManager.getImports().isEmpty()) {
for (final String imported : importManager.getImports()) {
final QualifiedName qn = getQualifiedNameConverter().toQualifiedName(imported);
generateImportStatement(qn, fileAppendable, context);
}
fileAppendable.newLine();
}
fileAppendable.append(appendable.getContent());
final String content = fileAppendable.getContent();
if (!Strings.isEmpty(content)) {
final String fileName = toFilename(name, FILENAME_SEPARATOR);
final String outputConfiguration = getOutputConfigurationName();
if (Strings.isEmpty(outputConfiguration)) {
context.getFileSystemAccess().generateFile(fileName, content);
} else {
context.getFileSystemAccess().generateFile(fileName, outputConfiguration, content);
}
return true;
}
return false;
} } | public class class_name {
protected boolean writeFile(QualifiedName name, ExtraLanguageAppendable appendable, IExtraLanguageGeneratorContext context) {
final ExtraLanguageAppendable fileAppendable = createAppendable(null, context);
generateFileHeader(name, fileAppendable, context);
final ImportManager importManager = appendable.getImportManager();
if (importManager != null && !importManager.getImports().isEmpty()) {
for (final String imported : importManager.getImports()) {
final QualifiedName qn = getQualifiedNameConverter().toQualifiedName(imported);
generateImportStatement(qn, fileAppendable, context); // depends on control dependency: [for], data = [none]
}
fileAppendable.newLine(); // depends on control dependency: [if], data = [none]
}
fileAppendable.append(appendable.getContent());
final String content = fileAppendable.getContent();
if (!Strings.isEmpty(content)) {
final String fileName = toFilename(name, FILENAME_SEPARATOR);
final String outputConfiguration = getOutputConfigurationName();
if (Strings.isEmpty(outputConfiguration)) {
context.getFileSystemAccess().generateFile(fileName, content); // depends on control dependency: [if], data = [none]
} else {
context.getFileSystemAccess().generateFile(fileName, outputConfiguration, content); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public Map<String, List<String>> unapplyAll(Iterable<String> values)
{
if (values == null) {
return Collections.emptyMap();
}
Map<String, List<String>> map = new HashMap<>();
for (String value : values) {
map.put(value, unapply(value));
}
return map;
} } | public class class_name {
public Map<String, List<String>> unapplyAll(Iterable<String> values)
{
if (values == null) {
return Collections.emptyMap(); // depends on control dependency: [if], data = [none]
}
Map<String, List<String>> map = new HashMap<>();
for (String value : values) {
map.put(value, unapply(value)); // depends on control dependency: [for], data = [value]
}
return map;
} } |
public class class_name {
public static Object createObject(String string) {
if (StringUtils.isNullOrBlank(string)) {
return null;
}
if (ReflectionUtils.isClassName(string)) {
try {
Class<?> clazz = ReflectionUtils.getClassForNameQuietly(string);
if (ReflectionUtils.isSingleton(clazz)) {
return ReflectionUtils.getSingletonFor(clazz);
} else {
return BeanUtils.getBean(clazz);
}
} catch (Exception e) {
return null;
}
}
int index = string.lastIndexOf(".");
if (index != -1) {
String field = string.substring(string.lastIndexOf('.') + 1);
String cStr = string.substring(0, string.lastIndexOf('.'));
if (ReflectionUtils.isClassName(cStr)) {
Class<?> clazz = ReflectionUtils.getClassForNameQuietly(cStr);
if (Reflect.onClass(clazz).containsField(field)) {
try {
return Reflect.onClass(clazz).get(field).get();
} catch (ReflectionException e) {
//ignore this;
}
}
if (Reflect.onClass(clazz).containsMethod(field)) {
try {
return Reflect.onClass(clazz).invoke(field).get();
} catch (ReflectionException e) {
//ignore the error
}
}
try {
return Reflect.onClass(clazz).create(field).get();
} catch (ReflectionException e) {
return null;
}
}
}
return null;
} } | public class class_name {
public static Object createObject(String string) {
if (StringUtils.isNullOrBlank(string)) {
return null; // depends on control dependency: [if], data = [none]
}
if (ReflectionUtils.isClassName(string)) {
try {
Class<?> clazz = ReflectionUtils.getClassForNameQuietly(string);
if (ReflectionUtils.isSingleton(clazz)) {
return ReflectionUtils.getSingletonFor(clazz); // depends on control dependency: [if], data = [none]
} else {
return BeanUtils.getBean(clazz); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
return null;
} // depends on control dependency: [catch], data = [none]
}
int index = string.lastIndexOf(".");
if (index != -1) {
String field = string.substring(string.lastIndexOf('.') + 1);
String cStr = string.substring(0, string.lastIndexOf('.'));
if (ReflectionUtils.isClassName(cStr)) {
Class<?> clazz = ReflectionUtils.getClassForNameQuietly(cStr);
if (Reflect.onClass(clazz).containsField(field)) {
try {
return Reflect.onClass(clazz).get(field).get(); // depends on control dependency: [try], data = [none]
} catch (ReflectionException e) {
//ignore this;
} // depends on control dependency: [catch], data = [none]
}
if (Reflect.onClass(clazz).containsMethod(field)) {
try {
return Reflect.onClass(clazz).invoke(field).get(); // depends on control dependency: [try], data = [none]
} catch (ReflectionException e) {
//ignore the error
} // depends on control dependency: [catch], data = [none]
}
try {
return Reflect.onClass(clazz).create(field).get(); // depends on control dependency: [try], data = [none]
} catch (ReflectionException e) {
return null;
} // depends on control dependency: [catch], data = [none]
}
}
return null;
} } |
public class class_name {
public void setInjectionOptions(final InjectionOptions injectionOptions) {
if (injectionOptions == null && this.injectionOptions == null) {
return;
} else if (injectionOptions == null) {
removeChild(this.injectionOptions);
this.injectionOptions = null;
} else if (this.injectionOptions == null) {
this.injectionOptions = new KeyValueNode<InjectionOptions>(CommonConstants.CS_INLINE_INJECTION_TITLE, injectionOptions);
appendChild(this.injectionOptions, false);
} else {
this.injectionOptions.setValue(injectionOptions);
}
} } | public class class_name {
public void setInjectionOptions(final InjectionOptions injectionOptions) {
if (injectionOptions == null && this.injectionOptions == null) {
return; // depends on control dependency: [if], data = [none]
} else if (injectionOptions == null) {
removeChild(this.injectionOptions); // depends on control dependency: [if], data = [none]
this.injectionOptions = null; // depends on control dependency: [if], data = [none]
} else if (this.injectionOptions == null) {
this.injectionOptions = new KeyValueNode<InjectionOptions>(CommonConstants.CS_INLINE_INJECTION_TITLE, injectionOptions); // depends on control dependency: [if], data = [none]
appendChild(this.injectionOptions, false); // depends on control dependency: [if], data = [(this.injectionOptions]
} else {
this.injectionOptions.setValue(injectionOptions); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean hasInfos(){
if(this.messageHandlers.containsKey(E_MessageType.INFO)){
return (this.messageHandlers.get(E_MessageType.INFO).getCount()==0)?false:true;
}
return false;
} } | public class class_name {
public boolean hasInfos(){
if(this.messageHandlers.containsKey(E_MessageType.INFO)){
return (this.messageHandlers.get(E_MessageType.INFO).getCount()==0)?false:true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
protected int scoreServiceDocument(ODataRequestContext requestContext, MediaType requiredMediaType) {
if (isServiceDocument(requestContext.getUri())) {
int scoreByFormat = scoreByFormat(getFormatOption(requestContext.getUri()), requiredMediaType);
int scoreByMediaType = scoreByMediaType(requestContext.getRequest().getAccept(), requiredMediaType);
return max(scoreByFormat, scoreByMediaType);
} else {
return DEFAULT_SCORE;
}
} } | public class class_name {
protected int scoreServiceDocument(ODataRequestContext requestContext, MediaType requiredMediaType) {
if (isServiceDocument(requestContext.getUri())) {
int scoreByFormat = scoreByFormat(getFormatOption(requestContext.getUri()), requiredMediaType);
int scoreByMediaType = scoreByMediaType(requestContext.getRequest().getAccept(), requiredMediaType);
return max(scoreByFormat, scoreByMediaType); // depends on control dependency: [if], data = [none]
} else {
return DEFAULT_SCORE; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Interval withDurationBeforeEnd(ReadableDuration duration) {
long durationMillis = DateTimeUtils.getDurationMillis(duration);
if (durationMillis == toDurationMillis()) {
return this;
}
Chronology chrono = getChronology();
long endMillis = getEndMillis();
long startMillis = chrono.add(endMillis, durationMillis, -1);
return new Interval(startMillis, endMillis, chrono);
} } | public class class_name {
public Interval withDurationBeforeEnd(ReadableDuration duration) {
long durationMillis = DateTimeUtils.getDurationMillis(duration);
if (durationMillis == toDurationMillis()) {
return this; // depends on control dependency: [if], data = [none]
}
Chronology chrono = getChronology();
long endMillis = getEndMillis();
long startMillis = chrono.add(endMillis, durationMillis, -1);
return new Interval(startMillis, endMillis, chrono);
} } |
public class class_name {
public Injector openAnalysisJob(final FileObject file) {
final JaxbJobReader reader = new JaxbJobReader(_configuration);
try {
final AnalysisJobBuilder ajb = reader.create(file);
return openAnalysisJob(file, ajb);
} catch (final NoSuchComponentException e) {
final String message;
if (Version.EDITION_COMMUNITY.equals(Version.getEdition())) {
message = "<html><p>Failed to open job because of a missing component:</p><pre>" + e.getMessage()
+ "</pre><p>This may happen if the job requires a "
+ "<a href=\"https://www.quadient.com/products/quadient-datacleaner#get-started-today\">"
+ "Commercial Edition of DataCleaner</a>, or an extension that you do not have installed.</p>"
+ "</html>";
} else {
message = "<html>Failed to open job because of a missing component: " + e.getMessage() + "<br/><br/>"
+ "This may happen if the job requires an extension that you do not have installed.</html>";
}
WidgetUtils.showErrorMessage("Cannot open job", message);
return null;
} catch (final NoSuchDatastoreException e) {
if (_windowContext == null) {
// This can happen in case of single-datastore + job file
// bootstrapping of DC
throw e;
}
final AnalysisJobMetadata metadata = reader.readMetadata(file);
final int result = JOptionPane
.showConfirmDialog(null, e.getMessage() + "\n\nDo you wish to open this job as a template?",
"Error: " + e.getMessage(), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
final OpenAnalysisJobAsTemplateDialog dialog =
new OpenAnalysisJobAsTemplateDialog(_windowContext, _configuration, file, metadata,
Providers.of(this));
dialog.setVisible(true);
}
return null;
} catch (final ComponentConfigurationException e) {
final String message;
final Throwable cause = e.getCause();
if (cause != null) {
// check for causes of the mis-configuration. If there's a cause
// with a message, then show the message first and foremost
// (usually a validation error).
if (!Strings.isNullOrEmpty(cause.getMessage())) {
message = cause.getMessage();
} else {
message = e.getMessage();
}
} else {
message = e.getMessage();
}
WidgetUtils.showErrorMessage("Failed to validate job configuration", message, e);
return null;
} catch (final RuntimeException e) {
logger.error("Unexpected failure when opening job: {}", file, e);
throw e;
}
} } | public class class_name {
public Injector openAnalysisJob(final FileObject file) {
final JaxbJobReader reader = new JaxbJobReader(_configuration);
try {
final AnalysisJobBuilder ajb = reader.create(file);
return openAnalysisJob(file, ajb); // depends on control dependency: [try], data = [none]
} catch (final NoSuchComponentException e) {
final String message;
if (Version.EDITION_COMMUNITY.equals(Version.getEdition())) {
message = "<html><p>Failed to open job because of a missing component:</p><pre>" + e.getMessage() // depends on control dependency: [if], data = [none]
+ "</pre><p>This may happen if the job requires a " // depends on control dependency: [if], data = [none]
+ "<a href=\"https://www.quadient.com/products/quadient-datacleaner#get-started-today\">"
+ "Commercial Edition of DataCleaner</a>, or an extension that you do not have installed.</p>"
+ "</html>";
} else {
message = "<html>Failed to open job because of a missing component: " + e.getMessage() + "<br/><br/>" // depends on control dependency: [if], data = [none]
+ "This may happen if the job requires an extension that you do not have installed.</html>"; // depends on control dependency: [if], data = [none]
}
WidgetUtils.showErrorMessage("Cannot open job", message);
return null;
} catch (final NoSuchDatastoreException e) { // depends on control dependency: [catch], data = [none]
if (_windowContext == null) {
// This can happen in case of single-datastore + job file
// bootstrapping of DC
throw e;
}
final AnalysisJobMetadata metadata = reader.readMetadata(file);
final int result = JOptionPane
.showConfirmDialog(null, e.getMessage() + "\n\nDo you wish to open this job as a template?",
"Error: " + e.getMessage(), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
final OpenAnalysisJobAsTemplateDialog dialog =
new OpenAnalysisJobAsTemplateDialog(_windowContext, _configuration, file, metadata,
Providers.of(this));
dialog.setVisible(true); // depends on control dependency: [if], data = [none]
}
return null;
} catch (final ComponentConfigurationException e) { // depends on control dependency: [catch], data = [none]
final String message;
final Throwable cause = e.getCause();
if (cause != null) {
// check for causes of the mis-configuration. If there's a cause
// with a message, then show the message first and foremost
// (usually a validation error).
if (!Strings.isNullOrEmpty(cause.getMessage())) {
message = cause.getMessage(); // depends on control dependency: [if], data = [none]
} else {
message = e.getMessage(); // depends on control dependency: [if], data = [none]
}
} else {
message = e.getMessage(); // depends on control dependency: [if], data = [none]
}
WidgetUtils.showErrorMessage("Failed to validate job configuration", message, e);
return null;
} catch (final RuntimeException e) { // depends on control dependency: [catch], data = [none]
logger.error("Unexpected failure when opening job: {}", file, e);
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
String getName() {
String path = getPath();
if (path.isEmpty()) {
return getDatabaseName() + "/documents";
} else {
return getDatabaseName() + "/documents/" + getPath();
}
} } | public class class_name {
String getName() {
String path = getPath();
if (path.isEmpty()) {
return getDatabaseName() + "/documents"; // depends on control dependency: [if], data = [none]
} else {
return getDatabaseName() + "/documents/" + getPath(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addPossiblesFailuresComplex() {
Set<Scenario> scenarios = this.getScenarios();
for (Scenario s : scenarios) {
for (Class<? extends Failure> c : s.getPossibleFailures().keySet()) {
if (!this.getPossibleFailures().containsKey(c)) {
this.addPossibleFailure(c, s.getPossibleFailures().get(c));
} else {
List<Set<NetworkElement>> elements = this
.getPossibleFailures().get(c);
// elements.addAll(s.getPossibleFailures().get(c));
for (Set<NetworkElement> sne : s.getPossibleFailures().get(
c)) {
if (!elements.contains(sne))
elements.add(sne);
}
this.addPossibleFailure(c, elements);
}
}
}
} } | public class class_name {
public void addPossiblesFailuresComplex() {
Set<Scenario> scenarios = this.getScenarios();
for (Scenario s : scenarios) {
for (Class<? extends Failure> c : s.getPossibleFailures().keySet()) {
if (!this.getPossibleFailures().containsKey(c)) {
this.addPossibleFailure(c, s.getPossibleFailures().get(c)); // depends on control dependency: [if], data = [none]
} else {
List<Set<NetworkElement>> elements = this
.getPossibleFailures().get(c);
// elements.addAll(s.getPossibleFailures().get(c));
for (Set<NetworkElement> sne : s.getPossibleFailures().get(
c)) {
if (!elements.contains(sne))
elements.add(sne);
}
this.addPossibleFailure(c, elements); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private int newlacon(State begin, State end, int pos) {
if (lacons.size() == 0) {
// skip 0
lacons.add(null);
}
Subre sub = new Subre((char)0, 0, begin, end);
sub.subno = pos;
lacons.add(sub);
return lacons.size() - 1; // it's the index into the array, -1.
} } | public class class_name {
private int newlacon(State begin, State end, int pos) {
if (lacons.size() == 0) {
// skip 0
lacons.add(null); // depends on control dependency: [if], data = [none]
}
Subre sub = new Subre((char)0, 0, begin, end);
sub.subno = pos;
lacons.add(sub);
return lacons.size() - 1; // it's the index into the array, -1.
} } |
public class class_name {
public MetaData parse(ByteBuffer buffer, int blockLength) {
// We must wait for the all the bytes of the header block to arrive.
// If they are not all available, accumulate them.
// When all are available, decode them.
int accumulated = blockBuffer == null ? 0 : blockBuffer.position();
int remaining = blockLength - accumulated;
if (buffer.remaining() < remaining) {
if (blockBuffer == null) {
blockBuffer = ByteBuffer.allocate(blockLength);
BufferUtils.clearToFill(blockBuffer);
}
blockBuffer.put(buffer);
return null;
} else {
int limit = buffer.limit();
buffer.limit(buffer.position() + remaining);
ByteBuffer toDecode;
if (blockBuffer != null) {
blockBuffer.put(buffer);
BufferUtils.flipToFlush(blockBuffer, 0);
toDecode = blockBuffer;
} else {
toDecode = buffer;
}
try {
return hpackDecoder.decode(toDecode);
} catch (HpackException.StreamException x) {
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.streamFailure(headerParser.getStreamId(), ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block");
return STREAM_FAILURE;
} catch (HpackException.CompressionException x) {
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.connectionFailure(buffer, ErrorCode.COMPRESSION_ERROR.code, "invalid_hpack_block");
return SESSION_FAILURE;
} catch (HpackException.SessionException x) {
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block");
return SESSION_FAILURE;
} finally {
buffer.limit(limit);
if (blockBuffer != null) {
blockBuffer = null;
}
}
}
} } | public class class_name {
public MetaData parse(ByteBuffer buffer, int blockLength) {
// We must wait for the all the bytes of the header block to arrive.
// If they are not all available, accumulate them.
// When all are available, decode them.
int accumulated = blockBuffer == null ? 0 : blockBuffer.position();
int remaining = blockLength - accumulated;
if (buffer.remaining() < remaining) {
if (blockBuffer == null) {
blockBuffer = ByteBuffer.allocate(blockLength); // depends on control dependency: [if], data = [none]
BufferUtils.clearToFill(blockBuffer); // depends on control dependency: [if], data = [(blockBuffer]
}
blockBuffer.put(buffer); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
} else {
int limit = buffer.limit();
buffer.limit(buffer.position() + remaining); // depends on control dependency: [if], data = [remaining)]
ByteBuffer toDecode;
if (blockBuffer != null) {
blockBuffer.put(buffer); // depends on control dependency: [if], data = [none]
BufferUtils.flipToFlush(blockBuffer, 0); // depends on control dependency: [if], data = [(blockBuffer]
toDecode = blockBuffer; // depends on control dependency: [if], data = [none]
} else {
toDecode = buffer; // depends on control dependency: [if], data = [none]
}
try {
return hpackDecoder.decode(toDecode); // depends on control dependency: [try], data = [none]
} catch (HpackException.StreamException x) {
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.streamFailure(headerParser.getStreamId(), ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block");
return STREAM_FAILURE;
} catch (HpackException.CompressionException x) { // depends on control dependency: [catch], data = [none]
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.connectionFailure(buffer, ErrorCode.COMPRESSION_ERROR.code, "invalid_hpack_block");
return SESSION_FAILURE;
} catch (HpackException.SessionException x) { // depends on control dependency: [catch], data = [none]
if (LOG.isDebugEnabled())
LOG.debug("hpack exception", x);
notifier.connectionFailure(buffer, ErrorCode.PROTOCOL_ERROR.code, "invalid_hpack_block");
return SESSION_FAILURE;
} finally { // depends on control dependency: [catch], data = [none]
buffer.limit(limit);
if (blockBuffer != null) {
blockBuffer = null; // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public static String formatDisplayListTerminalString(List<TerminalString> displayList, int termHeight, int termWidth) {
if (displayList == null || displayList.size() < 1)
return "";
// make sure that termWidth is > 0
if (termWidth < 1)
termWidth = 80; // setting it to default
int maxLength = 0;
for (TerminalString completion : displayList)
if (completion.getCharacters().length() > maxLength)
maxLength = completion.getCharacters().length();
maxLength = maxLength + 2; // adding two spaces for better readability
int numColumns = termWidth / maxLength;
if (numColumns > displayList.size()) // we dont need more columns than items
numColumns = displayList.size();
if (numColumns < 1)
numColumns = 1;
int numRows = displayList.size() / numColumns;
// add a row if we cant display all the items
if (numRows * numColumns < displayList.size())
numRows++;
StringBuilder completionOutput = new StringBuilder();
if (numRows > 1) {
// create the completion listing
for (int i = 0; i < numRows; i++) {
for (int c = 0; c < numColumns; c++) {
int fetch = i + (c * numRows);
if (fetch < displayList.size()) {
if (c == numColumns - 1) { // No need to pad the right most column
completionOutput.append(displayList.get(i + (c * numRows)).toString());
} else {
completionOutput.append(padRight(maxLength
+ displayList.get(i + (c * numRows)).getANSILength(),
displayList.get(i + (c * numRows)).toString()));
}
} else {
break;
}
}
completionOutput.append(Config.getLineSeparator());
}
}
else {
for (TerminalString ts : displayList) {
completionOutput.append(ts.toString()).append(" ");
}
completionOutput.append(Config.getLineSeparator());
}
return completionOutput.toString();
} } | public class class_name {
public static String formatDisplayListTerminalString(List<TerminalString> displayList, int termHeight, int termWidth) {
if (displayList == null || displayList.size() < 1)
return "";
// make sure that termWidth is > 0
if (termWidth < 1)
termWidth = 80; // setting it to default
int maxLength = 0;
for (TerminalString completion : displayList)
if (completion.getCharacters().length() > maxLength)
maxLength = completion.getCharacters().length();
maxLength = maxLength + 2; // adding two spaces for better readability
int numColumns = termWidth / maxLength;
if (numColumns > displayList.size()) // we dont need more columns than items
numColumns = displayList.size();
if (numColumns < 1)
numColumns = 1;
int numRows = displayList.size() / numColumns;
// add a row if we cant display all the items
if (numRows * numColumns < displayList.size())
numRows++;
StringBuilder completionOutput = new StringBuilder();
if (numRows > 1) {
// create the completion listing
for (int i = 0; i < numRows; i++) {
for (int c = 0; c < numColumns; c++) {
int fetch = i + (c * numRows);
if (fetch < displayList.size()) {
if (c == numColumns - 1) { // No need to pad the right most column
completionOutput.append(displayList.get(i + (c * numRows)).toString()); // depends on control dependency: [if], data = [(c]
} else {
completionOutput.append(padRight(maxLength
+ displayList.get(i + (c * numRows)).getANSILength(),
displayList.get(i + (c * numRows)).toString())); // depends on control dependency: [if], data = [none]
}
} else {
break;
}
}
completionOutput.append(Config.getLineSeparator()); // depends on control dependency: [for], data = [none]
}
}
else {
for (TerminalString ts : displayList) {
completionOutput.append(ts.toString()).append(" "); // depends on control dependency: [for], data = [ts]
}
completionOutput.append(Config.getLineSeparator()); // depends on control dependency: [if], data = [none]
}
return completionOutput.toString();
} } |
public class class_name {
public Observable<ServiceResponse<GatewayRouteListResultInner>> beginGetLearnedRoutesWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2018-04-01";
return service.beginGetLearnedRoutes(resourceGroupName, virtualNetworkGatewayName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<GatewayRouteListResultInner>>>() {
@Override
public Observable<ServiceResponse<GatewayRouteListResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<GatewayRouteListResultInner> clientResponse = beginGetLearnedRoutesDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<GatewayRouteListResultInner>> beginGetLearnedRoutesWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2018-04-01";
return service.beginGetLearnedRoutes(resourceGroupName, virtualNetworkGatewayName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<GatewayRouteListResultInner>>>() {
@Override
public Observable<ServiceResponse<GatewayRouteListResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<GatewayRouteListResultInner> clientResponse = beginGetLearnedRoutesDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public void marshall(UpdateApnsChannelRequest updateApnsChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateApnsChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateApnsChannelRequest.getAPNSChannelRequest(), APNSCHANNELREQUEST_BINDING);
protocolMarshaller.marshall(updateApnsChannelRequest.getApplicationId(), APPLICATIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateApnsChannelRequest updateApnsChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateApnsChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateApnsChannelRequest.getAPNSChannelRequest(), APNSCHANNELREQUEST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateApnsChannelRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void initChildOf(APMSpanBuilder builder, Reference ref) {
APMSpan parent = (APMSpan) ref.getReferredTo();
if (parent.getNodeBuilder() != null) {
nodeBuilder = new NodeBuilder(parent.getNodeBuilder());
traceContext = parent.traceContext;
// As it is not possible to know if a tag has been set after span
// creation, we use this situation to check if the parent span
// has the 'transaction.name' specified, to set on the trace
// context. This is required in case a child span is used to invoke
// another service (and needs to propagate the transaction
// name).
if (parent.getTags().containsKey(Constants.PROP_TRANSACTION_NAME)
&& traceContext.getTransaction() == null) {
traceContext.setTransaction(
parent.getTags().get(Constants.PROP_TRANSACTION_NAME).toString());
}
}
processRemainingReferences(builder, ref);
} } | public class class_name {
protected void initChildOf(APMSpanBuilder builder, Reference ref) {
APMSpan parent = (APMSpan) ref.getReferredTo();
if (parent.getNodeBuilder() != null) {
nodeBuilder = new NodeBuilder(parent.getNodeBuilder()); // depends on control dependency: [if], data = [(parent.getNodeBuilder()]
traceContext = parent.traceContext; // depends on control dependency: [if], data = [none]
// As it is not possible to know if a tag has been set after span
// creation, we use this situation to check if the parent span
// has the 'transaction.name' specified, to set on the trace
// context. This is required in case a child span is used to invoke
// another service (and needs to propagate the transaction
// name).
if (parent.getTags().containsKey(Constants.PROP_TRANSACTION_NAME)
&& traceContext.getTransaction() == null) {
traceContext.setTransaction(
parent.getTags().get(Constants.PROP_TRANSACTION_NAME).toString()); // depends on control dependency: [if], data = [none]
}
}
processRemainingReferences(builder, ref);
} } |
public class class_name {
public static void depthTo3D(CameraPinholeBrown param , GrayU16 depth , FastQueue<Point3D_F64> cloud ) {
cloud.reset();
Point2Transform2_F64 p2n = LensDistortionFactory.narrow(param).undistort_F64(true,false);
Point2D_F64 n = new Point2D_F64();
for( int y = 0; y < depth.height; y++ ) {
int index = depth.startIndex + y*depth.stride;
for( int x = 0; x < depth.width; x++ ) {
int mm = depth.data[index++] & 0xFFFF;
// skip pixels with no depth information
if( mm == 0 )
continue;
// this could all be precomputed to speed it up
p2n.compute(x,y,n);
Point3D_F64 p = cloud.grow();
p.z = mm;
p.x = n.x*p.z;
p.y = n.y*p.z;
}
}
} } | public class class_name {
public static void depthTo3D(CameraPinholeBrown param , GrayU16 depth , FastQueue<Point3D_F64> cloud ) {
cloud.reset();
Point2Transform2_F64 p2n = LensDistortionFactory.narrow(param).undistort_F64(true,false);
Point2D_F64 n = new Point2D_F64();
for( int y = 0; y < depth.height; y++ ) {
int index = depth.startIndex + y*depth.stride;
for( int x = 0; x < depth.width; x++ ) {
int mm = depth.data[index++] & 0xFFFF;
// skip pixels with no depth information
if( mm == 0 )
continue;
// this could all be precomputed to speed it up
p2n.compute(x,y,n); // depends on control dependency: [for], data = [x]
Point3D_F64 p = cloud.grow();
p.z = mm; // depends on control dependency: [for], data = [none]
p.x = n.x*p.z; // depends on control dependency: [for], data = [x]
p.y = n.y*p.z; // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
private static void remainLongest(Collection<Emit> collectedEmits)
{
if (collectedEmits.size() < 2) return;
Map<Integer, Emit> emitMapStart = new TreeMap<Integer, Emit>();
for (Emit emit : collectedEmits)
{
Emit pre = emitMapStart.get(emit.getStart());
if (pre == null || pre.size() < emit.size())
{
emitMapStart.put(emit.getStart(), emit);
}
}
if (emitMapStart.size() < 2)
{
collectedEmits.clear();
collectedEmits.addAll(emitMapStart.values());
return;
}
Map<Integer, Emit> emitMapEnd = new TreeMap<Integer, Emit>();
for (Emit emit : emitMapStart.values())
{
Emit pre = emitMapEnd.get(emit.getEnd());
if (pre == null || pre.size() < emit.size())
{
emitMapEnd.put(emit.getEnd(), emit);
}
}
collectedEmits.clear();
collectedEmits.addAll(emitMapEnd.values());
} } | public class class_name {
private static void remainLongest(Collection<Emit> collectedEmits)
{
if (collectedEmits.size() < 2) return;
Map<Integer, Emit> emitMapStart = new TreeMap<Integer, Emit>();
for (Emit emit : collectedEmits)
{
Emit pre = emitMapStart.get(emit.getStart());
if (pre == null || pre.size() < emit.size())
{
emitMapStart.put(emit.getStart(), emit); // depends on control dependency: [if], data = [none]
}
}
if (emitMapStart.size() < 2)
{
collectedEmits.clear(); // depends on control dependency: [if], data = [none]
collectedEmits.addAll(emitMapStart.values()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Map<Integer, Emit> emitMapEnd = new TreeMap<Integer, Emit>();
for (Emit emit : emitMapStart.values())
{
Emit pre = emitMapEnd.get(emit.getEnd());
if (pre == null || pre.size() < emit.size())
{
emitMapEnd.put(emit.getEnd(), emit); // depends on control dependency: [if], data = [none]
}
}
collectedEmits.clear();
collectedEmits.addAll(emitMapEnd.values());
} } |
public class class_name {
public void setSubscribedWorkteams(java.util.Collection<SubscribedWorkteam> subscribedWorkteams) {
if (subscribedWorkteams == null) {
this.subscribedWorkteams = null;
return;
}
this.subscribedWorkteams = new java.util.ArrayList<SubscribedWorkteam>(subscribedWorkteams);
} } | public class class_name {
public void setSubscribedWorkteams(java.util.Collection<SubscribedWorkteam> subscribedWorkteams) {
if (subscribedWorkteams == null) {
this.subscribedWorkteams = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.subscribedWorkteams = new java.util.ArrayList<SubscribedWorkteam>(subscribedWorkteams);
} } |
public class class_name {
void updateSearchResults(boolean selectFirstMatch)
{
clearHighlights();
searchPanel.setMessage("");
String query = searchPanel.getQuery();
if (query.isEmpty())
{
handleMatch(null);
return;
}
String text = getDocumentText();
boolean ignoreCase = !searchPanel.isCaseSensitive();
List<Point> appearances =
JTextComponents.find(text, query, ignoreCase);
addHighlights(appearances, highlightColor);
int caretPosition = textComponent.getCaretPosition();
Point match = JTextComponents.findNext(
text, query, caretPosition, ignoreCase);
if (match == null)
{
match = JTextComponents.findNext(
text, query, 0, ignoreCase);
}
if (selectFirstMatch)
{
handleMatch(match);
}
else
{
handleMatch(null);
}
if (appearances.isEmpty())
{
searchPanel.setMessage("Not found");
}
else
{
searchPanel.setMessage(
"Found " + appearances.size() + " times");
}
} } | public class class_name {
void updateSearchResults(boolean selectFirstMatch)
{
clearHighlights();
searchPanel.setMessage("");
String query = searchPanel.getQuery();
if (query.isEmpty())
{
handleMatch(null);
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
String text = getDocumentText();
boolean ignoreCase = !searchPanel.isCaseSensitive();
List<Point> appearances =
JTextComponents.find(text, query, ignoreCase);
addHighlights(appearances, highlightColor);
int caretPosition = textComponent.getCaretPosition();
Point match = JTextComponents.findNext(
text, query, caretPosition, ignoreCase);
if (match == null)
{
match = JTextComponents.findNext(
text, query, 0, ignoreCase);
// depends on control dependency: [if], data = [none]
}
if (selectFirstMatch)
{
handleMatch(match);
// depends on control dependency: [if], data = [none]
}
else
{
handleMatch(null);
// depends on control dependency: [if], data = [none]
}
if (appearances.isEmpty())
{
searchPanel.setMessage("Not found");
// depends on control dependency: [if], data = [none]
}
else
{
searchPanel.setMessage(
"Found " + appearances.size() + " times");
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private MediaType findContentType(final String url) {
if (url == null) {
return null;
}
if (url.startsWith("file")) {
return APPLICATION_OCTET_STREAM_TYPE;
} else if (url.startsWith("http")) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpHead httpHead = new HttpHead(url);
try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
if (response.getStatusLine().getStatusCode() == SC_OK) {
final Header contentType = response.getFirstHeader(CONTENT_TYPE);
if (contentType != null) {
return MediaType.valueOf(contentType.getValue());
}
}
}
} catch (final IOException e) {
LOGGER.warn("Unable to retrieve external content from {} due to {}", url, e.getMessage());
} catch (final Exception e) {
throw new RepositoryRuntimeException(e);
}
}
LOGGER.debug("Defaulting to octet stream for media type");
return APPLICATION_OCTET_STREAM_TYPE;
} } | public class class_name {
private MediaType findContentType(final String url) {
if (url == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (url.startsWith("file")) {
return APPLICATION_OCTET_STREAM_TYPE; // depends on control dependency: [if], data = [none]
} else if (url.startsWith("http")) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpHead httpHead = new HttpHead(url);
try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
if (response.getStatusLine().getStatusCode() == SC_OK) {
final Header contentType = response.getFirstHeader(CONTENT_TYPE);
if (contentType != null) {
return MediaType.valueOf(contentType.getValue()); // depends on control dependency: [if], data = [(contentType]
}
}
}
} catch (final IOException e) {
LOGGER.warn("Unable to retrieve external content from {} due to {}", url, e.getMessage());
} catch (final Exception e) {
throw new RepositoryRuntimeException(e);
}
}
LOGGER.debug("Defaulting to octet stream for media type");
return APPLICATION_OCTET_STREAM_TYPE;
} } |
public class class_name {
public QuadTreeIterator getIterator(boolean bSorted) {
if (!bSorted) {
QuadTreeImpl.QuadTreeIteratorImpl iterator = m_impl.getIterator();
return new QuadTreeIterator(iterator, false);
} else {
QuadTreeImpl.QuadTreeSortedIteratorImpl iterator = m_impl.getSortedIterator();
return new QuadTreeIterator(iterator, true);
}
} } | public class class_name {
public QuadTreeIterator getIterator(boolean bSorted) {
if (!bSorted) {
QuadTreeImpl.QuadTreeIteratorImpl iterator = m_impl.getIterator();
return new QuadTreeIterator(iterator, false); // depends on control dependency: [if], data = [none]
} else {
QuadTreeImpl.QuadTreeSortedIteratorImpl iterator = m_impl.getSortedIterator();
return new QuadTreeIterator(iterator, true); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void assertIsFile(Description description, File actual) {
assertNotNull(description, actual);
if (!actual.isFile()) {
String format = "expecting path:<%s> to represent an existing file";
throw failures.failure(description, new BasicErrorMessageFactory(format, actual));
}
} } | public class class_name {
public void assertIsFile(Description description, File actual) {
assertNotNull(description, actual);
if (!actual.isFile()) {
String format = "expecting path:<%s> to represent an existing file";
// depends on control dependency: [if], data = [none]
throw failures.failure(description, new BasicErrorMessageFactory(format, actual));
}
} } |
public class class_name {
public void registerListener(final StatusListener listener) {
listenersLock.writeLock().lock();
try {
listeners.add(listener);
final Level lvl = listener.getStatusLevel();
if (listenersLevel < lvl.intLevel()) {
listenersLevel = lvl.intLevel();
}
} finally {
listenersLock.writeLock().unlock();
}
} } | public class class_name {
public void registerListener(final StatusListener listener) {
listenersLock.writeLock().lock();
try {
listeners.add(listener); // depends on control dependency: [try], data = [none]
final Level lvl = listener.getStatusLevel();
if (listenersLevel < lvl.intLevel()) {
listenersLevel = lvl.intLevel(); // depends on control dependency: [if], data = [none]
}
} finally {
listenersLock.writeLock().unlock();
}
} } |
public class class_name {
protected void bindDependentKeyValue(PersistentProperty property, DependantValue key,
InFlightMetadataCollector mappings, String sessionFactoryBeanName) {
if (LOG.isDebugEnabled()) {
LOG.debug("[GrailsDomainBinder] binding [" + property.getName() + "] with dependant key");
}
PersistentEntity refDomainClass = property.getOwner();
final Mapping mapping = getMapping(refDomainClass.getJavaClass());
boolean hasCompositeIdentifier = hasCompositeIdentifier(mapping);
if ((shouldCollectionBindWithJoinColumn((ToMany) property) && hasCompositeIdentifier) ||
(hasCompositeIdentifier && ( property instanceof ManyToMany))) {
CompositeIdentity ci = (CompositeIdentity) mapping.getIdentity();
bindCompositeIdentifierToManyToOne((Association) property, key, ci, refDomainClass, EMPTY_PATH, sessionFactoryBeanName);
}
else {
bindSimpleValue(property, null, key, EMPTY_PATH, mappings, sessionFactoryBeanName);
}
} } | public class class_name {
protected void bindDependentKeyValue(PersistentProperty property, DependantValue key,
InFlightMetadataCollector mappings, String sessionFactoryBeanName) {
if (LOG.isDebugEnabled()) {
LOG.debug("[GrailsDomainBinder] binding [" + property.getName() + "] with dependant key"); // depends on control dependency: [if], data = [none]
}
PersistentEntity refDomainClass = property.getOwner();
final Mapping mapping = getMapping(refDomainClass.getJavaClass());
boolean hasCompositeIdentifier = hasCompositeIdentifier(mapping);
if ((shouldCollectionBindWithJoinColumn((ToMany) property) && hasCompositeIdentifier) ||
(hasCompositeIdentifier && ( property instanceof ManyToMany))) {
CompositeIdentity ci = (CompositeIdentity) mapping.getIdentity();
bindCompositeIdentifierToManyToOne((Association) property, key, ci, refDomainClass, EMPTY_PATH, sessionFactoryBeanName); // depends on control dependency: [if], data = [none]
}
else {
bindSimpleValue(property, null, key, EMPTY_PATH, mappings, sessionFactoryBeanName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addClassPath(String path) {
String[] paths = path.split(File.pathSeparator);
for (String cpPath : paths) {
// Check to support wild card classpath
if (cpPath.endsWith("*")) {
File dir = new File(cpPath.substring(0, cpPath.length() - 1));
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) addFile(file);
}
}
} else {
addFile(new File(cpPath));
}
}
} } | public class class_name {
public void addClassPath(String path) {
String[] paths = path.split(File.pathSeparator);
for (String cpPath : paths) {
// Check to support wild card classpath
if (cpPath.endsWith("*")) {
File dir = new File(cpPath.substring(0, cpPath.length() - 1));
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) addFile(file);
}
}
} else {
addFile(new File(cpPath)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void adaptHelperText() {
if (textInputLayout != null && TextUtils.isEmpty(getText())) {
textInputLayout.setHelperText(helperText);
textInputLayout.setHelperTextEnabled(true);
}
} } | public class class_name {
private void adaptHelperText() {
if (textInputLayout != null && TextUtils.isEmpty(getText())) {
textInputLayout.setHelperText(helperText); // depends on control dependency: [if], data = [none]
textInputLayout.setHelperTextEnabled(true); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public SemanticType.Array extractArrayType(SemanticType type, Environment environment,
ReadWriteTypeExtractor.Combinator<SemanticType.Array> combinator, SyntacticItem item) {
//
if (type != null) {
SemanticType.Array sourceArrayT = rwTypeExtractor.apply(type, environment, combinator);
//
if (sourceArrayT == null) {
syntaxError(item, EXPECTED_ARRAY);
} else {
return sourceArrayT;
}
}
return null;
} } | public class class_name {
public SemanticType.Array extractArrayType(SemanticType type, Environment environment,
ReadWriteTypeExtractor.Combinator<SemanticType.Array> combinator, SyntacticItem item) {
//
if (type != null) {
SemanticType.Array sourceArrayT = rwTypeExtractor.apply(type, environment, combinator);
//
if (sourceArrayT == null) {
syntaxError(item, EXPECTED_ARRAY); // depends on control dependency: [if], data = [none]
} else {
return sourceArrayT; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static IStandardExpression computeAttributeExpression(
final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {
if (!(tag instanceof AbstractProcessableElementTag)) {
return parseAttributeExpression(context, attributeValue);
}
final AbstractProcessableElementTag processableElementTag = (AbstractProcessableElementTag)tag;
final Attribute attribute = (Attribute) processableElementTag.getAttribute(attributeName);
IStandardExpression expression = attribute.getCachedStandardExpression();
if (expression != null) {
return expression;
}
expression = parseAttributeExpression(context, attributeValue);
// If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it!
if (expression != null && !(expression instanceof FragmentExpression) && attributeValue.indexOf('_') < 0) {
attribute.setCachedStandardExpression(expression);
}
return expression;
} } | public class class_name {
public static IStandardExpression computeAttributeExpression(
final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {
if (!(tag instanceof AbstractProcessableElementTag)) {
return parseAttributeExpression(context, attributeValue); // depends on control dependency: [if], data = [none]
}
final AbstractProcessableElementTag processableElementTag = (AbstractProcessableElementTag)tag;
final Attribute attribute = (Attribute) processableElementTag.getAttribute(attributeName);
IStandardExpression expression = attribute.getCachedStandardExpression();
if (expression != null) {
return expression; // depends on control dependency: [if], data = [none]
}
expression = parseAttributeExpression(context, attributeValue);
// If the expression has been correctly parsed AND it does not contain preprocessing marks (_), nor it is a FragmentExpression, cache it!
if (expression != null && !(expression instanceof FragmentExpression) && attributeValue.indexOf('_') < 0) {
attribute.setCachedStandardExpression(expression); // depends on control dependency: [if], data = [(expression]
}
return expression;
} } |
public class class_name {
public void setBoardEnabled(boolean enable) {
if (enable && mBoard == null) {
mBoard = makeBoard();
}
if (mBoard != null) {
mBoard.setBoardEnabled(enable);
}
} } | public class class_name {
public void setBoardEnabled(boolean enable) {
if (enable && mBoard == null) {
mBoard = makeBoard(); // depends on control dependency: [if], data = [none]
}
if (mBoard != null) {
mBoard.setBoardEnabled(enable); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void closeResponseOutput(boolean releaseChannel) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.entering(CLASS_NAME, "closeResponseOutput","["+this+"]");
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "releaseChannel->"+releaseChannel+", writerClosed->"+writerClosed);
}
// if user hasn't closed stream or writer on a forward, close it for them
if (writerClosed == false) {
// PK63328 starts - last flush to OutputStream
boolean isArdEnabled = false;
if (WebContainer.getWebContainer().getWebContainerConfig().isArdEnabled()) {
if (((WebAppDispatcherContext) _connContext.getRequest().getWebAppDispatcherContext()).getWebApp().getWebAppConfig().isArdEnabled()) {
isArdEnabled = true;
//PK89810 Start
WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
reqState.setAttribute("com.ibm.ws.webcontainer.appIsArdEnabled", true);
//PK89810 End
}
}
//The goal of this logic is to close the response, release the channel, and send as Content-Length instead of chunked.
//Previously we tried to just call close after calling setLastBuffer, but that doesn't work because if there is anything
//already in the Channel's byte buffer queue you don't want to indicate its the last buffer before you're really ready and truncate the response.
//Therefore, we must call flush with flushMode false so we can get all the data to the channel without it trying to
//send everything out to the client before its really the last buffer. We gate the checks with if (!isArdEnabled) so
//we don't indicate that the response is finished until we exit back out through the stack. Otherwise, it could try to close
//the connection and invalidate the request before we're even out of the Servlet container/servlet call stack
//All of this next if block is totally new since PK63328
if (!isArdEnabled){
_response.setFlushMode(false);
_response.setIsClosing(true);
try{
if (_gotOutputStream == true){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "flush output stream");
}
if ( !(_bufferedOut instanceof WCOutputStream) || !((WCOutputStream)_bufferedOut).isClosed())
_bufferedOut.flush();
}
else if (_gotWriter == true){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "flush writer");
}
_pwriter.flush();
}
}
catch (Throwable th){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.SEVERE)) {
logger.logp (Level.SEVERE, CLASS_NAME, "closeResponseOutput", "Error.while.flushing.last.response");
}
}
_response.setFlushMode(true);
}
//This code was always here minus the check for isArdEnabled and setLastBuffer(true)
//so we should continue calling close even for ard
//
try {
if (_gotOutputStream == true) {
if (!isArdEnabled){
//PK89810
// PM18543 - Add test for WCCustomProperties.COMPLETE_DATA_RESPONSE
if (WCCustomProperties.COMPLETE_DATA_RESPONSE && !WCCustomProperties.FINISH_RESPONSE_ON_CLOSE){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "setLastBuffer to true ");
}
_response.setLastBuffer(true); //PK89810, setLastBuffer in finish of BufferedWriter if CP is set
}
}
_bufferedOut.close();
_rawOut.close();
}
else if (_gotWriter == true) {
if (!isArdEnabled){
//PK89810
// PM18543 - Add test for WCCustomProperties.COMPLETE_DATA_RESPONSE
if (WCCustomProperties.COMPLETE_DATA_RESPONSE && !WCCustomProperties.FINISH_RESPONSE_ON_CLOSE){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "setLastBuffer to true ");
}
_response.setLastBuffer(true); //PK89810 , setLastBuffer in finish of BufferedServletOutputStream if CP is set
}
}
// PK63328 ends
_pwriter.close();
_rawOut.close();
}
// code below LIBERTY only
if (releaseChannel)
{
_response.releaseChannel();
WebContainerRequestState.getInstance(true).setCompleted(true);
}
// code above LIBERTY only
}
catch (Throwable th) {
logger.logp(Level.SEVERE, CLASS_NAME,"closeResponseOutput", "Error.while.closing.response.output",th);
}
}
//Not sure if we should be doing this outside of writeClosed
//This is not called by default. Only by WebServices and AsyncServlet completion
if (releaseChannel){
//check to avoid double release
WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
if (! reqState.isCompleted()) {
_response.releaseChannel();
if (reqState.getCurrentThreadsIExtendedRequest()==this.getRequest())
WebContainerRequestState.getInstance(true).setCompleted(true);
}
}
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.exiting(CLASS_NAME, "closeResponseOutput");
}
} } | public class class_name {
public void closeResponseOutput(boolean releaseChannel) {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.entering(CLASS_NAME, "closeResponseOutput","["+this+"]"); // depends on control dependency: [if], data = [none]
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "releaseChannel->"+releaseChannel+", writerClosed->"+writerClosed); // depends on control dependency: [if], data = [none]
}
// if user hasn't closed stream or writer on a forward, close it for them
if (writerClosed == false) {
// PK63328 starts - last flush to OutputStream
boolean isArdEnabled = false;
if (WebContainer.getWebContainer().getWebContainerConfig().isArdEnabled()) {
if (((WebAppDispatcherContext) _connContext.getRequest().getWebAppDispatcherContext()).getWebApp().getWebAppConfig().isArdEnabled()) {
isArdEnabled = true; // depends on control dependency: [if], data = [none]
//PK89810 Start
WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
reqState.setAttribute("com.ibm.ws.webcontainer.appIsArdEnabled", true); // depends on control dependency: [if], data = [none]
//PK89810 End
}
}
//The goal of this logic is to close the response, release the channel, and send as Content-Length instead of chunked.
//Previously we tried to just call close after calling setLastBuffer, but that doesn't work because if there is anything
//already in the Channel's byte buffer queue you don't want to indicate its the last buffer before you're really ready and truncate the response.
//Therefore, we must call flush with flushMode false so we can get all the data to the channel without it trying to
//send everything out to the client before its really the last buffer. We gate the checks with if (!isArdEnabled) so
//we don't indicate that the response is finished until we exit back out through the stack. Otherwise, it could try to close
//the connection and invalidate the request before we're even out of the Servlet container/servlet call stack
//All of this next if block is totally new since PK63328
if (!isArdEnabled){
_response.setFlushMode(false); // depends on control dependency: [if], data = [none]
_response.setIsClosing(true); // depends on control dependency: [if], data = [none]
try{
if (_gotOutputStream == true){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "flush output stream"); // depends on control dependency: [if], data = [none]
}
if ( !(_bufferedOut instanceof WCOutputStream) || !((WCOutputStream)_bufferedOut).isClosed())
_bufferedOut.flush();
}
else if (_gotWriter == true){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "flush writer"); // depends on control dependency: [if], data = [none]
}
_pwriter.flush(); // depends on control dependency: [if], data = [none]
}
}
catch (Throwable th){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.SEVERE)) {
logger.logp (Level.SEVERE, CLASS_NAME, "closeResponseOutput", "Error.while.flushing.last.response"); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
_response.setFlushMode(true); // depends on control dependency: [if], data = [none]
}
//This code was always here minus the check for isArdEnabled and setLastBuffer(true)
//so we should continue calling close even for ard
//
try {
if (_gotOutputStream == true) {
if (!isArdEnabled){
//PK89810
// PM18543 - Add test for WCCustomProperties.COMPLETE_DATA_RESPONSE
if (WCCustomProperties.COMPLETE_DATA_RESPONSE && !WCCustomProperties.FINISH_RESPONSE_ON_CLOSE){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "setLastBuffer to true "); // depends on control dependency: [if], data = [none]
}
_response.setLastBuffer(true); //PK89810, setLastBuffer in finish of BufferedWriter if CP is set // depends on control dependency: [if], data = [none]
}
}
_bufferedOut.close(); // depends on control dependency: [if], data = [none]
_rawOut.close(); // depends on control dependency: [if], data = [none]
}
else if (_gotWriter == true) {
if (!isArdEnabled){
//PK89810
// PM18543 - Add test for WCCustomProperties.COMPLETE_DATA_RESPONSE
if (WCCustomProperties.COMPLETE_DATA_RESPONSE && !WCCustomProperties.FINISH_RESPONSE_ON_CLOSE){
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.logp (Level.FINE, CLASS_NAME, "closeResponseOutput", "setLastBuffer to true "); // depends on control dependency: [if], data = [none]
}
_response.setLastBuffer(true); //PK89810 , setLastBuffer in finish of BufferedServletOutputStream if CP is set // depends on control dependency: [if], data = [none]
}
}
// PK63328 ends
_pwriter.close(); // depends on control dependency: [if], data = [none]
_rawOut.close(); // depends on control dependency: [if], data = [none]
}
// code below LIBERTY only
if (releaseChannel)
{
_response.releaseChannel(); // depends on control dependency: [if], data = [none]
WebContainerRequestState.getInstance(true).setCompleted(true); // depends on control dependency: [if], data = [none]
}
// code above LIBERTY only
}
catch (Throwable th) {
logger.logp(Level.SEVERE, CLASS_NAME,"closeResponseOutput", "Error.while.closing.response.output",th);
} // depends on control dependency: [catch], data = [none]
}
//Not sure if we should be doing this outside of writeClosed
//This is not called by default. Only by WebServices and AsyncServlet completion
if (releaseChannel){
//check to avoid double release
WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
if (! reqState.isCompleted()) {
_response.releaseChannel(); // depends on control dependency: [if], data = [none]
if (reqState.getCurrentThreadsIExtendedRequest()==this.getRequest())
WebContainerRequestState.getInstance(true).setCompleted(true);
}
}
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
logger.exiting(CLASS_NAME, "closeResponseOutput"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public QName toQName(String qname){
String prefix = "";
String localName = qname;
int colon = qname.indexOf(':');
if(colon!=-1){
prefix = qname.substring(0, colon);
localName = qname.substring(colon+1);
}
String ns = getNamespaceURI(prefix);
if(ns==null)
throw new IllegalArgumentException("undeclared prefix: "+prefix);
return new QName(ns, localName, prefix);
} } | public class class_name {
public QName toQName(String qname){
String prefix = "";
String localName = qname;
int colon = qname.indexOf(':');
if(colon!=-1){
prefix = qname.substring(0, colon); // depends on control dependency: [if], data = [none]
localName = qname.substring(colon+1); // depends on control dependency: [if], data = [(colon]
}
String ns = getNamespaceURI(prefix);
if(ns==null)
throw new IllegalArgumentException("undeclared prefix: "+prefix);
return new QName(ns, localName, prefix);
} } |
public class class_name {
@Override public RangeOfInt subList(int fromIndex, int toIndex) {
if ( (fromIndex == 0) && (toIndex == size) ) {
return this;
}
// Note that this is an IllegalArgumentException, not IndexOutOfBoundsException in order to
// match ArrayList.
if (fromIndex > toIndex) {
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex +
")");
}
// The text of this matches ArrayList
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
}
// Look very closely at the second parameter because the bounds checking is *different*
// from the get() method. get(toIndex) can throw an exception if toIndex >= start+size.
// But since a range is exclusive of it's right-bound, we can create a new sub-range
// with a right bound index of size, as opposed to size minus 1. I spent hours
// understanding this before fixing a bug with it. In the end, subList should do the same
// thing on a Range that it does on the equivalent ArrayList. I made tests for the same.
return RangeOfInt.of(start + fromIndex, start + toIndex);
} } | public class class_name {
@Override public RangeOfInt subList(int fromIndex, int toIndex) {
if ( (fromIndex == 0) && (toIndex == size) ) {
return this; // depends on control dependency: [if], data = [none]
}
// Note that this is an IllegalArgumentException, not IndexOutOfBoundsException in order to
// match ArrayList.
if (fromIndex > toIndex) {
throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex +
")");
}
// The text of this matches ArrayList
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
}
// Look very closely at the second parameter because the bounds checking is *different*
// from the get() method. get(toIndex) can throw an exception if toIndex >= start+size.
// But since a range is exclusive of it's right-bound, we can create a new sub-range
// with a right bound index of size, as opposed to size minus 1. I spent hours
// understanding this before fixing a bug with it. In the end, subList should do the same
// thing on a Range that it does on the equivalent ArrayList. I made tests for the same.
return RangeOfInt.of(start + fromIndex, start + toIndex); // depends on control dependency: [if], data = [toIndex)]
} } |
public class class_name {
public static List<InetSocketAddress> getIpListByRegistry(String registryIp) {
List<String[]> ips = new ArrayList<String[]>();
String defaultPort = null;
String[] srcIps = registryIp.split(",");
for (String add : srcIps) {
int a = add.indexOf("://");
if (a > -1) {
add = add.substring(a + 3); // 去掉协议头
}
String[] s1 = add.split(":");
if (s1.length > 1) {
if (defaultPort == null && s1[1] != null && s1[1].length() > 0) {
defaultPort = s1[1];
}
ips.add(new String[] { s1[0], s1[1] }); // 得到ip和端口
} else {
ips.add(new String[] { s1[0], defaultPort });
}
}
List<InetSocketAddress> ads = new ArrayList<InetSocketAddress>();
for (int j = 0; j < ips.size(); j++) {
String[] ip = ips.get(j);
try {
InetSocketAddress address = new InetSocketAddress(ip[0],
Integer.parseInt(ip[1] == null ? defaultPort : ip[1]));
ads.add(address);
} catch (Exception ignore) { //NOPMD
}
}
return ads;
} } | public class class_name {
public static List<InetSocketAddress> getIpListByRegistry(String registryIp) {
List<String[]> ips = new ArrayList<String[]>();
String defaultPort = null;
String[] srcIps = registryIp.split(",");
for (String add : srcIps) {
int a = add.indexOf("://");
if (a > -1) {
add = add.substring(a + 3); // 去掉协议头
}
String[] s1 = add.split(":");
if (s1.length > 1) {
if (defaultPort == null && s1[1] != null && s1[1].length() > 0) {
defaultPort = s1[1]; // depends on control dependency: [if], data = [none]
}
ips.add(new String[] { s1[0], s1[1] }); // 得到ip和端口 // depends on control dependency: [if], data = [none]
} else {
ips.add(new String[] { s1[0], defaultPort }); // depends on control dependency: [if], data = [none]
}
}
List<InetSocketAddress> ads = new ArrayList<InetSocketAddress>();
for (int j = 0; j < ips.size(); j++) {
String[] ip = ips.get(j);
try {
InetSocketAddress address = new InetSocketAddress(ip[0],
Integer.parseInt(ip[1] == null ? defaultPort : ip[1]));
ads.add(address);
} catch (Exception ignore) { //NOPMD
}
}
return ads;
} } |
public class class_name {
@Override
public Collection<Object> values() {
Collection<Object> values = new ArrayList<Object>();
for (Property property : getProperties(_scope)) {
values.add(property.getValue());
}
return values;
} } | public class class_name {
@Override
public Collection<Object> values() {
Collection<Object> values = new ArrayList<Object>();
for (Property property : getProperties(_scope)) {
values.add(property.getValue()); // depends on control dependency: [for], data = [property]
}
return values;
} } |
public class class_name {
protected String cleanUpLabel(final String label) {
if (label == null || label.length() == 0) {
return "ROOT";
// String constants are always interned
} else {
return tlp.basicCategory(label);
}
} } | public class class_name {
protected String cleanUpLabel(final String label) {
if (label == null || label.length() == 0) {
return "ROOT";
// depends on control dependency: [if], data = [none]
// String constants are always interned
} else {
return tlp.basicCategory(label);
// depends on control dependency: [if], data = [(label]
}
} } |
public class class_name {
public boolean log(String message) {
if (message == null) return false;
boolean ok;
try {
ok = loggly.log(token, tags, message).isExecuted();
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
} } | public class class_name {
public boolean log(String message) {
if (message == null) return false;
boolean ok;
try {
ok = loggly.log(token, tags, message).isExecuted(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
ok = false;
} // depends on control dependency: [catch], data = [none]
return ok;
} } |
public class class_name {
public void setImportSequences(String[] sequences) {
for (String s : sequences) {
s = s.trim();
if (s.length() > 0) {
String[] ts = s.split("\\s+");
List<String> sequence = new ArrayList<String>();
for (String t : ts) {
t = t.trim();
if (t.length() > 0) {
sequence.add(t);
}
}
this.importSequences.add(new StringSequence(sequence));
}
}
} } | public class class_name {
public void setImportSequences(String[] sequences) {
for (String s : sequences) {
s = s.trim(); // depends on control dependency: [for], data = [s]
if (s.length() > 0) {
String[] ts = s.split("\\s+");
List<String> sequence = new ArrayList<String>();
for (String t : ts) {
t = t.trim(); // depends on control dependency: [for], data = [t]
if (t.length() > 0) {
sequence.add(t); // depends on control dependency: [if], data = [none]
}
}
this.importSequences.add(new StringSequence(sequence)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void processIdle(Constants.Direction direction) throws Http2Exception {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "processIdle entry: stream " + myID);
}
// Can only receive HEADERS or PRIORITY frame in Idle state
if (direction == Constants.Direction.READ_IN) {
if (frameType == FrameTypes.HEADERS) {
// check to see if too many client streams are currently open for this stream's h2 connection
muxLink.incrementActiveClientStreams();
if (muxLink.getActiveClientStreams() > muxLink.getLocalConnectionSettings().getMaxConcurrentStreams()) {
RefusedStreamException rse = new RefusedStreamException("too many client-initiated streams are currently active; rejecting this stream");
rse.setConnectionError(false);
throw rse;
}
processHeadersPriority();
getHeadersFromFrame();
if (currentFrame.flagEndHeadersSet()) {
processCompleteHeaders(false);
setHeadersComplete();
} else {
muxLink.setContinuationExpected(true);
}
if (currentFrame.flagEndStreamSet()) {
endStream = true;
updateStreamState(StreamState.HALF_CLOSED_REMOTE);
if (currentFrame.flagEndHeadersSet()) {
setReadyForRead();
}
} else {
updateStreamState(StreamState.OPEN);
}
}
} else {
// send out a HEADER frame and update the stream state to OPEN
if (frameType == FrameTypes.HEADERS) {
updateStreamState(StreamState.OPEN);
}
writeFrameSync();
}
} } | public class class_name {
private void processIdle(Constants.Direction direction) throws Http2Exception {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "processIdle entry: stream " + myID);
}
// Can only receive HEADERS or PRIORITY frame in Idle state
if (direction == Constants.Direction.READ_IN) {
if (frameType == FrameTypes.HEADERS) {
// check to see if too many client streams are currently open for this stream's h2 connection
muxLink.incrementActiveClientStreams(); // depends on control dependency: [if], data = [none]
if (muxLink.getActiveClientStreams() > muxLink.getLocalConnectionSettings().getMaxConcurrentStreams()) {
RefusedStreamException rse = new RefusedStreamException("too many client-initiated streams are currently active; rejecting this stream");
rse.setConnectionError(false); // depends on control dependency: [if], data = [none]
throw rse;
}
processHeadersPriority(); // depends on control dependency: [if], data = [none]
getHeadersFromFrame(); // depends on control dependency: [if], data = [none]
if (currentFrame.flagEndHeadersSet()) {
processCompleteHeaders(false); // depends on control dependency: [if], data = [none]
setHeadersComplete(); // depends on control dependency: [if], data = [none]
} else {
muxLink.setContinuationExpected(true); // depends on control dependency: [if], data = [none]
}
if (currentFrame.flagEndStreamSet()) {
endStream = true; // depends on control dependency: [if], data = [none]
updateStreamState(StreamState.HALF_CLOSED_REMOTE); // depends on control dependency: [if], data = [none]
if (currentFrame.flagEndHeadersSet()) {
setReadyForRead(); // depends on control dependency: [if], data = [none]
}
} else {
updateStreamState(StreamState.OPEN); // depends on control dependency: [if], data = [none]
}
}
} else {
// send out a HEADER frame and update the stream state to OPEN
if (frameType == FrameTypes.HEADERS) {
updateStreamState(StreamState.OPEN); // depends on control dependency: [if], data = [none]
}
writeFrameSync();
}
} } |
public class class_name {
public static String initTree(CmsObject cms, String encoding, String skinUri) {
StringBuffer retValue = new StringBuffer(512);
String servletUrl = OpenCms.getSystemInfo().getOpenCmsContext();
// get the localized workplace messages
// TODO: Why a new message object, can it not be obtained from session?
Locale locale = cms.getRequestContext().getLocale();
CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(locale);
retValue.append("function initTreeResources() {\n");
retValue.append("\tinitResources(\"");
retValue.append(encoding);
retValue.append("\", \"");
retValue.append(PATH_WORKPLACE);
retValue.append("\", \"");
retValue.append(skinUri);
retValue.append("\", \"");
retValue.append(servletUrl);
retValue.append("\");\n");
// get all available resource types
List<I_CmsResourceType> allResTypes = OpenCms.getResourceManager().getResourceTypes();
for (int i = 0; i < allResTypes.size(); i++) {
// loop through all types
I_CmsResourceType type = allResTypes.get(i);
int curTypeId = type.getTypeId();
String curTypeName = type.getTypeName();
// get the settings for the resource type
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(curTypeName);
if (settings == null) {
if (LOG.isWarnEnabled()) {
LOG.warn(Messages.get().getBundle().key(Messages.LOG_MISSING_SETTINGS_ENTRY_1, curTypeName));
}
settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
CmsResourceTypePlain.getStaticTypeName());
}
retValue.append("\taddResourceType(");
retValue.append(curTypeId);
retValue.append(", \"");
retValue.append(curTypeName);
retValue.append("\",\t\"");
retValue.append(messages.key(settings.getKey()));
retValue.append("\",\t\"" + CmsWorkplace.RES_PATH_FILETYPES);
retValue.append(settings.getIcon());
retValue.append("\");\n");
}
retValue.append("}\n\n");
retValue.append("initTreeResources();\n");
String sharedFolder = OpenCms.getSiteManager().getSharedFolder();
if (sharedFolder != null) {
retValue.append("sharedFolderName = '" + sharedFolder + "';");
}
return retValue.toString();
} } | public class class_name {
public static String initTree(CmsObject cms, String encoding, String skinUri) {
StringBuffer retValue = new StringBuffer(512);
String servletUrl = OpenCms.getSystemInfo().getOpenCmsContext();
// get the localized workplace messages
// TODO: Why a new message object, can it not be obtained from session?
Locale locale = cms.getRequestContext().getLocale();
CmsMessages messages = OpenCms.getWorkplaceManager().getMessages(locale);
retValue.append("function initTreeResources() {\n");
retValue.append("\tinitResources(\"");
retValue.append(encoding);
retValue.append("\", \"");
retValue.append(PATH_WORKPLACE);
retValue.append("\", \"");
retValue.append(skinUri);
retValue.append("\", \"");
retValue.append(servletUrl);
retValue.append("\");\n");
// get all available resource types
List<I_CmsResourceType> allResTypes = OpenCms.getResourceManager().getResourceTypes();
for (int i = 0; i < allResTypes.size(); i++) {
// loop through all types
I_CmsResourceType type = allResTypes.get(i);
int curTypeId = type.getTypeId();
String curTypeName = type.getTypeName();
// get the settings for the resource type
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(curTypeName);
if (settings == null) {
if (LOG.isWarnEnabled()) {
LOG.warn(Messages.get().getBundle().key(Messages.LOG_MISSING_SETTINGS_ENTRY_1, curTypeName)); // depends on control dependency: [if], data = [none]
}
settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
CmsResourceTypePlain.getStaticTypeName()); // depends on control dependency: [if], data = [none]
}
retValue.append("\taddResourceType(");
retValue.append(curTypeId);
retValue.append(", \"");
retValue.append(curTypeName);
retValue.append("\",\t\"");
retValue.append(messages.key(settings.getKey()));
retValue.append("\",\t\"" + CmsWorkplace.RES_PATH_FILETYPES);
retValue.append(settings.getIcon());
retValue.append("\");\n"); // depends on control dependency: [for], data = [none]
}
retValue.append("}\n\n");
retValue.append("initTreeResources();\n");
String sharedFolder = OpenCms.getSiteManager().getSharedFolder();
if (sharedFolder != null) {
retValue.append("sharedFolderName = '" + sharedFolder + "';"); // depends on control dependency: [if], data = [none]
}
return retValue.toString();
} } |
public class class_name {
private NavigableMap<String, Object> parseConfiguration(Map<String, Object> configProps, PropertyService vProps) throws Exception {
final boolean trace = TraceComponent.isAnyTracingEnabled();
// WAS data source properties
NavigableMap<String, Object> wProps = new TreeMap<String, Object>();
String vPropsPID = null;
boolean recommendAuthAlias = false;
for (Map.Entry<String, Object> entry : configProps.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// look for vendor properties, which will be of the form properties.0.name
if (key.length () > TOTAL_PREFIX_LENGTH && key.charAt(BASE_PREFIX_LENGTH) == '.' && key.startsWith(BASE_PREFIX)) {
key = key.substring(TOTAL_PREFIX_LENGTH);
if (key.equals("config.referenceType")) {
if (vPropsPID == null)
vProps.setFactoryPID(vPropsPID = (String) value);
else
throw new SQLFeatureNotSupportedException(ConnectorService.getMessage("CARDINALITY_ERROR_J2CA8040", DATASOURCE, id, PropertyService.PROPERTIES));
} else {
if (value instanceof Long)
if (PropertyService.DURATION_S_INT_PROPS.contains(key) || PropertyService.DURATION_MS_INT_PROPS.contains(key))
value = ((Long) value).intValue(); // duration type: convert Long --> Integer
else if (PropertyService.DURATION_MIXED_PROPS.contains(key))
value = ((Long) value).toString(); // figure it out later by introspection
if (PropertyService.isPassword(key)) {
if (value instanceof SerializableProtectedString) {
String password = new String(((SerializableProtectedString) value).getChars());
value = PasswordUtil.getCryptoAlgorithm(password) == null ? password : PasswordUtil.decode(password);
} else if (value instanceof String) {
String password = (String) value;
value = PasswordUtil.getCryptoAlgorithm(password) == null ? password : PasswordUtil.decode(password);
}
if (DataSourceDef.password.name().equals(key))
recommendAuthAlias = true;
} else if (trace && tc.isDebugEnabled()) {
if(key.toLowerCase().equals("url")) {
if(value instanceof String)
Tr.debug(this, tc, "Found vendor property: " + key + '=' + PropertyService.filterURL((String) value));
} else {
Tr.debug(this, tc, "Found vendor property: " + key + '=' + value);
}
}
vProps.put(key, value);
}
} else if (key.indexOf('.') == -1 && !WPROPS_TO_SKIP.contains(key))
wProps.put(key, value);
}
//Don't send out auth alias recommendation message with UCP since it may be required to set the
//user and password as ds props
if(recommendAuthAlias && !"com.ibm.ws.jdbc.dataSource.properties.oracle.ucp".equals(vPropsPID))
ConnectorService.logMessage(Level.INFO, "RECOMMEND_AUTH_ALIAS_J2CA8050", id);
if (vPropsPID == null)
vProps.setFactoryPID(PropertyService.FACTORY_PID);
return wProps;
} } | public class class_name {
private NavigableMap<String, Object> parseConfiguration(Map<String, Object> configProps, PropertyService vProps) throws Exception {
final boolean trace = TraceComponent.isAnyTracingEnabled();
// WAS data source properties
NavigableMap<String, Object> wProps = new TreeMap<String, Object>();
String vPropsPID = null;
boolean recommendAuthAlias = false;
for (Map.Entry<String, Object> entry : configProps.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// look for vendor properties, which will be of the form properties.0.name
if (key.length () > TOTAL_PREFIX_LENGTH && key.charAt(BASE_PREFIX_LENGTH) == '.' && key.startsWith(BASE_PREFIX)) {
key = key.substring(TOTAL_PREFIX_LENGTH);
if (key.equals("config.referenceType")) {
if (vPropsPID == null)
vProps.setFactoryPID(vPropsPID = (String) value);
else
throw new SQLFeatureNotSupportedException(ConnectorService.getMessage("CARDINALITY_ERROR_J2CA8040", DATASOURCE, id, PropertyService.PROPERTIES));
} else {
if (value instanceof Long)
if (PropertyService.DURATION_S_INT_PROPS.contains(key) || PropertyService.DURATION_MS_INT_PROPS.contains(key))
value = ((Long) value).intValue(); // duration type: convert Long --> Integer
else if (PropertyService.DURATION_MIXED_PROPS.contains(key))
value = ((Long) value).toString(); // figure it out later by introspection
if (PropertyService.isPassword(key)) {
if (value instanceof SerializableProtectedString) {
String password = new String(((SerializableProtectedString) value).getChars());
value = PasswordUtil.getCryptoAlgorithm(password) == null ? password : PasswordUtil.decode(password); // depends on control dependency: [if], data = [none]
} else if (value instanceof String) {
String password = (String) value;
value = PasswordUtil.getCryptoAlgorithm(password) == null ? password : PasswordUtil.decode(password); // depends on control dependency: [if], data = [none]
}
if (DataSourceDef.password.name().equals(key))
recommendAuthAlias = true;
} else if (trace && tc.isDebugEnabled()) {
if(key.toLowerCase().equals("url")) {
if(value instanceof String)
Tr.debug(this, tc, "Found vendor property: " + key + '=' + PropertyService.filterURL((String) value));
} else {
Tr.debug(this, tc, "Found vendor property: " + key + '=' + value); // depends on control dependency: [if], data = [none]
}
}
vProps.put(key, value);
}
} else if (key.indexOf('.') == -1 && !WPROPS_TO_SKIP.contains(key))
wProps.put(key, value);
}
//Don't send out auth alias recommendation message with UCP since it may be required to set the
//user and password as ds props
if(recommendAuthAlias && !"com.ibm.ws.jdbc.dataSource.properties.oracle.ucp".equals(vPropsPID))
ConnectorService.logMessage(Level.INFO, "RECOMMEND_AUTH_ALIAS_J2CA8050", id);
if (vPropsPID == null)
vProps.setFactoryPID(PropertyService.FACTORY_PID);
return wProps;
} } |
public class class_name {
public GetMetricStatisticsResult withDatapoints(Datapoint... datapoints) {
if (this.datapoints == null) {
setDatapoints(new com.amazonaws.internal.SdkInternalList<Datapoint>(datapoints.length));
}
for (Datapoint ele : datapoints) {
this.datapoints.add(ele);
}
return this;
} } | public class class_name {
public GetMetricStatisticsResult withDatapoints(Datapoint... datapoints) {
if (this.datapoints == null) {
setDatapoints(new com.amazonaws.internal.SdkInternalList<Datapoint>(datapoints.length)); // depends on control dependency: [if], data = [none]
}
for (Datapoint ele : datapoints) {
this.datapoints.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static JSONObject getJSONFromUrlViaPOST(String url, List<NameValuePair> params) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
} } | public class class_name {
public static JSONObject getJSONFromUrlViaPOST(String url, List<NameValuePair> params) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params)); // depends on control dependency: [try], data = [none]
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent(); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n"); // depends on control dependency: [while], data = [none]
}
is.close(); // depends on control dependency: [try], data = [none]
json = sb.toString(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
} // depends on control dependency: [catch], data = [none]
// try parse the string to a JSON object
try {
jObj = new JSONObject(json); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} // depends on control dependency: [catch], data = [none]
// return JSON String
return jObj;
} } |
public class class_name {
protected ServerCnxnFactory createServerFactory() {
try {
ServerCnxnFactory serverFactory = new NIOServerCnxnFactory();
serverFactory.configure(new InetSocketAddress(zookeeperPort), 5000);
return serverFactory;
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to create default zookeeper server factory", e);
}
} } | public class class_name {
protected ServerCnxnFactory createServerFactory() {
try {
ServerCnxnFactory serverFactory = new NIOServerCnxnFactory();
serverFactory.configure(new InetSocketAddress(zookeeperPort), 5000); // depends on control dependency: [try], data = [none]
return serverFactory; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to create default zookeeper server factory", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static String scrubLanguage(String language) {
if ("ldpi".equals(language)
|| "mdpi".equals(language)
|| "hdpi".equals(language)
|| "xhdpi".equals(language)) {
return null; // HTC, you suck!
}
return language;
} } | public class class_name {
static String scrubLanguage(String language) {
if ("ldpi".equals(language)
|| "mdpi".equals(language)
|| "hdpi".equals(language)
|| "xhdpi".equals(language)) {
return null; // HTC, you suck! // depends on control dependency: [if], data = [none]
}
return language;
} } |
public class class_name {
public List<FacesConfigManagedBeanType<FacesConfigType<T>>> getAllManagedBean()
{
List<FacesConfigManagedBeanType<FacesConfigType<T>>> list = new ArrayList<FacesConfigManagedBeanType<FacesConfigType<T>>>();
List<Node> nodeList = childNode.get("managed-bean");
for(Node node: nodeList)
{
FacesConfigManagedBeanType<FacesConfigType<T>> type = new FacesConfigManagedBeanTypeImpl<FacesConfigType<T>>(this, "managed-bean", childNode, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<FacesConfigManagedBeanType<FacesConfigType<T>>> getAllManagedBean()
{
List<FacesConfigManagedBeanType<FacesConfigType<T>>> list = new ArrayList<FacesConfigManagedBeanType<FacesConfigType<T>>>();
List<Node> nodeList = childNode.get("managed-bean");
for(Node node: nodeList)
{
FacesConfigManagedBeanType<FacesConfigType<T>> type = new FacesConfigManagedBeanTypeImpl<FacesConfigType<T>>(this, "managed-bean", childNode, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
public void stop() {
counterCacheStarted.set(true); //avoid starting the counter cache if it hasn't started yet
if (listener != null && stateCache != null) {
stateCache.removeListener(listener);
}
listener = null;
stateCache = null;
} } | public class class_name {
public void stop() {
counterCacheStarted.set(true); //avoid starting the counter cache if it hasn't started yet
if (listener != null && stateCache != null) {
stateCache.removeListener(listener); // depends on control dependency: [if], data = [(listener]
}
listener = null;
stateCache = null;
} } |
public class class_name {
public final int getIndex(String uri, String localName)
{
int index;
if (super.getLength() < MAX)
{
// if we haven't got too many attributes let the
// super class look it up
index = super.getIndex(uri,localName);
return index;
}
// we have too many attributes and the super class is slow
// so find it quickly using our Hashtable.
// Form the key of format "{uri}localName"
m_buff.setLength(0);
m_buff.append('{').append(uri).append('}').append(localName);
String key = m_buff.toString();
Integer i = (Integer)m_indexFromQName.get(key);
if (i == null)
index = -1;
else
index = i.intValue();
return index;
} } | public class class_name {
public final int getIndex(String uri, String localName)
{
int index;
if (super.getLength() < MAX)
{
// if we haven't got too many attributes let the
// super class look it up
index = super.getIndex(uri,localName); // depends on control dependency: [if], data = [none]
return index; // depends on control dependency: [if], data = [none]
}
// we have too many attributes and the super class is slow
// so find it quickly using our Hashtable.
// Form the key of format "{uri}localName"
m_buff.setLength(0);
m_buff.append('{').append(uri).append('}').append(localName);
String key = m_buff.toString();
Integer i = (Integer)m_indexFromQName.get(key);
if (i == null)
index = -1;
else
index = i.intValue();
return index;
} } |
public class class_name {
private void notifyCreation(final RepositoryObject object, final Map<String, Object> data) {
for (final ExternalChangeListener listener : externalChangeListeners) {
listener.onCreate(object, data);
}
} } | public class class_name {
private void notifyCreation(final RepositoryObject object, final Map<String, Object> data) {
for (final ExternalChangeListener listener : externalChangeListeners) {
listener.onCreate(object, data); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
final void _shortDebugString(StringBuffer buf)
{
if (-1 != _position)
{
buf.append(_position);
}
buf.append("(");
buf.append(_state);
buf.append(")");
} } | public class class_name {
final void _shortDebugString(StringBuffer buf)
{
if (-1 != _position)
{
buf.append(_position); // depends on control dependency: [if], data = [_position)]
}
buf.append("(");
buf.append(_state);
buf.append(")");
} } |
public class class_name {
private final void advanceToNonNullItem() {
assert _iterator != null;
assert _currentItem == null;
while(_iterator.hasNext() && _currentItem == null) {
_currentItem = _iterator.next();
_currentIndex++;
}
} } | public class class_name {
private final void advanceToNonNullItem() {
assert _iterator != null;
assert _currentItem == null;
while(_iterator.hasNext() && _currentItem == null) {
_currentItem = _iterator.next(); // depends on control dependency: [while], data = [none]
_currentIndex++; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public void publish(String name, String mode) {
Map<String, String> params = null;
if (name != null && name.contains("?")) {
// read and utilize the query string values
params = new HashMap<String, String>();
String tmp = name;
// check if we start with '?' or not
if (name.charAt(0) != '?') {
tmp = name.split("\\?")[1];
} else if (name.charAt(0) == '?') {
tmp = name.substring(1);
}
// now break up into key/value blocks
String[] kvs = tmp.split("&");
// take each key/value block and break into its key value parts
for (String kv : kvs) {
String[] split = kv.split("=");
params.put(split[0], split[1]);
}
// grab the streams name
name = name.substring(0, name.indexOf("?"));
}
log.debug("publish called with name {} and mode {}", name, mode);
IConnection conn = Red5.getConnectionLocal();
if (conn instanceof IStreamCapableConnection) {
IScope scope = conn.getScope();
IStreamCapableConnection streamConn = (IStreamCapableConnection) conn;
Number streamId = conn.getStreamId();
if (StringUtils.isEmpty(name)) {
sendNSFailed(streamConn, StatusCodes.NS_FAILED, "The stream name may not be empty.", name, streamId);
log.error("The stream name may not be empty.");
return;
}
IStreamSecurityService security = (IStreamSecurityService) ScopeUtils.getScopeService(scope, IStreamSecurityService.class);
if (security != null) {
Set<IStreamPublishSecurity> handlers = security.getStreamPublishSecurity();
for (IStreamPublishSecurity handler : handlers) {
if (!handler.isPublishAllowed(scope, name, mode)) {
sendNSFailed(streamConn, StatusCodes.NS_PUBLISH_BADNAME, "You are not allowed to publish the stream.", name, streamId);
log.error("You are not allowed to publish the stream {}", name);
return;
}
}
}
IBroadcastScope bsScope = getBroadcastScope(scope, name);
if (bsScope != null && !bsScope.getProviders().isEmpty()) {
// another stream with that name is already published
sendNSFailed(streamConn, StatusCodes.NS_PUBLISH_BADNAME, name, name, streamId);
log.error("Bad name {}", name);
return;
}
IClientStream stream = streamConn.getStreamById(streamId);
if (stream != null && !(stream instanceof IClientBroadcastStream)) {
log.error("Stream not found or is not instance of IClientBroadcastStream, name: {}, streamId: {}", name, streamId);
return;
}
boolean created = false;
if (stream == null) {
stream = streamConn.newBroadcastStream(streamId);
created = true;
}
IClientBroadcastStream bs = (IClientBroadcastStream) stream;
try {
// set publish name
bs.setPublishedName(name);
// set stream parameters if they exist
if (params != null) {
bs.setParameters(params);
}
IContext context = conn.getScope().getContext();
IProviderService providerService = (IProviderService) context.getBean(IProviderService.BEAN_NAME);
// TODO handle registration failure
if (providerService.registerBroadcastStream(conn.getScope(), name, bs)) {
bsScope = getBroadcastScope(conn.getScope(), name);
bsScope.setClientBroadcastStream(bs);
if (conn instanceof BaseConnection) {
((BaseConnection) conn).registerBasicScope(bsScope);
}
}
log.debug("Mode: {}", mode);
if (IClientStream.MODE_RECORD.equals(mode)) {
bs.start();
bs.saveAs(name, false);
} else if (IClientStream.MODE_APPEND.equals(mode)) {
bs.start();
bs.saveAs(name, true);
} else {
bs.start();
}
bs.startPublishing();
} catch (IOException e) {
log.warn("Stream I/O exception", e);
sendNSFailed(streamConn, StatusCodes.NS_RECORD_NOACCESS, "The file could not be created/written to.", name, streamId);
bs.close();
if (created) {
streamConn.deleteStreamById(streamId);
}
} catch (Exception e) {
log.warn("Exception on publish", e);
}
}
} } | public class class_name {
public void publish(String name, String mode) {
Map<String, String> params = null;
if (name != null && name.contains("?")) {
// read and utilize the query string values
params = new HashMap<String, String>();
// depends on control dependency: [if], data = [none]
String tmp = name;
// check if we start with '?' or not
if (name.charAt(0) != '?') {
tmp = name.split("\\?")[1];
// depends on control dependency: [if], data = [none]
} else if (name.charAt(0) == '?') {
tmp = name.substring(1);
// depends on control dependency: [if], data = [none]
}
// now break up into key/value blocks
String[] kvs = tmp.split("&");
// take each key/value block and break into its key value parts
for (String kv : kvs) {
String[] split = kv.split("=");
params.put(split[0], split[1]);
// depends on control dependency: [for], data = [none]
}
// grab the streams name
name = name.substring(0, name.indexOf("?"));
// depends on control dependency: [if], data = [none]
}
log.debug("publish called with name {} and mode {}", name, mode);
IConnection conn = Red5.getConnectionLocal();
if (conn instanceof IStreamCapableConnection) {
IScope scope = conn.getScope();
IStreamCapableConnection streamConn = (IStreamCapableConnection) conn;
Number streamId = conn.getStreamId();
if (StringUtils.isEmpty(name)) {
sendNSFailed(streamConn, StatusCodes.NS_FAILED, "The stream name may not be empty.", name, streamId);
log.error("The stream name may not be empty.");
return;
}
IStreamSecurityService security = (IStreamSecurityService) ScopeUtils.getScopeService(scope, IStreamSecurityService.class);
if (security != null) {
Set<IStreamPublishSecurity> handlers = security.getStreamPublishSecurity();
for (IStreamPublishSecurity handler : handlers) {
if (!handler.isPublishAllowed(scope, name, mode)) {
sendNSFailed(streamConn, StatusCodes.NS_PUBLISH_BADNAME, "You are not allowed to publish the stream.", name, streamId);
log.error("You are not allowed to publish the stream {}", name);
return;
}
}
}
IBroadcastScope bsScope = getBroadcastScope(scope, name);
if (bsScope != null && !bsScope.getProviders().isEmpty()) {
// another stream with that name is already published
sendNSFailed(streamConn, StatusCodes.NS_PUBLISH_BADNAME, name, name, streamId);
log.error("Bad name {}", name);
return;
}
IClientStream stream = streamConn.getStreamById(streamId);
if (stream != null && !(stream instanceof IClientBroadcastStream)) {
log.error("Stream not found or is not instance of IClientBroadcastStream, name: {}, streamId: {}", name, streamId);
return;
}
boolean created = false;
if (stream == null) {
stream = streamConn.newBroadcastStream(streamId);
created = true;
}
IClientBroadcastStream bs = (IClientBroadcastStream) stream;
try {
// set publish name
bs.setPublishedName(name);
// set stream parameters if they exist
if (params != null) {
bs.setParameters(params);
}
IContext context = conn.getScope().getContext();
IProviderService providerService = (IProviderService) context.getBean(IProviderService.BEAN_NAME);
// TODO handle registration failure
if (providerService.registerBroadcastStream(conn.getScope(), name, bs)) {
bsScope = getBroadcastScope(conn.getScope(), name);
bsScope.setClientBroadcastStream(bs);
if (conn instanceof BaseConnection) {
((BaseConnection) conn).registerBasicScope(bsScope);
}
}
log.debug("Mode: {}", mode);
if (IClientStream.MODE_RECORD.equals(mode)) {
bs.start();
bs.saveAs(name, false);
} else if (IClientStream.MODE_APPEND.equals(mode)) {
bs.start();
bs.saveAs(name, true);
} else {
bs.start();
}
bs.startPublishing();
} catch (IOException e) {
log.warn("Stream I/O exception", e);
sendNSFailed(streamConn, StatusCodes.NS_RECORD_NOACCESS, "The file could not be created/written to.", name, streamId);
bs.close();
if (created) {
streamConn.deleteStreamById(streamId);
}
} catch (Exception e) {
log.warn("Exception on publish", e);
}
}
} } |
public class class_name {
boolean layout(IRing macrocycle, IRingSet ringset) {
final IAtomContainer anon = roundUpIfNeeded(AtomContainerManipulator.anonymise(macrocycle));
final Collection<Point2d[]> coords = TEMPLATES.getCoordinates(anon);
if (coords.isEmpty())
return false;
Point2d[] best = new Point2d[anon.getAtomCount()];
int bestOffset = selectCoords(coords, best, macrocycle, ringset);
for (int i = 0; i < macrocycle.getAtomCount(); i++) {
macrocycle.getAtom(i).setPoint2d(best[(bestOffset + i) % macrocycle.getAtomCount()]);
macrocycle.getAtom(i).setFlag(ISPLACED, true);
macrocycle.getAtom(i).setProperty(MACROCYCLE_ATOM_HINT, true);
}
macrocycle.setFlag(ISPLACED, true);
return true;
} } | public class class_name {
boolean layout(IRing macrocycle, IRingSet ringset) {
final IAtomContainer anon = roundUpIfNeeded(AtomContainerManipulator.anonymise(macrocycle));
final Collection<Point2d[]> coords = TEMPLATES.getCoordinates(anon);
if (coords.isEmpty())
return false;
Point2d[] best = new Point2d[anon.getAtomCount()];
int bestOffset = selectCoords(coords, best, macrocycle, ringset);
for (int i = 0; i < macrocycle.getAtomCount(); i++) {
macrocycle.getAtom(i).setPoint2d(best[(bestOffset + i) % macrocycle.getAtomCount()]); // depends on control dependency: [for], data = [i]
macrocycle.getAtom(i).setFlag(ISPLACED, true); // depends on control dependency: [for], data = [i]
macrocycle.getAtom(i).setProperty(MACROCYCLE_ATOM_HINT, true); // depends on control dependency: [for], data = [i]
}
macrocycle.setFlag(ISPLACED, true);
return true;
} } |
public class class_name {
public static Cursor makeCursor( String name) {
Image image = getImage(name);
if (null == image)
return null;
Cursor cursor;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
if (debug) {
ImageObserver obs = new ImageObserver() {
public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {
return true;
}
};
System.out.println(" bestCursorSize = "+ tk.getBestCursorSize(image.getWidth(obs), image.getHeight(obs)));
System.out.println(" getMaximumCursorColors = "+ tk.getMaximumCursorColors());
}
cursor = tk.createCustomCursor(image, new Point(17,17), name);
} catch (IndexOutOfBoundsException e) {
System.out.println("NavigatedPanel createCustomCursor failed " + e);
return null;
}
return cursor;
} } | public class class_name {
public static Cursor makeCursor( String name) {
Image image = getImage(name);
if (null == image)
return null;
Cursor cursor;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
if (debug) {
ImageObserver obs = new ImageObserver() {
public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {
return true;
}
};
System.out.println(" bestCursorSize = "+ tk.getBestCursorSize(image.getWidth(obs), image.getHeight(obs))); // depends on control dependency: [if], data = [none]
System.out.println(" getMaximumCursorColors = "+ tk.getMaximumCursorColors()); // depends on control dependency: [if], data = [none]
}
cursor = tk.createCustomCursor(image, new Point(17,17), name); // depends on control dependency: [try], data = [none]
} catch (IndexOutOfBoundsException e) {
System.out.println("NavigatedPanel createCustomCursor failed " + e);
return null;
} // depends on control dependency: [catch], data = [none]
return cursor;
} } |
public class class_name {
private int readCorner2(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 4, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
} } | public class class_name {
private int readCorner2(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(0, numColumns - 4, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1; // depends on control dependency: [if], data = [none]
}
return currentByte;
} } |
public class class_name {
@Nonnull
@ReturnsMutableCopy
public static byte [] decode (@Nonnull final byte [] aSource,
final int nOfs,
final int nLen,
final int nOptions) throws IOException
{
// Lots of error checking and exception throwing
ValueEnforcer.isArrayOfsLen (aSource, nOfs, nLen);
if (nLen == 0)
return ArrayHelper.EMPTY_BYTE_ARRAY;
ValueEnforcer.isTrue (nLen >= 4,
() -> "Base64-encoded string must have at least four characters, but length specified was " +
nLen);
final byte [] aDecodabet = _getDecodabet (nOptions);
// Estimate on array size
final int len34 = nLen * 3 / 4;
// Upper limit on size of output
final byte [] outBuff = new byte [len34];
// Keep track of where we're writing
int outBuffPosn = 0;
// Four byte buffer from source, eliminating white space
final byte [] b4 = new byte [4];
// Keep track of four byte input buffer
int b4Posn = 0;
// Source array counter
int i;
// Special value from DECODABET
byte sbiDecode;
for (i = nOfs; i < nOfs + nLen; i++)
{
// Loop through source
sbiDecode = aDecodabet[aSource[i] & 0xFF];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if (sbiDecode >= WHITE_SPACE_ENC)
{
if (sbiDecode >= EQUALS_SIGN_ENC)
{
b4[b4Posn++] = aSource[i]; // Save non-whitespace
if (b4Posn > 3)
{ // Time to decode?
outBuffPosn += _decode4to3 (b4, 0, outBuff, outBuffPosn, nOptions);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (aSource[i] == EQUALS_SIGN)
break;
}
}
}
else
{
// There's a bad input character in the Base64 stream.
throw new IOException ("Bad Base64 input character decimal " + (aSource[i] & 0xFF) + " in array position " + i);
}
}
final byte [] aOut = new byte [outBuffPosn];
System.arraycopy (outBuff, 0, aOut, 0, outBuffPosn);
return aOut;
} } | public class class_name {
@Nonnull
@ReturnsMutableCopy
public static byte [] decode (@Nonnull final byte [] aSource,
final int nOfs,
final int nLen,
final int nOptions) throws IOException
{
// Lots of error checking and exception throwing
ValueEnforcer.isArrayOfsLen (aSource, nOfs, nLen);
if (nLen == 0)
return ArrayHelper.EMPTY_BYTE_ARRAY;
ValueEnforcer.isTrue (nLen >= 4,
() -> "Base64-encoded string must have at least four characters, but length specified was " +
nLen);
final byte [] aDecodabet = _getDecodabet (nOptions);
// Estimate on array size
final int len34 = nLen * 3 / 4;
// Upper limit on size of output
final byte [] outBuff = new byte [len34];
// Keep track of where we're writing
int outBuffPosn = 0;
// Four byte buffer from source, eliminating white space
final byte [] b4 = new byte [4];
// Keep track of four byte input buffer
int b4Posn = 0;
// Source array counter
int i;
// Special value from DECODABET
byte sbiDecode;
for (i = nOfs; i < nOfs + nLen; i++)
{
// Loop through source
sbiDecode = aDecodabet[aSource[i] & 0xFF];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if (sbiDecode >= WHITE_SPACE_ENC)
{
if (sbiDecode >= EQUALS_SIGN_ENC)
{
b4[b4Posn++] = aSource[i]; // Save non-whitespace // depends on control dependency: [if], data = [none]
if (b4Posn > 3)
{ // Time to decode?
outBuffPosn += _decode4to3 (b4, 0, outBuff, outBuffPosn, nOptions); // depends on control dependency: [if], data = [none]
b4Posn = 0; // depends on control dependency: [if], data = [none]
// If that was the equals sign, break out of 'for' loop
if (aSource[i] == EQUALS_SIGN)
break;
}
}
}
else
{
// There's a bad input character in the Base64 stream.
throw new IOException ("Bad Base64 input character decimal " + (aSource[i] & 0xFF) + " in array position " + i);
}
}
final byte [] aOut = new byte [outBuffPosn];
System.arraycopy (outBuff, 0, aOut, 0, outBuffPosn);
return aOut;
} } |
public class class_name {
public void init(Record recFileHdr, ClassInfo recClassInfo, Record recFieldData, boolean markUnusedFields)
{
m_recFileHdr = recFileHdr;
m_recClassInfo = recClassInfo;
m_recFieldData = recFieldData;
this.markUnusedFields = markUnusedFields;
int iOldKeyOrder = m_recFileHdr.getDefaultOrder();
try {
if (!m_recFileHdr.getField(FileHdr.FILE_NAME).equals(m_recClassInfo.getField(ClassInfo.CLASS_NAME)))
{
m_recFileHdr.getField(FileHdr.FILE_NAME).moveFieldToThis(m_recClassInfo.getField(ClassInfo.CLASS_NAME));
m_recFileHdr.setKeyArea(FileHdr.FILE_NAME_KEY);
if (!m_recFileHdr.seek("="))
m_recFileHdr.addNew();
}
} catch (DBException ex) {
ex.printStackTrace();
} finally {
m_recFileHdr.setKeyArea(iOldKeyOrder);
}
} } | public class class_name {
public void init(Record recFileHdr, ClassInfo recClassInfo, Record recFieldData, boolean markUnusedFields)
{
m_recFileHdr = recFileHdr;
m_recClassInfo = recClassInfo;
m_recFieldData = recFieldData;
this.markUnusedFields = markUnusedFields;
int iOldKeyOrder = m_recFileHdr.getDefaultOrder();
try {
if (!m_recFileHdr.getField(FileHdr.FILE_NAME).equals(m_recClassInfo.getField(ClassInfo.CLASS_NAME)))
{
m_recFileHdr.getField(FileHdr.FILE_NAME).moveFieldToThis(m_recClassInfo.getField(ClassInfo.CLASS_NAME)); // depends on control dependency: [if], data = [none]
m_recFileHdr.setKeyArea(FileHdr.FILE_NAME_KEY); // depends on control dependency: [if], data = [none]
if (!m_recFileHdr.seek("="))
m_recFileHdr.addNew();
}
} catch (DBException ex) {
ex.printStackTrace();
} finally { // depends on control dependency: [catch], data = [none]
m_recFileHdr.setKeyArea(iOldKeyOrder);
}
} } |
public class class_name {
public java.util.List<Double> getLoadAverage() {
if (loadAverage == null) {
loadAverage = new com.amazonaws.internal.SdkInternalList<Double>();
}
return loadAverage;
} } | public class class_name {
public java.util.List<Double> getLoadAverage() {
if (loadAverage == null) {
loadAverage = new com.amazonaws.internal.SdkInternalList<Double>(); // depends on control dependency: [if], data = [none]
}
return loadAverage;
} } |
public class class_name {
public ListStacksResult withStackSummaries(StackSummary... stackSummaries) {
if (this.stackSummaries == null) {
setStackSummaries(new com.amazonaws.internal.SdkInternalList<StackSummary>(stackSummaries.length));
}
for (StackSummary ele : stackSummaries) {
this.stackSummaries.add(ele);
}
return this;
} } | public class class_name {
public ListStacksResult withStackSummaries(StackSummary... stackSummaries) {
if (this.stackSummaries == null) {
setStackSummaries(new com.amazonaws.internal.SdkInternalList<StackSummary>(stackSummaries.length)); // depends on control dependency: [if], data = [none]
}
for (StackSummary ele : stackSummaries) {
this.stackSummaries.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public MessageBuilder replaceFirst(String target, String replacement)
{
int index = builder.indexOf(target);
if (index != -1)
{
builder.replace(index, index + target.length(), replacement);
}
return this;
} } | public class class_name {
public MessageBuilder replaceFirst(String target, String replacement)
{
int index = builder.indexOf(target);
if (index != -1)
{
builder.replace(index, index + target.length(), replacement); // depends on control dependency: [if], data = [(index]
}
return this;
} } |
public class class_name {
public PutTargetsResult withFailedEntries(PutTargetsResultEntry... failedEntries) {
if (this.failedEntries == null) {
setFailedEntries(new java.util.ArrayList<PutTargetsResultEntry>(failedEntries.length));
}
for (PutTargetsResultEntry ele : failedEntries) {
this.failedEntries.add(ele);
}
return this;
} } | public class class_name {
public PutTargetsResult withFailedEntries(PutTargetsResultEntry... failedEntries) {
if (this.failedEntries == null) {
setFailedEntries(new java.util.ArrayList<PutTargetsResultEntry>(failedEntries.length)); // depends on control dependency: [if], data = [none]
}
for (PutTargetsResultEntry ele : failedEntries) {
this.failedEntries.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void makeGenerators(Task task) {
if (this.cookieGenerator != null) {
if (!(this.cookieGenerator instanceof NoCookieGenerator)) {
this.setCookie(this.cookieGenerator.get(task));
}
}
if (this.headerGenerator != null) {
if (!(this.headerGenerator instanceof NoHeaderGenerator)) {
Map headers = this.headerGenerator.get(task);
this.setHttpHeader(headers);
}
}
} } | public class class_name {
private void makeGenerators(Task task) {
if (this.cookieGenerator != null) {
if (!(this.cookieGenerator instanceof NoCookieGenerator)) {
this.setCookie(this.cookieGenerator.get(task)); // depends on control dependency: [if], data = [none]
}
}
if (this.headerGenerator != null) {
if (!(this.headerGenerator instanceof NoHeaderGenerator)) {
Map headers = this.headerGenerator.get(task);
this.setHttpHeader(headers); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public int fireNextItem(final AgendaFilter filter,
int fireCount,
int fireLimit) throws ConsequenceException {
// Because rules can be on the agenda, but after network evaluation produce no full matches, the
// engine uses tryAgain to drive a loop to find a rule that has matches, until there are no more rules left to try.
// once rule with 1..n matches is found, it'll return back to the outer loop.
boolean tryagain;
int localFireCount = 0;
do {
tryagain = false;
evaluateEagerList();
final InternalAgendaGroup group = getNextFocus();
// if there is a group with focus
if ( group != null ) {
localFireCount = ruleEvaluator.evaluateAndFire(filter, fireCount, fireLimit, group);
// it produced no full matches, so drive the search to the next rule
if ( localFireCount == 0 ) {
// nothing matched
tryagain = true;
propagationList.flush(); // There may actions to process, which create new rule matches
}
}
} while ( tryagain );
return localFireCount;
} } | public class class_name {
public int fireNextItem(final AgendaFilter filter,
int fireCount,
int fireLimit) throws ConsequenceException {
// Because rules can be on the agenda, but after network evaluation produce no full matches, the
// engine uses tryAgain to drive a loop to find a rule that has matches, until there are no more rules left to try.
// once rule with 1..n matches is found, it'll return back to the outer loop.
boolean tryagain;
int localFireCount = 0;
do {
tryagain = false;
evaluateEagerList();
final InternalAgendaGroup group = getNextFocus();
// if there is a group with focus
if ( group != null ) {
localFireCount = ruleEvaluator.evaluateAndFire(filter, fireCount, fireLimit, group); // depends on control dependency: [if], data = [none]
// it produced no full matches, so drive the search to the next rule
if ( localFireCount == 0 ) {
// nothing matched
tryagain = true; // depends on control dependency: [if], data = [none]
propagationList.flush(); // There may actions to process, which create new rule matches // depends on control dependency: [if], data = [none]
}
}
} while ( tryagain );
return localFireCount;
} } |
public class class_name {
public void addTransports(final List<JingleTransport> transports) {
synchronized (transports) {
for (JingleTransport transport : transports) {
addJingleTransport(transport);
}
}
} } | public class class_name {
public void addTransports(final List<JingleTransport> transports) {
synchronized (transports) {
for (JingleTransport transport : transports) {
addJingleTransport(transport); // depends on control dependency: [for], data = [transport]
}
}
} } |
public class class_name {
@SuppressWarnings("null")
public static <T> VarOptItemsSketch<T> heapify(final Memory srcMem,
final ArrayOfItemsSerDe<T> serDe) {
final int numPreLongs = getAndCheckPreLongs(srcMem);
final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcMem));
final int serVer = extractSerVer(srcMem);
final int familyId = extractFamilyID(srcMem);
final int flags = extractFlags(srcMem);
final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0;
final boolean isGadget = (flags & GADGET_FLAG_MASK) != 0;
// Check values
if ((numPreLongs != Family.VAROPT.getMinPreLongs())
&& (numPreLongs != Family.VAROPT.getMaxPreLongs())
&& (numPreLongs != PreambleUtil.VO_WARMUP_PRELONGS)) {
throw new SketchesArgumentException(
"Possible corruption: Must have " + Family.VAROPT.getMinPreLongs()
+ ", " + PreambleUtil.VO_WARMUP_PRELONGS + ", or "
+ Family.VAROPT.getMaxPreLongs() + " preLongs. Found: " + numPreLongs);
}
if (serVer != SER_VER) {
throw new SketchesArgumentException(
"Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer);
}
final int reqFamilyId = Family.VAROPT.getID();
if (familyId != reqFamilyId) {
throw new SketchesArgumentException(
"Possible Corruption: FamilyID must be " + reqFamilyId + ": " + familyId);
}
final int k = extractK(srcMem);
if (k < 1) {
throw new SketchesArgumentException("Possible Corruption: k must be at least 1: " + k);
}
if (isEmpty) {
assert numPreLongs == Family.VAROPT.getMinPreLongs();
return new VarOptItemsSketch<>(k, rf);
}
final long n = extractN(srcMem);
if (n < 0) {
throw new SketchesArgumentException("Possible Corruption: n cannot be negative: " + n);
}
// get rest of preamble
final int hCount = extractHRegionItemCount(srcMem);
final int rCount = extractRRegionItemCount(srcMem);
if (hCount < 0) {
throw new SketchesArgumentException("Possible Corruption: H region count cannot be "
+ "negative: " + hCount);
}
if (rCount < 0) {
throw new SketchesArgumentException("Possible Corruption: R region count cannot be "
+ "negative: " + rCount);
}
double totalRWeight = 0.0;
if (numPreLongs == Family.VAROPT.getMaxPreLongs()) {
if (rCount > 0) {
totalRWeight = extractTotalRWeight(srcMem);
} else {
throw new SketchesArgumentException(
"Possible Corruption: "
+ Family.VAROPT.getMaxPreLongs() + " preLongs but no items in R region");
}
}
final int preLongBytes = numPreLongs << 3;
final int totalItems = hCount + rCount;
int allocatedItems = k + 1; // default to full
if (rCount == 0) {
// Not in sampling mode, so determine size to allocate, using ceilingLog2(hCount) as minimum
final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k), "heapify");
final int minLgSize = Util.toLog2(Util.ceilingPowerOf2(hCount), "heapify");
final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(),
Math.max(minLgSize, MIN_LG_ARR_ITEMS));
allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize);
if (allocatedItems == k) {
++allocatedItems;
}
}
// allocate full-sized ArrayLists, but we store only hCount weights at any moment
final long weightOffsetBytes = TOTAL_WEIGHT_R_DOUBLE + (rCount > 0 ? Double.BYTES : 0);
final ArrayList<Double> weightList = new ArrayList<>(allocatedItems);
final double[] wts = new double[allocatedItems];
srcMem.getDoubleArray(weightOffsetBytes, wts, 0, hCount);
// can't use Arrays.asList(wts) since double[] rather than Double[]
for (int i = 0; i < hCount; ++ i) {
if (wts[i] <= 0.0) {
throw new SketchesArgumentException("Possible Corruption: "
+ "Non-positive weight in heapify(): " + wts[i]);
}
weightList.add(wts[i]);
}
// marks, if we have a gadget
long markBytes = 0;
int markCount = 0;
ArrayList<Boolean> markList = null;
if (isGadget) {
final long markOffsetBytes = preLongBytes + ((long) hCount * Double.BYTES);
markBytes = ArrayOfBooleansSerDe.computeBytesNeeded(hCount);
markList = new ArrayList<>(allocatedItems);
final ArrayOfBooleansSerDe booleansSerDe = new ArrayOfBooleansSerDe();
final Boolean[] markArray = booleansSerDe.deserializeFromMemory(
srcMem.region(markOffsetBytes, (hCount >>> 3) + 1), hCount);
for (Boolean mark : markArray) {
if (mark) { ++markCount; }
}
markList.addAll(Arrays.asList(markArray));
}
final long offsetBytes = preLongBytes + ((long) hCount * Double.BYTES) + markBytes;
final T[] data = serDe.deserializeFromMemory(
srcMem.region(offsetBytes, srcMem.getCapacity() - offsetBytes), totalItems);
final List<T> wrappedData = Arrays.asList(data);
final ArrayList<T> dataList = new ArrayList<>(allocatedItems);
dataList.addAll(wrappedData.subList(0, hCount));
// Load items in R as needed
if (rCount > 0) {
weightList.add(-1.0); // the gap
if (isGadget) { markList.add(false); } // the gap
for (int i = 0; i < rCount; ++i) {
weightList.add(-1.0);
if (isGadget) { markList.add(false); }
}
dataList.add(null); // the gap
dataList.addAll(wrappedData.subList(hCount, totalItems));
}
final VarOptItemsSketch<T> sketch =
new VarOptItemsSketch<>(dataList, weightList, k, n,
allocatedItems, rf, hCount, rCount, totalRWeight);
if (isGadget) {
sketch.marks_ = markList;
sketch.numMarksInH_ = markCount;
}
return sketch;
} } | public class class_name {
@SuppressWarnings("null")
public static <T> VarOptItemsSketch<T> heapify(final Memory srcMem,
final ArrayOfItemsSerDe<T> serDe) {
final int numPreLongs = getAndCheckPreLongs(srcMem);
final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcMem));
final int serVer = extractSerVer(srcMem);
final int familyId = extractFamilyID(srcMem);
final int flags = extractFlags(srcMem);
final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0;
final boolean isGadget = (flags & GADGET_FLAG_MASK) != 0;
// Check values
if ((numPreLongs != Family.VAROPT.getMinPreLongs())
&& (numPreLongs != Family.VAROPT.getMaxPreLongs())
&& (numPreLongs != PreambleUtil.VO_WARMUP_PRELONGS)) {
throw new SketchesArgumentException(
"Possible corruption: Must have " + Family.VAROPT.getMinPreLongs()
+ ", " + PreambleUtil.VO_WARMUP_PRELONGS + ", or "
+ Family.VAROPT.getMaxPreLongs() + " preLongs. Found: " + numPreLongs);
}
if (serVer != SER_VER) {
throw new SketchesArgumentException(
"Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer);
}
final int reqFamilyId = Family.VAROPT.getID();
if (familyId != reqFamilyId) {
throw new SketchesArgumentException(
"Possible Corruption: FamilyID must be " + reqFamilyId + ": " + familyId);
}
final int k = extractK(srcMem);
if (k < 1) {
throw new SketchesArgumentException("Possible Corruption: k must be at least 1: " + k);
}
if (isEmpty) {
assert numPreLongs == Family.VAROPT.getMinPreLongs();
return new VarOptItemsSketch<>(k, rf); // depends on control dependency: [if], data = [none]
}
final long n = extractN(srcMem);
if (n < 0) {
throw new SketchesArgumentException("Possible Corruption: n cannot be negative: " + n);
}
// get rest of preamble
final int hCount = extractHRegionItemCount(srcMem);
final int rCount = extractRRegionItemCount(srcMem);
if (hCount < 0) {
throw new SketchesArgumentException("Possible Corruption: H region count cannot be "
+ "negative: " + hCount);
}
if (rCount < 0) {
throw new SketchesArgumentException("Possible Corruption: R region count cannot be "
+ "negative: " + rCount);
}
double totalRWeight = 0.0;
if (numPreLongs == Family.VAROPT.getMaxPreLongs()) {
if (rCount > 0) {
totalRWeight = extractTotalRWeight(srcMem); // depends on control dependency: [if], data = [none]
} else {
throw new SketchesArgumentException(
"Possible Corruption: "
+ Family.VAROPT.getMaxPreLongs() + " preLongs but no items in R region");
}
}
final int preLongBytes = numPreLongs << 3;
final int totalItems = hCount + rCount;
int allocatedItems = k + 1; // default to full
if (rCount == 0) {
// Not in sampling mode, so determine size to allocate, using ceilingLog2(hCount) as minimum
final int ceilingLgK = Util.toLog2(Util.ceilingPowerOf2(k), "heapify");
final int minLgSize = Util.toLog2(Util.ceilingPowerOf2(hCount), "heapify");
final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(),
Math.max(minLgSize, MIN_LG_ARR_ITEMS));
allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize); // depends on control dependency: [if], data = [none]
if (allocatedItems == k) {
++allocatedItems; // depends on control dependency: [if], data = [none]
}
}
// allocate full-sized ArrayLists, but we store only hCount weights at any moment
final long weightOffsetBytes = TOTAL_WEIGHT_R_DOUBLE + (rCount > 0 ? Double.BYTES : 0);
final ArrayList<Double> weightList = new ArrayList<>(allocatedItems);
final double[] wts = new double[allocatedItems];
srcMem.getDoubleArray(weightOffsetBytes, wts, 0, hCount);
// can't use Arrays.asList(wts) since double[] rather than Double[]
for (int i = 0; i < hCount; ++ i) {
if (wts[i] <= 0.0) {
throw new SketchesArgumentException("Possible Corruption: "
+ "Non-positive weight in heapify(): " + wts[i]);
}
weightList.add(wts[i]); // depends on control dependency: [for], data = [i]
}
// marks, if we have a gadget
long markBytes = 0;
int markCount = 0;
ArrayList<Boolean> markList = null;
if (isGadget) {
final long markOffsetBytes = preLongBytes + ((long) hCount * Double.BYTES);
markBytes = ArrayOfBooleansSerDe.computeBytesNeeded(hCount); // depends on control dependency: [if], data = [none]
markList = new ArrayList<>(allocatedItems); // depends on control dependency: [if], data = [none]
final ArrayOfBooleansSerDe booleansSerDe = new ArrayOfBooleansSerDe();
final Boolean[] markArray = booleansSerDe.deserializeFromMemory(
srcMem.region(markOffsetBytes, (hCount >>> 3) + 1), hCount);
for (Boolean mark : markArray) {
if (mark) { ++markCount; } // depends on control dependency: [if], data = [none]
}
markList.addAll(Arrays.asList(markArray)); // depends on control dependency: [if], data = [none]
}
final long offsetBytes = preLongBytes + ((long) hCount * Double.BYTES) + markBytes;
final T[] data = serDe.deserializeFromMemory(
srcMem.region(offsetBytes, srcMem.getCapacity() - offsetBytes), totalItems);
final List<T> wrappedData = Arrays.asList(data);
final ArrayList<T> dataList = new ArrayList<>(allocatedItems);
dataList.addAll(wrappedData.subList(0, hCount));
// Load items in R as needed
if (rCount > 0) {
weightList.add(-1.0); // the gap // depends on control dependency: [if], data = [0)]
if (isGadget) { markList.add(false); } // the gap // depends on control dependency: [if], data = [none]
for (int i = 0; i < rCount; ++i) {
weightList.add(-1.0); // depends on control dependency: [for], data = [none]
if (isGadget) { markList.add(false); } // depends on control dependency: [if], data = [none]
}
dataList.add(null); // the gap // depends on control dependency: [if], data = [none]
dataList.addAll(wrappedData.subList(hCount, totalItems)); // depends on control dependency: [if], data = [none]
}
final VarOptItemsSketch<T> sketch =
new VarOptItemsSketch<>(dataList, weightList, k, n,
allocatedItems, rf, hCount, rCount, totalRWeight);
if (isGadget) {
sketch.marks_ = markList; // depends on control dependency: [if], data = [none]
sketch.numMarksInH_ = markCount; // depends on control dependency: [if], data = [none]
}
return sketch;
} } |
public class class_name {
public static <T extends ImageBase<T>, O extends ImageBase>
void add(T inputA, T inputB, O output) {
if( inputA instanceof ImageGray) {
if (GrayU8.class == inputA.getClass()) {
PixelMath.add((GrayU8) inputA, (GrayU8) inputB, (GrayU16) output);
} else if (GrayS8.class == inputA.getClass()) {
PixelMath.add((GrayS8) inputA, (GrayS8) inputB, (GrayS16) output);
} else if (GrayU16.class == inputA.getClass()) {
PixelMath.add((GrayU16) inputA, (GrayU16) inputB, (GrayS32) output);
} else if (GrayS16.class == inputA.getClass()) {
PixelMath.add((GrayS16) inputA, (GrayS16) inputB, (GrayS32) output);
} else if (GrayS32.class == inputA.getClass()) {
PixelMath.add((GrayS32) inputA, (GrayS32) inputB, (GrayS32) output);
} else if (GrayS64.class == inputA.getClass()) {
PixelMath.add((GrayS64) inputA, (GrayS64) inputB, (GrayS64) output);
} else if (GrayF32.class == inputA.getClass()) {
PixelMath.add((GrayF32) inputA, (GrayF32) inputB, (GrayF32) output);
} else if (GrayF64.class == inputA.getClass()) {
PixelMath.add((GrayF64) inputA, (GrayF64) inputB, (GrayF64) output);
} else {
throw new IllegalArgumentException("Unknown image Type: " + inputA.getClass().getSimpleName());
}
} else if (inputA instanceof Planar) {
Planar inA = (Planar)inputA;
Planar inB = (Planar)inputB;
Planar out = (Planar)output;
for (int i = 0; i < inA.getNumBands(); i++) {
add(inA.getBand(i),inB.getBand(i),out.getBand(i));
}
}
} } | public class class_name {
public static <T extends ImageBase<T>, O extends ImageBase>
void add(T inputA, T inputB, O output) {
if( inputA instanceof ImageGray) {
if (GrayU8.class == inputA.getClass()) {
PixelMath.add((GrayU8) inputA, (GrayU8) inputB, (GrayU16) output); // depends on control dependency: [if], data = [none]
} else if (GrayS8.class == inputA.getClass()) {
PixelMath.add((GrayS8) inputA, (GrayS8) inputB, (GrayS16) output); // depends on control dependency: [if], data = [none]
} else if (GrayU16.class == inputA.getClass()) {
PixelMath.add((GrayU16) inputA, (GrayU16) inputB, (GrayS32) output); // depends on control dependency: [if], data = [none]
} else if (GrayS16.class == inputA.getClass()) {
PixelMath.add((GrayS16) inputA, (GrayS16) inputB, (GrayS32) output); // depends on control dependency: [if], data = [none]
} else if (GrayS32.class == inputA.getClass()) {
PixelMath.add((GrayS32) inputA, (GrayS32) inputB, (GrayS32) output); // depends on control dependency: [if], data = [none]
} else if (GrayS64.class == inputA.getClass()) {
PixelMath.add((GrayS64) inputA, (GrayS64) inputB, (GrayS64) output); // depends on control dependency: [if], data = [none]
} else if (GrayF32.class == inputA.getClass()) {
PixelMath.add((GrayF32) inputA, (GrayF32) inputB, (GrayF32) output); // depends on control dependency: [if], data = [none]
} else if (GrayF64.class == inputA.getClass()) {
PixelMath.add((GrayF64) inputA, (GrayF64) inputB, (GrayF64) output); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unknown image Type: " + inputA.getClass().getSimpleName());
}
} else if (inputA instanceof Planar) {
Planar inA = (Planar)inputA;
Planar inB = (Planar)inputB;
Planar out = (Planar)output;
for (int i = 0; i < inA.getNumBands(); i++) {
add(inA.getBand(i),inB.getBand(i),out.getBand(i)); // depends on control dependency: [for], data = [i]
}
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.