code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private Map<CmsExportname, String> computeVfsExportnames() {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_UPDATE_EXPORTNAME_PROP_START_0));
}
CmsSiteManagerImpl sm = OpenCms.getSiteManager();
List<CmsResource> resources;
CmsObject cms = null;
try {
// this will always be in the root site
cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserExport());
resources = cms.readResourcesWithProperty(CmsPropertyDefinition.PROPERTY_EXPORTNAME);
synchronized (m_lockSetExportnames) {
Map<CmsExportname, String> exportnameResources = new HashMap<CmsExportname, String>();
for (int i = 0, n = resources.size(); i < n; i++) {
CmsResource res = resources.get(i);
try {
String foldername = res.getRootPath();
String exportname = cms.readPropertyObject(
foldername,
CmsPropertyDefinition.PROPERTY_EXPORTNAME,
false).getValue();
CmsSite site = sm.getSiteForRootPath(foldername);
if (exportname != null) {
if (exportname.charAt(exportname.length() - 1) != '/') {
exportname = exportname + "/";
}
if (exportname.charAt(0) != '/') {
exportname = "/" + exportname;
}
// export name has to be system-wide unique
// the folder name is a root path
exportnameResources.put(new CmsExportname(exportname, site), foldername);
}
} catch (CmsException e) {
// should never happen, folder will not be added
LOG.error(e.getLocalizedMessage(), e);
}
}
return Collections.unmodifiableMap(exportnameResources);
}
} catch (CmsException e) {
// should never happen, no resources will be added at all
LOG.error(e.getLocalizedMessage(), e);
return Collections.emptyMap();
}
} } | public class class_name {
private Map<CmsExportname, String> computeVfsExportnames() {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_UPDATE_EXPORTNAME_PROP_START_0)); // depends on control dependency: [if], data = [none]
}
CmsSiteManagerImpl sm = OpenCms.getSiteManager();
List<CmsResource> resources;
CmsObject cms = null;
try {
// this will always be in the root site
cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserExport()); // depends on control dependency: [try], data = [none]
resources = cms.readResourcesWithProperty(CmsPropertyDefinition.PROPERTY_EXPORTNAME); // depends on control dependency: [try], data = [none]
synchronized (m_lockSetExportnames) { // depends on control dependency: [try], data = [none]
Map<CmsExportname, String> exportnameResources = new HashMap<CmsExportname, String>();
for (int i = 0, n = resources.size(); i < n; i++) {
CmsResource res = resources.get(i);
try {
String foldername = res.getRootPath();
String exportname = cms.readPropertyObject(
foldername,
CmsPropertyDefinition.PROPERTY_EXPORTNAME,
false).getValue();
CmsSite site = sm.getSiteForRootPath(foldername);
if (exportname != null) {
if (exportname.charAt(exportname.length() - 1) != '/') {
exportname = exportname + "/"; // depends on control dependency: [if], data = [none]
}
if (exportname.charAt(0) != '/') {
exportname = "/" + exportname; // depends on control dependency: [if], data = [none]
}
// export name has to be system-wide unique
// the folder name is a root path
exportnameResources.put(new CmsExportname(exportname, site), foldername); // depends on control dependency: [if], data = [(exportname]
}
} catch (CmsException e) {
// should never happen, folder will not be added
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
return Collections.unmodifiableMap(exportnameResources);
}
} catch (CmsException e) {
// should never happen, no resources will be added at all
LOG.error(e.getLocalizedMessage(), e);
return Collections.emptyMap();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(ResourceLocation resourceLocation, ProtocolMarshaller protocolMarshaller) {
if (resourceLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resourceLocation.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
protocolMarshaller.marshall(resourceLocation.getRegionName(), REGIONNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ResourceLocation resourceLocation, ProtocolMarshaller protocolMarshaller) {
if (resourceLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resourceLocation.getAvailabilityZone(), AVAILABILITYZONE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(resourceLocation.getRegionName(), REGIONNAME_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 {
public static String join(String[] array, String separator) {
if (array == null || array.length == 0) {
return "";
}
if (array.length == 1) {
return array[0] == null ? "null" : array[0];
}
StringBuilder buf = new StringBuilder();
buf.append(array[0]);
for (int i = 1; i < array.length; i++) {
buf.append(separator).append(array[i]);
}
return buf.toString();
} } | public class class_name {
public static String join(String[] array, String separator) {
if (array == null || array.length == 0) {
return ""; // depends on control dependency: [if], data = [none]
}
if (array.length == 1) {
return array[0] == null ? "null" : array[0]; // depends on control dependency: [if], data = [none]
}
StringBuilder buf = new StringBuilder();
buf.append(array[0]);
for (int i = 1; i < array.length; i++) {
buf.append(separator).append(array[i]); // depends on control dependency: [for], data = [i]
}
return buf.toString();
} } |
public class class_name {
@Override
public CPMeasurementUnit remove(Serializable primaryKey)
throws NoSuchCPMeasurementUnitException {
Session session = null;
try {
session = openSession();
CPMeasurementUnit cpMeasurementUnit = (CPMeasurementUnit)session.get(CPMeasurementUnitImpl.class,
primaryKey);
if (cpMeasurementUnit == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchCPMeasurementUnitException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(cpMeasurementUnit);
}
catch (NoSuchCPMeasurementUnitException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } | public class class_name {
@Override
public CPMeasurementUnit remove(Serializable primaryKey)
throws NoSuchCPMeasurementUnitException {
Session session = null;
try {
session = openSession();
CPMeasurementUnit cpMeasurementUnit = (CPMeasurementUnit)session.get(CPMeasurementUnitImpl.class,
primaryKey);
if (cpMeasurementUnit == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); // depends on control dependency: [if], data = [none]
}
throw new NoSuchCPMeasurementUnitException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(cpMeasurementUnit);
}
catch (NoSuchCPMeasurementUnitException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} } |
public class class_name {
@Override
public synchronized List<EntityAuditEvent> listEvents(String entityId, String startKey, short maxResults)
throws AtlasException {
List<EntityAuditEvent> events = new ArrayList<>();
String myStartKey = startKey;
if (myStartKey == null) {
myStartKey = entityId;
}
SortedMap<String, EntityAuditEvent> subMap = auditEvents.tailMap(myStartKey);
for (EntityAuditEvent event : subMap.values()) {
if (events.size() < maxResults && event.getEntityId().equals(entityId)) {
events.add(event);
}
}
return events;
} } | public class class_name {
@Override
public synchronized List<EntityAuditEvent> listEvents(String entityId, String startKey, short maxResults)
throws AtlasException {
List<EntityAuditEvent> events = new ArrayList<>();
String myStartKey = startKey;
if (myStartKey == null) {
myStartKey = entityId; // depends on control dependency: [if], data = [none]
}
SortedMap<String, EntityAuditEvent> subMap = auditEvents.tailMap(myStartKey);
for (EntityAuditEvent event : subMap.values()) {
if (events.size() < maxResults && event.getEntityId().equals(entityId)) {
events.add(event); // depends on control dependency: [if], data = [none]
}
}
return events;
} } |
public class class_name {
public String translate(final Values values) {
final ArrayList<Values.Row> rows = new ArrayList<>(values.getRows());
final String[] aliases = values.getAliases();
// If aliases does not exist, throw an exception.
// Otherwise, apply them to the columns.
if (aliases == null || aliases.length == 0) {
throw new DatabaseEngineRuntimeException("Values requires aliases to avoid ambiguous columns names.");
} else {
rows.forEach(row -> {
final List<Expression> expressions = row.getExpressions();
for (int i = 0; i < expressions.size() && i < aliases.length; i++) {
// DISCLAIMER : May have side-effects because will change the state of the row's expressions.
expressions.get(i).alias(aliases[i]);
}
});
}
// Put each row on a select for union operator to work.
final List<Expression> rowsWithSelect = rows.stream()
.map(SqlBuilder::select)
.collect(Collectors.toList());
// By default, use UNION ALL to express VALUES.
// This way, only engines that support VALUES will implement it.
// Since the amount of values can be quite large, a linear UNION can cause Stack Overflow.
// To avoid it, we model this UNION as a binary tree.
final Union union = rowsToUnion(rowsWithSelect);
if (values.isEnclosed()) {
union.enclose();
}
return translate(union);
} } | public class class_name {
public String translate(final Values values) {
final ArrayList<Values.Row> rows = new ArrayList<>(values.getRows());
final String[] aliases = values.getAliases();
// If aliases does not exist, throw an exception.
// Otherwise, apply them to the columns.
if (aliases == null || aliases.length == 0) {
throw new DatabaseEngineRuntimeException("Values requires aliases to avoid ambiguous columns names.");
} else {
rows.forEach(row -> {
final List<Expression> expressions = row.getExpressions(); // depends on control dependency: [if], data = [none]
for (int i = 0; i < expressions.size() && i < aliases.length; i++) {
// DISCLAIMER : May have side-effects because will change the state of the row's expressions.
expressions.get(i).alias(aliases[i]); // depends on control dependency: [for], data = [i]
}
});
}
// Put each row on a select for union operator to work.
final List<Expression> rowsWithSelect = rows.stream()
.map(SqlBuilder::select)
.collect(Collectors.toList());
// By default, use UNION ALL to express VALUES.
// This way, only engines that support VALUES will implement it.
// Since the amount of values can be quite large, a linear UNION can cause Stack Overflow.
// To avoid it, we model this UNION as a binary tree.
final Union union = rowsToUnion(rowsWithSelect);
if (values.isEnclosed()) {
union.enclose();
}
return translate(union);
} } |
public class class_name {
private int findIndex(Entry<?> entry) {
int childrenSize = getChildren().size();
for (int i = 0; i < childrenSize; i++) {
Node node = getChildren().get(i);
if (node instanceof DayEntryView) {
DayEntryView view = (DayEntryView) node;
Entry<?> viewEntry = view.getEntry();
if (viewEntry.getStartAsZonedDateTime().isAfter(entry.getStartAsZonedDateTime())) {
return i;
}
}
}
return childrenSize;
} } | public class class_name {
private int findIndex(Entry<?> entry) {
int childrenSize = getChildren().size();
for (int i = 0; i < childrenSize; i++) {
Node node = getChildren().get(i);
if (node instanceof DayEntryView) {
DayEntryView view = (DayEntryView) node;
Entry<?> viewEntry = view.getEntry();
if (viewEntry.getStartAsZonedDateTime().isAfter(entry.getStartAsZonedDateTime())) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
return childrenSize;
} } |
public class class_name {
public <T> T read(final Reader reader, final DataTypeDescriptor<T> descriptor) {
try {
return jsonFormat.read(reader, descriptor);
} catch (Exception e) {
throw propagate(e);
}
} } | public class class_name {
public <T> T read(final Reader reader, final DataTypeDescriptor<T> descriptor) {
try {
return jsonFormat.read(reader, descriptor); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw propagate(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
protected void indexNode(Node node, EntityMetadata entityMetadata)
{
// Do nothing as
if (this.indexManager.getIndexer() != null
&& !this.indexManager.getIndexer().getClass().getSimpleName().equals("RedisIndexer"))
{
super.indexNode(node, entityMetadata);
}
} } | public class class_name {
@Override
protected void indexNode(Node node, EntityMetadata entityMetadata)
{
// Do nothing as
if (this.indexManager.getIndexer() != null
&& !this.indexManager.getIndexer().getClass().getSimpleName().equals("RedisIndexer"))
{
super.indexNode(node, entityMetadata); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final String encode(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
StringBuilder result = new StringBuilder(maxEncodedSize(len));
try {
encodeTo(result, bytes, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return result.toString();
} } | public class class_name {
public final String encode(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
StringBuilder result = new StringBuilder(maxEncodedSize(len));
try {
encodeTo(result, bytes, off, len); // depends on control dependency: [try], data = [none]
} catch (IOException impossible) {
throw new AssertionError(impossible);
} // depends on control dependency: [catch], data = [none]
return result.toString();
} } |
public class class_name {
public boolean skipTemplate(EnclosingScope scope) {
int start = index;
if (tryAndMatch(false, LeftAngle) == null) {
return true;
} else {
boolean firstTime = true;
while (tryAndMatch(false, RightAngle) == null) {
if (!firstTime && tryAndMatch(false,Comma) == null) {
// Failed to match a comma. Something is wrong
index = start;
return false;
} else if (!skipLifetimeIdentifier(scope) && !skipType(scope)) {
index = start;
return false;
}
firstTime = false;
}
}
//
return true;
} } | public class class_name {
public boolean skipTemplate(EnclosingScope scope) {
int start = index;
if (tryAndMatch(false, LeftAngle) == null) {
return true; // depends on control dependency: [if], data = [none]
} else {
boolean firstTime = true;
while (tryAndMatch(false, RightAngle) == null) {
if (!firstTime && tryAndMatch(false,Comma) == null) {
// Failed to match a comma. Something is wrong
index = start; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
} else if (!skipLifetimeIdentifier(scope) && !skipType(scope)) {
index = start; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
firstTime = false; // depends on control dependency: [while], data = [none]
}
}
//
return true;
} } |
public class class_name {
public void getCredentials(@NonNull final BaseCallback<Credentials, CredentialsManagerException> callback) {
String accessToken = storage.retrieveString(KEY_ACCESS_TOKEN);
final String refreshToken = storage.retrieveString(KEY_REFRESH_TOKEN);
String idToken = storage.retrieveString(KEY_ID_TOKEN);
String tokenType = storage.retrieveString(KEY_TOKEN_TYPE);
Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT);
String scope = storage.retrieveString(KEY_SCOPE);
if (isEmpty(accessToken) && isEmpty(idToken) || expiresAt == null) {
callback.onFailure(new CredentialsManagerException("No Credentials were previously set."));
return;
}
if (expiresAt > getCurrentTimeInMillis()) {
callback.onSuccess(recreateCredentials(idToken, accessToken, tokenType, refreshToken, new Date(expiresAt), scope));
return;
}
if (refreshToken == null) {
callback.onFailure(new CredentialsManagerException("Credentials have expired and no Refresh Token was available to renew them."));
return;
}
authClient.renewAuth(refreshToken).start(new AuthenticationCallback<Credentials>() {
@Override
public void onSuccess(Credentials fresh) {
//RefreshTokens don't expire. It should remain the same
Credentials credentials = new Credentials(fresh.getIdToken(), fresh.getAccessToken(), fresh.getType(), refreshToken, fresh.getExpiresAt(), fresh.getScope());
saveCredentials(credentials);
callback.onSuccess(credentials);
}
@Override
public void onFailure(AuthenticationException error) {
callback.onFailure(new CredentialsManagerException("An error occurred while trying to use the Refresh Token to renew the Credentials.", error));
}
});
} } | public class class_name {
public void getCredentials(@NonNull final BaseCallback<Credentials, CredentialsManagerException> callback) {
String accessToken = storage.retrieveString(KEY_ACCESS_TOKEN);
final String refreshToken = storage.retrieveString(KEY_REFRESH_TOKEN);
String idToken = storage.retrieveString(KEY_ID_TOKEN);
String tokenType = storage.retrieveString(KEY_TOKEN_TYPE);
Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT);
String scope = storage.retrieveString(KEY_SCOPE);
if (isEmpty(accessToken) && isEmpty(idToken) || expiresAt == null) {
callback.onFailure(new CredentialsManagerException("No Credentials were previously set.")); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (expiresAt > getCurrentTimeInMillis()) {
callback.onSuccess(recreateCredentials(idToken, accessToken, tokenType, refreshToken, new Date(expiresAt), scope)); // depends on control dependency: [if], data = [(expiresAt]
return; // depends on control dependency: [if], data = [none]
}
if (refreshToken == null) {
callback.onFailure(new CredentialsManagerException("Credentials have expired and no Refresh Token was available to renew them.")); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
authClient.renewAuth(refreshToken).start(new AuthenticationCallback<Credentials>() {
@Override
public void onSuccess(Credentials fresh) {
//RefreshTokens don't expire. It should remain the same
Credentials credentials = new Credentials(fresh.getIdToken(), fresh.getAccessToken(), fresh.getType(), refreshToken, fresh.getExpiresAt(), fresh.getScope());
saveCredentials(credentials);
callback.onSuccess(credentials);
}
@Override
public void onFailure(AuthenticationException error) {
callback.onFailure(new CredentialsManagerException("An error occurred while trying to use the Refresh Token to renew the Credentials.", error));
}
});
} } |
public class class_name {
public static byte[] sha256(final byte[] dataParam) {
if (dataParam == null || dataParam.length == 0) {
return new byte[] {};
}
try {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(dataParam);
}
//
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
} } | public class class_name {
public static byte[] sha256(final byte[] dataParam) {
if (dataParam == null || dataParam.length == 0) {
return new byte[] {}; // depends on control dependency: [if], data = [none]
}
try {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(dataParam); // depends on control dependency: [try], data = [none]
}
//
catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected static String[] parseMACs (String text)
{
if (text == null) {
return new String[0];
}
Matcher m = MACRegex.matcher(text);
ArrayList<String> list = new ArrayList<String>();
while (m.find()) {
String mac = m.group(1).toUpperCase();
mac = mac.replace(':', '-');
// "Didn't you get that memo?" Apparently some people are not
// up on MAC addresses actually being unique, so we will ignore those.
//
// 44-45-53-XX-XX-XX - PPP Adaptor
// 00-53-45-XX-XX-XX - PPP Adaptor
// 00-E0-06-09-55-66 - Some bogus run of ASUS motherboards
// 00-04-4B-80-80-03 - Some nvidia built-in lan issues
// 00-03-8A-XX-XX-XX - MiniWAN or AOL software
// 02-03-8A-00-00-11 - Westell Dual (USB/Ethernet) modem
// FF-FF-FF-FF-FF-FF - Tunnel adapter Teredo
// 02-00-4C-4F-4F-50 - MSFT thinger, loopback of some sort
// 00-00-00-00-00-00(-00-E0) - IP6 tunnel
if (mac.startsWith("44-45-53")) {
continue;
} else if (mac.startsWith("00-53-45-00")) {
continue;
} else if (mac.startsWith("00-E0-06-09-55-66")) {
continue;
} else if (mac.startsWith("00-04-4B-80-80-03")) {
continue;
} else if (mac.startsWith("00-03-8A")) {
continue;
} else if (mac.startsWith("02-03-8A-00-00-11")) {
continue;
} else if (mac.startsWith("FF-FF-FF-FF-FF-FF")) {
continue;
} else if (mac.startsWith("02-00-4C-4F-4F-50")) {
continue;
} else if (mac.startsWith("00-00-00-00-00-00")) {
continue;
}
list.add(mac);
}
return list.toArray(new String[0]);
} } | public class class_name {
protected static String[] parseMACs (String text)
{
if (text == null) {
return new String[0]; // depends on control dependency: [if], data = [none]
}
Matcher m = MACRegex.matcher(text);
ArrayList<String> list = new ArrayList<String>();
while (m.find()) {
String mac = m.group(1).toUpperCase();
mac = mac.replace(':', '-'); // depends on control dependency: [while], data = [none]
// "Didn't you get that memo?" Apparently some people are not
// up on MAC addresses actually being unique, so we will ignore those.
//
// 44-45-53-XX-XX-XX - PPP Adaptor
// 00-53-45-XX-XX-XX - PPP Adaptor
// 00-E0-06-09-55-66 - Some bogus run of ASUS motherboards
// 00-04-4B-80-80-03 - Some nvidia built-in lan issues
// 00-03-8A-XX-XX-XX - MiniWAN or AOL software
// 02-03-8A-00-00-11 - Westell Dual (USB/Ethernet) modem
// FF-FF-FF-FF-FF-FF - Tunnel adapter Teredo
// 02-00-4C-4F-4F-50 - MSFT thinger, loopback of some sort
// 00-00-00-00-00-00(-00-E0) - IP6 tunnel
if (mac.startsWith("44-45-53")) {
continue;
} else if (mac.startsWith("00-53-45-00")) {
continue;
} else if (mac.startsWith("00-E0-06-09-55-66")) {
continue;
} else if (mac.startsWith("00-04-4B-80-80-03")) {
continue;
} else if (mac.startsWith("00-03-8A")) {
continue;
} else if (mac.startsWith("02-03-8A-00-00-11")) {
continue;
} else if (mac.startsWith("FF-FF-FF-FF-FF-FF")) {
continue;
} else if (mac.startsWith("02-00-4C-4F-4F-50")) {
continue;
} else if (mac.startsWith("00-00-00-00-00-00")) {
continue;
}
list.add(mac); // depends on control dependency: [while], data = [none]
}
return list.toArray(new String[0]);
} } |
public class class_name {
public static void writeInts(String fieldName, List<Integer> data, JsonGenerator gen)
throws IOException {
if (!data.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (Integer d : data) {
gen.writeNumber(d);
}
gen.writeEndArray();
}
} } | public class class_name {
public static void writeInts(String fieldName, List<Integer> data, JsonGenerator gen)
throws IOException {
if (!data.isEmpty()) {
gen.writeArrayFieldStart(fieldName);
for (Integer d : data) {
gen.writeNumber(d); // depends on control dependency: [for], data = [d]
}
gen.writeEndArray();
}
} } |
public class class_name {
public void setBuckets(java.util.Collection<Bucket> buckets) {
if (buckets == null) {
this.buckets = null;
return;
}
this.buckets = new com.amazonaws.internal.SdkInternalList<Bucket>(buckets);
} } | public class class_name {
public void setBuckets(java.util.Collection<Bucket> buckets) {
if (buckets == null) {
this.buckets = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.buckets = new com.amazonaws.internal.SdkInternalList<Bucket>(buckets);
} } |
public class class_name {
private void handlePurgeProject(final HttpServletRequest req,
final HttpServletResponse resp, final Session session) throws ServletException,
IOException {
final User user = session.getUser();
final HashMap<String, Object> ret = new HashMap<>();
boolean isOperationSuccessful = true;
try {
Project project = null;
final String projectParam = getParam(req, "project");
if (StringUtils.isNumeric(projectParam)) {
project = this.projectManager.getProject(Integer.parseInt(projectParam)); // get
// project
// by
// Id
} else {
project = this.projectManager.getProject(projectParam); // get project by
// name (name cannot
// start
// from ints)
}
// invalid project
if (project == null) {
ret.put(ERROR_PARAM, "invalid project");
isOperationSuccessful = false;
}
// project is already deleted
if (isOperationSuccessful
&& this.projectManager.isActiveProject(project.getId())) {
ret.put(ERROR_PARAM, "Project " + project.getName()
+ " should be deleted before purging");
isOperationSuccessful = false;
}
// only eligible users can purge a project
if (isOperationSuccessful && !hasPermission(project, user, Type.ADMIN)) {
ret.put(ERROR_PARAM, "Cannot purge. User '" + user.getUserId()
+ "' is not an ADMIN.");
isOperationSuccessful = false;
}
if (isOperationSuccessful) {
this.projectManager.purgeProject(project, user);
}
} catch (final Exception e) {
ret.put(ERROR_PARAM, e.getMessage());
isOperationSuccessful = false;
}
ret.put("success", isOperationSuccessful);
this.writeJSON(resp, ret);
} } | public class class_name {
private void handlePurgeProject(final HttpServletRequest req,
final HttpServletResponse resp, final Session session) throws ServletException,
IOException {
final User user = session.getUser();
final HashMap<String, Object> ret = new HashMap<>();
boolean isOperationSuccessful = true;
try {
Project project = null;
final String projectParam = getParam(req, "project");
if (StringUtils.isNumeric(projectParam)) {
project = this.projectManager.getProject(Integer.parseInt(projectParam)); // get // depends on control dependency: [if], data = [none]
// project
// by
// Id
} else {
project = this.projectManager.getProject(projectParam); // get project by // depends on control dependency: [if], data = [none]
// name (name cannot
// start
// from ints)
}
// invalid project
if (project == null) {
ret.put(ERROR_PARAM, "invalid project"); // depends on control dependency: [if], data = [none]
isOperationSuccessful = false; // depends on control dependency: [if], data = [none]
}
// project is already deleted
if (isOperationSuccessful
&& this.projectManager.isActiveProject(project.getId())) {
ret.put(ERROR_PARAM, "Project " + project.getName()
+ " should be deleted before purging"); // depends on control dependency: [if], data = [none]
isOperationSuccessful = false; // depends on control dependency: [if], data = [none]
}
// only eligible users can purge a project
if (isOperationSuccessful && !hasPermission(project, user, Type.ADMIN)) {
ret.put(ERROR_PARAM, "Cannot purge. User '" + user.getUserId()
+ "' is not an ADMIN."); // depends on control dependency: [if], data = [none]
isOperationSuccessful = false; // depends on control dependency: [if], data = [none]
}
if (isOperationSuccessful) {
this.projectManager.purgeProject(project, user); // depends on control dependency: [if], data = [none]
}
} catch (final Exception e) {
ret.put(ERROR_PARAM, e.getMessage());
isOperationSuccessful = false;
}
ret.put("success", isOperationSuccessful);
this.writeJSON(resp, ret);
} } |
public class class_name {
@Override public JobV3 fillFromImpl( Job job ) {
if( job == null ) return this;
// Handle fields in subclasses:
PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES);
PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.CONSISTENT); // TODO: make consistent and remove
key = new JobKeyV3(job._key);
description = job._description;
warnings = job.warns();
progress = job.progress();
progress_msg = job.progress_msg();
// Bogus status; Job no longer has these states, but we fake it for /3/Job poller's.
// Notice state "CREATED" no long exists and is never returned.
// Notice new state "CANCEL_PENDING".
if( job.isRunning() )
if( job.stop_requested() ) status = "CANCEL_PENDING";
else status = "RUNNING";
else
if( job.stop_requested() ) status = "CANCELLED";
else status = "DONE";
Throwable ex = job.ex();
if( ex != null ) status = "FAILED";
exception = ex == null ? null : ex.toString();
if (ex!=null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
stacktrace = sw.toString();
}
msec = job.msec();
ready_for_view = job.readyForView();
Keyed dest_type;
Value value = null;
if (job._result != null) {
value = DKV.get(job._result);
}
if (value != null) {
dest_type = (Keyed) TypeMap.theFreezable(value.type());
} else {
dest_type = (Keyed) TypeMap.theFreezable(job._typeid);
}
dest = job._result == null ? null : KeyV3.make(dest_type.makeSchema(), job._result);
return this;
} } | public class class_name {
@Override public JobV3 fillFromImpl( Job job ) {
if( job == null ) return this;
// Handle fields in subclasses:
PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES);
PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.CONSISTENT); // TODO: make consistent and remove
key = new JobKeyV3(job._key);
description = job._description;
warnings = job.warns();
progress = job.progress();
progress_msg = job.progress_msg();
// Bogus status; Job no longer has these states, but we fake it for /3/Job poller's.
// Notice state "CREATED" no long exists and is never returned.
// Notice new state "CANCEL_PENDING".
if( job.isRunning() )
if( job.stop_requested() ) status = "CANCEL_PENDING";
else status = "RUNNING";
else
if( job.stop_requested() ) status = "CANCELLED";
else status = "DONE";
Throwable ex = job.ex();
if( ex != null ) status = "FAILED";
exception = ex == null ? null : ex.toString();
if (ex!=null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw); // depends on control dependency: [if], data = [none]
stacktrace = sw.toString(); // depends on control dependency: [if], data = [none]
}
msec = job.msec();
ready_for_view = job.readyForView();
Keyed dest_type;
Value value = null;
if (job._result != null) {
value = DKV.get(job._result); // depends on control dependency: [if], data = [(job._result]
}
if (value != null) {
dest_type = (Keyed) TypeMap.theFreezable(value.type()); // depends on control dependency: [if], data = [(value]
} else {
dest_type = (Keyed) TypeMap.theFreezable(job._typeid); // depends on control dependency: [if], data = [none]
}
dest = job._result == null ? null : KeyV3.make(dest_type.makeSchema(), job._result);
return this;
} } |
public class class_name {
public void removeOverlay(Overlay overlay) {
if (overlay==null) throw new NullPointerException();
for (Component c: layeredPane.getComponents()) {
if (c instanceof OverlayComponent && ((OverlayComponent)c).overlay==overlay) {
overlay.removeOverlayComponent((OverlayComponent)c);
layeredPane.remove(c);
layeredPane.revalidate();
layeredPane.repaint();
return;
}
}
throw new IllegalArgumentException("Overlay not part of this viewer");
} } | public class class_name {
public void removeOverlay(Overlay overlay) {
if (overlay==null) throw new NullPointerException();
for (Component c: layeredPane.getComponents()) {
if (c instanceof OverlayComponent && ((OverlayComponent)c).overlay==overlay) {
overlay.removeOverlayComponent((OverlayComponent)c); // depends on control dependency: [if], data = [none]
layeredPane.remove(c); // depends on control dependency: [if], data = [none]
layeredPane.revalidate(); // depends on control dependency: [if], data = [none]
layeredPane.repaint(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
throw new IllegalArgumentException("Overlay not part of this viewer");
} } |
public class class_name {
protected void beanDefinitionCheck() {
for (int i = 0; i < beanDefinitions.size(); i++) {
for (int j = i + 1; j < beanDefinitions.size(); j++) {
BeanDefinition b1 = beanDefinitions.get(i);
BeanDefinition b2 = beanDefinitions.get(j);
// Two components' id are equal
if (VerifyUtils.isNotEmpty(b1.getId())
&& VerifyUtils.isNotEmpty(b2.getId())
&& b1.getId().equals(b2.getId())) {
error("Duplicated bean ID of " + b1.getClassName() + " and " + b2.getClassName());
}
if (b1.getClassName().equals(b2.getClassName())) {
// Two components' class name are equal, but one of them does not set id.
if (VerifyUtils.isEmpty(b1.getId()) || VerifyUtils.isEmpty(b2.getId())) {
error("Duplicated class definition. Please set a ID for " + b1.getClassName());
} else {
// Their id are different, save them to memo.
// When the component is injecting by type, throw an exception.
errorMemo.add(b1.getClassName());
}
}
for (String iname1 : b1.getInterfaceNames()) {
for (String iname2 : b2.getInterfaceNames()) {
if (iname1.equals(iname2)) {
// Two components' interface name are equal, but one of them does not set id.
if (VerifyUtils.isEmpty(b1.getId()) || VerifyUtils.isEmpty(b2.getId())) {
error("Duplicated class definition. Please set a ID for " + b1.getClassName());
} else {
// Their id are different, save them to memo.
// When the component is injecting by type, throw an exception.
errorMemo.add(iname1);
}
}
}
}
}
}
} } | public class class_name {
protected void beanDefinitionCheck() {
for (int i = 0; i < beanDefinitions.size(); i++) {
for (int j = i + 1; j < beanDefinitions.size(); j++) {
BeanDefinition b1 = beanDefinitions.get(i);
BeanDefinition b2 = beanDefinitions.get(j);
// Two components' id are equal
if (VerifyUtils.isNotEmpty(b1.getId())
&& VerifyUtils.isNotEmpty(b2.getId())
&& b1.getId().equals(b2.getId())) {
error("Duplicated bean ID of " + b1.getClassName() + " and " + b2.getClassName());
// depends on control dependency: [if], data = [none]
}
if (b1.getClassName().equals(b2.getClassName())) {
// Two components' class name are equal, but one of them does not set id.
if (VerifyUtils.isEmpty(b1.getId()) || VerifyUtils.isEmpty(b2.getId())) {
error("Duplicated class definition. Please set a ID for " + b1.getClassName());
// depends on control dependency: [if], data = [none]
} else {
// Their id are different, save them to memo.
// When the component is injecting by type, throw an exception.
errorMemo.add(b1.getClassName());
// depends on control dependency: [if], data = [none]
}
}
for (String iname1 : b1.getInterfaceNames()) {
for (String iname2 : b2.getInterfaceNames()) {
if (iname1.equals(iname2)) {
// Two components' interface name are equal, but one of them does not set id.
if (VerifyUtils.isEmpty(b1.getId()) || VerifyUtils.isEmpty(b2.getId())) {
error("Duplicated class definition. Please set a ID for " + b1.getClassName());
// depends on control dependency: [if], data = [none]
} else {
// Their id are different, save them to memo.
// When the component is injecting by type, throw an exception.
errorMemo.add(iname1);
// depends on control dependency: [if], data = [none]
}
}
}
}
}
}
} } |
public class class_name {
public static <T> List<T> getAt(ListWithDefault<T> self, Range range) {
RangeInfo info = subListBorders(self.size(), range);
// if a positive index is accessed not initialized so far
// initialization up to that index takes place
if (self.size() < info.to) {
self.get(info.to - 1);
}
List<T> answer = self.subList(info.from, info.to);
if (info.reverse) {
answer = ListWithDefault.newInstance(reverse(answer), self.isLazyDefaultValues(), self.getInitClosure());
} else {
// instead of using the SubList backed by the parent list, a new ArrayList instance is used
answer = ListWithDefault.newInstance(new ArrayList<T>(answer), self.isLazyDefaultValues(), self.getInitClosure());
}
return answer;
} } | public class class_name {
public static <T> List<T> getAt(ListWithDefault<T> self, Range range) {
RangeInfo info = subListBorders(self.size(), range);
// if a positive index is accessed not initialized so far
// initialization up to that index takes place
if (self.size() < info.to) {
self.get(info.to - 1); // depends on control dependency: [if], data = [none]
}
List<T> answer = self.subList(info.from, info.to);
if (info.reverse) {
answer = ListWithDefault.newInstance(reverse(answer), self.isLazyDefaultValues(), self.getInitClosure()); // depends on control dependency: [if], data = [none]
} else {
// instead of using the SubList backed by the parent list, a new ArrayList instance is used
answer = ListWithDefault.newInstance(new ArrayList<T>(answer), self.isLazyDefaultValues(), self.getInitClosure()); // depends on control dependency: [if], data = [none]
}
return answer;
} } |
public class class_name {
public List<Model> getModels() {
ArrayList<Model> list = new ArrayList<>(mItems.size());
for (Item item : mItems.getItems()) {
if (mReverseInterceptor != null) {
list.add(mReverseInterceptor.intercept(item));
} else if (item instanceof IModelItem) {
list.add((Model) ((IModelItem) item).getModel());
} else {
throw new RuntimeException("to get the list of models, the item either needs to implement `IModelItem` or you have to provide a `reverseInterceptor`");
}
}
return list;
} } | public class class_name {
public List<Model> getModels() {
ArrayList<Model> list = new ArrayList<>(mItems.size());
for (Item item : mItems.getItems()) {
if (mReverseInterceptor != null) {
list.add(mReverseInterceptor.intercept(item)); // depends on control dependency: [if], data = [(mReverseInterceptor]
} else if (item instanceof IModelItem) {
list.add((Model) ((IModelItem) item).getModel()); // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("to get the list of models, the item either needs to implement `IModelItem` or you have to provide a `reverseInterceptor`");
}
}
return list;
} } |
public class class_name {
public void removeAnchor(String a) {
if(anchors == null) {
anchors = new HashMap<String, Node>();
}
anchors.put(a, null);
} } | public class class_name {
public void removeAnchor(String a) {
if(anchors == null) {
anchors = new HashMap<String, Node>(); // depends on control dependency: [if], data = [none]
}
anchors.put(a, null);
} } |
public class class_name {
private void stage5Term(final ProtoNetwork network, int pct) {
if (pct > 0) {
stageOutput("Equivalencing terms");
int tct = p2.stage3EquivalenceTerms(network);
stageOutput("(" + tct + " equivalences)");
} else {
stageOutput("Skipping term equivalencing");
}
} } | public class class_name {
private void stage5Term(final ProtoNetwork network, int pct) {
if (pct > 0) {
stageOutput("Equivalencing terms"); // depends on control dependency: [if], data = [none]
int tct = p2.stage3EquivalenceTerms(network);
stageOutput("(" + tct + " equivalences)"); // depends on control dependency: [if], data = [none]
} else {
stageOutput("Skipping term equivalencing"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static void sendResponse(String output, HttpServletResponse response)
throws IOException {
PrintWriter out = null;
try {
out = response.getWriter();
out.write(output);
} finally {
if (out != null) {
out.close();
}
}
} } | public class class_name {
static void sendResponse(String output, HttpServletResponse response)
throws IOException {
PrintWriter out = null;
try {
out = response.getWriter();
out.write(output);
} finally {
if (out != null) {
out.close(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public void onResume() {
super.onResume();
if(ProfileService.getInstance(getActivity().getApplicationContext()).isActive(this, Profile.NETWORK)) {
if(!PermissionUtils.isGranted(this, Manifest.permission.ACCESS_NETWORK_STATE)) {
Log.e(getClass().getSimpleName(), "Failed to register a receiver for changes in network state. ",
new IckleBotRuntimeException(
new PermissionDeniedException(Manifest.permission.ACCESS_NETWORK_STATE, Profile.NETWORK)));
}
else {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(networkStateReceiver, intentFilter);
}
}
} } | public class class_name {
@Override
public void onResume() {
super.onResume();
if(ProfileService.getInstance(getActivity().getApplicationContext()).isActive(this, Profile.NETWORK)) {
if(!PermissionUtils.isGranted(this, Manifest.permission.ACCESS_NETWORK_STATE)) {
Log.e(getClass().getSimpleName(), "Failed to register a receiver for changes in network state. ",
new IckleBotRuntimeException(
new PermissionDeniedException(Manifest.permission.ACCESS_NETWORK_STATE, Profile.NETWORK))); // depends on control dependency: [if], data = [none]
}
else {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // depends on control dependency: [if], data = [none]
getActivity().registerReceiver(networkStateReceiver, intentFilter); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static int[] markWalkableTriangles(Context ctx, float walkableSlopeAngle, float[] verts, int[] tris, int nt,
AreaModification areaMod) {
int[] areas = new int[nt];
float walkableThr = (float) Math.cos(walkableSlopeAngle / 180.0f * Math.PI);
float norm[] = new float[3];
for (int i = 0; i < nt; ++i) {
int tri = i * 3;
calcTriNormal(verts, tris[tri], tris[tri + 1], tris[tri + 2], norm);
// Check if the face is walkable.
if (norm[1] > walkableThr)
areas[i] = areaMod.apply(areas[i]);
}
return areas;
} } | public class class_name {
public static int[] markWalkableTriangles(Context ctx, float walkableSlopeAngle, float[] verts, int[] tris, int nt,
AreaModification areaMod) {
int[] areas = new int[nt];
float walkableThr = (float) Math.cos(walkableSlopeAngle / 180.0f * Math.PI);
float norm[] = new float[3];
for (int i = 0; i < nt; ++i) {
int tri = i * 3;
calcTriNormal(verts, tris[tri], tris[tri + 1], tris[tri + 2], norm); // depends on control dependency: [for], data = [none]
// Check if the face is walkable.
if (norm[1] > walkableThr)
areas[i] = areaMod.apply(areas[i]);
}
return areas;
} } |
public class class_name {
public static void split2(InterleavedF32 interleaved , GrayF32 band0 , GrayF32 band1 ) {
if( interleaved.numBands != 2 )
throw new IllegalArgumentException("Input interleaved image must have 2 bands");
InputSanityCheck.checkSameShape(band0, interleaved);
InputSanityCheck.checkSameShape(band1, interleaved);
for( int y = 0; y < interleaved.height; y++ ) {
int indexTran = interleaved.startIndex + y*interleaved.stride;
int indexReal = band0.startIndex + y*band0.stride;
int indexImg = band1.startIndex + y*band1.stride;
for( int x = 0; x < interleaved.width; x++, indexTran += 2 ) {
band0.data[indexReal++] = interleaved.data[indexTran];
band1.data[indexImg++] = interleaved.data[indexTran+1];
}
}
} } | public class class_name {
public static void split2(InterleavedF32 interleaved , GrayF32 band0 , GrayF32 band1 ) {
if( interleaved.numBands != 2 )
throw new IllegalArgumentException("Input interleaved image must have 2 bands");
InputSanityCheck.checkSameShape(band0, interleaved);
InputSanityCheck.checkSameShape(band1, interleaved);
for( int y = 0; y < interleaved.height; y++ ) {
int indexTran = interleaved.startIndex + y*interleaved.stride;
int indexReal = band0.startIndex + y*band0.stride;
int indexImg = band1.startIndex + y*band1.stride;
for( int x = 0; x < interleaved.width; x++, indexTran += 2 ) {
band0.data[indexReal++] = interleaved.data[indexTran]; // depends on control dependency: [for], data = [none]
band1.data[indexImg++] = interleaved.data[indexTran+1]; // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
public void dumpGrid() {
StringBuilder dumpGridSb = new StringBuilder();
Formatter fmt = new Formatter(dumpGridSb);
fmt.format(" ");
for (int iCol = 0; iCol < 9; iCol++) {
fmt.format("Col: %d ", iCol);
}
fmt.format("\n");
for (int iRow = 0; iRow < 9; iRow++) {
fmt.format("Row " + iRow + ": ");
for (int iCol = 0; iCol < 9; iCol++) {
if (cells[iRow][iCol].getValue() != null) {
fmt.format(" --- %d --- ", cells[iRow][iCol].getValue());
} else {
StringBuilder sb = new StringBuilder();
Set<Integer> perms = cells[iRow][iCol].getFree();
for (int i = 1; i <= 9; i++) {
if (perms.contains(i)) {
sb.append(i);
} else {
sb.append(' ');
}
}
fmt.format(" %-10s", sb.toString());
}
}
fmt.format("\n");
}
fmt.close();
System.out.println(dumpGridSb);
} } | public class class_name {
public void dumpGrid() {
StringBuilder dumpGridSb = new StringBuilder();
Formatter fmt = new Formatter(dumpGridSb);
fmt.format(" ");
for (int iCol = 0; iCol < 9; iCol++) {
fmt.format("Col: %d ", iCol); // depends on control dependency: [for], data = [iCol]
}
fmt.format("\n");
for (int iRow = 0; iRow < 9; iRow++) {
fmt.format("Row " + iRow + ": "); // depends on control dependency: [for], data = [iRow]
for (int iCol = 0; iCol < 9; iCol++) {
if (cells[iRow][iCol].getValue() != null) {
fmt.format(" --- %d --- ", cells[iRow][iCol].getValue()); // depends on control dependency: [if], data = [none]
} else {
StringBuilder sb = new StringBuilder();
Set<Integer> perms = cells[iRow][iCol].getFree();
for (int i = 1; i <= 9; i++) {
if (perms.contains(i)) {
sb.append(i); // depends on control dependency: [if], data = [none]
} else {
sb.append(' '); // depends on control dependency: [if], data = [none]
}
}
fmt.format(" %-10s", sb.toString()); // depends on control dependency: [if], data = [none]
}
}
fmt.format("\n"); // depends on control dependency: [for], data = [none]
}
fmt.close();
System.out.println(dumpGridSb);
} } |
public class class_name {
@SuppressWarnings({"unused"})
private void doTreeTagOld(JCas jcas) {
File tmpDocument = null;
BufferedWriter tmpFileWriter;
ArrayList<Token> tokens = new ArrayList<Token>();
try {
// create a temporary file and write our pre-existing tokens to it.
tmpDocument = File.createTempFile("postokens", null);
tmpFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpDocument), "UTF-8"));
// iterate over existing tokens
FSIterator ai = jcas.getAnnotationIndex(Token.type).iterator();
while(ai.hasNext()) {
Token t = (Token) ai.next();
tokens.add(t);
if (!(t.getBegin() == t.getEnd())){
tmpFileWriter.write(t.getCoveredText() + ttprops.newLineSeparator);
}
}
tmpFileWriter.close();
} catch(IOException e) {
Logger.printError("Something went wrong creating a temporary file for the treetagger to process.");
System.exit(-1);
}
// Possible End-of-Sentence Tags
HashSet<String> hsEndOfSentenceTag = new HashSet<String>();
hsEndOfSentenceTag.add("SENT"); // ENGLISH, FRENCH, GREEK,
hsEndOfSentenceTag.add("$."); // GERMAN, DUTCH
hsEndOfSentenceTag.add("FS"); // SPANISH
hsEndOfSentenceTag.add("_Z_Fst"); // ESTONIAN
hsEndOfSentenceTag.add("_Z_Int"); // ESTONIAN
hsEndOfSentenceTag.add("_Z_Exc"); // ESTONIAN
hsEndOfSentenceTag.add("ew"); // CHINESE
try {
Process p = ttprops.getTreeTaggingProcess(tmpDocument);
Logger.printDetail(component, "TreeTagger (pos tagging) with: " + ttprops.parFileName);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
Sentence sentence = null;
// iterate over all the output lines and tokens array (which have the same source and are hence symmetric)
int i = 0;
String s = null;
while ((s = in.readLine()) != null) {
// grab a token
Token token = tokens.get(i++);
// modified (Aug 29, 2011): Handle empty tokens (such as empty lines) in input file
while (token.getCoveredText().equals("")){
// if part of the configuration, also add sentences to the jcas document
if ((annotate_sentences) && (token.getPos() != null && token.getPos().equals("EMPTYLINE"))) {
// Establish sentence structure
if (sentence == null) {
sentence = new Sentence(jcas);
sentence.setBegin(token.getBegin());
}
// Finish current sentence if end-of-sentence pos was found or document ended
sentence.setEnd(token.getEnd());
if (sentence.getBegin() < sentence.getEnd()){
sentence.addToIndexes();
}
// Make sure current sentence is not active anymore so that a new one might be created
sentence = null;
// sentence = new Sentence(jcas);
}
token.removeFromIndexes();
token = tokens.get(i++);
}
// remove tokens, otherwise they are in the index twice
token.removeFromIndexes();
// set part of speech tag and add to indexes again
if (!(token.getCoveredText().equals(""))){
token.setPos(s);
token.addToIndexes();
}
// if part of the configuration, also add sentences to the jcas document
if(annotate_sentences) {
// Establish sentence structure
if (sentence == null) {
sentence = new Sentence(jcas);
sentence.setBegin(token.getBegin());
}
// Finish current sentence if end-of-sentence pos was found or document ended
if (hsEndOfSentenceTag.contains(s) || i == tokens.size()) {
sentence.setEnd(token.getEnd());
sentence.addToIndexes();
// Make sure current sentence is not active anymore so that a new one might be created
sentence = null;
}
}
}
while (i < tokens.size()){
if (!(sentence == null)){
sentence.setEnd(tokens.get(tokens.size()-1).getEnd());
sentence.addToIndexes();
}
Token token = tokens.get(i++);
if (token.getPos() != null && token.getPos().equals("EMPTYLINE")){
token.removeFromIndexes();
}
}
in.close();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Delete temporary files
tmpDocument.delete();
}
} } | public class class_name {
@SuppressWarnings({"unused"})
private void doTreeTagOld(JCas jcas) {
File tmpDocument = null;
BufferedWriter tmpFileWriter;
ArrayList<Token> tokens = new ArrayList<Token>();
try {
// create a temporary file and write our pre-existing tokens to it.
tmpDocument = File.createTempFile("postokens", null); // depends on control dependency: [try], data = [none]
tmpFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpDocument), "UTF-8")); // depends on control dependency: [try], data = [none]
// iterate over existing tokens
FSIterator ai = jcas.getAnnotationIndex(Token.type).iterator();
while(ai.hasNext()) {
Token t = (Token) ai.next();
tokens.add(t); // depends on control dependency: [while], data = [none]
if (!(t.getBegin() == t.getEnd())){
tmpFileWriter.write(t.getCoveredText() + ttprops.newLineSeparator); // depends on control dependency: [if], data = [none]
}
}
tmpFileWriter.close(); // depends on control dependency: [try], data = [none]
} catch(IOException e) {
Logger.printError("Something went wrong creating a temporary file for the treetagger to process.");
System.exit(-1);
} // depends on control dependency: [catch], data = [none]
// Possible End-of-Sentence Tags
HashSet<String> hsEndOfSentenceTag = new HashSet<String>();
hsEndOfSentenceTag.add("SENT"); // ENGLISH, FRENCH, GREEK,
hsEndOfSentenceTag.add("$."); // GERMAN, DUTCH
hsEndOfSentenceTag.add("FS"); // SPANISH
hsEndOfSentenceTag.add("_Z_Fst"); // ESTONIAN
hsEndOfSentenceTag.add("_Z_Int"); // ESTONIAN
hsEndOfSentenceTag.add("_Z_Exc"); // ESTONIAN
hsEndOfSentenceTag.add("ew"); // CHINESE
try {
Process p = ttprops.getTreeTaggingProcess(tmpDocument);
Logger.printDetail(component, "TreeTagger (pos tagging) with: " + ttprops.parFileName); // depends on control dependency: [try], data = [none]
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
Sentence sentence = null;
// iterate over all the output lines and tokens array (which have the same source and are hence symmetric)
int i = 0;
String s = null;
while ((s = in.readLine()) != null) {
// grab a token
Token token = tokens.get(i++);
// modified (Aug 29, 2011): Handle empty tokens (such as empty lines) in input file
while (token.getCoveredText().equals("")){
// if part of the configuration, also add sentences to the jcas document
if ((annotate_sentences) && (token.getPos() != null && token.getPos().equals("EMPTYLINE"))) {
// Establish sentence structure
if (sentence == null) {
sentence = new Sentence(jcas); // depends on control dependency: [if], data = [none]
sentence.setBegin(token.getBegin()); // depends on control dependency: [if], data = [none]
}
// Finish current sentence if end-of-sentence pos was found or document ended
sentence.setEnd(token.getEnd()); // depends on control dependency: [if], data = [none]
if (sentence.getBegin() < sentence.getEnd()){
sentence.addToIndexes(); // depends on control dependency: [if], data = [none]
}
// Make sure current sentence is not active anymore so that a new one might be created
sentence = null; // depends on control dependency: [if], data = [none]
// sentence = new Sentence(jcas);
}
token.removeFromIndexes(); // depends on control dependency: [while], data = [none]
token = tokens.get(i++); // depends on control dependency: [while], data = [none]
}
// remove tokens, otherwise they are in the index twice
token.removeFromIndexes(); // depends on control dependency: [while], data = [none]
// set part of speech tag and add to indexes again
if (!(token.getCoveredText().equals(""))){
token.setPos(s); // depends on control dependency: [if], data = [none]
token.addToIndexes(); // depends on control dependency: [if], data = [none]
}
// if part of the configuration, also add sentences to the jcas document
if(annotate_sentences) {
// Establish sentence structure
if (sentence == null) {
sentence = new Sentence(jcas); // depends on control dependency: [if], data = [none]
sentence.setBegin(token.getBegin()); // depends on control dependency: [if], data = [none]
}
// Finish current sentence if end-of-sentence pos was found or document ended
if (hsEndOfSentenceTag.contains(s) || i == tokens.size()) {
sentence.setEnd(token.getEnd()); // depends on control dependency: [if], data = [none]
sentence.addToIndexes(); // depends on control dependency: [if], data = [none]
// Make sure current sentence is not active anymore so that a new one might be created
sentence = null; // depends on control dependency: [if], data = [none]
}
}
}
while (i < tokens.size()){
if (!(sentence == null)){
sentence.setEnd(tokens.get(tokens.size()-1).getEnd()); // depends on control dependency: [if], data = [none]
sentence.addToIndexes(); // depends on control dependency: [if], data = [none]
}
Token token = tokens.get(i++);
if (token.getPos() != null && token.getPos().equals("EMPTYLINE")){
token.removeFromIndexes(); // depends on control dependency: [if], data = [none]
}
}
in.close(); // depends on control dependency: [try], data = [none]
p.destroy(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} finally { // depends on control dependency: [catch], data = [none]
// Delete temporary files
tmpDocument.delete();
}
} } |
public class class_name {
public static Instant parseInstant(String value) {
TemporalAccessor temporalAccessor =
DateTimeFormatter.ofPattern(LOOSE_PARSER_FORMAT)
.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor).toInstant();
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault()).toInstant();
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault()).toInstant();
} } | public class class_name {
public static Instant parseInstant(String value) {
TemporalAccessor temporalAccessor =
DateTimeFormatter.ofPattern(LOOSE_PARSER_FORMAT)
.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor).toInstant(); // depends on control dependency: [if], data = [none]
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault()).toInstant(); // depends on control dependency: [if], data = [none]
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault()).toInstant();
} } |
public class class_name {
protected void extendPathFilter(List<Term> terms, String searchRoot) {
if (!CmsResource.isFolder(searchRoot)) {
searchRoot += "/";
}
terms.add(new Term(CmsSearchField.FIELD_PARENT_FOLDERS, searchRoot));
} } | public class class_name {
protected void extendPathFilter(List<Term> terms, String searchRoot) {
if (!CmsResource.isFolder(searchRoot)) {
searchRoot += "/"; // depends on control dependency: [if], data = [none]
}
terms.add(new Term(CmsSearchField.FIELD_PARENT_FOLDERS, searchRoot));
} } |
public class class_name {
public void setResourceId(String resourceId) {
try {
if (!m_resourceBuilder.isFolder()) {
m_resourceBuilder.setResourceId(new CmsUUID(resourceId));
} else {
m_resourceBuilder.setResourceId(new CmsUUID());
}
} catch (Throwable e) {
setThrowable(e);
}
} } | public class class_name {
public void setResourceId(String resourceId) {
try {
if (!m_resourceBuilder.isFolder()) {
m_resourceBuilder.setResourceId(new CmsUUID(resourceId)); // depends on control dependency: [if], data = [none]
} else {
m_resourceBuilder.setResourceId(new CmsUUID()); // depends on control dependency: [if], data = [none]
}
} catch (Throwable e) {
setThrowable(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static double getLimitByUserAndCounter(EntityManager em, PrincipalUser user, PolicyCounter counter) {
PolicyLimit pLimit = findPolicyLimitByUserAndCounter(em, user, counter);
if (pLimit != null) {
return pLimit.getLimit();
}
return counter.getDefaultValue();
} } | public class class_name {
public static double getLimitByUserAndCounter(EntityManager em, PrincipalUser user, PolicyCounter counter) {
PolicyLimit pLimit = findPolicyLimitByUserAndCounter(em, user, counter);
if (pLimit != null) {
return pLimit.getLimit(); // depends on control dependency: [if], data = [none]
}
return counter.getDefaultValue();
} } |
public class class_name {
protected void injectMethodTimer() {
methodEntertime = newLocal(Type.LONG_TYPE);
invokeStatic(Type.getType(System.class), Method.getMethod(CURRENT_TIME_MILLIS_METHODNAME));
storeLocal(methodEntertime);
/*
* Inject debug information
*/
if (Agent.debug) {
getStatic(Type.getType(System.class), "err", Type.getType(PrintStream.class));
push("Javametrics: Calling instrumented method: " + className + "." + methodName);
invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println(java.lang.String)"));
}
} } | public class class_name {
protected void injectMethodTimer() {
methodEntertime = newLocal(Type.LONG_TYPE);
invokeStatic(Type.getType(System.class), Method.getMethod(CURRENT_TIME_MILLIS_METHODNAME));
storeLocal(methodEntertime);
/*
* Inject debug information
*/
if (Agent.debug) {
getStatic(Type.getType(System.class), "err", Type.getType(PrintStream.class)); // depends on control dependency: [if], data = [none]
push("Javametrics: Calling instrumented method: " + className + "." + methodName); // depends on control dependency: [if], data = [none]
invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println(java.lang.String)")); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Row addLastChild()
{
assert (this.treeTable.m_nbColumns > 0) : "Table should have at least one column before adding items";
Row newItem = new Row( this.treeTable );
newItem.m_tr = DOM.createTR();
newItem.m_tr.setPropertyObject( "linkedItem", newItem );
newItem.m_tr.setInnerHTML( this.treeTable.m_rowTemplate );
// DOM add
Row lastParentLeaf = getLastLeaf();
Element trToInsertAfter = lastParentLeaf.m_tr;
if( trToInsertAfter != null )
{
int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter );
int before = after + 1;
DOM.insertChild( this.treeTable.m_body, newItem.m_tr, before );
}
else
{
DOM.appendChild( this.treeTable.m_body, newItem.m_tr );
}
// logical add
newItem.m_parent = this;
getChilds().add( newItem );
signalStateChange();
// take care of the left padding
Element firstTd = DOM.getChild( newItem.m_tr, 0 );
firstTd.getStyle().setPaddingLeft( newItem.getLevel() * this.treeTable.treePadding, Unit.PX );
return newItem;
} } | public class class_name {
public Row addLastChild()
{
assert (this.treeTable.m_nbColumns > 0) : "Table should have at least one column before adding items";
Row newItem = new Row( this.treeTable );
newItem.m_tr = DOM.createTR();
newItem.m_tr.setPropertyObject( "linkedItem", newItem );
newItem.m_tr.setInnerHTML( this.treeTable.m_rowTemplate );
// DOM add
Row lastParentLeaf = getLastLeaf();
Element trToInsertAfter = lastParentLeaf.m_tr;
if( trToInsertAfter != null )
{
int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter );
int before = after + 1;
DOM.insertChild( this.treeTable.m_body, newItem.m_tr, before ); // depends on control dependency: [if], data = [none]
}
else
{
DOM.appendChild( this.treeTable.m_body, newItem.m_tr ); // depends on control dependency: [if], data = [none]
}
// logical add
newItem.m_parent = this;
getChilds().add( newItem );
signalStateChange();
// take care of the left padding
Element firstTd = DOM.getChild( newItem.m_tr, 0 );
firstTd.getStyle().setPaddingLeft( newItem.getLevel() * this.treeTable.treePadding, Unit.PX );
return newItem;
} } |
public class class_name {
public void marshall(RemoveLayerVersionPermissionRequest removeLayerVersionPermissionRequest, ProtocolMarshaller protocolMarshaller) {
if (removeLayerVersionPermissionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getLayerName(), LAYERNAME_BINDING);
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getVersionNumber(), VERSIONNUMBER_BINDING);
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getStatementId(), STATEMENTID_BINDING);
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getRevisionId(), REVISIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RemoveLayerVersionPermissionRequest removeLayerVersionPermissionRequest, ProtocolMarshaller protocolMarshaller) {
if (removeLayerVersionPermissionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getLayerName(), LAYERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getVersionNumber(), VERSIONNUMBER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getStatementId(), STATEMENTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeLayerVersionPermissionRequest.getRevisionId(), REVISIONID_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 static void computeCosineWindow( GrayF64 cosine ) {
double cosX[] = new double[ cosine.width ];
for( int x = 0; x < cosine.width; x++ ) {
cosX[x] = 0.5*(1 - Math.cos( 2.0*Math.PI*x/(cosine.width-1) ));
}
for( int y = 0; y < cosine.height; y++ ) {
int index = cosine.startIndex + y*cosine.stride;
double cosY = 0.5*(1 - Math.cos( 2.0*Math.PI*y/(cosine.height-1) ));
for( int x = 0; x < cosine.width; x++ ) {
cosine.data[index++] = cosX[x]*cosY;
}
}
} } | public class class_name {
protected static void computeCosineWindow( GrayF64 cosine ) {
double cosX[] = new double[ cosine.width ];
for( int x = 0; x < cosine.width; x++ ) {
cosX[x] = 0.5*(1 - Math.cos( 2.0*Math.PI*x/(cosine.width-1) )); // depends on control dependency: [for], data = [x]
}
for( int y = 0; y < cosine.height; y++ ) {
int index = cosine.startIndex + y*cosine.stride;
double cosY = 0.5*(1 - Math.cos( 2.0*Math.PI*y/(cosine.height-1) ));
for( int x = 0; x < cosine.width; x++ ) {
cosine.data[index++] = cosX[x]*cosY; // depends on control dependency: [for], data = [x]
}
}
} } |
public class class_name {
public String getProxyTicketFor(final String service) {
if (this.attributePrincipal != null) {
logger.debug("Requesting PT from principal: {} and for service: {}", attributePrincipal, service);
final String pt = this.attributePrincipal.getProxyTicketFor(service);
logger.debug("Get PT: {}", pt);
return pt;
}
return null;
} } | public class class_name {
public String getProxyTicketFor(final String service) {
if (this.attributePrincipal != null) {
logger.debug("Requesting PT from principal: {} and for service: {}", attributePrincipal, service); // depends on control dependency: [if], data = [none]
final String pt = this.attributePrincipal.getProxyTicketFor(service);
logger.debug("Get PT: {}", pt); // depends on control dependency: [if], data = [none]
return pt; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
void gcInternal()
{
JNIReference ref = null;
while ((ref = (JNIReference) mRefQueue.poll()) != null)
{
ref.delete();
}
} } | public class class_name {
void gcInternal()
{
JNIReference ref = null;
while ((ref = (JNIReference) mRefQueue.poll()) != null)
{
ref.delete(); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public java.util.List<ScheduledInstancesNetworkInterface> getNetworkInterfaces() {
if (networkInterfaces == null) {
networkInterfaces = new com.amazonaws.internal.SdkInternalList<ScheduledInstancesNetworkInterface>();
}
return networkInterfaces;
} } | public class class_name {
public java.util.List<ScheduledInstancesNetworkInterface> getNetworkInterfaces() {
if (networkInterfaces == null) {
networkInterfaces = new com.amazonaws.internal.SdkInternalList<ScheduledInstancesNetworkInterface>(); // depends on control dependency: [if], data = [none]
}
return networkInterfaces;
} } |
public class class_name {
public static String remove(String str, char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
} } | public class class_name {
public static String remove(String str, char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str; // depends on control dependency: [if], data = [none]
}
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i]; // depends on control dependency: [if], data = [none]
}
}
return new String(chars, 0, pos);
} } |
public class class_name {
private static DoubleConsumer adapt(Sink<Double> sink) {
if (sink instanceof DoubleConsumer) {
return (DoubleConsumer) sink;
} else {
// if (Tripwire.ENABLED)
// Tripwire.trip(AbstractPipeline.class,
// "using DoubleStream.adapt(Sink<Double> s)");
return sink::accept;
}
} } | public class class_name {
private static DoubleConsumer adapt(Sink<Double> sink) {
if (sink instanceof DoubleConsumer) {
return (DoubleConsumer) sink; // depends on control dependency: [if], data = [none]
} else {
// if (Tripwire.ENABLED)
// Tripwire.trip(AbstractPipeline.class,
// "using DoubleStream.adapt(Sink<Double> s)");
return sink::accept; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void locked (@Nonnull final Runnable aRunnable)
{
ValueEnforcer.notNull (aRunnable, "Runnable");
lock ();
try
{
aRunnable.run ();
}
finally
{
unlock ();
}
} } | public class class_name {
public void locked (@Nonnull final Runnable aRunnable)
{
ValueEnforcer.notNull (aRunnable, "Runnable");
lock ();
try
{
aRunnable.run (); // depends on control dependency: [try], data = [none]
}
finally
{
unlock ();
}
} } |
public class class_name {
public void copyFrom(LockSet other) {
if (other.array.length != array.length) {
array = new int[other.array.length];
}
System.arraycopy(other.array, 0, array, 0, array.length);
this.defaultLockCount = other.defaultLockCount;
} } | public class class_name {
public void copyFrom(LockSet other) {
if (other.array.length != array.length) {
array = new int[other.array.length]; // depends on control dependency: [if], data = [none]
}
System.arraycopy(other.array, 0, array, 0, array.length);
this.defaultLockCount = other.defaultLockCount;
} } |
public class class_name {
public void marshall(UpdateAppRequest updateAppRequest, ProtocolMarshaller protocolMarshaller) {
if (updateAppRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateAppRequest.getAppId(), APPID_BINDING);
protocolMarshaller.marshall(updateAppRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(updateAppRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(updateAppRequest.getRoleName(), ROLENAME_BINDING);
protocolMarshaller.marshall(updateAppRequest.getServerGroups(), SERVERGROUPS_BINDING);
protocolMarshaller.marshall(updateAppRequest.getTags(), TAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateAppRequest updateAppRequest, ProtocolMarshaller protocolMarshaller) {
if (updateAppRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateAppRequest.getAppId(), APPID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateAppRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateAppRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateAppRequest.getRoleName(), ROLENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateAppRequest.getServerGroups(), SERVERGROUPS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateAppRequest.getTags(), TAGS_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 {
public Query query(DataRange dataRange) {
RowPosition startPosition = dataRange.startKey();
RowPosition stopPosition = dataRange.stopKey();
Token startToken = startPosition.getToken();
Token stopToken = stopPosition.getToken();
boolean isSameToken = startToken.compareTo(stopToken) == 0 && !tokenMapper.isMinimum(startToken);
BooleanClause.Occur occur = isSameToken ? MUST : SHOULD;
boolean includeStart = tokenMapper.includeStart(startPosition);
boolean includeStop = tokenMapper.includeStop(stopPosition);
SliceQueryFilter sqf;
if (startPosition instanceof DecoratedKey) {
sqf = (SliceQueryFilter) dataRange.columnFilter(((DecoratedKey) startPosition).getKey());
} else {
sqf = (SliceQueryFilter) dataRange.columnFilter(ByteBufferUtil.EMPTY_BYTE_BUFFER);
}
Composite startName = sqf.start();
Composite stopName = sqf.finish();
BooleanQuery query = new BooleanQuery();
if (!startName.isEmpty()) {
BooleanQuery q = new BooleanQuery();
q.add(tokenMapper.query(startToken), MUST);
q.add(clusteringKeyMapper.query(startName, null), MUST);
query.add(q, occur);
includeStart = false;
}
if (!stopName.isEmpty()) {
BooleanQuery q = new BooleanQuery();
q.add(tokenMapper.query(stopToken), MUST);
q.add(clusteringKeyMapper.query(null, stopName), MUST);
query.add(q, occur);
includeStop = false;
}
if (!isSameToken) {
Query rangeQuery = tokenMapper.query(startToken, stopToken, includeStart, includeStop);
if (rangeQuery != null) query.add(rangeQuery, SHOULD);
} else if (query.getClauses().length == 0) {
return tokenMapper.query(startToken);
}
return query.getClauses().length == 0 ? null : query;
} } | public class class_name {
public Query query(DataRange dataRange) {
RowPosition startPosition = dataRange.startKey();
RowPosition stopPosition = dataRange.stopKey();
Token startToken = startPosition.getToken();
Token stopToken = stopPosition.getToken();
boolean isSameToken = startToken.compareTo(stopToken) == 0 && !tokenMapper.isMinimum(startToken);
BooleanClause.Occur occur = isSameToken ? MUST : SHOULD;
boolean includeStart = tokenMapper.includeStart(startPosition);
boolean includeStop = tokenMapper.includeStop(stopPosition);
SliceQueryFilter sqf;
if (startPosition instanceof DecoratedKey) {
sqf = (SliceQueryFilter) dataRange.columnFilter(((DecoratedKey) startPosition).getKey()); // depends on control dependency: [if], data = [none]
} else {
sqf = (SliceQueryFilter) dataRange.columnFilter(ByteBufferUtil.EMPTY_BYTE_BUFFER); // depends on control dependency: [if], data = [none]
}
Composite startName = sqf.start();
Composite stopName = sqf.finish();
BooleanQuery query = new BooleanQuery();
if (!startName.isEmpty()) {
BooleanQuery q = new BooleanQuery();
q.add(tokenMapper.query(startToken), MUST); // depends on control dependency: [if], data = [none]
q.add(clusteringKeyMapper.query(startName, null), MUST); // depends on control dependency: [if], data = [none]
query.add(q, occur); // depends on control dependency: [if], data = [none]
includeStart = false; // depends on control dependency: [if], data = [none]
}
if (!stopName.isEmpty()) {
BooleanQuery q = new BooleanQuery();
q.add(tokenMapper.query(stopToken), MUST); // depends on control dependency: [if], data = [none]
q.add(clusteringKeyMapper.query(null, stopName), MUST); // depends on control dependency: [if], data = [none]
query.add(q, occur); // depends on control dependency: [if], data = [none]
includeStop = false; // depends on control dependency: [if], data = [none]
}
if (!isSameToken) {
Query rangeQuery = tokenMapper.query(startToken, stopToken, includeStart, includeStop);
if (rangeQuery != null) query.add(rangeQuery, SHOULD);
} else if (query.getClauses().length == 0) {
return tokenMapper.query(startToken); // depends on control dependency: [if], data = [none]
}
return query.getClauses().length == 0 ? null : query;
} } |
public class class_name {
public List<Column> getColumns(final String catalog, final String schemaPattern, final String tableNamePattern,
final String columnNamePattern)
throws SQLException {
final List<Column> list = new ArrayList<>();
try (ResultSet results = databaseMetadata.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern)) {
if (results != null) {
bind(results, Column.class, list);
}
}
return list;
} } | public class class_name {
public List<Column> getColumns(final String catalog, final String schemaPattern, final String tableNamePattern,
final String columnNamePattern)
throws SQLException {
final List<Column> list = new ArrayList<>();
try (ResultSet results = databaseMetadata.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern)) {
if (results != null) {
bind(results, Column.class, list); // depends on control dependency: [if], data = [(results]
}
}
return list;
} } |
public class class_name {
@javax.annotation.Nonnull
public com.simiacryptus.util.StreamNanoHTTPD init() throws IOException {
com.simiacryptus.util.StreamNanoHTTPD.this.start(30000);
new Thread(() -> {
try {
Thread.sleep(100);
if(null != gatewayUri) Desktop.getDesktop().browse(gatewayUri);
} catch (@javax.annotation.Nonnull final Exception e) {
e.printStackTrace();
}
}).start();
return this;
} } | public class class_name {
@javax.annotation.Nonnull
public com.simiacryptus.util.StreamNanoHTTPD init() throws IOException {
com.simiacryptus.util.StreamNanoHTTPD.this.start(30000);
new Thread(() -> {
try {
Thread.sleep(100); // depends on control dependency: [try], data = [none]
if(null != gatewayUri) Desktop.getDesktop().browse(gatewayUri);
} catch (@javax.annotation.Nonnull final Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}).start();
return this;
} } |
public class class_name {
public synchronized ActionForward handleException( Throwable ex, ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException
{
PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, mapping ) );
try
{
ExceptionsHandler eh = Handlers.get( getServletContext() ).getExceptionsHandler();
FlowControllerHandlerContext context = getHandlerContext();
// First, put the exception into the request (or other applicable context).
Throwable unwrapped = eh.unwrapException( context, ex );
eh.exposeException( context, unwrapped, mapping );
return eh.handleException( context, unwrapped, mapping, form );
}
finally
{
setPerRequestState( prevState );
}
} } | public class class_name {
public synchronized ActionForward handleException( Throwable ex, ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException
{
PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, mapping ) );
try
{
ExceptionsHandler eh = Handlers.get( getServletContext() ).getExceptionsHandler();
FlowControllerHandlerContext context = getHandlerContext();
// First, put the exception into the request (or other applicable context).
Throwable unwrapped = eh.unwrapException( context, ex );
eh.exposeException( context, unwrapped, mapping ); // depends on control dependency: [try], data = [none]
return eh.handleException( context, unwrapped, mapping, form ); // depends on control dependency: [try], data = [none]
}
finally
{
setPerRequestState( prevState );
}
} } |
public class class_name {
synchronized TaskInProgress findTaskToKill(List<TaskAttemptID> tasksToExclude) {
TaskInProgress killMe = null;
for (Iterator it = runningTasks.values().iterator(); it.hasNext();) {
TaskInProgress tip = (TaskInProgress) it.next();
if (tasksToExclude != null
&& tasksToExclude.contains(tip.getTask().getTaskID())) {
// exclude this task
continue;
}
if ((tip.getRunState() == TaskStatus.State.RUNNING ||
tip.getRunState() == TaskStatus.State.COMMIT_PENDING) &&
!tip.wasKilled) {
if (killMe == null) {
killMe = tip;
} else if (!tip.getTask().isMapTask()) {
//reduce task, give priority
if (killMe.getTask().isMapTask() ||
(tip.getTask().getProgress().get() <
killMe.getTask().getProgress().get())) {
killMe = tip;
}
} else if (killMe.getTask().isMapTask() &&
tip.getTask().getProgress().get() <
killMe.getTask().getProgress().get()) {
//map task, only add if the progress is lower
killMe = tip;
}
}
}
return killMe;
} } | public class class_name {
synchronized TaskInProgress findTaskToKill(List<TaskAttemptID> tasksToExclude) {
TaskInProgress killMe = null;
for (Iterator it = runningTasks.values().iterator(); it.hasNext();) {
TaskInProgress tip = (TaskInProgress) it.next();
if (tasksToExclude != null
&& tasksToExclude.contains(tip.getTask().getTaskID())) {
// exclude this task
continue;
}
if ((tip.getRunState() == TaskStatus.State.RUNNING ||
tip.getRunState() == TaskStatus.State.COMMIT_PENDING) &&
!tip.wasKilled) {
if (killMe == null) {
killMe = tip; // depends on control dependency: [if], data = [none]
} else if (!tip.getTask().isMapTask()) {
//reduce task, give priority
if (killMe.getTask().isMapTask() ||
(tip.getTask().getProgress().get() <
killMe.getTask().getProgress().get())) {
killMe = tip; // depends on control dependency: [if], data = [none]
}
} else if (killMe.getTask().isMapTask() &&
tip.getTask().getProgress().get() <
killMe.getTask().getProgress().get()) {
//map task, only add if the progress is lower
killMe = tip; // depends on control dependency: [if], data = [none]
}
}
}
return killMe;
} } |
public class class_name {
private Connector getConnectorById(Evse evse, Long id, boolean exceptionIfNotFound) {
for (Connector connector:evse.getConnectors()) {
if (id.equals(connector.getId())) {
return connector;
}
}
if (exceptionIfNotFound) {
throw new EntityNotFoundException(String.format("Unable to find connector with id '%s'", id));
} else {
return null;
}
} } | public class class_name {
private Connector getConnectorById(Evse evse, Long id, boolean exceptionIfNotFound) {
for (Connector connector:evse.getConnectors()) {
if (id.equals(connector.getId())) {
return connector; // depends on control dependency: [if], data = [none]
}
}
if (exceptionIfNotFound) {
throw new EntityNotFoundException(String.format("Unable to find connector with id '%s'", id));
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public HandlerType<HandlerChainType<T>> getOrCreateHandler()
{
List<Node> nodeList = childNode.get("handler");
if (nodeList != null && nodeList.size() > 0)
{
return new HandlerTypeImpl<HandlerChainType<T>>(this, "handler", childNode, nodeList.get(0));
}
return createHandler();
} } | public class class_name {
public HandlerType<HandlerChainType<T>> getOrCreateHandler()
{
List<Node> nodeList = childNode.get("handler");
if (nodeList != null && nodeList.size() > 0)
{
return new HandlerTypeImpl<HandlerChainType<T>>(this, "handler", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createHandler();
} } |
public class class_name {
public static final Renderer<Boolean> instance() { // NOPMD it's thread save!
if (BooleanRenderer.instanceRenderer == null) {
synchronized (BooleanRenderer.class) {
if (BooleanRenderer.instanceRenderer == null) {
BooleanRenderer.instanceRenderer = new BooleanRenderer();
}
}
}
return BooleanRenderer.instanceRenderer;
} } | public class class_name {
public static final Renderer<Boolean> instance() { // NOPMD it's thread save!
if (BooleanRenderer.instanceRenderer == null) {
synchronized (BooleanRenderer.class) { // depends on control dependency: [if], data = [none]
if (BooleanRenderer.instanceRenderer == null) {
BooleanRenderer.instanceRenderer = new BooleanRenderer(); // depends on control dependency: [if], data = [none]
}
}
}
return BooleanRenderer.instanceRenderer;
} } |
public class class_name {
@Override
public boolean isActive() {
try {
validateInitialization();
} catch (InvalidStateException ex) {
return false;
}
return informerWatchDog.isActive() && serverWatchDog.isActive();
} } | public class class_name {
@Override
public boolean isActive() {
try {
validateInitialization(); // depends on control dependency: [try], data = [none]
} catch (InvalidStateException ex) {
return false;
} // depends on control dependency: [catch], data = [none]
return informerWatchDog.isActive() && serverWatchDog.isActive();
} } |
public class class_name {
public void delete() {
try {
Files.deleteIfExists(file.file().toPath());
} catch (IOException e) {
throw new StorageException(e);
}
} } | public class class_name {
public void delete() {
try {
Files.deleteIfExists(file.file().toPath()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new StorageException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setPrivateIpAddresses(java.util.Collection<NetworkInterfacePrivateIpAddress> privateIpAddresses) {
if (privateIpAddresses == null) {
this.privateIpAddresses = null;
return;
}
this.privateIpAddresses = new com.amazonaws.internal.SdkInternalList<NetworkInterfacePrivateIpAddress>(privateIpAddresses);
} } | public class class_name {
public void setPrivateIpAddresses(java.util.Collection<NetworkInterfacePrivateIpAddress> privateIpAddresses) {
if (privateIpAddresses == null) {
this.privateIpAddresses = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.privateIpAddresses = new com.amazonaws.internal.SdkInternalList<NetworkInterfacePrivateIpAddress>(privateIpAddresses);
} } |
public class class_name {
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity",
"checkstyle:returncount", "checkstyle:magicnumber"})
public boolean compile(IProgressMonitor progress) {
final IProgressMonitor monitor = progress == null ? new NullProgressMonitor() : progress;
try {
monitor.beginTask(Messages.SarlBatchCompiler_42, 18);
if (!checkConfiguration(monitor)) {
return false;
}
monitor.worked(1);
final ResourceSet resourceSet = this.resourceSetProvider.get();
configureExtraLanguageGenerators();
if (!configureWorkspace(resourceSet, monitor)) {
return false;
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Utils.dump(getGeneratorConfig(), false));
}
monitor.worked(2);
monitor.subTask(Messages.SarlBatchCompiler_43);
if (this.generatorConfigProvider instanceof GeneratorConfigProvider) {
((GeneratorConfigProvider) this.generatorConfigProvider).install(resourceSet, getGeneratorConfig());
}
if (monitor.isCanceled()) {
return false;
}
if (this.generatorConfigProvider2 instanceof GeneratorConfigProvider2) {
((GeneratorConfigProvider2) this.generatorConfigProvider2).install(resourceSet, getGeneratorConfig2());
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Utils.dump(getGeneratorConfig2(), false));
}
if (monitor.isCanceled()) {
return false;
}
monitor.worked(3);
monitor.subTask(Messages.SarlBatchCompiler_44);
final File stubClassDirectory = createTempDir(BINCLASS_FOLDER_PREFIX);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(4);
try {
monitor.subTask(Messages.SarlBatchCompiler_45);
this.compilerPhases.setIndexing(resourceSet, true);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(5);
// install a type provider without index lookup for the first phase
installJvmTypeProvider(resourceSet, stubClassDirectory, true, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(6);
loadSARLFiles(resourceSet, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(7);
final File stubSourceDirectory = createStubs(resourceSet, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(8);
if (!preCompileStubs(stubSourceDirectory, stubClassDirectory, monitor)) {
if (monitor.isCanceled()) {
return false;
}
reportInternalWarning(Messages.SarlBatchCompiler_2);
}
monitor.worked(9);
if (!preCompileJava(stubSourceDirectory, stubClassDirectory, monitor)) {
if (monitor.isCanceled()) {
return false;
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_3);
}
}
monitor.worked(10);
} finally {
monitor.subTask(Messages.SarlBatchCompiler_46);
this.compilerPhases.setIndexing(resourceSet, false);
if (monitor.isCanceled()) {
return false;
}
}
monitor.worked(11);
// install a fresh type provider for the second phase, so we clear all previously cached classes and misses.
installJvmTypeProvider(resourceSet, stubClassDirectory, false, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(12);
generateJvmElements(resourceSet, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(13);
final List<Resource> validatedResources = new ArrayList<>();
final List<Issue> issues = validate(resourceSet, validatedResources, monitor);
if (monitor.isCanceled()) {
return false;
}
if (!issues.isEmpty()) {
if (reportCompilationIssues(issues)) {
return false;
}
}
monitor.worked(14);
overrideXtextInternalLoggers();
generateJavaFiles(validatedResources, monitor);
if (monitor.isCanceled()) {
return false;
}
monitor.worked(15);
if (isJavaPostCompilationEnable()) {
postCompileJava(monitor);
if (monitor.isCanceled()) {
return false;
}
}
monitor.worked(16);
} finally {
monitor.subTask(Messages.SarlBatchCompiler_47);
destroyClassLoader(this.jvmTypesClassLoader);
destroyClassLoader(this.annotationProcessingClassLoader);
if (isDeleteTempDirectory()) {
monitor.subTask(Messages.SarlBatchCompiler_48);
for (final File file : this.tempFolders) {
cleanFolder(file, ACCEPT_ALL_FILTER, true, true);
}
}
unconfigureExtraLanguageGenerators();
monitor.done();
}
return true;
} } | public class class_name {
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity",
"checkstyle:returncount", "checkstyle:magicnumber"})
public boolean compile(IProgressMonitor progress) {
final IProgressMonitor monitor = progress == null ? new NullProgressMonitor() : progress;
try {
monitor.beginTask(Messages.SarlBatchCompiler_42, 18); // depends on control dependency: [try], data = [none]
if (!checkConfiguration(monitor)) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(1); // depends on control dependency: [try], data = [none]
final ResourceSet resourceSet = this.resourceSetProvider.get();
configureExtraLanguageGenerators(); // depends on control dependency: [try], data = [none]
if (!configureWorkspace(resourceSet, monitor)) {
return false; // depends on control dependency: [if], data = [none]
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Utils.dump(getGeneratorConfig(), false)); // depends on control dependency: [if], data = [none]
}
monitor.worked(2); // depends on control dependency: [try], data = [none]
monitor.subTask(Messages.SarlBatchCompiler_43); // depends on control dependency: [try], data = [none]
if (this.generatorConfigProvider instanceof GeneratorConfigProvider) {
((GeneratorConfigProvider) this.generatorConfigProvider).install(resourceSet, getGeneratorConfig()); // depends on control dependency: [if], data = [none]
}
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
if (this.generatorConfigProvider2 instanceof GeneratorConfigProvider2) {
((GeneratorConfigProvider2) this.generatorConfigProvider2).install(resourceSet, getGeneratorConfig2()); // depends on control dependency: [if], data = [none]
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Utils.dump(getGeneratorConfig2(), false)); // depends on control dependency: [if], data = [none]
}
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(3); // depends on control dependency: [try], data = [none]
monitor.subTask(Messages.SarlBatchCompiler_44); // depends on control dependency: [try], data = [none]
final File stubClassDirectory = createTempDir(BINCLASS_FOLDER_PREFIX);
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(4); // depends on control dependency: [try], data = [none]
try {
monitor.subTask(Messages.SarlBatchCompiler_45); // depends on control dependency: [try], data = [none]
this.compilerPhases.setIndexing(resourceSet, true); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(5); // depends on control dependency: [try], data = [none]
// install a type provider without index lookup for the first phase
installJvmTypeProvider(resourceSet, stubClassDirectory, true, monitor); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(6); // depends on control dependency: [try], data = [none]
loadSARLFiles(resourceSet, monitor); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(7); // depends on control dependency: [try], data = [none]
final File stubSourceDirectory = createStubs(resourceSet, monitor);
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(8); // depends on control dependency: [try], data = [none]
if (!preCompileStubs(stubSourceDirectory, stubClassDirectory, monitor)) {
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
reportInternalWarning(Messages.SarlBatchCompiler_2); // depends on control dependency: [if], data = [none]
}
monitor.worked(9); // depends on control dependency: [try], data = [none]
if (!preCompileJava(stubSourceDirectory, stubClassDirectory, monitor)) {
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_3); // depends on control dependency: [if], data = [none]
}
}
monitor.worked(10); // depends on control dependency: [try], data = [none]
} finally {
monitor.subTask(Messages.SarlBatchCompiler_46);
this.compilerPhases.setIndexing(resourceSet, false);
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
}
monitor.worked(11); // depends on control dependency: [try], data = [none]
// install a fresh type provider for the second phase, so we clear all previously cached classes and misses.
installJvmTypeProvider(resourceSet, stubClassDirectory, false, monitor); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(12); // depends on control dependency: [try], data = [none]
generateJvmElements(resourceSet, monitor); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(13); // depends on control dependency: [try], data = [none]
final List<Resource> validatedResources = new ArrayList<>();
final List<Issue> issues = validate(resourceSet, validatedResources, monitor);
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
if (!issues.isEmpty()) {
if (reportCompilationIssues(issues)) {
return false; // depends on control dependency: [if], data = [none]
}
}
monitor.worked(14); // depends on control dependency: [try], data = [none]
overrideXtextInternalLoggers(); // depends on control dependency: [try], data = [none]
generateJavaFiles(validatedResources, monitor); // depends on control dependency: [try], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
monitor.worked(15); // depends on control dependency: [try], data = [none]
if (isJavaPostCompilationEnable()) {
postCompileJava(monitor); // depends on control dependency: [if], data = [none]
if (monitor.isCanceled()) {
return false; // depends on control dependency: [if], data = [none]
}
}
monitor.worked(16); // depends on control dependency: [try], data = [none]
} finally {
monitor.subTask(Messages.SarlBatchCompiler_47);
destroyClassLoader(this.jvmTypesClassLoader);
destroyClassLoader(this.annotationProcessingClassLoader);
if (isDeleteTempDirectory()) {
monitor.subTask(Messages.SarlBatchCompiler_48); // depends on control dependency: [if], data = [none]
for (final File file : this.tempFolders) {
cleanFolder(file, ACCEPT_ALL_FILTER, true, true); // depends on control dependency: [for], data = [file]
}
}
unconfigureExtraLanguageGenerators();
monitor.done();
}
return true;
} } |
public class class_name {
public static final void appendValueToSql(StringBuilder sql, Object value) {
if (value == null) {
sql.append("NULL");
} else if (value instanceof Boolean) {
Boolean bool = (Boolean)value;
if (bool) {
sql.append('1');
} else {
sql.append('0');
}
} else {
appendEscapedSQLString(sql, value.toString());
}
} } | public class class_name {
public static final void appendValueToSql(StringBuilder sql, Object value) {
if (value == null) {
sql.append("NULL"); // depends on control dependency: [if], data = [none]
} else if (value instanceof Boolean) {
Boolean bool = (Boolean)value;
if (bool) {
sql.append('1'); // depends on control dependency: [if], data = [none]
} else {
sql.append('0'); // depends on control dependency: [if], data = [none]
}
} else {
appendEscapedSQLString(sql, value.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<Resource<L>> removeResource(Resource<L> doomedResource) {
graphLockWrite.lock();
try {
List<Resource<L>> removedResources = new ArrayList<Resource<L>>();
Resource<L> resourceToRemove = getResource(doomedResource.getID());
if (resourceToRemove != null) {
getAllDescendants(resourceToRemove, removedResources);
removedResources.add(resourceToRemove);
removedResources.forEach(r -> this.resourcesGraph.removeVertex(r));
}
return Collections.unmodifiableList(removedResources);
} finally {
graphLockWrite.unlock();
}
} } | public class class_name {
public List<Resource<L>> removeResource(Resource<L> doomedResource) {
graphLockWrite.lock();
try {
List<Resource<L>> removedResources = new ArrayList<Resource<L>>();
Resource<L> resourceToRemove = getResource(doomedResource.getID());
if (resourceToRemove != null) {
getAllDescendants(resourceToRemove, removedResources); // depends on control dependency: [if], data = [(resourceToRemove]
removedResources.add(resourceToRemove); // depends on control dependency: [if], data = [(resourceToRemove]
removedResources.forEach(r -> this.resourcesGraph.removeVertex(r)); // depends on control dependency: [if], data = [none]
}
return Collections.unmodifiableList(removedResources); // depends on control dependency: [try], data = [none]
} finally {
graphLockWrite.unlock();
}
} } |
public class class_name {
private List<List<EventData>> split(List<EventData> datas) {
List<List<EventData>> result = new ArrayList<List<EventData>>();
if (datas == null || datas.size() == 0) {
return result;
} else {
int[] bits = new int[datas.size()];// 初始化一个标记,用于标明对应的记录是否已分入某个batch
for (int i = 0; i < bits.length; i++) {
// 跳过已经被分入batch的
while (i < bits.length && bits[i] == 1) {
i++;
}
if (i >= bits.length) { // 已处理完成,退出
break;
}
// 开始添加batch,最大只加入batchSize个数的对象
List<EventData> batch = new ArrayList<EventData>();
bits[i] = 1;
batch.add(datas.get(i));
for (int j = i + 1; j < bits.length && batch.size() < batchSize; j++) {
if (bits[j] == 0 && canBatch(datas.get(i), datas.get(j))) {
batch.add(datas.get(j));
bits[j] = 1;// 修改为已加入
}
}
result.add(batch);
}
return result;
}
} } | public class class_name {
private List<List<EventData>> split(List<EventData> datas) {
List<List<EventData>> result = new ArrayList<List<EventData>>();
if (datas == null || datas.size() == 0) {
return result; // depends on control dependency: [if], data = [none]
} else {
int[] bits = new int[datas.size()];// 初始化一个标记,用于标明对应的记录是否已分入某个batch
for (int i = 0; i < bits.length; i++) {
// 跳过已经被分入batch的
while (i < bits.length && bits[i] == 1) {
i++; // depends on control dependency: [while], data = [none]
}
if (i >= bits.length) { // 已处理完成,退出
break;
}
// 开始添加batch,最大只加入batchSize个数的对象
List<EventData> batch = new ArrayList<EventData>();
bits[i] = 1; // depends on control dependency: [for], data = [i]
batch.add(datas.get(i)); // depends on control dependency: [for], data = [i]
for (int j = i + 1; j < bits.length && batch.size() < batchSize; j++) {
if (bits[j] == 0 && canBatch(datas.get(i), datas.get(j))) {
batch.add(datas.get(j)); // depends on control dependency: [if], data = [none]
bits[j] = 1;// 修改为已加入 // depends on control dependency: [if], data = [none]
}
}
result.add(batch); // depends on control dependency: [for], data = [none]
}
return result; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<JvmTypeReference> findTypeValues(JvmAnnotationTarget op, Class<? extends Annotation> annotationType) {
final JvmAnnotationReference reference = this.lookup.findAnnotation(op, annotationType);
if (reference != null) {
return findTypeValues(reference);
}
return null;
} } | public class class_name {
public List<JvmTypeReference> findTypeValues(JvmAnnotationTarget op, Class<? extends Annotation> annotationType) {
final JvmAnnotationReference reference = this.lookup.findAnnotation(op, annotationType);
if (reference != null) {
return findTypeValues(reference); // depends on control dependency: [if], data = [(reference]
}
return null;
} } |
public class class_name {
public static String extractPort(final String host) {
if (containsPort(host)) {
return host.substring(host.indexOf(":") + 1, host.length());
} else {
return null;
}
} } | public class class_name {
public static String extractPort(final String host) {
if (containsPort(host)) {
return host.substring(host.indexOf(":") + 1, host.length()); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private <T extends Throwable> T ignoreWarnOrFail(Throwable throwable, final Class<T> exceptionClassToRaise, String msgKey, Object... objs) {
// Read the value each time in order to allow for changes to the onError setting
switch ((OnError) properties.get(OnErrorUtil.CFG_KEY_ON_ERROR)) {
case IGNORE:
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "ignoring error: " + msgKey, objs);
return null;
case WARN:
Tr.warning(tc, msgKey, objs);
return null;
case FAIL:
try {
if (throwable != null && exceptionClassToRaise.isInstance(throwable))
return exceptionClassToRaise.cast(throwable);
Constructor<T> con = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<T>>() {
@Override
public Constructor<T> run() throws NoSuchMethodException {
return exceptionClassToRaise.getConstructor(String.class);
}
});
String message = msgKey == null ? throwable.getMessage() : Tr.formatMessage(tc, msgKey, objs);
T failure = con.newInstance(message);
failure.initCause(throwable);
return failure;
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getCause());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
} } | public class class_name {
private <T extends Throwable> T ignoreWarnOrFail(Throwable throwable, final Class<T> exceptionClassToRaise, String msgKey, Object... objs) {
// Read the value each time in order to allow for changes to the onError setting
switch ((OnError) properties.get(OnErrorUtil.CFG_KEY_ON_ERROR)) {
case IGNORE:
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "ignoring error: " + msgKey, objs);
return null;
case WARN:
Tr.warning(tc, msgKey, objs);
return null;
case FAIL:
try {
if (throwable != null && exceptionClassToRaise.isInstance(throwable))
return exceptionClassToRaise.cast(throwable);
Constructor<T> con = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<T>>() {
@Override
public Constructor<T> run() throws NoSuchMethodException {
return exceptionClassToRaise.getConstructor(String.class);
}
});
String message = msgKey == null ? throwable.getMessage() : Tr.formatMessage(tc, msgKey, objs);
T failure = con.newInstance(message);
failure.initCause(throwable); // depends on control dependency: [try], data = [none]
return failure; // depends on control dependency: [try], data = [none]
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getCause());
} catch (RuntimeException e) { // depends on control dependency: [catch], data = [none]
throw e;
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
static Predicate<DateValue> byHourFilter(int[] hours) {
int hoursByBit = 0;
for (int hour : hours) {
hoursByBit |= 1 << hour;
}
if ((hoursByBit & LOW_24_BITS) == LOW_24_BITS) {
return Predicates.alwaysTrue();
}
final int bitField = hoursByBit;
return new Predicate<DateValue>() {
private static final long serialVersionUID = -6284974028385246889L;
public boolean apply(DateValue date) {
if (!(date instanceof TimeValue)) {
return false;
}
TimeValue tv = (TimeValue) date;
return (bitField & (1 << tv.hour())) != 0;
}
};
} } | public class class_name {
static Predicate<DateValue> byHourFilter(int[] hours) {
int hoursByBit = 0;
for (int hour : hours) {
hoursByBit |= 1 << hour; // depends on control dependency: [for], data = [hour]
}
if ((hoursByBit & LOW_24_BITS) == LOW_24_BITS) {
return Predicates.alwaysTrue(); // depends on control dependency: [if], data = [none]
}
final int bitField = hoursByBit;
return new Predicate<DateValue>() {
private static final long serialVersionUID = -6284974028385246889L;
public boolean apply(DateValue date) {
if (!(date instanceof TimeValue)) {
return false; // depends on control dependency: [if], data = [none]
}
TimeValue tv = (TimeValue) date;
return (bitField & (1 << tv.hour())) != 0;
}
};
} } |
public class class_name {
public static Optional<Node> getContainingNode(final Node node) {
try {
if (node.getDepth() == 0) {
return empty();
}
// check ancestors recursively only either of the following two cases applies:
// 1. the PARENT is a FEDORA_PAIRTREE
// 2. the PARENT is FEDORA_NON_RDF_SOURCE_DESCRIPTION
final Node parent = node.getParent();
if (parent.isNodeType(FEDORA_PAIRTREE) || parent.isNodeType(FEDORA_NON_RDF_SOURCE_DESCRIPTION)) {
return getContainingNode(parent);
}
return Optional.of(parent);
} catch (final RepositoryException ex) {
throw new RepositoryRuntimeException(ex);
}
} } | public class class_name {
public static Optional<Node> getContainingNode(final Node node) {
try {
if (node.getDepth() == 0) {
return empty(); // depends on control dependency: [if], data = [none]
}
// check ancestors recursively only either of the following two cases applies:
// 1. the PARENT is a FEDORA_PAIRTREE
// 2. the PARENT is FEDORA_NON_RDF_SOURCE_DESCRIPTION
final Node parent = node.getParent();
if (parent.isNodeType(FEDORA_PAIRTREE) || parent.isNodeType(FEDORA_NON_RDF_SOURCE_DESCRIPTION)) {
return getContainingNode(parent); // depends on control dependency: [if], data = [none]
}
return Optional.of(parent); // depends on control dependency: [try], data = [none]
} catch (final RepositoryException ex) {
throw new RepositoryRuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void
parse()
throws IOException
{
this.url = request.getRequestURL().toString(); // does not include query
// The mock servlet code does not construct a query string,
// so if we are doing testing, construct from parametermap.
if(DapController.TESTING) {
this.querystring = makeQueryString(this.request);
} else {
this.querystring = request.getQueryString(); // raw (undecoded)
}
XURI xuri;
try {
xuri = new XURI(this.url).parseQuery(this.querystring);
} catch (URISyntaxException e) {
throw new IOException(e);
}
// Now, construct various items
StringBuilder buf = new StringBuilder();
buf.append(request.getScheme());
buf.append("://");
buf.append(request.getServerName());
int port = request.getServerPort();
if(port > 0) {
buf.append(":");
buf.append(port);
}
this.server = buf.toString();
// There appears to be some inconsistency in how the url path is divided up
// depending on if this is a spring controller vs a raw servlet.
// Try to canonicalize so that context path always ends with id
// and servletpath does not start with it.
String id = controller.getServletID();
String sp = DapUtil.canonicalpath(request.getServletPath());
String cp = DapUtil.canonicalpath(request.getContextPath());
if(!cp.endsWith(id)) // probably spring ; contextpath does not ends with id
cp = cp + "/" + id;
buf.append(cp);
this.controllerpath = buf.toString();
sp = HTTPUtil.relpath(sp);
if(sp.startsWith(id)) // probably spring also
sp = sp.substring(id.length());
this.datasetpath = HTTPUtil.relpath(sp);
this.datasetpath = DapUtil.nullify(this.datasetpath);
this.mode = null;
if(this.datasetpath == null) {
// Presume mode is a capabilities request
this.mode = RequestMode.CAPABILITIES;
this.format = ResponseFormat.HTML;
} else {
// Decompose path by '.'
String[] pieces = this.datasetpath.split("[.]");
// Search backward looking for the mode (dmr or dap)
// meanwhile capturing the format extension
int modepos = 0;
for(int i = pieces.length - 1; i >= 1; i--) {//ignore first piece
String ext = pieces[i];
// We assume that the set of response formats does not interset the set of request modes
RequestMode mode = RequestMode.modeFor(ext);
ResponseFormat format = ResponseFormat.formatFor(ext);
if(mode != null) {
// Stop here
this.mode = mode;
modepos = i;
break;
} else if(format != null) {
if(this.format != null)
throw new DapException("Multiple response formats specified: " + ext)
.setCode(HttpServletResponse.SC_BAD_REQUEST);
this.format = format;
}
}
// Set the datasetpath to the entire path before the mode defining extension.
if(modepos > 0)
this.datasetpath = DapUtil.join(pieces, ".", 0, modepos);
}
if(this.mode == null)
this.mode = RequestMode.DSR;
if(this.format == null)
this.format = ResponseFormat.NONE;
// Parse the query string into a Map
if(querystring != null && querystring.length() > 0)
this.queries = xuri.getQueryFields();
// For testing purposes, get the desired endianness to use with replies
String p = queryLookup(Dap4Util.DAP4ENDIANTAG);
if(p != null) {
Integer oz = DapUtil.stringToInteger(p);
if(oz == null)
this.order = ByteOrder.LITTLE_ENDIAN;
else
this.order = (oz != 0 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
}
// Ditto for no checksum
p = queryLookup(Dap4Util.DAP4CSUMTAG);
if(p != null) {
this.checksummode = ChecksumMode.modeFor(p);
}
if(this.checksummode == null)
this.checksummode = DEFAULTCSUM;
if(DEBUG) {
DapLog.debug("DapRequest: controllerpath =" + this.controllerpath);
DapLog.debug("DapRequest: extension=" + (this.mode == null ? "null" : this.mode.extension()));
DapLog.debug("DapRequest: datasetpath=" + this.datasetpath);
}
} } | public class class_name {
protected void
parse()
throws IOException
{
this.url = request.getRequestURL().toString(); // does not include query
// The mock servlet code does not construct a query string,
// so if we are doing testing, construct from parametermap.
if(DapController.TESTING) {
this.querystring = makeQueryString(this.request);
} else {
this.querystring = request.getQueryString(); // raw (undecoded)
}
XURI xuri;
try {
xuri = new XURI(this.url).parseQuery(this.querystring);
} catch (URISyntaxException e) {
throw new IOException(e);
}
// Now, construct various items
StringBuilder buf = new StringBuilder();
buf.append(request.getScheme());
buf.append("://");
buf.append(request.getServerName());
int port = request.getServerPort();
if(port > 0) {
buf.append(":");
buf.append(port);
}
this.server = buf.toString();
// There appears to be some inconsistency in how the url path is divided up
// depending on if this is a spring controller vs a raw servlet.
// Try to canonicalize so that context path always ends with id
// and servletpath does not start with it.
String id = controller.getServletID();
String sp = DapUtil.canonicalpath(request.getServletPath());
String cp = DapUtil.canonicalpath(request.getContextPath());
if(!cp.endsWith(id)) // probably spring ; contextpath does not ends with id
cp = cp + "/" + id;
buf.append(cp);
this.controllerpath = buf.toString();
sp = HTTPUtil.relpath(sp);
if(sp.startsWith(id)) // probably spring also
sp = sp.substring(id.length());
this.datasetpath = HTTPUtil.relpath(sp);
this.datasetpath = DapUtil.nullify(this.datasetpath);
this.mode = null;
if(this.datasetpath == null) {
// Presume mode is a capabilities request
this.mode = RequestMode.CAPABILITIES;
this.format = ResponseFormat.HTML;
} else {
// Decompose path by '.'
String[] pieces = this.datasetpath.split("[.]");
// Search backward looking for the mode (dmr or dap)
// meanwhile capturing the format extension
int modepos = 0;
for(int i = pieces.length - 1; i >= 1; i--) {//ignore first piece
String ext = pieces[i];
// We assume that the set of response formats does not interset the set of request modes
RequestMode mode = RequestMode.modeFor(ext);
ResponseFormat format = ResponseFormat.formatFor(ext);
if(mode != null) {
// Stop here
this.mode = mode; // depends on control dependency: [if], data = [none]
modepos = i; // depends on control dependency: [if], data = [none]
break;
} else if(format != null) {
if(this.format != null)
throw new DapException("Multiple response formats specified: " + ext)
.setCode(HttpServletResponse.SC_BAD_REQUEST);
this.format = format; // depends on control dependency: [if], data = [none]
}
}
// Set the datasetpath to the entire path before the mode defining extension.
if(modepos > 0)
this.datasetpath = DapUtil.join(pieces, ".", 0, modepos);
}
if(this.mode == null)
this.mode = RequestMode.DSR;
if(this.format == null)
this.format = ResponseFormat.NONE;
// Parse the query string into a Map
if(querystring != null && querystring.length() > 0)
this.queries = xuri.getQueryFields();
// For testing purposes, get the desired endianness to use with replies
String p = queryLookup(Dap4Util.DAP4ENDIANTAG);
if(p != null) {
Integer oz = DapUtil.stringToInteger(p);
if(oz == null)
this.order = ByteOrder.LITTLE_ENDIAN;
else
this.order = (oz != 0 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
}
// Ditto for no checksum
p = queryLookup(Dap4Util.DAP4CSUMTAG);
if(p != null) {
this.checksummode = ChecksumMode.modeFor(p);
}
if(this.checksummode == null)
this.checksummode = DEFAULTCSUM;
if(DEBUG) {
DapLog.debug("DapRequest: controllerpath =" + this.controllerpath);
DapLog.debug("DapRequest: extension=" + (this.mode == null ? "null" : this.mode.extension()));
DapLog.debug("DapRequest: datasetpath=" + this.datasetpath);
}
} } |
public class class_name {
public long getPosition() {
try {
return reader.getFilePointer();
} catch (IOException ex) {
logger.logp(Level.SEVERE, className, "getPosition", "HPEL_ErrorReadingFileOffset", new Object[]{file, ex.getMessage()});
}
return -1L;
} } | public class class_name {
public long getPosition() {
try {
return reader.getFilePointer(); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
logger.logp(Level.SEVERE, className, "getPosition", "HPEL_ErrorReadingFileOffset", new Object[]{file, ex.getMessage()});
} // depends on control dependency: [catch], data = [none]
return -1L;
} } |
public class class_name {
public static Object duplicate(Object object, boolean deepCopy) {
if (object == null) return null;
if (object instanceof Number) return object;
if (object instanceof String) return object;
if (object instanceof Date) return ((Date) object).clone();
if (object instanceof Boolean) return object;
RefBoolean before = new RefBooleanImpl();
try {
Object copy = ThreadLocalDuplication.get(object, before);
if (copy != null) {
return copy;
}
if (object instanceof Collection) return ((Collection) object).duplicate(deepCopy);
if (object instanceof Duplicable) return ((Duplicable) object).duplicate(deepCopy);
if (object instanceof UDF) return ((UDF) object).duplicate();
if (object instanceof List) return duplicateList((List) object, deepCopy);
if (object instanceof Map) return duplicateMap((Map) object, deepCopy);
if (object instanceof Serializable) {
try {
String ser = JavaConverter.serialize((Serializable) object);
return JavaConverter.deserialize(ser);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
}
finally {
if (!before.toBooleanValue()) ThreadLocalDuplication.reset();
}
return object;
} } | public class class_name {
public static Object duplicate(Object object, boolean deepCopy) {
if (object == null) return null;
if (object instanceof Number) return object;
if (object instanceof String) return object;
if (object instanceof Date) return ((Date) object).clone();
if (object instanceof Boolean) return object;
RefBoolean before = new RefBooleanImpl();
try {
Object copy = ThreadLocalDuplication.get(object, before);
if (copy != null) {
return copy; // depends on control dependency: [if], data = [none]
}
if (object instanceof Collection) return ((Collection) object).duplicate(deepCopy);
if (object instanceof Duplicable) return ((Duplicable) object).duplicate(deepCopy);
if (object instanceof UDF) return ((UDF) object).duplicate();
if (object instanceof List) return duplicateList((List) object, deepCopy);
if (object instanceof Map) return duplicateMap((Map) object, deepCopy);
if (object instanceof Serializable) {
try {
String ser = JavaConverter.serialize((Serializable) object);
return JavaConverter.deserialize(ser); // depends on control dependency: [try], data = [none]
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
} // depends on control dependency: [catch], data = [none]
}
}
finally {
if (!before.toBooleanValue()) ThreadLocalDuplication.reset();
}
return object;
} } |
public class class_name {
public static void fillRepoLinks ( final ChannelInformation channel, final List<MenuEntry> links, final String baseName, final int basePriority, final String prefix, final int priorityOffset, final Function<String, LinkTarget> targetFunction )
{
Objects.requireNonNull ( channel, "'channel' must not be null" );
Objects.requireNonNull ( links, "'links' must not be null" );
Objects.requireNonNull ( baseName, "'baseName' must not be null" );
Objects.requireNonNull ( prefix, "'prefix' must not be null" );
Objects.requireNonNull ( targetFunction, "'targetFunction' must not be null" );
links.add ( new MenuEntry ( baseName, basePriority, prefix + " (by ID)", priorityOffset, targetFunction.apply ( channel.getId () ), Modifier.LINK, null ) );
int i = 1;
for ( final String name : channel.getNames () )
{
final LinkTarget target = targetFunction.apply ( name );
if ( target != null )
{
links.add ( new MenuEntry ( baseName, basePriority, String.format ( "%s (name: %s)", prefix, name ), priorityOffset + i, target, Modifier.LINK, null ) );
}
i++;
}
} } | public class class_name {
public static void fillRepoLinks ( final ChannelInformation channel, final List<MenuEntry> links, final String baseName, final int basePriority, final String prefix, final int priorityOffset, final Function<String, LinkTarget> targetFunction )
{
Objects.requireNonNull ( channel, "'channel' must not be null" );
Objects.requireNonNull ( links, "'links' must not be null" );
Objects.requireNonNull ( baseName, "'baseName' must not be null" );
Objects.requireNonNull ( prefix, "'prefix' must not be null" );
Objects.requireNonNull ( targetFunction, "'targetFunction' must not be null" );
links.add ( new MenuEntry ( baseName, basePriority, prefix + " (by ID)", priorityOffset, targetFunction.apply ( channel.getId () ), Modifier.LINK, null ) );
int i = 1;
for ( final String name : channel.getNames () )
{
final LinkTarget target = targetFunction.apply ( name );
if ( target != null )
{
links.add ( new MenuEntry ( baseName, basePriority, String.format ( "%s (name: %s)", prefix, name ), priorityOffset + i, target, Modifier.LINK, null ) ); // depends on control dependency: [if], data = [null )]
}
i++; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public boolean executeKeyEvent(KeyEvent event) {
mTempRect.setEmpty();
if (!canScroll()) {
if (isFocused()) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
}
return false;
}
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_UP, false);
} else {
handled = fullScroll(View.FOCUS_UP, false);
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_DOWN, false);
} else {
handled = fullScroll(View.FOCUS_DOWN, false);
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_LEFT, true);
} else {
handled = fullScroll(View.FOCUS_LEFT, true);
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_RIGHT, true);
} else {
handled = fullScroll(View.FOCUS_RIGHT, true);
}
break;
}
}
return handled;
} } | public class class_name {
public boolean executeKeyEvent(KeyEvent event) {
mTempRect.setEmpty();
if (!canScroll()) {
if (isFocused()) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_UP, false); // depends on control dependency: [if], data = [none]
} else {
handled = fullScroll(View.FOCUS_UP, false); // depends on control dependency: [if], data = [none]
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_DOWN, false); // depends on control dependency: [if], data = [none]
} else {
handled = fullScroll(View.FOCUS_DOWN, false); // depends on control dependency: [if], data = [none]
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_LEFT, true); // depends on control dependency: [if], data = [none]
} else {
handled = fullScroll(View.FOCUS_LEFT, true); // depends on control dependency: [if], data = [none]
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_RIGHT, true); // depends on control dependency: [if], data = [none]
} else {
handled = fullScroll(View.FOCUS_RIGHT, true); // depends on control dependency: [if], data = [none]
}
break;
}
}
return handled;
} } |
public class class_name {
public void setOptions(
String[] labels, String[] descriptions, int defaultIndex)
{
if (labels.length != descriptions.length) {
throw new IllegalArgumentException("Labels/descriptions mismatch.");
}
if (labels.length > 0) {
this.optionLabels = labels.clone();
this.optionDescriptions = descriptions.clone();
this.defaultOptionIndex = defaultIndex;
}
else {
// use placeholders for empty list of choices
this.optionLabels = new String[]{NO_CHOICES};
this.optionDescriptions = new String[]{NO_CHOICES_DESCRIPTION};
this.defaultOptionIndex = 0;
}
// reset to default value
resetToDefault();
// refresh the edit component
if (this.editComponent != null) {
this.editComponent.refresh();
}
} } | public class class_name {
public void setOptions(
String[] labels, String[] descriptions, int defaultIndex)
{
if (labels.length != descriptions.length) {
throw new IllegalArgumentException("Labels/descriptions mismatch.");
}
if (labels.length > 0) {
this.optionLabels = labels.clone(); // depends on control dependency: [if], data = [none]
this.optionDescriptions = descriptions.clone(); // depends on control dependency: [if], data = [none]
this.defaultOptionIndex = defaultIndex; // depends on control dependency: [if], data = [none]
}
else {
// use placeholders for empty list of choices
this.optionLabels = new String[]{NO_CHOICES}; // depends on control dependency: [if], data = [none]
this.optionDescriptions = new String[]{NO_CHOICES_DESCRIPTION}; // depends on control dependency: [if], data = [none]
this.defaultOptionIndex = 0; // depends on control dependency: [if], data = [none]
}
// reset to default value
resetToDefault();
// refresh the edit component
if (this.editComponent != null) {
this.editComponent.refresh(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void onClick(View view) {
final ProgressDialog dialog = progressDialogFactory.show(view.getContext(), I18NConstants.DLG_SHARE, I18NConstants.DLG_SHARE_MESSAGE + " " + shareType.getDisplayName() + "...");
ShareOptions shareOptions = ShareUtils.getUserShareOptions(context);
shareOptions.setText(provider.getShareText());
ShareUtils.registerShare(context, entity, shareOptions, new ShareAddListener() {
@Override
public void onError(SocializeException error) {
dialog.dismiss();
alertDialogFactory.showToast(context, "Share failed. Please try again");
}
@Override
public void onCreate(Share share) {
dialog.dismiss();
if(onActionBarEventListener != null) {
onActionBarEventListener.onPostShare(actionBarView, share);
}
}
}, SocialNetwork.valueOf(shareType));
} } | public class class_name {
@Override
public void onClick(View view) {
final ProgressDialog dialog = progressDialogFactory.show(view.getContext(), I18NConstants.DLG_SHARE, I18NConstants.DLG_SHARE_MESSAGE + " " + shareType.getDisplayName() + "...");
ShareOptions shareOptions = ShareUtils.getUserShareOptions(context);
shareOptions.setText(provider.getShareText());
ShareUtils.registerShare(context, entity, shareOptions, new ShareAddListener() {
@Override
public void onError(SocializeException error) {
dialog.dismiss();
alertDialogFactory.showToast(context, "Share failed. Please try again");
}
@Override
public void onCreate(Share share) {
dialog.dismiss();
if(onActionBarEventListener != null) {
onActionBarEventListener.onPostShare(actionBarView, share); // depends on control dependency: [if], data = [none]
}
}
}, SocialNetwork.valueOf(shareType));
} } |
public class class_name {
@Override
public String getCoreDurableSubName(String jmsClientID, String jmsSubName) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getCoreDurableSubName", new Object[] { jmsClientID, jmsSubName });
String retSubName;
if ((jmsClientID == null) || ("".equals(jmsClientID))) {
retSubName = jmsSubName;
} else {
retSubName = jmsClientID + SUB_CONCATENATOR + jmsSubName;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "getCoreDurableSubName", retSubName);
return retSubName;
} } | public class class_name {
@Override
public String getCoreDurableSubName(String jmsClientID, String jmsSubName) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getCoreDurableSubName", new Object[] { jmsClientID, jmsSubName });
String retSubName;
if ((jmsClientID == null) || ("".equals(jmsClientID))) {
retSubName = jmsSubName; // depends on control dependency: [if], data = [none]
} else {
retSubName = jmsClientID + SUB_CONCATENATOR + jmsSubName; // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "getCoreDurableSubName", retSubName);
return retSubName;
} } |
public class class_name {
public static Version stringToVersion(String str) {
if (str == null || str.isEmpty() || str.equals("0")) {
return Version.emptyVersion;
}
if (str.equals("1") || str.equals("1.0") || str.equals("1.0.0"))
return VERSION_1_0;
return new Version(str);
} } | public class class_name {
public static Version stringToVersion(String str) {
if (str == null || str.isEmpty() || str.equals("0")) {
return Version.emptyVersion; // depends on control dependency: [if], data = [none]
}
if (str.equals("1") || str.equals("1.0") || str.equals("1.0.0"))
return VERSION_1_0;
return new Version(str);
} } |
public class class_name {
public void close(boolean write) {
SimpleLog appLog = database.logger.appLog;
try {
if (cacheReadonly) {
if (dataFile != null) {
dataFile.close();
dataFile = null;
}
return;
}
StopWatch sw = new StopWatch();
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close(" + write + ") : start");
if (write) {
cache.saveAll();
Error.printSystemOut("saveAll: " + sw.elapsedTime());
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : save data");
if (fileModified || freeBlocks.isModified()) {
// set empty
dataFile.seek(LONG_EMPTY_SIZE);
dataFile.writeLong(freeBlocks.getLostBlocksSize());
// set end
dataFile.seek(LONG_FREE_POS_POS);
dataFile.writeLong(fileFreePosition);
// set saved flag;
dataFile.seek(FLAGS_POS);
int flag = BitMap.set(0, FLAG_ISSAVED);
if (hasRowInfo) {
flag = BitMap.set(flag, FLAG_ROWINFO);
}
dataFile.writeInt(flag);
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : flags");
//
if (dataFile.length() != fileFreePosition) {
dataFile.seek(fileFreePosition);
}
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : seek end");
Error.printSystemOut("pos and flags: " + sw.elapsedTime());
}
}
if (dataFile != null) {
dataFile.close();
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : close");
dataFile = null;
Error.printSystemOut("close: " + sw.elapsedTime());
}
boolean empty = fileFreePosition == INITIAL_FREE_POS;
if (empty) {
fa.removeElement(fileName);
fa.removeElement(backupFileName);
}
} catch (Throwable e) {
appLog.logContext(e, null);
throw Error.error(ErrorCode.FILE_IO_ERROR,
ErrorCode.M_DataFileCache_close, new Object[] {
e, fileName
});
}
} } | public class class_name {
public void close(boolean write) {
SimpleLog appLog = database.logger.appLog;
try {
if (cacheReadonly) {
if (dataFile != null) {
dataFile.close(); // depends on control dependency: [if], data = [none]
dataFile = null; // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
StopWatch sw = new StopWatch();
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close(" + write + ") : start"); // depends on control dependency: [try], data = [none]
if (write) {
cache.saveAll(); // depends on control dependency: [if], data = [none]
Error.printSystemOut("saveAll: " + sw.elapsedTime()); // depends on control dependency: [if], data = [none]
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : save data"); // depends on control dependency: [if], data = [none]
if (fileModified || freeBlocks.isModified()) {
// set empty
dataFile.seek(LONG_EMPTY_SIZE); // depends on control dependency: [if], data = [none]
dataFile.writeLong(freeBlocks.getLostBlocksSize()); // depends on control dependency: [if], data = [none]
// set end
dataFile.seek(LONG_FREE_POS_POS); // depends on control dependency: [if], data = [none]
dataFile.writeLong(fileFreePosition); // depends on control dependency: [if], data = [none]
// set saved flag;
dataFile.seek(FLAGS_POS); // depends on control dependency: [if], data = [none]
int flag = BitMap.set(0, FLAG_ISSAVED);
if (hasRowInfo) {
flag = BitMap.set(flag, FLAG_ROWINFO); // depends on control dependency: [if], data = [none]
}
dataFile.writeInt(flag); // depends on control dependency: [if], data = [none]
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : flags"); // depends on control dependency: [if], data = [none]
//
if (dataFile.length() != fileFreePosition) {
dataFile.seek(fileFreePosition); // depends on control dependency: [if], data = [fileFreePosition)]
}
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : seek end"); // depends on control dependency: [if], data = [none]
Error.printSystemOut("pos and flags: " + sw.elapsedTime()); // depends on control dependency: [if], data = [none]
}
}
if (dataFile != null) {
dataFile.close(); // depends on control dependency: [if], data = [none]
appLog.sendLine(SimpleLog.LOG_NORMAL,
"DataFileCache.close() : close"); // depends on control dependency: [if], data = [none]
dataFile = null; // depends on control dependency: [if], data = [none]
Error.printSystemOut("close: " + sw.elapsedTime()); // depends on control dependency: [if], data = [none]
}
boolean empty = fileFreePosition == INITIAL_FREE_POS;
if (empty) {
fa.removeElement(fileName); // depends on control dependency: [if], data = [none]
fa.removeElement(backupFileName); // depends on control dependency: [if], data = [none]
}
} catch (Throwable e) {
appLog.logContext(e, null);
throw Error.error(ErrorCode.FILE_IO_ERROR,
ErrorCode.M_DataFileCache_close, new Object[] {
e, fileName
});
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static WordChoiceReport evaluate(
SemanticSpace sspace,
WordChoiceEvaluation test,
Similarity.SimType vectorComparisonType) {
Collection<MultipleChoiceQuestion> questions = test.getQuestions();
int correct = 0;
int unanswerable = 0;
question_loop:
// Answer each question by using the vectors from the provided Semantic
// Space
for (MultipleChoiceQuestion question : questions) {
String promptWord = question.getPrompt();
// get the vector for the prompt
Vector promptVector = sspace.getVector(promptWord);
// check that the s-space had the prompt word
if (promptVector == null) {
unanswerable++;
continue;
}
int answerIndex = 0;
double closestOption = Double.MIN_VALUE;
// find the options whose vector has the highest similarity (or
// equivalent comparison measure) to the prompt word. The
// running assumption hear is that for the value returned by the
// comparison method, a high value implies more similar vectors.
int optionIndex = 0;
for (String optionWord : question.getOptions()) {
// Get the vector for the option
Vector optionVector = sspace.getVector(optionWord);
// check that the s-space had the option word
if (optionVector == null) {
unanswerable++;
continue question_loop;
}
double similarity = Similarity.getSimilarity(
vectorComparisonType,
promptVector, optionVector);
if (similarity > closestOption) {
answerIndex = optionIndex;
closestOption = similarity;
}
optionIndex++;
}
// see whether our guess matched with the correct index
if (answerIndex == question.getCorrectAnswer()) {
correct++;
}
}
return new SimpleReport(questions.size(), correct, unanswerable);
} } | public class class_name {
public static WordChoiceReport evaluate(
SemanticSpace sspace,
WordChoiceEvaluation test,
Similarity.SimType vectorComparisonType) {
Collection<MultipleChoiceQuestion> questions = test.getQuestions();
int correct = 0;
int unanswerable = 0;
question_loop:
// Answer each question by using the vectors from the provided Semantic
// Space
for (MultipleChoiceQuestion question : questions) {
String promptWord = question.getPrompt();
// get the vector for the prompt
Vector promptVector = sspace.getVector(promptWord);
// check that the s-space had the prompt word
if (promptVector == null) {
unanswerable++; // depends on control dependency: [if], data = [none]
continue;
}
int answerIndex = 0;
double closestOption = Double.MIN_VALUE;
// find the options whose vector has the highest similarity (or
// equivalent comparison measure) to the prompt word. The
// running assumption hear is that for the value returned by the
// comparison method, a high value implies more similar vectors.
int optionIndex = 0;
for (String optionWord : question.getOptions()) {
// Get the vector for the option
Vector optionVector = sspace.getVector(optionWord);
// check that the s-space had the option word
if (optionVector == null) {
unanswerable++; // depends on control dependency: [if], data = [none]
continue question_loop;
}
double similarity = Similarity.getSimilarity(
vectorComparisonType,
promptVector, optionVector);
if (similarity > closestOption) {
answerIndex = optionIndex; // depends on control dependency: [if], data = [none]
closestOption = similarity; // depends on control dependency: [if], data = [none]
}
optionIndex++; // depends on control dependency: [for], data = [none]
}
// see whether our guess matched with the correct index
if (answerIndex == question.getCorrectAnswer()) {
correct++; // depends on control dependency: [if], data = [none]
}
}
return new SimpleReport(questions.size(), correct, unanswerable);
} } |
public class class_name {
protected int optimize( List<Point2D_I32> contour , int c0,int c1,int c2 ) {
double bestDistance = computeCost(contour,c0,c1,c2,0);
int bestIndex = 0;
for( int i = -searchRadius; i <= searchRadius; i++ ) {
if( i == 0 ) {
// if it found a better point in the first half stop the search since that's probably the correct
// direction. Could be improved by remember past search direction
if( bestIndex != 0 )
break;
} else {
double found = computeCost(contour, c0, c1, c2, i);
if (found < bestDistance) {
bestDistance = found;
bestIndex = i;
}
}
}
return CircularIndex.addOffset(c1, bestIndex, contour.size());
} } | public class class_name {
protected int optimize( List<Point2D_I32> contour , int c0,int c1,int c2 ) {
double bestDistance = computeCost(contour,c0,c1,c2,0);
int bestIndex = 0;
for( int i = -searchRadius; i <= searchRadius; i++ ) {
if( i == 0 ) {
// if it found a better point in the first half stop the search since that's probably the correct
// direction. Could be improved by remember past search direction
if( bestIndex != 0 )
break;
} else {
double found = computeCost(contour, c0, c1, c2, i);
if (found < bestDistance) {
bestDistance = found; // depends on control dependency: [if], data = [none]
bestIndex = i; // depends on control dependency: [if], data = [none]
}
}
}
return CircularIndex.addOffset(c1, bestIndex, contour.size());
} } |
public class class_name {
static int writeVInt(byte[] array, int offset, int value) {
assert value >= 0 : "Can't v-code negative ints.";
while (value > 0x7F) {
array[offset++] = (byte) (0x80 | (value & 0x7F));
value >>= 7;
}
array[offset++] = (byte) value;
return offset;
} } | public class class_name {
static int writeVInt(byte[] array, int offset, int value) {
assert value >= 0 : "Can't v-code negative ints.";
while (value > 0x7F) {
array[offset++] = (byte) (0x80 | (value & 0x7F));
// depends on control dependency: [while], data = [(value]
value >>= 7;
// depends on control dependency: [while], data = [none]
}
array[offset++] = (byte) value;
return offset;
} } |
public class class_name {
public synchronized void logoutAllUsers(Context context) {
getAuthInfoMap(context);
for (String userId : mCurrentAccessInfo.keySet()) {
BoxSession session = new BoxSession(context, userId);
logout(session);
}
authStorage.clearAuthInfoMap(context);
} } | public class class_name {
public synchronized void logoutAllUsers(Context context) {
getAuthInfoMap(context);
for (String userId : mCurrentAccessInfo.keySet()) {
BoxSession session = new BoxSession(context, userId);
logout(session); // depends on control dependency: [for], data = [none]
}
authStorage.clearAuthInfoMap(context);
} } |
public class class_name {
@Override
@OnWave(EditorWaves.DO_SELECT_EVENT_ACTION)
protected void processWave(final Wave wave) {
if (EditorWaves.DO_SELECT_EVENT == wave.waveType()) {
final JRebirthEvent event = wave.get(PropertiesWaves.EVENT_OBJECT);
view().getNodeName().setText(event.target());
}
} } | public class class_name {
@Override
@OnWave(EditorWaves.DO_SELECT_EVENT_ACTION)
protected void processWave(final Wave wave) {
if (EditorWaves.DO_SELECT_EVENT == wave.waveType()) {
final JRebirthEvent event = wave.get(PropertiesWaves.EVENT_OBJECT);
view().getNodeName().setText(event.target()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public double angleTo(LineSegment other) {
double angle1 = Math.atan2(this.start.y - this.end.y, this.start.x - this.end.x);
double angle2 = Math.atan2(other.start.y - other.end.y, other.start.x - other.end.x);
double angle = Math.toDegrees(angle1 - angle2);
if (angle <= -180) {
angle += 360;
}
if (angle >= 180) {
angle -= 360;
}
return angle;
} } | public class class_name {
public double angleTo(LineSegment other) {
double angle1 = Math.atan2(this.start.y - this.end.y, this.start.x - this.end.x);
double angle2 = Math.atan2(other.start.y - other.end.y, other.start.x - other.end.x);
double angle = Math.toDegrees(angle1 - angle2);
if (angle <= -180) {
angle += 360; // depends on control dependency: [if], data = [none]
}
if (angle >= 180) {
angle -= 360; // depends on control dependency: [if], data = [none]
}
return angle;
} } |
public class class_name {
public static HijriAdjustment of(
String variant,
int adjustment
) {
int index = variant.indexOf(':');
if (index == -1) {
return new HijriAdjustment(variant, adjustment);
} else {
return new HijriAdjustment(variant.substring(0, index), adjustment);
}
} } | public class class_name {
public static HijriAdjustment of(
String variant,
int adjustment
) {
int index = variant.indexOf(':');
if (index == -1) {
return new HijriAdjustment(variant, adjustment); // depends on control dependency: [if], data = [none]
} else {
return new HijriAdjustment(variant.substring(0, index), adjustment); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Map.Entry<String, String> cutDirectoryInformation(final java.net.URL path) {
Map.Entry<String, String> ret = null;
String pre;
String suf;
String parse;
final StringBuffer tmp = new StringBuffer();
parse = path.toExternalForm();
if (parse.endsWith("/")) {
pre = parse;
suf = "";
} else {
final StringTokenizer tokenizer = new StringTokenizer(path.getFile(), "/");
tmp.append(path.getProtocol());
tmp.append(":");
tmp.append(path.getHost());
pre = "";
while (tokenizer.hasMoreElements()) {
tmp.append(pre);
pre = tokenizer.nextToken();
tmp.append("/");
}
suf = pre;
pre = tmp.toString();
}
ret = new Entry<String, String>(pre, suf);
return ret;
} } | public class class_name {
public static Map.Entry<String, String> cutDirectoryInformation(final java.net.URL path) {
Map.Entry<String, String> ret = null;
String pre;
String suf;
String parse;
final StringBuffer tmp = new StringBuffer();
parse = path.toExternalForm();
if (parse.endsWith("/")) {
pre = parse; // depends on control dependency: [if], data = [none]
suf = ""; // depends on control dependency: [if], data = [none]
} else {
final StringTokenizer tokenizer = new StringTokenizer(path.getFile(), "/");
tmp.append(path.getProtocol()); // depends on control dependency: [if], data = [none]
tmp.append(":"); // depends on control dependency: [if], data = [none]
tmp.append(path.getHost()); // depends on control dependency: [if], data = [none]
pre = ""; // depends on control dependency: [if], data = [none]
while (tokenizer.hasMoreElements()) {
tmp.append(pre); // depends on control dependency: [while], data = [none]
pre = tokenizer.nextToken(); // depends on control dependency: [while], data = [none]
tmp.append("/"); // depends on control dependency: [while], data = [none]
}
suf = pre; // depends on control dependency: [if], data = [none]
pre = tmp.toString(); // depends on control dependency: [if], data = [none]
}
ret = new Entry<String, String>(pre, suf);
return ret;
} } |
public class class_name {
public void marshall(PutFileEntry putFileEntry, ProtocolMarshaller protocolMarshaller) {
if (putFileEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putFileEntry.getFilePath(), FILEPATH_BINDING);
protocolMarshaller.marshall(putFileEntry.getFileMode(), FILEMODE_BINDING);
protocolMarshaller.marshall(putFileEntry.getFileContent(), FILECONTENT_BINDING);
protocolMarshaller.marshall(putFileEntry.getSourceFile(), SOURCEFILE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(PutFileEntry putFileEntry, ProtocolMarshaller protocolMarshaller) {
if (putFileEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putFileEntry.getFilePath(), FILEPATH_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putFileEntry.getFileMode(), FILEMODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putFileEntry.getFileContent(), FILECONTENT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putFileEntry.getSourceFile(), SOURCEFILE_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 void recalcOutDeliveryMode() {
// Changes are required.
if (inDmOverride.equals(ApiJmsConstants.DELIVERY_MODE_PERSISTENT)) {
outboundDeliveryMode = PersistenceType.PERSISTENT;
}
else if (inDmOverride.equals(ApiJmsConstants.DELIVERY_MODE_NONPERSISTENT)) {
outboundDeliveryMode = PersistenceType.NON_PERSISTENT;
}
else {
// Dest.deliveryMode is validated on set, so treating everything else
// as app should be ok here.
if (inDeliveryMode == DeliveryMode.PERSISTENT) {
outboundDeliveryMode = PersistenceType.PERSISTENT;
}
else {
outboundDeliveryMode = PersistenceType.NON_PERSISTENT;
}
}
} } | public class class_name {
private void recalcOutDeliveryMode() {
// Changes are required.
if (inDmOverride.equals(ApiJmsConstants.DELIVERY_MODE_PERSISTENT)) {
outboundDeliveryMode = PersistenceType.PERSISTENT; // depends on control dependency: [if], data = [none]
}
else if (inDmOverride.equals(ApiJmsConstants.DELIVERY_MODE_NONPERSISTENT)) {
outboundDeliveryMode = PersistenceType.NON_PERSISTENT; // depends on control dependency: [if], data = [none]
}
else {
// Dest.deliveryMode is validated on set, so treating everything else
// as app should be ok here.
if (inDeliveryMode == DeliveryMode.PERSISTENT) {
outboundDeliveryMode = PersistenceType.PERSISTENT; // depends on control dependency: [if], data = [none]
}
else {
outboundDeliveryMode = PersistenceType.NON_PERSISTENT; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static <D extends ImageGray<D>>
void hessian( DerivativeType type , D derivX , D derivY , D derivXX , D derivYY , D derivXY , BorderType borderType ) {
ImageBorder<D> border = BorderType.SKIP == borderType ? null : FactoryImageBorder.wrap(borderType, derivX);
switch( type ) {
case PREWITT:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianPrewitt((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border);
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianPrewitt((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border);
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
case SOBEL:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianSobel((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border);
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianSobel((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border);
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
case THREE:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianThree((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border);
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianThree((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border);
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
default:
throw new IllegalArgumentException("Unsupported derivative type "+type);
}
} } | public class class_name {
public static <D extends ImageGray<D>>
void hessian( DerivativeType type , D derivX , D derivY , D derivXX , D derivYY , D derivXY , BorderType borderType ) {
ImageBorder<D> border = BorderType.SKIP == borderType ? null : FactoryImageBorder.wrap(borderType, derivX);
switch( type ) {
case PREWITT:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianPrewitt((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border); // depends on control dependency: [if], data = [none]
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianPrewitt((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
case SOBEL:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianSobel((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border); // depends on control dependency: [if], data = [none]
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianSobel((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
case THREE:
if( derivX instanceof GrayF32) {
HessianFromGradient.hessianThree((GrayF32) derivX, (GrayF32) derivY, (GrayF32) derivXX, (GrayF32) derivYY, (GrayF32) derivXY, (ImageBorder_F32) border); // depends on control dependency: [if], data = [none]
} else if( derivX instanceof GrayS16) {
HessianFromGradient.hessianThree((GrayS16) derivX, (GrayS16) derivY, (GrayS16) derivXX, (GrayS16) derivYY, (GrayS16) derivXY, (ImageBorder_S32) border); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unknown input image type: "+derivX.getClass().getSimpleName());
}
break;
default:
throw new IllegalArgumentException("Unsupported derivative type "+type);
}
} } |
public class class_name {
@Override
public int compare(AVA a1, AVA a2) {
boolean a1Has2253 = a1.hasRFC2253Keyword();
boolean a2Has2253 = a2.hasRFC2253Keyword();
if (a1Has2253) {
if (a2Has2253) {
return a1.toRFC2253CanonicalString().compareTo
(a2.toRFC2253CanonicalString());
} else {
return -1;
}
} else {
if (a2Has2253) {
return 1;
} else {
int[] a1Oid = a1.getObjectIdentifier().toIntArray();
int[] a2Oid = a2.getObjectIdentifier().toIntArray();
int pos = 0;
int len = (a1Oid.length > a2Oid.length) ? a2Oid.length :
a1Oid.length;
while (pos < len && a1Oid[pos] == a2Oid[pos]) {
++pos;
}
return (pos == len) ? a1Oid.length - a2Oid.length :
a1Oid[pos] - a2Oid[pos];
}
}
} } | public class class_name {
@Override
public int compare(AVA a1, AVA a2) {
boolean a1Has2253 = a1.hasRFC2253Keyword();
boolean a2Has2253 = a2.hasRFC2253Keyword();
if (a1Has2253) {
if (a2Has2253) {
return a1.toRFC2253CanonicalString().compareTo
(a2.toRFC2253CanonicalString()); // depends on control dependency: [if], data = [none]
} else {
return -1; // depends on control dependency: [if], data = [none]
}
} else {
if (a2Has2253) {
return 1; // depends on control dependency: [if], data = [none]
} else {
int[] a1Oid = a1.getObjectIdentifier().toIntArray();
int[] a2Oid = a2.getObjectIdentifier().toIntArray();
int pos = 0;
int len = (a1Oid.length > a2Oid.length) ? a2Oid.length :
a1Oid.length;
while (pos < len && a1Oid[pos] == a2Oid[pos]) {
++pos; // depends on control dependency: [while], data = [none]
}
return (pos == len) ? a1Oid.length - a2Oid.length :
a1Oid[pos] - a2Oid[pos]; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void add(final T node) {
if ( this.firstNode == null ) {
this.firstNode = node;
this.lastNode = node;
} else {
this.lastNode.setNext( node );
node.setPrevious( this.lastNode );
this.lastNode = node;
}
this.size++;
} } | public class class_name {
public void add(final T node) {
if ( this.firstNode == null ) {
this.firstNode = node; // depends on control dependency: [if], data = [none]
this.lastNode = node; // depends on control dependency: [if], data = [none]
} else {
this.lastNode.setNext( node ); // depends on control dependency: [if], data = [none]
node.setPrevious( this.lastNode ); // depends on control dependency: [if], data = [none]
this.lastNode = node; // depends on control dependency: [if], data = [none]
}
this.size++;
} } |
public class class_name {
public File getOutputFile(File input, String ext) {
File source;
File destination;
if (input.getAbsolutePath().startsWith(internalSources.getAbsolutePath())) {
source = internalSources;
destination = destinationForInternals;
} else if (input.getAbsolutePath().startsWith(externalSources.getAbsolutePath())) {
source = externalSources;
destination = destinationForExternals;
} else {
return null;
}
String jsFileName = input.getName().substring(0, input.getName().length() - ".ts".length()) + "." + ext;
String path = input.getParentFile().getAbsolutePath().substring(source.getAbsolutePath().length());
return new File(destination, path + "/" + jsFileName);
} } | public class class_name {
public File getOutputFile(File input, String ext) {
File source;
File destination;
if (input.getAbsolutePath().startsWith(internalSources.getAbsolutePath())) {
source = internalSources; // depends on control dependency: [if], data = [none]
destination = destinationForInternals; // depends on control dependency: [if], data = [none]
} else if (input.getAbsolutePath().startsWith(externalSources.getAbsolutePath())) {
source = externalSources; // depends on control dependency: [if], data = [none]
destination = destinationForExternals; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
String jsFileName = input.getName().substring(0, input.getName().length() - ".ts".length()) + "." + ext;
String path = input.getParentFile().getAbsolutePath().substring(source.getAbsolutePath().length());
return new File(destination, path + "/" + jsFileName);
} } |
public class class_name {
@Nullable
public static Symbol getDeclaredSymbol(Tree tree) {
if (tree instanceof AnnotationTree) {
return getSymbol(((AnnotationTree) tree).getAnnotationType());
}
if (tree instanceof PackageTree) {
return getSymbol((PackageTree) tree);
}
if (tree instanceof TypeParameterTree) {
Type type = ((JCTypeParameter) tree).type;
return type == null ? null : type.tsym;
}
if (tree instanceof ClassTree) {
return getSymbol((ClassTree) tree);
}
if (tree instanceof MethodTree) {
return getSymbol((MethodTree) tree);
}
if (tree instanceof VariableTree) {
return getSymbol((VariableTree) tree);
}
return null;
} } | public class class_name {
@Nullable
public static Symbol getDeclaredSymbol(Tree tree) {
if (tree instanceof AnnotationTree) {
return getSymbol(((AnnotationTree) tree).getAnnotationType()); // depends on control dependency: [if], data = [none]
}
if (tree instanceof PackageTree) {
return getSymbol((PackageTree) tree); // depends on control dependency: [if], data = [none]
}
if (tree instanceof TypeParameterTree) {
Type type = ((JCTypeParameter) tree).type;
return type == null ? null : type.tsym; // depends on control dependency: [if], data = [none]
}
if (tree instanceof ClassTree) {
return getSymbol((ClassTree) tree); // depends on control dependency: [if], data = [none]
}
if (tree instanceof MethodTree) {
return getSymbol((MethodTree) tree); // depends on control dependency: [if], data = [none]
}
if (tree instanceof VariableTree) {
return getSymbol((VariableTree) tree); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public TwoDimTableV3 fillFromImpl(TwoDimTable t) {
name = t.getTableHeader();
description = t.getTableDescription();
final int rows = t.getRowDim();
rowcount = rows;
boolean have_row_header_cols = t.getColHeaderForRowHeaders() != null;
for (int r=0; r<rows; ++r) {
if (!have_row_header_cols) break;
have_row_header_cols &= t.getRowHeaders()[r] != null;
}
if (have_row_header_cols) {
final int cols = t.getColDim()+1;
columns = new ColumnSpecsBase[cols];
columns[0] = new ColumnSpecsBase();
columns[0].name = pythonify(t.getColHeaderForRowHeaders());
columns[0].type = "string";
columns[0].format = "%s";
columns[0].description = t.getColHeaderForRowHeaders();
for (int c = 1; c < cols; ++c) {
columns[c] = new ColumnSpecsBase();
columns[c].name = pythonify(t.getColHeaders()[c - 1]);
columns[c].type = t.getColTypes()[c - 1];
columns[c].format = t.getColFormats()[c - 1];
columns[c].description = t.getColHeaders()[c - 1];
}
data = new IcedWrapper[cols][rows];
data[0] = new IcedWrapper[t.getRowDim()];
for (int r = 0; r < t.getRowDim(); ++r) {
data[0][r] = new IcedWrapper(t.getRowHeaders()[r]);
}
IcedWrapper[][] cellValues = t.getCellValues();
for (int c = 1; c < cols; ++c) {
data[c] = new IcedWrapper[rows];
for (int r = 0; r < rows; ++r) {
data[c][r] = cellValues[r][c - 1];
}
}
} else {
final int cols = t.getColDim();
columns = new ColumnSpecsBase[cols];
for (int c = 0; c < cols; ++c) {
columns[c] = new ColumnSpecsBase();
columns[c].name = pythonify(t.getColHeaders()[c]);
columns[c].type = t.getColTypes()[c];
columns[c].format = t.getColFormats()[c];
columns[c].description = t.getColHeaders()[c];
}
data = new IcedWrapper[cols][rows];
IcedWrapper[][] cellValues = t.getCellValues();
for (int c = 0; c < cols; ++c) {
data[c] = new IcedWrapper[rows];
for (int r = 0; r < rows; ++r) {
data[c][r] = cellValues[r][c];
}
}
}
return this;
} } | public class class_name {
@Override
public TwoDimTableV3 fillFromImpl(TwoDimTable t) {
name = t.getTableHeader();
description = t.getTableDescription();
final int rows = t.getRowDim();
rowcount = rows;
boolean have_row_header_cols = t.getColHeaderForRowHeaders() != null;
for (int r=0; r<rows; ++r) {
if (!have_row_header_cols) break;
have_row_header_cols &= t.getRowHeaders()[r] != null; // depends on control dependency: [for], data = [r]
}
if (have_row_header_cols) {
final int cols = t.getColDim()+1;
columns = new ColumnSpecsBase[cols]; // depends on control dependency: [if], data = [none]
columns[0] = new ColumnSpecsBase(); // depends on control dependency: [if], data = [none]
columns[0].name = pythonify(t.getColHeaderForRowHeaders()); // depends on control dependency: [if], data = [none]
columns[0].type = "string"; // depends on control dependency: [if], data = [none]
columns[0].format = "%s"; // depends on control dependency: [if], data = [none]
columns[0].description = t.getColHeaderForRowHeaders(); // depends on control dependency: [if], data = [none]
for (int c = 1; c < cols; ++c) {
columns[c] = new ColumnSpecsBase(); // depends on control dependency: [for], data = [c]
columns[c].name = pythonify(t.getColHeaders()[c - 1]); // depends on control dependency: [for], data = [c]
columns[c].type = t.getColTypes()[c - 1]; // depends on control dependency: [for], data = [c]
columns[c].format = t.getColFormats()[c - 1]; // depends on control dependency: [for], data = [c]
columns[c].description = t.getColHeaders()[c - 1]; // depends on control dependency: [for], data = [c]
}
data = new IcedWrapper[cols][rows]; // depends on control dependency: [if], data = [none]
data[0] = new IcedWrapper[t.getRowDim()]; // depends on control dependency: [if], data = [none]
for (int r = 0; r < t.getRowDim(); ++r) {
data[0][r] = new IcedWrapper(t.getRowHeaders()[r]); // depends on control dependency: [for], data = [r]
}
IcedWrapper[][] cellValues = t.getCellValues();
for (int c = 1; c < cols; ++c) {
data[c] = new IcedWrapper[rows]; // depends on control dependency: [for], data = [c]
for (int r = 0; r < rows; ++r) {
data[c][r] = cellValues[r][c - 1]; // depends on control dependency: [for], data = [r]
}
}
} else {
final int cols = t.getColDim();
columns = new ColumnSpecsBase[cols]; // depends on control dependency: [if], data = [none]
for (int c = 0; c < cols; ++c) {
columns[c] = new ColumnSpecsBase(); // depends on control dependency: [for], data = [c]
columns[c].name = pythonify(t.getColHeaders()[c]); // depends on control dependency: [for], data = [c]
columns[c].type = t.getColTypes()[c]; // depends on control dependency: [for], data = [c]
columns[c].format = t.getColFormats()[c]; // depends on control dependency: [for], data = [c]
columns[c].description = t.getColHeaders()[c]; // depends on control dependency: [for], data = [c]
}
data = new IcedWrapper[cols][rows]; // depends on control dependency: [if], data = [none]
IcedWrapper[][] cellValues = t.getCellValues();
for (int c = 0; c < cols; ++c) {
data[c] = new IcedWrapper[rows]; // depends on control dependency: [for], data = [c]
for (int r = 0; r < rows; ++r) {
data[c][r] = cellValues[r][c]; // depends on control dependency: [for], data = [r]
}
}
}
return this;
} } |
public class class_name {
boolean rule2(final IFactory factory, final Inclusion[] gcis) {
boolean result = false;
if (lhs instanceof Conjunction) {
Conjunction conjunction = (Conjunction) lhs;
final AbstractConcept[] concepts = conjunction.getConcepts();
if (concepts.length == 1) {
// unwrap redundant conjuncts
gcis[0] = new GCI(concepts[0], rhs);
result = true;
} else if (concepts.length == 0) {
log.warn("Empty conjunct detected in: " + this);
gcis[0] = new GCI(IFactory.TOP_CONCEPT, rhs);
result = true;
} else {
// Swap out any non-Concept concepts (ie Existentials)
for (int i = 0; !result && i < concepts.length; i++) {
if (!(concepts[i] instanceof Concept)) {
final Concept a = getA(factory, concepts[i]);
gcis[0] = new GCI(concepts[i], a);
final AbstractConcept[] newConcepts = new AbstractConcept[concepts.length];
System.arraycopy(concepts, 0, newConcepts, 0,
concepts.length);
newConcepts[i] = a;
gcis[1] = new GCI(new Conjunction(newConcepts), rhs);
result = true;
}
}
if (!result) {
if (concepts.length > 2) {
// Binarise a conjunction of Concepts (expected/assumed
// by NF1)
result = true;
final AbstractConcept[] newConcepts = new AbstractConcept[concepts.length - 1];
System.arraycopy(concepts, 1, newConcepts, 0,
concepts.length - 1);
final AbstractConcept d = new Conjunction(newConcepts);
final Concept a = getA(factory, d);
final AbstractConcept cAndA = new Conjunction(
new AbstractConcept[] { concepts[0], a });
gcis[0] = new GCI(cAndA, rhs);
gcis[1] = new GCI(d, a);
} else if (concepts.length < 2) {
throw new AssertionError(
"Conjunctions of fewer than "
+ "two elements should not exist at this point: "
+ this);
}
}
}
}
return result;
} } | public class class_name {
boolean rule2(final IFactory factory, final Inclusion[] gcis) {
boolean result = false;
if (lhs instanceof Conjunction) {
Conjunction conjunction = (Conjunction) lhs;
final AbstractConcept[] concepts = conjunction.getConcepts();
if (concepts.length == 1) {
// unwrap redundant conjuncts
gcis[0] = new GCI(concepts[0], rhs);
result = true;
} else if (concepts.length == 0) {
log.warn("Empty conjunct detected in: " + this);
gcis[0] = new GCI(IFactory.TOP_CONCEPT, rhs);
result = true;
} else {
// Swap out any non-Concept concepts (ie Existentials)
for (int i = 0; !result && i < concepts.length; i++) {
if (!(concepts[i] instanceof Concept)) {
final Concept a = getA(factory, concepts[i]);
gcis[0] = new GCI(concepts[i], a);
// depends on control dependency: [if], data = [none]
final AbstractConcept[] newConcepts = new AbstractConcept[concepts.length];
System.arraycopy(concepts, 0, newConcepts, 0,
concepts.length);
// depends on control dependency: [if], data = [none]
newConcepts[i] = a;
// depends on control dependency: [if], data = [none]
gcis[1] = new GCI(new Conjunction(newConcepts), rhs);
// depends on control dependency: [if], data = [none]
result = true;
// depends on control dependency: [if], data = [none]
}
}
if (!result) {
if (concepts.length > 2) {
// Binarise a conjunction of Concepts (expected/assumed
// by NF1)
result = true;
final AbstractConcept[] newConcepts = new AbstractConcept[concepts.length - 1];
System.arraycopy(concepts, 1, newConcepts, 0,
concepts.length - 1);
final AbstractConcept d = new Conjunction(newConcepts);
final Concept a = getA(factory, d);
final AbstractConcept cAndA = new Conjunction(
new AbstractConcept[] { concepts[0], a });
gcis[0] = new GCI(cAndA, rhs);
gcis[1] = new GCI(d, a);
} else if (concepts.length < 2) {
throw new AssertionError(
"Conjunctions of fewer than "
+ "two elements should not exist at this point: "
+ this);
}
}
}
}
return result;
} } |
public class class_name {
@Override
public boolean isScoreProperty() {
if (findAnnotation(Score.class) != null) {
return true;
}
return findAnnotation(org.springframework.data.solr.repository.Score.class) != null;
} } | public class class_name {
@Override
public boolean isScoreProperty() {
if (findAnnotation(Score.class) != null) {
return true; // depends on control dependency: [if], data = [none]
}
return findAnnotation(org.springframework.data.solr.repository.Score.class) != null;
} } |
public class class_name {
public double getLowerBound(final int kappa) {
if (!hasHip(mem)) {
return getIconConfidenceLB(PreambleUtil.getLgK(mem), getNumCoupons(mem), kappa);
}
return getHipConfidenceLB(PreambleUtil.getLgK(mem), getNumCoupons(mem), getHipAccum(mem), kappa);
} } | public class class_name {
public double getLowerBound(final int kappa) {
if (!hasHip(mem)) {
return getIconConfidenceLB(PreambleUtil.getLgK(mem), getNumCoupons(mem), kappa); // depends on control dependency: [if], data = [none]
}
return getHipConfidenceLB(PreambleUtil.getLgK(mem), getNumCoupons(mem), getHipAccum(mem), kappa);
} } |
public class class_name {
public Paragraph<PS, SEG, S> concat(Paragraph<PS, SEG, S> p) {
if(p.length() == 0) {
return this;
}
if(length() == 0) {
return p;
}
List<SEG> updatedSegs;
SEG leftSeg = segments.get(segments.size() - 1);
SEG rightSeg = p.segments.get(0);
Optional<SEG> joined = segmentOps.joinSeg(leftSeg, rightSeg);
if(joined.isPresent()) {
SEG segment = joined.get();
updatedSegs = new ArrayList<>(segments.size() + p.segments.size() - 1);
updatedSegs.addAll(segments.subList(0, segments.size()-1));
updatedSegs.add(segment);
updatedSegs.addAll(p.segments.subList(1, p.segments.size()));
} else {
updatedSegs = new ArrayList<>(segments.size() + p.segments.size());
updatedSegs.addAll(segments);
updatedSegs.addAll(p.segments);
}
StyleSpans<S> updatedStyles;
StyleSpan<S> leftSpan = styles.getStyleSpan(styles.getSpanCount() - 1);
StyleSpan<S> rightSpan = p.styles.getStyleSpan(0);
Optional<S> merge = segmentOps.joinStyle(leftSpan.getStyle(), rightSpan.getStyle());
if (merge.isPresent()) {
int startOfMerge = styles.position(styles.getSpanCount() - 1, 0).toOffset();
StyleSpans<S> updatedLeftSpan = styles.subView(0, startOfMerge);
int endOfMerge = p.styles.position(1, 0).toOffset();
StyleSpans<S> updatedRightSpan = p.styles.subView(endOfMerge, p.styles.length());
updatedStyles = updatedLeftSpan
.append(merge.get(), leftSpan.getLength() + rightSpan.getLength())
.concat(updatedRightSpan);
} else {
updatedStyles = styles.concat(p.styles);
}
return new Paragraph<>(paragraphStyle, segmentOps, updatedSegs, updatedStyles);
} } | public class class_name {
public Paragraph<PS, SEG, S> concat(Paragraph<PS, SEG, S> p) {
if(p.length() == 0) {
return this; // depends on control dependency: [if], data = [none]
}
if(length() == 0) {
return p; // depends on control dependency: [if], data = [none]
}
List<SEG> updatedSegs;
SEG leftSeg = segments.get(segments.size() - 1);
SEG rightSeg = p.segments.get(0);
Optional<SEG> joined = segmentOps.joinSeg(leftSeg, rightSeg);
if(joined.isPresent()) {
SEG segment = joined.get();
updatedSegs = new ArrayList<>(segments.size() + p.segments.size() - 1); // depends on control dependency: [if], data = [none]
updatedSegs.addAll(segments.subList(0, segments.size()-1)); // depends on control dependency: [if], data = [none]
updatedSegs.add(segment); // depends on control dependency: [if], data = [none]
updatedSegs.addAll(p.segments.subList(1, p.segments.size())); // depends on control dependency: [if], data = [none]
} else {
updatedSegs = new ArrayList<>(segments.size() + p.segments.size()); // depends on control dependency: [if], data = [none]
updatedSegs.addAll(segments); // depends on control dependency: [if], data = [none]
updatedSegs.addAll(p.segments); // depends on control dependency: [if], data = [none]
}
StyleSpans<S> updatedStyles;
StyleSpan<S> leftSpan = styles.getStyleSpan(styles.getSpanCount() - 1);
StyleSpan<S> rightSpan = p.styles.getStyleSpan(0);
Optional<S> merge = segmentOps.joinStyle(leftSpan.getStyle(), rightSpan.getStyle());
if (merge.isPresent()) {
int startOfMerge = styles.position(styles.getSpanCount() - 1, 0).toOffset();
StyleSpans<S> updatedLeftSpan = styles.subView(0, startOfMerge);
int endOfMerge = p.styles.position(1, 0).toOffset();
StyleSpans<S> updatedRightSpan = p.styles.subView(endOfMerge, p.styles.length());
updatedStyles = updatedLeftSpan
.append(merge.get(), leftSpan.getLength() + rightSpan.getLength())
.concat(updatedRightSpan);
} else {
updatedStyles = styles.concat(p.styles);
}
return new Paragraph<>(paragraphStyle, segmentOps, updatedSegs, updatedStyles);
} } |
public class class_name {
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
super.close();
synchronized (baseClients) {
for (WebClient wc : baseClients) {
wc.close();
}
}
String moduleName = getModuleName();
synchronized (clientsPerModule) {
List<JAXRSClientImpl> clients = clientsPerModule.get(moduleName);
if (clients != null) { // the only way this isn't null is if the same client was closed twice
clients.remove(this);
if (clients.isEmpty()) {
for (String id : busCache.keySet()) {
if (id.startsWith(moduleName) || id.startsWith("unknown:")) {
busCache.remove(id).shutdown(false);
}
}
clientsPerModule.remove(moduleName);
}
}
}
baseClients = null;
}
} } | public class class_name {
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
super.close(); // depends on control dependency: [if], data = [none]
synchronized (baseClients) { // depends on control dependency: [if], data = [none]
for (WebClient wc : baseClients) {
wc.close(); // depends on control dependency: [for], data = [wc]
}
}
String moduleName = getModuleName();
synchronized (clientsPerModule) { // depends on control dependency: [if], data = [none]
List<JAXRSClientImpl> clients = clientsPerModule.get(moduleName);
if (clients != null) { // the only way this isn't null is if the same client was closed twice
clients.remove(this); // depends on control dependency: [if], data = [none]
if (clients.isEmpty()) {
for (String id : busCache.keySet()) {
if (id.startsWith(moduleName) || id.startsWith("unknown:")) {
busCache.remove(id).shutdown(false); // depends on control dependency: [if], data = [none]
}
}
clientsPerModule.remove(moduleName); // depends on control dependency: [if], data = [none]
}
}
}
baseClients = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void writeColumns(Table htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)
throws IOException
{
if (columns != null && !columns.isEmpty())
{
Put p = new Put(HBaseUtils.getBytes(rowKey));
for (String columnName : columns.keySet())
{
p.addColumn(columnFamilyName.getBytes(), Bytes.toBytes(columnName),
HBaseUtils.getBytes(columns.get(columnName)));
}
htable.put(p);
}
} } | public class class_name {
@Override
public void writeColumns(Table htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)
throws IOException
{
if (columns != null && !columns.isEmpty())
{
Put p = new Put(HBaseUtils.getBytes(rowKey));
for (String columnName : columns.keySet())
{
p.addColumn(columnFamilyName.getBytes(), Bytes.toBytes(columnName),
HBaseUtils.getBytes(columns.get(columnName))); // depends on control dependency: [for], data = [none]
}
htable.put(p);
}
} } |
public class class_name {
private static Record createRecord(ByteBuffer data, int bytesToBlockEnd, Record lastRecord) {
int bytesToDataEnd = data.remaining();
RecordType type = RecordType.UNKNOWN;
int bytes = -1;
if ((lastRecord.getType() == RecordType.NONE)
&& ((bytesToDataEnd + LevelDbConstants.HEADER_LENGTH) <= bytesToBlockEnd)) {
// Can write entire record in current block
type = RecordType.FULL;
bytes = bytesToDataEnd;
} else if (lastRecord.getType() == RecordType.NONE) {
// On first write but can't fit in current block
type = RecordType.FIRST;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
} else if (bytesToDataEnd + LevelDbConstants.HEADER_LENGTH <= bytesToBlockEnd) {
// At end of record
type = RecordType.LAST;
bytes = bytesToDataEnd;
} else {
// In middle somewhere
type = RecordType.MIDDLE;
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH;
}
return new Record(type, bytes);
} } | public class class_name {
private static Record createRecord(ByteBuffer data, int bytesToBlockEnd, Record lastRecord) {
int bytesToDataEnd = data.remaining();
RecordType type = RecordType.UNKNOWN;
int bytes = -1;
if ((lastRecord.getType() == RecordType.NONE)
&& ((bytesToDataEnd + LevelDbConstants.HEADER_LENGTH) <= bytesToBlockEnd)) {
// Can write entire record in current block
type = RecordType.FULL; // depends on control dependency: [if], data = [none]
bytes = bytesToDataEnd; // depends on control dependency: [if], data = [none]
} else if (lastRecord.getType() == RecordType.NONE) {
// On first write but can't fit in current block
type = RecordType.FIRST; // depends on control dependency: [if], data = [none]
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH; // depends on control dependency: [if], data = [none]
} else if (bytesToDataEnd + LevelDbConstants.HEADER_LENGTH <= bytesToBlockEnd) {
// At end of record
type = RecordType.LAST; // depends on control dependency: [if], data = [none]
bytes = bytesToDataEnd; // depends on control dependency: [if], data = [none]
} else {
// In middle somewhere
type = RecordType.MIDDLE; // depends on control dependency: [if], data = [none]
bytes = bytesToBlockEnd - LevelDbConstants.HEADER_LENGTH; // depends on control dependency: [if], data = [none]
}
return new Record(type, bytes);
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public void pushMessage(IPipe pipe, IMessage message) throws IOException {
if (message instanceof RTMPMessage) {
final IRTMPEvent msg = ((RTMPMessage) message).getBody();
// if writes are delayed, queue the data and sort it by time
if (queue == null) {
if (usePriority) {
if (log.isTraceEnabled()) {
log.trace("Creating priority typed packet queue. queueThreshold={}", queueThreshold);
}
// if we want ordering / comparing built-in
queue = new PriorityBlockingQueue<>(queueThreshold <= 0 ? 240 : queueThreshold, comparator);
} else {
if (log.isTraceEnabled()) {
log.trace("Creating non-priority typed packet queue");
}
// process as received
queue = new LinkedBlockingQueue<>();
}
}
if (msg instanceof IStreamData) {
// get the type
byte dataType = msg.getDataType();
// get the timestamp
int timestamp = msg.getTimestamp();
if (log.isTraceEnabled()) {
log.trace("Stream data, body saved, timestamp: {} data type: {} class type: {}", timestamp, dataType, msg.getClass().getName());
}
// if the last message was a reset or we just started, use the header timer
if (startTimestamp == -1) {
startTimestamp = timestamp;
timestamp = 0;
} else {
timestamp -= startTimestamp;
}
// offer to the queue
try {
QueuedMediaData queued = new QueuedMediaData(timestamp, dataType, (IStreamData) msg);
if (log.isTraceEnabled()) {
log.trace("Inserting packet into queue. timestamp: {} queue size: {}, codecId={}, isConfig={}", timestamp, queue.size(), queued.codecId, queued.config);
}
if (queue.size() > queueThreshold) {
if (queue.size() % 20 == 0) {
log.warn("Queue size is greater than threshold. queue size={} threshold={}", queue.size(), queueThreshold);
}
}
if (queue.size() < 2 * queueThreshold) {
// Cap queue size to prevent a runaway stream causing OOM.
queue.offer(queued, offerTimeout, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
log.warn("Stream data was not accepted by the queue - timestamp: {} data type: {}", timestamp, dataType, e);
}
}
// initialize a writer
if (writer == null) {
executor.submit(new Runnable() {
public void run() {
Thread.currentThread().setName("ProFileConsumer-" + path.getFileName());
try {
if (log.isTraceEnabled()) {
log.trace("Running FileConsumer thread. queue size: {} initialized: {} writerNotNull={}", queue.size(), initialized, (writer != null));
}
init();
while (writer != null) {
if (log.isTraceEnabled()) {
log.trace("Processing packet from queue. queue size: {}", queue.size());
}
try {
QueuedMediaData queued = queue.take();
if (queued != null) {
// get data type
byte dataType = queued.getDataType();
// get timestamp
int timestamp = queued.getTimestamp();
ITag tag = queued.getData();
// ensure that our first video frame written is a key frame
if (queued.isVideo()) {
if (log.isTraceEnabled()) {
log.trace("pushMessage video - waitForKeyframe: {} gotKeyframe: {} timestamp: {}", waitForVideoKeyframe, gotKeyFrame, queued.getTimestamp());
}
if (queued.codecId == VideoCodec.AVC.getId()) {
if (queued.isConfig()) {
videoConfigurationTag = tag;
gotKeyFrame = true;
}
if (videoConfigurationTag == null && waitForVideoKeyframe) {
continue;
}
} else {
if (queued.frameType == VideoData.FrameType.KEYFRAME) {
gotKeyFrame = true;
}
if (waitForVideoKeyframe && !gotKeyFrame) {
continue;
}
}
} else if (queued.isAudio()) {
if (queued.isConfig()) {
audioConfigurationTag = tag;
}
}
if (queued.isVideo()) {
if (log.isTraceEnabled()) {
log.trace("Writing packet. frameType={} timestamp={}", queued.frameType, queued.getTimestamp() );
}
}
// write
write(dataType, timestamp, tag);
// clean up
queued.dispose();
} else {
if (log.isTraceEnabled()) {
log.trace("Queued media is null. queue size: {}", queue.size());
}
}
} catch (InterruptedException e) {
log.warn("{}", e.getMessage(), e);
}
//finally {
// if (log.isTraceEnabled()) {
// log.trace("Clearing queue. queue size: {}", queue.size());
// }
// queue.clear();
//}
}
} catch (IOException e) {
log.warn("{}", e.getMessage(), e);
}
}
});
}
} else if (message instanceof ResetMessage) {
startTimestamp = -1;
} else if (log.isDebugEnabled()) {
log.debug("Ignoring pushed message: {}", message);
}
} } | public class class_name {
@SuppressWarnings("rawtypes")
public void pushMessage(IPipe pipe, IMessage message) throws IOException {
if (message instanceof RTMPMessage) {
final IRTMPEvent msg = ((RTMPMessage) message).getBody();
// if writes are delayed, queue the data and sort it by time
if (queue == null) {
if (usePriority) {
if (log.isTraceEnabled()) {
log.trace("Creating priority typed packet queue. queueThreshold={}", queueThreshold);
// depends on control dependency: [if], data = [none]
}
// if we want ordering / comparing built-in
queue = new PriorityBlockingQueue<>(queueThreshold <= 0 ? 240 : queueThreshold, comparator);
// depends on control dependency: [if], data = [none]
} else {
if (log.isTraceEnabled()) {
log.trace("Creating non-priority typed packet queue");
// depends on control dependency: [if], data = [none]
}
// process as received
queue = new LinkedBlockingQueue<>();
// depends on control dependency: [if], data = [none]
}
}
if (msg instanceof IStreamData) {
// get the type
byte dataType = msg.getDataType();
// get the timestamp
int timestamp = msg.getTimestamp();
if (log.isTraceEnabled()) {
log.trace("Stream data, body saved, timestamp: {} data type: {} class type: {}", timestamp, dataType, msg.getClass().getName());
// depends on control dependency: [if], data = [none]
}
// if the last message was a reset or we just started, use the header timer
if (startTimestamp == -1) {
startTimestamp = timestamp;
// depends on control dependency: [if], data = [none]
timestamp = 0;
// depends on control dependency: [if], data = [none]
} else {
timestamp -= startTimestamp;
// depends on control dependency: [if], data = [none]
}
// offer to the queue
try {
QueuedMediaData queued = new QueuedMediaData(timestamp, dataType, (IStreamData) msg);
if (log.isTraceEnabled()) {
log.trace("Inserting packet into queue. timestamp: {} queue size: {}, codecId={}, isConfig={}", timestamp, queue.size(), queued.codecId, queued.config);
// depends on control dependency: [if], data = [none]
}
if (queue.size() > queueThreshold) {
if (queue.size() % 20 == 0) {
log.warn("Queue size is greater than threshold. queue size={} threshold={}", queue.size(), queueThreshold);
// depends on control dependency: [if], data = [none]
}
}
if (queue.size() < 2 * queueThreshold) {
// Cap queue size to prevent a runaway stream causing OOM.
queue.offer(queued, offerTimeout, TimeUnit.MILLISECONDS);
// depends on control dependency: [if], data = [none]
}
} catch (InterruptedException e) {
log.warn("Stream data was not accepted by the queue - timestamp: {} data type: {}", timestamp, dataType, e);
}
// depends on control dependency: [catch], data = [none]
}
// initialize a writer
if (writer == null) {
executor.submit(new Runnable() {
public void run() {
Thread.currentThread().setName("ProFileConsumer-" + path.getFileName());
try {
if (log.isTraceEnabled()) {
log.trace("Running FileConsumer thread. queue size: {} initialized: {} writerNotNull={}", queue.size(), initialized, (writer != null));
// depends on control dependency: [if], data = [none]
}
init();
// depends on control dependency: [try], data = [none]
while (writer != null) {
if (log.isTraceEnabled()) {
log.trace("Processing packet from queue. queue size: {}", queue.size());
// depends on control dependency: [if], data = [none]
}
try {
QueuedMediaData queued = queue.take();
if (queued != null) {
// get data type
byte dataType = queued.getDataType();
// get timestamp
int timestamp = queued.getTimestamp();
ITag tag = queued.getData();
// ensure that our first video frame written is a key frame
if (queued.isVideo()) {
if (log.isTraceEnabled()) {
log.trace("pushMessage video - waitForKeyframe: {} gotKeyframe: {} timestamp: {}", waitForVideoKeyframe, gotKeyFrame, queued.getTimestamp());
// depends on control dependency: [if], data = [none]
}
if (queued.codecId == VideoCodec.AVC.getId()) {
if (queued.isConfig()) {
videoConfigurationTag = tag;
// depends on control dependency: [if], data = [none]
gotKeyFrame = true;
// depends on control dependency: [if], data = [none]
}
if (videoConfigurationTag == null && waitForVideoKeyframe) {
continue;
}
} else {
if (queued.frameType == VideoData.FrameType.KEYFRAME) {
gotKeyFrame = true;
// depends on control dependency: [if], data = [none]
}
if (waitForVideoKeyframe && !gotKeyFrame) {
continue;
}
}
} else if (queued.isAudio()) {
if (queued.isConfig()) {
audioConfigurationTag = tag;
// depends on control dependency: [if], data = [none]
}
}
if (queued.isVideo()) {
if (log.isTraceEnabled()) {
log.trace("Writing packet. frameType={} timestamp={}", queued.frameType, queued.getTimestamp() );
// depends on control dependency: [if], data = [none]
}
}
// write
write(dataType, timestamp, tag);
// depends on control dependency: [if], data = [none]
// clean up
queued.dispose();
// depends on control dependency: [if], data = [none]
} else {
if (log.isTraceEnabled()) {
log.trace("Queued media is null. queue size: {}", queue.size());
// depends on control dependency: [if], data = [none]
}
}
} catch (InterruptedException e) {
log.warn("{}", e.getMessage(), e);
}
// depends on control dependency: [catch], data = [none]
//finally {
// if (log.isTraceEnabled()) {
// log.trace("Clearing queue. queue size: {}", queue.size());
// }
// queue.clear();
//}
}
} catch (IOException e) {
log.warn("{}", e.getMessage(), e);
}
// depends on control dependency: [catch], data = [none]
}
});
// depends on control dependency: [if], data = [none]
}
} else if (message instanceof ResetMessage) {
startTimestamp = -1;
} else if (log.isDebugEnabled()) {
log.debug("Ignoring pushed message: {}", message);
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.