code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public void setInstanceIds(java.util.Collection<InstanceIdDetail> instanceIds) {
if (instanceIds == null) {
this.instanceIds = null;
return;
}
this.instanceIds = new java.util.ArrayList<InstanceIdDetail>(instanceIds);
} }
|
public class class_name {
public void setInstanceIds(java.util.Collection<InstanceIdDetail> instanceIds) {
if (instanceIds == null) {
this.instanceIds = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.instanceIds = new java.util.ArrayList<InstanceIdDetail>(instanceIds);
} }
|
public class class_name {
public void setDetectionAttributes(java.util.Collection<String> detectionAttributes) {
if (detectionAttributes == null) {
this.detectionAttributes = null;
return;
}
this.detectionAttributes = new java.util.ArrayList<String>(detectionAttributes);
} }
|
public class class_name {
public void setDetectionAttributes(java.util.Collection<String> detectionAttributes) {
if (detectionAttributes == null) {
this.detectionAttributes = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.detectionAttributes = new java.util.ArrayList<String>(detectionAttributes);
} }
|
public class class_name {
protected void init(String line) throws ProblemFormatException {
StringTokenizer st = new StringTokenizer(line);
try {
this.id = st.nextToken();
this.dimension = Integer.valueOf(st.nextToken());
this.capacity = Integer.valueOf(st.nextToken());
this.knapsackItems = new ArrayList<KnapsackItem>(this.dimension);
for (int i = 0; i < dimension; i++) {
int weight = Integer.valueOf(st.nextToken());
int price = Integer.valueOf(st.nextToken());
this.knapsackItems.add(new KnapsackItem(i, weight, price));
}
if (st.hasMoreTokens())
throw new ProblemFormatException("Too many elements in line");
} catch (NoSuchElementException e) {
throw new ProblemFormatException("Insufficient number of elements in line");
} catch (NumberFormatException e) {
throw new ProblemFormatException("Non numeric elements found in line");
}
this.addOperations = new ArrayList<AddOperation>(this.dimension);
this.removeOperations = new ArrayList<RemoveOperation>(this.dimension);
AddOperation addTmp;
RemoveOperation removeTmp;
for (int i = 0; i < this.dimension; i++) {
addTmp = new AddOperation(this.knapsackItems.get(i));
removeTmp = new RemoveOperation(this.knapsackItems.get(i));
// set reverses
addTmp.setReverse(removeTmp);
removeTmp.setReverse(addTmp);
// add operations to list
this.addOperations.add(addTmp);
this.removeOperations.add(removeTmp);
}
List<Integer> tmp = new ArrayList<Integer>(this.dimension);
for (int i = 0; i < this.dimension; ++i) tmp.add(0);
this.startingConfiguration = new Configuration(tmp, "Empty knapsack created");
} }
|
public class class_name {
protected void init(String line) throws ProblemFormatException {
StringTokenizer st = new StringTokenizer(line);
try {
this.id = st.nextToken();
this.dimension = Integer.valueOf(st.nextToken());
this.capacity = Integer.valueOf(st.nextToken());
this.knapsackItems = new ArrayList<KnapsackItem>(this.dimension);
for (int i = 0; i < dimension; i++) {
int weight = Integer.valueOf(st.nextToken());
int price = Integer.valueOf(st.nextToken());
this.knapsackItems.add(new KnapsackItem(i, weight, price)); // depends on control dependency: [for], data = [i]
}
if (st.hasMoreTokens())
throw new ProblemFormatException("Too many elements in line");
} catch (NoSuchElementException e) {
throw new ProblemFormatException("Insufficient number of elements in line");
} catch (NumberFormatException e) {
throw new ProblemFormatException("Non numeric elements found in line");
}
this.addOperations = new ArrayList<AddOperation>(this.dimension);
this.removeOperations = new ArrayList<RemoveOperation>(this.dimension);
AddOperation addTmp;
RemoveOperation removeTmp;
for (int i = 0; i < this.dimension; i++) {
addTmp = new AddOperation(this.knapsackItems.get(i));
removeTmp = new RemoveOperation(this.knapsackItems.get(i));
// set reverses
addTmp.setReverse(removeTmp);
removeTmp.setReverse(addTmp);
// add operations to list
this.addOperations.add(addTmp);
this.removeOperations.add(removeTmp);
}
List<Integer> tmp = new ArrayList<Integer>(this.dimension);
for (int i = 0; i < this.dimension; ++i) tmp.add(0);
this.startingConfiguration = new Configuration(tmp, "Empty knapsack created");
} }
|
public class class_name {
private void addQueryParams(final Request request) {
if (dateCreatedFrom != null) {
request.addQueryParam("DateCreatedFrom", dateCreatedFrom.toString());
}
if (dateCreatedTo != null) {
request.addQueryParam("DateCreatedTo", dateCreatedTo.toString());
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize()));
}
} }
|
public class class_name {
private void addQueryParams(final Request request) {
if (dateCreatedFrom != null) {
request.addQueryParam("DateCreatedFrom", dateCreatedFrom.toString()); // depends on control dependency: [if], data = [none]
}
if (dateCreatedTo != null) {
request.addQueryParam("DateCreatedTo", dateCreatedTo.toString()); // depends on control dependency: [if], data = [none]
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize())); // depends on control dependency: [if], data = [(getPageSize()]
}
} }
|
public class class_name {
public int compareTo (@Nonnull final VersionRange rhs)
{
int i = m_aFloorVersion.compareTo (rhs.m_aFloorVersion);
if (i == 0)
{
if (m_bIncludeFloor && !rhs.m_bIncludeFloor)
{
// this < rhs
i = -1;
}
else
if (!m_bIncludeFloor && rhs.m_bIncludeFloor)
{
// this > rhs
i = +1;
}
if (i == 0)
{
// compare ceiling
if (m_aCeilVersion != null && rhs.m_aCeilVersion == null)
i = -1;
else
if (m_aCeilVersion == null && rhs.m_aCeilVersion != null)
i = +1;
else
if (m_aCeilVersion != null && rhs.m_aCeilVersion != null)
i = m_aCeilVersion.compareTo (rhs.m_aCeilVersion);
// else i stays 0 if both are null
if (i == 0)
{
if (m_bIncludeCeil && !rhs.m_bIncludeCeil)
i = +1;
else
if (!m_bIncludeCeil && rhs.m_bIncludeCeil)
i = -1;
}
}
}
return i;
} }
|
public class class_name {
public int compareTo (@Nonnull final VersionRange rhs)
{
int i = m_aFloorVersion.compareTo (rhs.m_aFloorVersion);
if (i == 0)
{
if (m_bIncludeFloor && !rhs.m_bIncludeFloor)
{
// this < rhs
i = -1; // depends on control dependency: [if], data = [none]
}
else
if (!m_bIncludeFloor && rhs.m_bIncludeFloor)
{
// this > rhs
i = +1; // depends on control dependency: [if], data = [none]
}
if (i == 0)
{
// compare ceiling
if (m_aCeilVersion != null && rhs.m_aCeilVersion == null)
i = -1;
else
if (m_aCeilVersion == null && rhs.m_aCeilVersion != null)
i = +1;
else
if (m_aCeilVersion != null && rhs.m_aCeilVersion != null)
i = m_aCeilVersion.compareTo (rhs.m_aCeilVersion);
// else i stays 0 if both are null
if (i == 0)
{
if (m_bIncludeCeil && !rhs.m_bIncludeCeil)
i = +1;
else
if (!m_bIncludeCeil && rhs.m_bIncludeCeil)
i = -1;
}
}
}
return i;
} }
|
public class class_name {
private CompletionStage<Void> initializeSentinels() {
if (closed) {
return closeFuture;
}
Duration timeout = getTimeout();
List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> connectionFutures = potentiallyConnectSentinels();
if (connectionFutures.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
if (closed) {
return closeAsync();
}
SentinelTopologyRefreshConnections collector = collectConnections(connectionFutures);
CompletionStage<SentinelTopologyRefreshConnections> completionStage = collector.getOrTimeout(timeout, redisClient
.getResources().eventExecutorGroup());
return completionStage.whenComplete((aVoid, throwable) -> {
if (throwable != null) {
closeAsync();
}
}).thenApply(noop -> (Void) null);
} }
|
public class class_name {
private CompletionStage<Void> initializeSentinels() {
if (closed) {
return closeFuture; // depends on control dependency: [if], data = [none]
}
Duration timeout = getTimeout();
List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> connectionFutures = potentiallyConnectSentinels();
if (connectionFutures.isEmpty()) {
return CompletableFuture.completedFuture(null); // depends on control dependency: [if], data = [none]
}
if (closed) {
return closeAsync(); // depends on control dependency: [if], data = [none]
}
SentinelTopologyRefreshConnections collector = collectConnections(connectionFutures);
CompletionStage<SentinelTopologyRefreshConnections> completionStage = collector.getOrTimeout(timeout, redisClient
.getResources().eventExecutorGroup());
return completionStage.whenComplete((aVoid, throwable) -> {
if (throwable != null) {
closeAsync();
}
}).thenApply(noop -> (Void) null);
} }
|
public class class_name {
protected void fail(final Receiver<Void> receiver, final ServerFailure failure) {
this.reuse();
failure.setRequestContext(this);
Set<Throwable> causes = null;
for (final AbstractRequest<?, ?> request : new ArrayList<>(this.state.invocations)) {
try {
request.onFail(failure);
} catch (final Throwable t) {
if (causes == null) {
causes = new HashSet<>();
}
causes.add(t);
}
}
if (receiver != null) {
try {
receiver.onFailure(failure);
} catch (final Throwable t) {
if (causes == null) {
causes = new HashSet<>();
}
causes.add(t);
}
}
if (causes != null) {
throw new UmbrellaException(causes);
}
} }
|
public class class_name {
protected void fail(final Receiver<Void> receiver, final ServerFailure failure) {
this.reuse();
failure.setRequestContext(this);
Set<Throwable> causes = null;
for (final AbstractRequest<?, ?> request : new ArrayList<>(this.state.invocations)) {
try {
request.onFail(failure); // depends on control dependency: [try], data = [none]
} catch (final Throwable t) {
if (causes == null) {
causes = new HashSet<>(); // depends on control dependency: [if], data = [none]
}
causes.add(t);
} // depends on control dependency: [catch], data = [none]
}
if (receiver != null) {
try {
receiver.onFailure(failure); // depends on control dependency: [try], data = [none]
} catch (final Throwable t) {
if (causes == null) {
causes = new HashSet<>(); // depends on control dependency: [if], data = [none]
}
causes.add(t);
} // depends on control dependency: [catch], data = [none]
}
if (causes != null) {
throw new UmbrellaException(causes);
}
} }
|
public class class_name {
public void tag(Table table)
{
int size = table.size();
if (size == 0) return;
int tagSize = id2tag.length;
double[][] net = new double[size][tagSize];
for (int i = 0; i < size; ++i)
{
LinkedList<double[]> scoreList = computeScoreList(table, i);
for (int tag = 0; tag < tagSize; ++tag)
{
net[i][tag] = computeScore(scoreList, tag);
}
}
if (size == 1)
{
double maxScore = -1e10;
int bestTag = 0;
for (int tag = 0; tag < net[0].length; ++tag)
{
if (net[0][tag] > maxScore)
{
maxScore = net[0][tag];
bestTag = tag;
}
}
table.setLast(0, id2tag[bestTag]);
return;
}
int[][] from = new int[size][tagSize];
double[][] maxScoreAt = new double[2][tagSize]; // 滚动数组
System.arraycopy(net[0], 0, maxScoreAt[0], 0, tagSize); // 初始preI=0, maxScoreAt[preI][pre] = net[0][pre]
int curI = 0;
for (int i = 1; i < size; ++i)
{
curI = i & 1;
int preI = 1 - curI;
for (int now = 0; now < tagSize; ++now)
{
double maxScore = -1e10;
for (int pre = 0; pre < tagSize; ++pre)
{
double score = maxScoreAt[preI][pre] + matrix[pre][now] + net[i][now];
if (score > maxScore)
{
maxScore = score;
from[i][now] = pre;
maxScoreAt[curI][now] = maxScore;
}
}
net[i][now] = maxScore;
}
}
// 反向回溯最佳路径
double maxScore = -1e10;
int maxTag = 0;
for (int tag = 0; tag < tagSize; ++tag)
{
if (maxScoreAt[curI][tag] > maxScore)
{
maxScore = maxScoreAt[curI][tag];
maxTag = tag;
}
}
table.setLast(size - 1, id2tag[maxTag]);
maxTag = from[size - 1][maxTag];
for (int i = size - 2; i > 0; --i)
{
table.setLast(i, id2tag[maxTag]);
maxTag = from[i][maxTag];
}
table.setLast(0, id2tag[maxTag]);
} }
|
public class class_name {
public void tag(Table table)
{
int size = table.size();
if (size == 0) return;
int tagSize = id2tag.length;
double[][] net = new double[size][tagSize];
for (int i = 0; i < size; ++i)
{
LinkedList<double[]> scoreList = computeScoreList(table, i);
for (int tag = 0; tag < tagSize; ++tag)
{
net[i][tag] = computeScore(scoreList, tag); // depends on control dependency: [for], data = [tag]
}
}
if (size == 1)
{
double maxScore = -1e10;
int bestTag = 0;
for (int tag = 0; tag < net[0].length; ++tag)
{
if (net[0][tag] > maxScore)
{
maxScore = net[0][tag]; // depends on control dependency: [if], data = [none]
bestTag = tag; // depends on control dependency: [if], data = [none]
}
}
table.setLast(0, id2tag[bestTag]); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
int[][] from = new int[size][tagSize];
double[][] maxScoreAt = new double[2][tagSize]; // 滚动数组
System.arraycopy(net[0], 0, maxScoreAt[0], 0, tagSize); // 初始preI=0, maxScoreAt[preI][pre] = net[0][pre]
int curI = 0;
for (int i = 1; i < size; ++i)
{
curI = i & 1; // depends on control dependency: [for], data = [i]
int preI = 1 - curI;
for (int now = 0; now < tagSize; ++now)
{
double maxScore = -1e10;
for (int pre = 0; pre < tagSize; ++pre)
{
double score = maxScoreAt[preI][pre] + matrix[pre][now] + net[i][now];
if (score > maxScore)
{
maxScore = score; // depends on control dependency: [if], data = [none]
from[i][now] = pre; // depends on control dependency: [if], data = [none]
maxScoreAt[curI][now] = maxScore; // depends on control dependency: [if], data = [none]
}
}
net[i][now] = maxScore; // depends on control dependency: [for], data = [now]
}
}
// 反向回溯最佳路径
double maxScore = -1e10;
int maxTag = 0;
for (int tag = 0; tag < tagSize; ++tag)
{
if (maxScoreAt[curI][tag] > maxScore)
{
maxScore = maxScoreAt[curI][tag]; // depends on control dependency: [if], data = [none]
maxTag = tag; // depends on control dependency: [if], data = [none]
}
}
table.setLast(size - 1, id2tag[maxTag]);
maxTag = from[size - 1][maxTag];
for (int i = size - 2; i > 0; --i)
{
table.setLast(i, id2tag[maxTag]); // depends on control dependency: [for], data = [i]
maxTag = from[i][maxTag]; // depends on control dependency: [for], data = [i]
}
table.setLast(0, id2tag[maxTag]);
} }
|
public class class_name {
private Object[] getObjectIdsImpl(Context cx, Object object) {
if (!(object instanceof Scriptable) || object == Undefined.instance) {
return Context.emptyArgs;
}
Object[] ids;
Scriptable scriptable = (Scriptable)object;
if (scriptable instanceof DebuggableObject) {
ids = ((DebuggableObject)scriptable).getAllIds();
} else {
ids = scriptable.getIds();
}
Scriptable proto = scriptable.getPrototype();
Scriptable parent = scriptable.getParentScope();
int extra = 0;
if (proto != null) {
++extra;
}
if (parent != null) {
++extra;
}
if (extra != 0) {
Object[] tmp = new Object[extra + ids.length];
System.arraycopy(ids, 0, tmp, extra, ids.length);
ids = tmp;
extra = 0;
if (proto != null) {
ids[extra++] = "__proto__";
}
if (parent != null) {
ids[extra++] = "__parent__";
}
}
return ids;
} }
|
public class class_name {
private Object[] getObjectIdsImpl(Context cx, Object object) {
if (!(object instanceof Scriptable) || object == Undefined.instance) {
return Context.emptyArgs; // depends on control dependency: [if], data = [none]
}
Object[] ids;
Scriptable scriptable = (Scriptable)object;
if (scriptable instanceof DebuggableObject) {
ids = ((DebuggableObject)scriptable).getAllIds(); // depends on control dependency: [if], data = [none]
} else {
ids = scriptable.getIds(); // depends on control dependency: [if], data = [none]
}
Scriptable proto = scriptable.getPrototype();
Scriptable parent = scriptable.getParentScope();
int extra = 0;
if (proto != null) {
++extra; // depends on control dependency: [if], data = [none]
}
if (parent != null) {
++extra; // depends on control dependency: [if], data = [none]
}
if (extra != 0) {
Object[] tmp = new Object[extra + ids.length];
System.arraycopy(ids, 0, tmp, extra, ids.length); // depends on control dependency: [if], data = [none]
ids = tmp; // depends on control dependency: [if], data = [none]
extra = 0; // depends on control dependency: [if], data = [none]
if (proto != null) {
ids[extra++] = "__proto__"; // depends on control dependency: [if], data = [none]
}
if (parent != null) {
ids[extra++] = "__parent__"; // depends on control dependency: [if], data = [none]
}
}
return ids;
} }
|
public class class_name {
private GeneralValidator<DPO, RI, RO, RHI> build() {
// Create validator
GeneralValidator<DPO, RI, RO, RHI> validator = new GeneralValidator<DPO, RI, RO, RHI>();
// Add triggers
for (Trigger trigger : addedTriggers) {
validator.addTrigger(trigger);
}
// Add data providers
for (DataProvider<DPO> dataProvider : addedDataProviders) {
validator.addDataProvider(dataProvider);
}
// Map data providers output to rules input
validator.setDataProviderToRuleMappingStrategy(dataProviderToRuleMapping);
validator.setRuleInputTransformers(addedRuleInputTransformers);
// Add rules
for (Rule<RI, RO> rule : addedRules) {
validator.addRule(rule);
}
// Map rules output to result handlers input
validator.setRuleToResultHandlerMappingStrategy(ruleToResultHandlerMapping);
validator.setResultHandlerInputTransformers(addedResultHandlerInputTransformers);
// Add result handlers
for (ResultHandler<RHI> resultHandler : addedResultHandlers) {
validator.addResultHandler(resultHandler);
}
return validator;
} }
|
public class class_name {
private GeneralValidator<DPO, RI, RO, RHI> build() {
// Create validator
GeneralValidator<DPO, RI, RO, RHI> validator = new GeneralValidator<DPO, RI, RO, RHI>();
// Add triggers
for (Trigger trigger : addedTriggers) {
validator.addTrigger(trigger); // depends on control dependency: [for], data = [trigger]
}
// Add data providers
for (DataProvider<DPO> dataProvider : addedDataProviders) {
validator.addDataProvider(dataProvider); // depends on control dependency: [for], data = [dataProvider]
}
// Map data providers output to rules input
validator.setDataProviderToRuleMappingStrategy(dataProviderToRuleMapping);
validator.setRuleInputTransformers(addedRuleInputTransformers);
// Add rules
for (Rule<RI, RO> rule : addedRules) {
validator.addRule(rule); // depends on control dependency: [for], data = [rule]
}
// Map rules output to result handlers input
validator.setRuleToResultHandlerMappingStrategy(ruleToResultHandlerMapping);
validator.setResultHandlerInputTransformers(addedResultHandlerInputTransformers);
// Add result handlers
for (ResultHandler<RHI> resultHandler : addedResultHandlers) {
validator.addResultHandler(resultHandler); // depends on control dependency: [for], data = [resultHandler]
}
return validator;
} }
|
public class class_name {
public final List<PhoneNumberData> getSuggstions(final String psearch, final int plimit,
final Locale plocale) {
final List<PhoneNumberData> suggestList = new ArrayList<>(plimit);
final String cleanedPhoneNumber = cleanString(psearch);
PhoneCountryCodeData foundCounty = null;
final List<PhoneCountryCodeData> possibleCountries = new ArrayList<>(plimit);
for (final PhoneCountryCodeData countryCode : CreatePhoneCountryConstantsClass.create(plocale)
.countryCodeData()) {
if (cleanedPhoneNumber.startsWith(countryCode.getCountryCode())) {
foundCounty = countryCode;
break;
}
if (countryCode.getCountryCode().startsWith(cleanedPhoneNumber)) {
possibleCountries.add(countryCode);
}
}
if (foundCounty == null) {
// we don't have found a matching country, show possible countries
for (final PhoneCountryCodeData country : possibleCountries) {
final PhoneNumberData entry = new PhoneNumberData();
entry.setCountryCode(country.getCountryCode());
entry.setCountryName(country.getCountryCodeName());
suggestList.add(entry);
}
} else {
// we do have a country, search for possible area codes
final String phoneNumberWork =
StringUtils.substring(cleanedPhoneNumber, foundCounty.getCountryCode().length());
for (final PhoneAreaCodeData areaCode : foundCounty.getAreaCodeData()) {
if (!areaCode.isRegEx() && areaCode.getAreaCode().startsWith(phoneNumberWork)) {
final PhoneNumberData entry = new PhoneNumberData();
entry.setCountryCode(foundCounty.getCountryCode());
entry.setCountryName(foundCounty.getCountryCodeName());
entry.setAreaCode(areaCode.getAreaCode());
entry.setAreaName(areaCode.getAreaName());
suggestList.add(entry);
}
}
}
Collections.sort(suggestList, new PhoneNumberSuggestComperator());
if (suggestList.size() >= plimit) {
return suggestList.subList(0, plimit);
}
return suggestList;
} }
|
public class class_name {
public final List<PhoneNumberData> getSuggstions(final String psearch, final int plimit,
final Locale plocale) {
final List<PhoneNumberData> suggestList = new ArrayList<>(plimit);
final String cleanedPhoneNumber = cleanString(psearch);
PhoneCountryCodeData foundCounty = null;
final List<PhoneCountryCodeData> possibleCountries = new ArrayList<>(plimit);
for (final PhoneCountryCodeData countryCode : CreatePhoneCountryConstantsClass.create(plocale)
.countryCodeData()) {
if (cleanedPhoneNumber.startsWith(countryCode.getCountryCode())) {
foundCounty = countryCode; // depends on control dependency: [if], data = [none]
break;
}
if (countryCode.getCountryCode().startsWith(cleanedPhoneNumber)) {
possibleCountries.add(countryCode); // depends on control dependency: [if], data = [none]
}
}
if (foundCounty == null) {
// we don't have found a matching country, show possible countries
for (final PhoneCountryCodeData country : possibleCountries) {
final PhoneNumberData entry = new PhoneNumberData();
entry.setCountryCode(country.getCountryCode()); // depends on control dependency: [for], data = [country]
entry.setCountryName(country.getCountryCodeName()); // depends on control dependency: [for], data = [country]
suggestList.add(entry); // depends on control dependency: [for], data = [none]
}
} else {
// we do have a country, search for possible area codes
final String phoneNumberWork =
StringUtils.substring(cleanedPhoneNumber, foundCounty.getCountryCode().length());
for (final PhoneAreaCodeData areaCode : foundCounty.getAreaCodeData()) {
if (!areaCode.isRegEx() && areaCode.getAreaCode().startsWith(phoneNumberWork)) {
final PhoneNumberData entry = new PhoneNumberData();
entry.setCountryCode(foundCounty.getCountryCode()); // depends on control dependency: [if], data = [none]
entry.setCountryName(foundCounty.getCountryCodeName()); // depends on control dependency: [if], data = [none]
entry.setAreaCode(areaCode.getAreaCode()); // depends on control dependency: [if], data = [none]
entry.setAreaName(areaCode.getAreaName()); // depends on control dependency: [if], data = [none]
suggestList.add(entry); // depends on control dependency: [if], data = [none]
}
}
}
Collections.sort(suggestList, new PhoneNumberSuggestComperator());
if (suggestList.size() >= plimit) {
return suggestList.subList(0, plimit); // depends on control dependency: [if], data = [none]
}
return suggestList;
} }
|
public class class_name {
static <T extends Annotation> Class<?> getTypeOfConstraintValidator(
final Class<? extends ConstraintValidator<T, ?>> constraintClass) {
int candidateCount = 0;
Class<?> result = null;
for (final Method method : constraintClass.getMethods()) {
if (method.getName().equals("isValid") && method.getParameterTypes().length == 2
&& method.getReturnType().isAssignableFrom(Boolean.TYPE)) {
final Class<?> firstArgType = method.getParameterTypes()[0];
if (result == null || result.isAssignableFrom(firstArgType)) {
result = firstArgType;
}
candidateCount++;
}
}
if (candidateCount == 0) {
throw new IllegalStateException("ConstraintValidators must have a isValid method");
} else if (candidateCount > 2) {
throw new IllegalStateException(
"ConstraintValidators must have no more than two isValid methods");
}
return result;
} }
|
public class class_name {
static <T extends Annotation> Class<?> getTypeOfConstraintValidator(
final Class<? extends ConstraintValidator<T, ?>> constraintClass) {
int candidateCount = 0;
Class<?> result = null;
for (final Method method : constraintClass.getMethods()) {
if (method.getName().equals("isValid") && method.getParameterTypes().length == 2
&& method.getReturnType().isAssignableFrom(Boolean.TYPE)) {
final Class<?> firstArgType = method.getParameterTypes()[0];
if (result == null || result.isAssignableFrom(firstArgType)) {
result = firstArgType; // depends on control dependency: [if], data = [none]
}
candidateCount++;
}
}
if (candidateCount == 0) {
throw new IllegalStateException("ConstraintValidators must have a isValid method");
} else if (candidateCount > 2) {
throw new IllegalStateException(
"ConstraintValidators must have no more than two isValid methods");
}
return result;
} }
|
public class class_name {
public void contextInitialized(ServletContextEvent sce) {
LogLog.debug("Start to initialize log4j");
LogLog.debug("Confige CXF to use log4j!");
ServletContext sc = sce.getServletContext();
if (Log4jWebUtils.isWatchDisabled(sc)) {
Log4jWebUtils.reload(sc);
} else {
Log4jWebUtils.reloadAndWatch(sc, Log4jWebUtils.getWatchDelay(sc));
}
logger.info("Log4j initialized...");
} }
|
public class class_name {
public void contextInitialized(ServletContextEvent sce) {
LogLog.debug("Start to initialize log4j");
LogLog.debug("Confige CXF to use log4j!");
ServletContext sc = sce.getServletContext();
if (Log4jWebUtils.isWatchDisabled(sc)) {
Log4jWebUtils.reload(sc); // depends on control dependency: [if], data = [none]
} else {
Log4jWebUtils.reloadAndWatch(sc, Log4jWebUtils.getWatchDelay(sc)); // depends on control dependency: [if], data = [none]
}
logger.info("Log4j initialized...");
} }
|
public class class_name {
public ResponseBuilder updateResource(final Resource res) {
final String baseUrl = getBaseUrl();
final String identifier = baseUrl + req.getPartition() + req.getPath() +
(ACL.equals(req.getExt()) ? "?ext=acl" : "");
if (isNull(sparqlUpdate)) {
throw new WebApplicationException("Missing Sparql-Update body", BAD_REQUEST);
}
final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);
// Check if this is already deleted
checkDeleted(res, identifier);
// Check the cache
final EntityTag etag = new EntityTag(md5Hex(res.getModified() + identifier));
checkCache(req.getRequest(), res.getModified(), etag);
LOGGER.debug("Updating {} via PATCH", identifier);
final IRI graphName = ACL.equals(req.getExt()) ? PreferAccessControl : PreferUserManaged;
final IRI otherGraph = ACL.equals(req.getExt()) ? PreferUserManaged : PreferAccessControl;
// Put triples in buffer
final List<Triple> triples = updateGraph(res, graphName);
try (final TrellisDataset dataset = TrellisDataset.createDataset()) {
triples.stream().map(skolemizeTriples(resourceService, baseUrl))
.map(t -> rdf.createQuad(graphName, t.getSubject(), t.getPredicate(), t.getObject()))
.forEachOrdered(dataset::add);
// Add audit-related triples
audit.ifPresent(svc -> svc.update(res.getIdentifier(), session).stream()
.map(skolemizeQuads(resourceService, baseUrl)).forEachOrdered(dataset::add));
// Add existing LDP type
dataset.add(rdf.createQuad(PreferServerManaged, res.getIdentifier(), RDF.type, res.getInteractionModel()));
// Check any constraints
final List<ConstraintViolation> violations = constraintServices.stream()
.flatMap(svc -> dataset.getGraph(graphName).map(Stream::of).orElseGet(Stream::empty)
.flatMap(g -> svc.constrainedBy(res.getInteractionModel(), baseUrl, g)))
.collect(toList());
if (!violations.isEmpty()) {
final ResponseBuilder err = status(CONFLICT);
violations.forEach(v -> err.link(v.getConstraint().getIRIString(), LDP.constrainedBy.getIRIString()));
throw new WebApplicationException(err.build());
}
// When updating User or ACL triples, be sure to add the other category to the dataset
try (final Stream<? extends Triple> remaining = res.stream(otherGraph)) {
remaining.map(t -> rdf.createQuad(otherGraph, t.getSubject(), t.getPredicate(), t.getObject()))
.forEachOrdered(dataset::add);
}
// Save new dataset
if (resourceService.put(res.getIdentifier(), dataset.asDataset())) {
final ResponseBuilder builder = ok();
ldpResourceTypes(res.getInteractionModel()).map(IRI::getIRIString)
.forEach(type -> builder.link(type, "type"));
return ofNullable(req.getPrefer()).flatMap(Prefer::getPreference).filter(PREFER_REPRESENTATION::equals)
.map(prefer -> {
final RDFSyntax syntax = getSyntax(req.getHeaders().getAcceptableMediaTypes(), empty())
.orElseThrow(NotAcceptableException::new);
final IRI profile = ofNullable(getProfile(req.getHeaders().getAcceptableMediaTypes(), syntax))
.orElseGet(() -> getDefaultProfile(syntax, identifier));
final StreamingOutput stream = new StreamingOutput() {
@Override
public void write(final OutputStream out) throws IOException {
ioService.write(triples.stream().map(unskolemizeTriples(resourceService, baseUrl)),
out, syntax, profile);
}
};
return builder.header(PREFERENCE_APPLIED, "return=representation").type(syntax.mediaType)
.entity(stream);
}).orElseGet(() -> builder.status(NO_CONTENT));
}
}
LOGGER.error("Unable to persist data to location at {}", res.getIdentifier());
return serverError().type(TEXT_PLAIN)
.entity("Unable to persist data. Please consult the logs for more information");
} }
|
public class class_name {
public ResponseBuilder updateResource(final Resource res) {
final String baseUrl = getBaseUrl();
final String identifier = baseUrl + req.getPartition() + req.getPath() +
(ACL.equals(req.getExt()) ? "?ext=acl" : "");
if (isNull(sparqlUpdate)) {
throw new WebApplicationException("Missing Sparql-Update body", BAD_REQUEST);
}
final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);
// Check if this is already deleted
checkDeleted(res, identifier);
// Check the cache
final EntityTag etag = new EntityTag(md5Hex(res.getModified() + identifier));
checkCache(req.getRequest(), res.getModified(), etag);
LOGGER.debug("Updating {} via PATCH", identifier);
final IRI graphName = ACL.equals(req.getExt()) ? PreferAccessControl : PreferUserManaged;
final IRI otherGraph = ACL.equals(req.getExt()) ? PreferUserManaged : PreferAccessControl;
// Put triples in buffer
final List<Triple> triples = updateGraph(res, graphName);
try (final TrellisDataset dataset = TrellisDataset.createDataset()) {
triples.stream().map(skolemizeTriples(resourceService, baseUrl))
.map(t -> rdf.createQuad(graphName, t.getSubject(), t.getPredicate(), t.getObject()))
.forEachOrdered(dataset::add);
// Add audit-related triples
audit.ifPresent(svc -> svc.update(res.getIdentifier(), session).stream()
.map(skolemizeQuads(resourceService, baseUrl)).forEachOrdered(dataset::add));
// Add existing LDP type
dataset.add(rdf.createQuad(PreferServerManaged, res.getIdentifier(), RDF.type, res.getInteractionModel()));
// Check any constraints
final List<ConstraintViolation> violations = constraintServices.stream()
.flatMap(svc -> dataset.getGraph(graphName).map(Stream::of).orElseGet(Stream::empty)
.flatMap(g -> svc.constrainedBy(res.getInteractionModel(), baseUrl, g)))
.collect(toList());
if (!violations.isEmpty()) {
final ResponseBuilder err = status(CONFLICT);
violations.forEach(v -> err.link(v.getConstraint().getIRIString(), LDP.constrainedBy.getIRIString())); // depends on control dependency: [if], data = [none]
throw new WebApplicationException(err.build());
}
// When updating User or ACL triples, be sure to add the other category to the dataset
try (final Stream<? extends Triple> remaining = res.stream(otherGraph)) {
remaining.map(t -> rdf.createQuad(otherGraph, t.getSubject(), t.getPredicate(), t.getObject()))
.forEachOrdered(dataset::add);
}
// Save new dataset
if (resourceService.put(res.getIdentifier(), dataset.asDataset())) {
final ResponseBuilder builder = ok();
ldpResourceTypes(res.getInteractionModel()).map(IRI::getIRIString)
.forEach(type -> builder.link(type, "type"));
return ofNullable(req.getPrefer()).flatMap(Prefer::getPreference).filter(PREFER_REPRESENTATION::equals)
.map(prefer -> {
final RDFSyntax syntax = getSyntax(req.getHeaders().getAcceptableMediaTypes(), empty())
.orElseThrow(NotAcceptableException::new);
final IRI profile = ofNullable(getProfile(req.getHeaders().getAcceptableMediaTypes(), syntax))
.orElseGet(() -> getDefaultProfile(syntax, identifier));
final StreamingOutput stream = new StreamingOutput() {
@Override
public void write(final OutputStream out) throws IOException {
ioService.write(triples.stream().map(unskolemizeTriples(resourceService, baseUrl)),
out, syntax, profile);
}
};
return builder.header(PREFERENCE_APPLIED, "return=representation").type(syntax.mediaType)
.entity(stream);
}).orElseGet(() -> builder.status(NO_CONTENT));
}
}
LOGGER.error("Unable to persist data to location at {}", res.getIdentifier());
return serverError().type(TEXT_PLAIN)
.entity("Unable to persist data. Please consult the logs for more information");
} }
|
public class class_name {
@Override
public EClass getIfcProductDefinitionShape() {
if (ifcProductDefinitionShapeEClass == null) {
ifcProductDefinitionShapeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(455);
}
return ifcProductDefinitionShapeEClass;
} }
|
public class class_name {
@Override
public EClass getIfcProductDefinitionShape() {
if (ifcProductDefinitionShapeEClass == null) {
ifcProductDefinitionShapeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(455);
// depends on control dependency: [if], data = [none]
}
return ifcProductDefinitionShapeEClass;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> char[] getFirstCharArray(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CharArrayArgument) {
return ((CharArrayArgument) singularArgument).val;
}
}
return null;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <K, V> char[] getFirstCharArray(CommandArgs<K, V> commandArgs) {
for (SingularArgument singularArgument : commandArgs.singularArguments) {
if (singularArgument instanceof CharArrayArgument) {
return ((CharArrayArgument) singularArgument).val; // depends on control dependency: [if], data = [none]
}
}
return null;
} }
|
public class class_name {
public byte[] getSecret (PrivateKey key)
{
if (_secret == null) {
_secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt);
}
return _secret;
} }
|
public class class_name {
public byte[] getSecret (PrivateKey key)
{
if (_secret == null) {
_secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt); // depends on control dependency: [if], data = [none]
}
return _secret;
} }
|
public class class_name {
public void hide() {
div.removeFromParent();
if (scrollDisabled) {
RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO);
}
if (type == LoaderType.CIRCULAR) {
preLoader.removeFromParent();
} else if (type == LoaderType.PROGRESS) {
progress.removeFromParent();
}
} }
|
public class class_name {
public void hide() {
div.removeFromParent();
if (scrollDisabled) {
RootPanel.get().getElement().getStyle().setOverflow(Style.Overflow.AUTO); // depends on control dependency: [if], data = [none]
}
if (type == LoaderType.CIRCULAR) {
preLoader.removeFromParent(); // depends on control dependency: [if], data = [none]
} else if (type == LoaderType.PROGRESS) {
progress.removeFromParent(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static <T> T[] reverse(T[] array)
{
if(array == null)
return array;
int s = 0;
int e = array.length - 1;
while(s < e)
{
// swap index e and s
T tmp = array[e];
array[e] = array[s];
array[s] = tmp;
s++;
e--;
}
return array;
} }
|
public class class_name {
public static <T> T[] reverse(T[] array)
{
if(array == null)
return array;
int s = 0;
int e = array.length - 1;
while(s < e)
{
// swap index e and s
T tmp = array[e];
array[e] = array[s]; // depends on control dependency: [while], data = [none]
array[s] = tmp; // depends on control dependency: [while], data = [none]
s++; // depends on control dependency: [while], data = [none]
e--; // depends on control dependency: [while], data = [none]
}
return array;
} }
|
public class class_name {
public void run() {
setRunning(true);
try {
addInfo("listening on " + listener);
while (!Thread.currentThread().isInterrupted()) {
T client = listener.acceptClient();
if (!configureClient(client)) {
addError(client + ": connection dropped");
client.close();
continue;
}
try {
executor.execute(new ClientWrapper(client));
}
catch (RejectedExecutionException ex) {
addError(client + ": connection dropped");
client.close();
}
}
}
catch (InterruptedException ex) {
assert true; // ok... we'll shut down
}
catch (Exception ex) {
addError("listener: " + ex);
}
setRunning(false);
addInfo("shutting down");
listener.close();
} }
|
public class class_name {
public void run() {
setRunning(true);
try {
addInfo("listening on " + listener); // depends on control dependency: [try], data = [none]
while (!Thread.currentThread().isInterrupted()) {
T client = listener.acceptClient();
if (!configureClient(client)) {
addError(client + ": connection dropped"); // depends on control dependency: [if], data = [none]
client.close(); // depends on control dependency: [if], data = [none]
continue;
}
try {
executor.execute(new ClientWrapper(client)); // depends on control dependency: [try], data = [none]
}
catch (RejectedExecutionException ex) {
addError(client + ": connection dropped");
client.close();
} // depends on control dependency: [catch], data = [none]
}
}
catch (InterruptedException ex) {
assert true; // ok... we'll shut down
} // depends on control dependency: [catch], data = [none]
catch (Exception ex) {
addError("listener: " + ex);
} // depends on control dependency: [catch], data = [none]
setRunning(false);
addInfo("shutting down");
listener.close();
} }
|
public class class_name {
public static StorageDirView getDirWithMaxFreeSpace(long bytesToBeAvailable,
BlockStoreLocation location, BlockMetadataManagerView mManagerView) {
long maxFreeSize = -1;
StorageDirView selectedDirView = null;
if (location.equals(BlockStoreLocation.anyTier())) {
for (StorageTierView tierView : mManagerView.getTierViews()) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView;
maxFreeSize = dirView.getAvailableBytes();
}
}
}
} else {
String tierAlias = location.tierAlias();
StorageTierView tierView = mManagerView.getTierView(tierAlias);
if (location.equals(BlockStoreLocation.anyDirInTier(tierAlias))) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView;
maxFreeSize = dirView.getAvailableBytes();
}
}
} else {
int dirIndex = location.dir();
StorageDirView dirView = tierView.getDirView(dirIndex);
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView;
}
}
}
return selectedDirView;
} }
|
public class class_name {
public static StorageDirView getDirWithMaxFreeSpace(long bytesToBeAvailable,
BlockStoreLocation location, BlockMetadataManagerView mManagerView) {
long maxFreeSize = -1;
StorageDirView selectedDirView = null;
if (location.equals(BlockStoreLocation.anyTier())) {
for (StorageTierView tierView : mManagerView.getTierViews()) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView; // depends on control dependency: [if], data = [none]
maxFreeSize = dirView.getAvailableBytes(); // depends on control dependency: [if], data = [none]
}
}
}
} else {
String tierAlias = location.tierAlias();
StorageTierView tierView = mManagerView.getTierView(tierAlias);
if (location.equals(BlockStoreLocation.anyDirInTier(tierAlias))) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView; // depends on control dependency: [if], data = [none]
maxFreeSize = dirView.getAvailableBytes(); // depends on control dependency: [if], data = [none]
}
}
} else {
int dirIndex = location.dir();
StorageDirView dirView = tierView.getDirView(dirIndex);
if (dirView.getCommittedBytes() + dirView.getAvailableBytes() >= bytesToBeAvailable
&& dirView.getAvailableBytes() > maxFreeSize) {
selectedDirView = dirView; // depends on control dependency: [if], data = [none]
}
}
}
return selectedDirView;
} }
|
public class class_name {
private int compareIntervals(Interval<K> i1, Interval<K> i2) {
int res1 = compare(i1.up, i2.low);
if (res1 < 0 || res1 <= 0 && (!i1.includeUpper || !i2.includeLower)) {
return -1;
}
int res2 = compare(i2.up, i1.low);
if (res2 < 0 || res2 <= 0 && (!i2.includeUpper || !i1.includeLower)) {
return 1;
}
return 0;
} }
|
public class class_name {
private int compareIntervals(Interval<K> i1, Interval<K> i2) {
int res1 = compare(i1.up, i2.low);
if (res1 < 0 || res1 <= 0 && (!i1.includeUpper || !i2.includeLower)) {
return -1; // depends on control dependency: [if], data = [none]
}
int res2 = compare(i2.up, i1.low);
if (res2 < 0 || res2 <= 0 && (!i2.includeUpper || !i1.includeLower)) {
return 1; // depends on control dependency: [if], data = [none]
}
return 0;
} }
|
public class class_name {
protected void propagateOnTouch(GVRPickedObject hit)
{
if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))
{
GVREventManager eventManager = getGVRContext().getEventManager();
GVRSceneObject hitObject = hit.getHitObject();
if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))
{
eventManager.sendEvent(this, ITouchEvents.class, "onTouchStart", hitObject, hit);
}
if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))
{
eventManager.sendEvent(hitObject, ITouchEvents.class, "onTouchStart", hitObject, hit);
}
if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))
{
eventManager.sendEvent(mScene, ITouchEvents.class, "onTouchStart", hitObject, hit);
}
}
} }
|
public class class_name {
protected void propagateOnTouch(GVRPickedObject hit)
{
if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))
{
GVREventManager eventManager = getGVRContext().getEventManager();
GVRSceneObject hitObject = hit.getHitObject();
if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))
{
eventManager.sendEvent(this, ITouchEvents.class, "onTouchStart", hitObject, hit); // depends on control dependency: [if], data = [none]
}
if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))
{
eventManager.sendEvent(hitObject, ITouchEvents.class, "onTouchStart", hitObject, hit); // depends on control dependency: [if], data = [none]
}
if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))
{
eventManager.sendEvent(mScene, ITouchEvents.class, "onTouchStart", hitObject, hit); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private UndeliverableReturnCode handleUndeliverableMessage(
SIMPMessage message,
String alternateUser,
TransactionCommon tran,
int exceptionReason,
String[] exceptionStrings,
SIBUuid8 sourceMEUuid,
String subscriptionID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "handleUndeliverableMessage",
new Object[] { message,
alternateUser,
tran,
Integer.valueOf(exceptionReason),
exceptionStrings,
sourceMEUuid,
subscriptionID });
boolean sendComplete = false;
boolean defaultInUse = false; // Assume non-default exception destination is being used.
UndeliverableReturnCode rc = UndeliverableReturnCode.OK;
LocalTransaction localTran = null;
rc = checkMessage(message);
if (rc == UndeliverableReturnCode.BLOCK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc);
return rc;
}
// Unless we're told to discard this message, try to send it to an exception destination
if (rc != UndeliverableReturnCode.DISCARD)
{
JsMessage msg = null;
try {
msg = message.getMessage().getReceived();
} catch (MessageCopyFailedException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:568:1.137",
this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
// F001333-14610
// Pass the subscription ID to be set on the message properties.
msg = setMessageProperties(msg, exceptionReason, exceptionStrings, subscriptionID);
/*
* If Destination is not null, get the exception destination.
* If it is null - this indicates the default exception destination was required
* so use this instead.
*/
String newExceptionDestination = null;
if (_originalDestination != null)
{
newExceptionDestination = _originalDestination.getExceptionDestination();
if (newExceptionDestination == null || newExceptionDestination.equals(""))
{
if (_originalDestination.isToBeDeleted()) {
newExceptionDestination = _defaultExceptionDestinationName;
defaultInUse = true;
}
else
{
// In the past, this could only arise if we were forcing the put after the message
// had arrived across a link but the destination was full. i.e. BLOCK was returned but
// forcePut was true so that ordering was broken (but thats what happens with links).
// This situation is now handled elsewhere in the code (see defect 4644630 so wE'll return an error
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
}
if (newExceptionDestination.equals(JsConstants.DEFAULT_EXCEPTION_DESTINATION))
{
newExceptionDestination = _defaultExceptionDestinationName;
defaultInUse = true;
}
}
else
{
newExceptionDestination = _defaultExceptionDestinationName;
defaultInUse = true;
}
/*
* Entering synch block.
* We MUST put the ExceptionDestination instance on a destination. Ideally
* we would have an instance per consumer point (since there will be a
* producerSession instance per consumerpoint). We cannot do this because we
* cannot get references to the consumerpoints at the time we need to use the
* ExceptionDestination.
*
* Rather than perform a destination lookup every time we call
* this method, we synchronize on one instance. If a different dest is needed
* then we do a lookup within the synchronized block. This
* introduces an optimisation for consecutive sends to the same exception
* destination.
*/
synchronized (_exceptionDestinationLock)
{
/*
* If inputhandler ref has not been created yet, or exception destination has changed
* since the last call of this method, then get the inputhandler associated
* with the given exception destination
*
* This inputhandler will be used to send messages to the exception destination
*/
if (_inputHandler == null || !newExceptionDestination.equals(_exceptionDestinationName))
{
_exceptionDestinationName = newExceptionDestination;
/*
* Try to get an inputhandler to the exception destination specified in the
* destination's definition. If this fails, (e.g. if the exception destination
* does not exist) then attempt to get one to the default (which should ALWAYS
* succeed). If this fails then report a fatal error.
*/
//Get the named destination from the destination manager
try
{
_exceptionDestination =
_messageProcessor.getDestinationManager().
getDestination(_exceptionDestinationName, true);
// Check whether bus security is enabled
if (_messageProcessor.isBusSecure())
{
// Check authority to access exc destination
AccessResult result = checkExceptionDestinationAccess(msg,
null,
alternateUser,
defaultInUse);
// Handle access denied
if (!result.isAllowed())
{
// Report and audit the event
handleAccessDenied(result, msg, alternateUser);
// Return with "BLOCK". This is the same behaviour as things like
// q full, etc. It means, for example, that messages will be backed
// up on transmission queues if they cannot be delivered to either
// target or exception destination.
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK;
}
}
// Set the priority in the message based on the exception destinations default
msg.setPriority(_exceptionDestination.getDefaultPriority());
// Get the inputhandler associated with it
_inputHandler = _exceptionDestination.getInputHandler(_exceptionDestination.isPubSub() ? ProtocolType.PUBSUBINPUT : ProtocolType.UNICASTINPUT,
_messageProcessor.getMessagingEngineUuid(),
null);
} catch (SIException e)
{
// No FFDC code needed
SibTr.exception(tc, e);
/*
* If it was the default exception destination we failed to reference, then exit.
* Otherwise retry with the default
*/
if (defaultInUse)
{
/*
* ERROR : SYSTEM.DEFAULT.EXCEPTION.DESTINATION.<MENAME> queue did
* not exist on the ME. This should ALWAYS exist.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:710:1.137",
this);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:716:1.137",
e,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
/* Generate warning but retry with default exception destination */
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e });
/* Get the default and retry */
_exceptionDestinationName = _defaultExceptionDestinationName;
/* Retry on the default ex.dest. */
//Get the named destination from the destination manager
try
{
_exceptionDestination =
_messageProcessor.getDestinationManager().
getDestination(_exceptionDestinationName, true);
// Check whether bus security is enabled
if (_messageProcessor.isBusSecure())
{
// Check authority to access to default exc destination
AccessResult result = checkExceptionDestinationAccess(msg,
null,
alternateUser,
true);
// Handle access denied
if (!result.isAllowed())
{
// Report and audit the event
handleAccessDenied(result, msg, alternateUser);
// Return with "BLOCK". This is the same behaviour as things like
// q full, etc. It means, for example, that messages will be backed
// up on transmission queues if they cannot be delivered to either
// target or exception destination.
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK;
}
}
// Set the priority in the message based on the exception destinations default
msg.setPriority(_exceptionDestination.getDefaultPriority());
// Get the inputhandler associated with it
_inputHandler = _exceptionDestination.getInputHandler(_exceptionDestination.isPubSub() ? ProtocolType.PUBSUBINPUT : ProtocolType.UNICASTINPUT,
_messageProcessor.getMessagingEngineUuid(),
null);
defaultInUse = true;
} catch (SIException e2)
{
/*
* ERROR : SYSTEM.DEFAULT.EXCEPTION.DESTINATION.<MENAME> queue did
* not exist on the ME. This should ALWAYS exist.
*/
FFDCFilter.processException(
e2,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:786:1.137",
this);
SibTr.exception(tc, e);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:793:1.137",
e2,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
} // Inputhandler to an exception destination obtained
}
/*
* Send the message using whichever exception destination we have chosen. If it
* is unsuccessful and it is not aimed at the default - then get an inputhandler
* to the default and retry the send. If a send to the default fails (which will
* be on the local ME) then retry every 10 seconds.
*/
sendComplete = false;
while (!sendComplete)
{
// 533027 We need to create a new MessageItem each time round the loop,
// as we could fail at an unexpected point (such as while allocating an
// id to the message), and hence leave the MessageItem in an inconsistent state
// (such as with callbacks still registered).
MessageItem newItem = new MessageItem(msg);
//Set this in the msgItem as we want to generate a new systemUUID if needed
newItem.setRequiresNewId(message.getRequiresNewId());
try
{
newItem.setStoreAtSendTime(message.isToBeStoredAtSendTime());
TransactionCommon transaction = null;
if (tran == null)
{
localTran = _exceptionDestination.getTxManager().createLocalTransaction(false);
transaction = localTran;
}
else
{
transaction = tran;
}
_inputHandler.handleMessage(newItem,
transaction, sourceMEUuid);
JsMessagingEngine me = _messageProcessor.getMessagingEngine();
if (me.isEventNotificationEnabled() ||
UserTrace.tc_mt.isDebugEnabled())
{
String apiMsgId = null;
String correlationId = null;
if (message.getMessage() instanceof JsApiMessage)
{
apiMsgId = ((JsApiMessage) message.getMessage()).getApiMessageId();
correlationId = ((JsApiMessage) message.getMessage()).getCorrelationId();
}
else
{
if (message.getMessage().getApiMessageIdAsBytes() != null)
apiMsgId = new String(message.getMessage().getApiMessageIdAsBytes());
if (message.getMessage().getCorrelationIdAsBytes() != null)
correlationId = new String(message.getMessage().getCorrelationIdAsBytes());
}
if (TraceComponent.isAnyTracingEnabled() && UserTrace.tc_mt.isDebugEnabled())
{
if (message.getMessage().isApiMessage())
SibTr.debug(UserTrace.tc_mt,
nls_mt.getFormattedMessage(
"MESSAGE_EXCEPTION_DESTINATIONED_CWSJU0012",
new Object[] {
apiMsgId,
message.getMessage().getSystemMessageId(),
correlationId,
_exceptionDestinationName,
Integer.valueOf(exceptionReason),
message.getMessage().getExceptionMessage() },
null));
}
if (me.isEventNotificationEnabled())
{
fireMessageExceptionedEvent(apiMsgId,
message,
exceptionReason);
}
}
/* Send was successful so exit while loop and return OK */
sendComplete = true;
} catch (SIException e)
{
// No FFDC code needed
if (!defaultInUse)
{
/* Generate warning but retry with default exception destination */
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e });
UndeliverableReturnCode rc2 = sendToDefaultExceptionDestination(msg);
// If the above worked then carry on, if it failed then return
if (rc2 != UndeliverableReturnCode.OK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc2);
return rc2;
}
else
{
//Everything was ok, set that we are using the default
defaultInUse = true;
}
}
else
{
if (e instanceof SIMPLimitExceededException)
{
// Warning : Default exception destination full
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK;
}
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:938:1.137",
this);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:944:1.137",
e,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
} catch (MessageStoreRuntimeException e)
{
// No FFDC code needed
if (!defaultInUse)
{
UndeliverableReturnCode rc2 = sendToDefaultExceptionDestination(msg);
// If the above worked then carry on, if it failed then return
if (rc2 != UndeliverableReturnCode.OK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc2);
return rc2;
}
else
{
//Everything was ok, set that we are using the default
defaultInUse = true;
}
}
else
{
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:981:1.137",
this);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:986:1.137",
e,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
}
}
} // End of synchronisation
}
// If report messages required - generate and send here
if (message.getMessage().getReportException() != null)
{
// Create the ReportHandler object if not already created
if (_reportHandler == null)
_reportHandler = new ReportHandler(_messageProcessor);
TransactionCommon transaction = null;
if (tran == null)
{
transaction = localTran;
}
else
{
transaction = tran;
}
try
{
_reportHandler.handleMessage(message, transaction, SIApiConstants.REPORT_EXCEPTION);
} catch (Exception e)
{
// ERROR : Cannot send report message
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:1029:1.137",
this);
SibTr.error(tc, "EXCEPTION_DESTINATION_ERROR_CWSIP0295",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName() });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
}
if (localTran != null)
{
try
{
localTran.commit();
} catch (SIException e)
{
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:1056:1.137",
this);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:1061:1.137",
e,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
}
}
// If we got here then everything worked ok
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc);
return rc;
} }
|
public class class_name {
private UndeliverableReturnCode handleUndeliverableMessage(
SIMPMessage message,
String alternateUser,
TransactionCommon tran,
int exceptionReason,
String[] exceptionStrings,
SIBUuid8 sourceMEUuid,
String subscriptionID)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "handleUndeliverableMessage",
new Object[] { message,
alternateUser,
tran,
Integer.valueOf(exceptionReason),
exceptionStrings,
sourceMEUuid,
subscriptionID });
boolean sendComplete = false;
boolean defaultInUse = false; // Assume non-default exception destination is being used.
UndeliverableReturnCode rc = UndeliverableReturnCode.OK;
LocalTransaction localTran = null;
rc = checkMessage(message);
if (rc == UndeliverableReturnCode.BLOCK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc);
return rc; // depends on control dependency: [if], data = [none]
}
// Unless we're told to discard this message, try to send it to an exception destination
if (rc != UndeliverableReturnCode.DISCARD)
{
JsMessage msg = null;
try {
msg = message.getMessage().getReceived(); // depends on control dependency: [try], data = [none]
} catch (MessageCopyFailedException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:568:1.137",
this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
} // depends on control dependency: [catch], data = [none]
// F001333-14610
// Pass the subscription ID to be set on the message properties.
msg = setMessageProperties(msg, exceptionReason, exceptionStrings, subscriptionID); // depends on control dependency: [if], data = [none]
/*
* If Destination is not null, get the exception destination.
* If it is null - this indicates the default exception destination was required
* so use this instead.
*/
String newExceptionDestination = null;
if (_originalDestination != null)
{
newExceptionDestination = _originalDestination.getExceptionDestination(); // depends on control dependency: [if], data = [none]
if (newExceptionDestination == null || newExceptionDestination.equals(""))
{
if (_originalDestination.isToBeDeleted()) {
newExceptionDestination = _defaultExceptionDestinationName; // depends on control dependency: [if], data = [none]
defaultInUse = true; // depends on control dependency: [if], data = [none]
}
else
{
// In the past, this could only arise if we were forcing the put after the message
// had arrived across a link but the destination was full. i.e. BLOCK was returned but
// forcePut was true so that ordering was broken (but thats what happens with links).
// This situation is now handled elsewhere in the code (see defect 4644630 so wE'll return an error
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR; // depends on control dependency: [if], data = [none]
}
}
if (newExceptionDestination.equals(JsConstants.DEFAULT_EXCEPTION_DESTINATION))
{
newExceptionDestination = _defaultExceptionDestinationName; // depends on control dependency: [if], data = [none]
defaultInUse = true; // depends on control dependency: [if], data = [none]
}
}
else
{
newExceptionDestination = _defaultExceptionDestinationName; // depends on control dependency: [if], data = [none]
defaultInUse = true; // depends on control dependency: [if], data = [none]
}
/*
* Entering synch block.
* We MUST put the ExceptionDestination instance on a destination. Ideally
* we would have an instance per consumer point (since there will be a
* producerSession instance per consumerpoint). We cannot do this because we
* cannot get references to the consumerpoints at the time we need to use the
* ExceptionDestination.
*
* Rather than perform a destination lookup every time we call
* this method, we synchronize on one instance. If a different dest is needed
* then we do a lookup within the synchronized block. This
* introduces an optimisation for consecutive sends to the same exception
* destination.
*/
synchronized (_exceptionDestinationLock) // depends on control dependency: [if], data = [none]
{
/*
* If inputhandler ref has not been created yet, or exception destination has changed
* since the last call of this method, then get the inputhandler associated
* with the given exception destination
*
* This inputhandler will be used to send messages to the exception destination
*/
if (_inputHandler == null || !newExceptionDestination.equals(_exceptionDestinationName))
{
_exceptionDestinationName = newExceptionDestination; // depends on control dependency: [if], data = [none]
/*
* Try to get an inputhandler to the exception destination specified in the
* destination's definition. If this fails, (e.g. if the exception destination
* does not exist) then attempt to get one to the default (which should ALWAYS
* succeed). If this fails then report a fatal error.
*/
//Get the named destination from the destination manager
try
{
_exceptionDestination =
_messageProcessor.getDestinationManager().
getDestination(_exceptionDestinationName, true); // depends on control dependency: [try], data = [exception]
// Check whether bus security is enabled
if (_messageProcessor.isBusSecure())
{
// Check authority to access exc destination
AccessResult result = checkExceptionDestinationAccess(msg,
null,
alternateUser,
defaultInUse);
// Handle access denied
if (!result.isAllowed())
{
// Report and audit the event
handleAccessDenied(result, msg, alternateUser); // depends on control dependency: [if], data = [none]
// Return with "BLOCK". This is the same behaviour as things like
// q full, etc. It means, for example, that messages will be backed
// up on transmission queues if they cannot be delivered to either
// target or exception destination.
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK; // depends on control dependency: [if], data = [none]
}
}
// Set the priority in the message based on the exception destinations default
msg.setPriority(_exceptionDestination.getDefaultPriority()); // depends on control dependency: [try], data = [exception]
// Get the inputhandler associated with it
_inputHandler = _exceptionDestination.getInputHandler(_exceptionDestination.isPubSub() ? ProtocolType.PUBSUBINPUT : ProtocolType.UNICASTINPUT,
_messageProcessor.getMessagingEngineUuid(),
null); // depends on control dependency: [try], data = [exception]
} catch (SIException e)
{
// No FFDC code needed
SibTr.exception(tc, e);
/*
* If it was the default exception destination we failed to reference, then exit.
* Otherwise retry with the default
*/
if (defaultInUse)
{
/*
* ERROR : SYSTEM.DEFAULT.EXCEPTION.DESTINATION.<MENAME> queue did
* not exist on the ME. This should ALWAYS exist.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:710:1.137",
this); // depends on control dependency: [if], data = [none]
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:716:1.137",
e,
_exceptionDestinationName }); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR; // depends on control dependency: [if], data = [none]
}
/* Generate warning but retry with default exception destination */
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e });
/* Get the default and retry */
_exceptionDestinationName = _defaultExceptionDestinationName;
/* Retry on the default ex.dest. */
//Get the named destination from the destination manager
try
{
_exceptionDestination =
_messageProcessor.getDestinationManager().
getDestination(_exceptionDestinationName, true); // depends on control dependency: [try], data = [exception]
// Check whether bus security is enabled
if (_messageProcessor.isBusSecure())
{
// Check authority to access to default exc destination
AccessResult result = checkExceptionDestinationAccess(msg,
null,
alternateUser,
true);
// Handle access denied
if (!result.isAllowed())
{
// Report and audit the event
handleAccessDenied(result, msg, alternateUser); // depends on control dependency: [if], data = [none]
// Return with "BLOCK". This is the same behaviour as things like
// q full, etc. It means, for example, that messages will be backed
// up on transmission queues if they cannot be delivered to either
// target or exception destination.
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK; // depends on control dependency: [if], data = [none]
}
}
// Set the priority in the message based on the exception destinations default
msg.setPriority(_exceptionDestination.getDefaultPriority()); // depends on control dependency: [try], data = [exception]
// Get the inputhandler associated with it
_inputHandler = _exceptionDestination.getInputHandler(_exceptionDestination.isPubSub() ? ProtocolType.PUBSUBINPUT : ProtocolType.UNICASTINPUT,
_messageProcessor.getMessagingEngineUuid(),
null); // depends on control dependency: [try], data = [exception]
defaultInUse = true; // depends on control dependency: [try], data = [none]
} catch (SIException e2)
{
/*
* ERROR : SYSTEM.DEFAULT.EXCEPTION.DESTINATION.<MENAME> queue did
* not exist on the ME. This should ALWAYS exist.
*/
FFDCFilter.processException(
e2,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:786:1.137",
this);
SibTr.exception(tc, e);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:793:1.137",
e2,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
} // depends on control dependency: [catch], data = [none]
} // Inputhandler to an exception destination obtained // depends on control dependency: [catch], data = [none]
}
/*
* Send the message using whichever exception destination we have chosen. If it
* is unsuccessful and it is not aimed at the default - then get an inputhandler
* to the default and retry the send. If a send to the default fails (which will
* be on the local ME) then retry every 10 seconds.
*/
sendComplete = false;
while (!sendComplete)
{
// 533027 We need to create a new MessageItem each time round the loop,
// as we could fail at an unexpected point (such as while allocating an
// id to the message), and hence leave the MessageItem in an inconsistent state
// (such as with callbacks still registered).
MessageItem newItem = new MessageItem(msg);
//Set this in the msgItem as we want to generate a new systemUUID if needed
newItem.setRequiresNewId(message.getRequiresNewId()); // depends on control dependency: [while], data = [none]
try
{
newItem.setStoreAtSendTime(message.isToBeStoredAtSendTime()); // depends on control dependency: [try], data = [none]
TransactionCommon transaction = null;
if (tran == null)
{
localTran = _exceptionDestination.getTxManager().createLocalTransaction(false); // depends on control dependency: [if], data = [none]
transaction = localTran; // depends on control dependency: [if], data = [none]
}
else
{
transaction = tran; // depends on control dependency: [if], data = [none]
}
_inputHandler.handleMessage(newItem,
transaction, sourceMEUuid); // depends on control dependency: [try], data = [none]
JsMessagingEngine me = _messageProcessor.getMessagingEngine();
if (me.isEventNotificationEnabled() ||
UserTrace.tc_mt.isDebugEnabled())
{
String apiMsgId = null;
String correlationId = null;
if (message.getMessage() instanceof JsApiMessage)
{
apiMsgId = ((JsApiMessage) message.getMessage()).getApiMessageId(); // depends on control dependency: [if], data = [none]
correlationId = ((JsApiMessage) message.getMessage()).getCorrelationId(); // depends on control dependency: [if], data = [none]
}
else
{
if (message.getMessage().getApiMessageIdAsBytes() != null)
apiMsgId = new String(message.getMessage().getApiMessageIdAsBytes());
if (message.getMessage().getCorrelationIdAsBytes() != null)
correlationId = new String(message.getMessage().getCorrelationIdAsBytes());
}
if (TraceComponent.isAnyTracingEnabled() && UserTrace.tc_mt.isDebugEnabled())
{
if (message.getMessage().isApiMessage())
SibTr.debug(UserTrace.tc_mt,
nls_mt.getFormattedMessage(
"MESSAGE_EXCEPTION_DESTINATIONED_CWSJU0012",
new Object[] {
apiMsgId,
message.getMessage().getSystemMessageId(),
correlationId,
_exceptionDestinationName,
Integer.valueOf(exceptionReason),
message.getMessage().getExceptionMessage() },
null));
}
if (me.isEventNotificationEnabled())
{
fireMessageExceptionedEvent(apiMsgId,
message,
exceptionReason); // depends on control dependency: [if], data = [none]
}
}
/* Send was successful so exit while loop and return OK */
sendComplete = true; // depends on control dependency: [try], data = [none]
} catch (SIException e)
{
// No FFDC code needed
if (!defaultInUse)
{
/* Generate warning but retry with default exception destination */
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e }); // depends on control dependency: [if], data = [none]
UndeliverableReturnCode rc2 = sendToDefaultExceptionDestination(msg);
// If the above worked then carry on, if it failed then return
if (rc2 != UndeliverableReturnCode.OK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc2);
return rc2; // depends on control dependency: [if], data = [none]
}
else
{
//Everything was ok, set that we are using the default
defaultInUse = true; // depends on control dependency: [if], data = [none]
}
}
else
{
if (e instanceof SIMPLimitExceededException)
{
// Warning : Default exception destination full
SibTr.warning(tc, "EXCEPTION_DESTINATION_WARNING_CWSIP0291",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName(), e }); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.BLOCK);
return UndeliverableReturnCode.BLOCK; // depends on control dependency: [if], data = [none]
}
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:938:1.137",
this); // depends on control dependency: [if], data = [none]
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:944:1.137",
e,
_exceptionDestinationName }); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR; // depends on control dependency: [if], data = [none]
}
} catch (MessageStoreRuntimeException e) // depends on control dependency: [catch], data = [none]
{
// No FFDC code needed
if (!defaultInUse)
{
UndeliverableReturnCode rc2 = sendToDefaultExceptionDestination(msg);
// If the above worked then carry on, if it failed then return
if (rc2 != UndeliverableReturnCode.OK)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc2);
return rc2; // depends on control dependency: [if], data = [none]
}
else
{
//Everything was ok, set that we are using the default
defaultInUse = true; // depends on control dependency: [if], data = [none]
}
}
else
{
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:981:1.137",
this); // depends on control dependency: [if], data = [none]
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:986:1.137",
e,
_exceptionDestinationName }); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR; // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
} // End of synchronisation
}
// If report messages required - generate and send here
if (message.getMessage().getReportException() != null)
{
// Create the ReportHandler object if not already created
if (_reportHandler == null)
_reportHandler = new ReportHandler(_messageProcessor);
TransactionCommon transaction = null;
if (tran == null)
{
transaction = localTran; // depends on control dependency: [if], data = [none]
}
else
{
transaction = tran; // depends on control dependency: [if], data = [none]
}
try
{
_reportHandler.handleMessage(message, transaction, SIApiConstants.REPORT_EXCEPTION); // depends on control dependency: [try], data = [none]
} catch (Exception e)
{
// ERROR : Cannot send report message
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:1029:1.137",
this);
SibTr.error(tc, "EXCEPTION_DESTINATION_ERROR_CWSIP0295",
new Object[] { _exceptionDestinationName, _messageProcessor.getMessagingEngineName() });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
} // depends on control dependency: [catch], data = [none]
}
if (localTran != null)
{
try
{
localTran.commit(); // depends on control dependency: [try], data = [none]
} catch (SIException e)
{
/*
* ERROR : Cannot deliver to local SYSTEM.DEFAULT.EXCEPTION.DESTINATION.
*/
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl.handleUndeliverableMessage",
"1:1056:1.137",
this);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0003",
new Object[] {
"com.ibm.ws.sib.processor.impl.ExceptionDestinationHandlerImpl",
"1:1061:1.137",
e,
_exceptionDestinationName });
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", UndeliverableReturnCode.ERROR);
return UndeliverableReturnCode.ERROR;
} // depends on control dependency: [catch], data = [none]
}
// If we got here then everything worked ok
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "handleUndeliverableMessage", rc);
return rc;
} }
|
public class class_name {
public static <T> byte[] toByteArray(T message, Schema<T> schema, LinkedBuffer buffer)
{
if (buffer.start != buffer.offset)
throw new IllegalArgumentException("Buffer previously used and had not been reset.");
final XmlXOutput output = new XmlXOutput(buffer, schema);
final String name = schema.messageName();
try
{
// header and start root element
output.tail = output.sink.writeByte(XmlXOutput.END_TAG, output,
output.sink.writeStrAscii(name, output,
output.sink.writeByte(XmlXOutput.START_TAG, output,
output.sink.writeByteArray(HEADER, output, output.tail))));
schema.writeTo(output, message);
// end root element
output.tail = output.sink.writeByte(XmlXOutput.END_TAG, output,
output.sink.writeStrAscii(name, output,
output.sink.writeByteArray(XmlXOutput.START_SLASH_TAG, output, output.tail)));
}
catch (IOException e)
{
throw new RuntimeException("Serializing to a byte array threw an IOException " +
"(should never happen).", e);
}
return output.toByteArray();
} }
|
public class class_name {
public static <T> byte[] toByteArray(T message, Schema<T> schema, LinkedBuffer buffer)
{
if (buffer.start != buffer.offset)
throw new IllegalArgumentException("Buffer previously used and had not been reset.");
final XmlXOutput output = new XmlXOutput(buffer, schema);
final String name = schema.messageName();
try
{
// header and start root element
output.tail = output.sink.writeByte(XmlXOutput.END_TAG, output,
output.sink.writeStrAscii(name, output,
output.sink.writeByte(XmlXOutput.START_TAG, output,
output.sink.writeByteArray(HEADER, output, output.tail)))); // depends on control dependency: [try], data = [none]
schema.writeTo(output, message); // depends on control dependency: [try], data = [none]
// end root element
output.tail = output.sink.writeByte(XmlXOutput.END_TAG, output,
output.sink.writeStrAscii(name, output,
output.sink.writeByteArray(XmlXOutput.START_SLASH_TAG, output, output.tail))); // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
throw new RuntimeException("Serializing to a byte array threw an IOException " +
"(should never happen).", e);
} // depends on control dependency: [catch], data = [none]
return output.toByteArray();
} }
|
public class class_name {
@Override
public synchronized void add(DiscoveryEntry discoveryEntry) {
logger.debug("adding discovery entry: {}", discoveryEntry);
if (!(discoveryEntry instanceof GlobalDiscoveryEntryPersisted)) {
return;
}
GlobalDiscoveryEntryPersisted globalDiscoveryEntry = (GlobalDiscoveryEntryPersisted) discoveryEntry;
if (globalDiscoveryEntry.getDomain() == null || globalDiscoveryEntry.getInterfaceName() == null
|| globalDiscoveryEntry.getParticipantId() == null || globalDiscoveryEntry.getAddress() == null) {
String message = "discoveryEntry being registered is not complete: " + discoveryEntry;
logger.error(message);
throw new JoynrCommunicationException(message);
}
GlobalDiscoveryEntryPersisted discoveryEntryFound = entityManager.find(GlobalDiscoveryEntryPersisted.class,
discoveryEntry.getParticipantId());
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
if (discoveryEntryFound != null) {
entityManager.merge(discoveryEntry);
} else {
entityManager.persist(discoveryEntry);
}
transaction.commit();
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
logger.error("unable to add discoveryEntry: " + discoveryEntry, e);
}
} }
|
public class class_name {
@Override
public synchronized void add(DiscoveryEntry discoveryEntry) {
logger.debug("adding discovery entry: {}", discoveryEntry);
if (!(discoveryEntry instanceof GlobalDiscoveryEntryPersisted)) {
return; // depends on control dependency: [if], data = [none]
}
GlobalDiscoveryEntryPersisted globalDiscoveryEntry = (GlobalDiscoveryEntryPersisted) discoveryEntry;
if (globalDiscoveryEntry.getDomain() == null || globalDiscoveryEntry.getInterfaceName() == null
|| globalDiscoveryEntry.getParticipantId() == null || globalDiscoveryEntry.getAddress() == null) {
String message = "discoveryEntry being registered is not complete: " + discoveryEntry;
logger.error(message); // depends on control dependency: [if], data = [none]
throw new JoynrCommunicationException(message);
}
GlobalDiscoveryEntryPersisted discoveryEntryFound = entityManager.find(GlobalDiscoveryEntryPersisted.class,
discoveryEntry.getParticipantId());
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin(); // depends on control dependency: [try], data = [none]
if (discoveryEntryFound != null) {
entityManager.merge(discoveryEntry); // depends on control dependency: [if], data = [none]
} else {
entityManager.persist(discoveryEntry); // depends on control dependency: [if], data = [none]
}
transaction.commit(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback(); // depends on control dependency: [if], data = [none]
}
logger.error("unable to add discoveryEntry: " + discoveryEntry, e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public void setQueues(final Collection<String> queues) {
for (final Worker worker : this.workers) {
worker.setQueues(queues);
}
} }
|
public class class_name {
@Override
public void setQueues(final Collection<String> queues) {
for (final Worker worker : this.workers) {
worker.setQueues(queues); // depends on control dependency: [for], data = [worker]
}
} }
|
public class class_name {
@Nonnull
public ExpressionTreeElement addSubTree(@Nonnull final ExpressionTree tree) {
assertNotEmptySlot();
final ExpressionTreeElement root = tree.getRoot();
if (!root.isEmptySlot()) {
root.makeMaxPriority();
addElementToNextFreeSlot(root);
}
return this;
} }
|
public class class_name {
@Nonnull
public ExpressionTreeElement addSubTree(@Nonnull final ExpressionTree tree) {
assertNotEmptySlot();
final ExpressionTreeElement root = tree.getRoot();
if (!root.isEmptySlot()) {
root.makeMaxPriority(); // depends on control dependency: [if], data = [none]
addElementToNextFreeSlot(root); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
protected final void writeIndexLikeList( List<String> dirs, List<String> files, PrintWriter writer )
{
// JarIndex is sorting the directories by ascending order.
// it has no value but cosmetic since it will be read into a
// hashtable by the classloader, but we'll do so anyway.
Collections.sort( dirs );
Collections.sort( files );
Iterator iter = dirs.iterator();
while ( iter.hasNext() )
{
String dir = (String) iter.next();
// try to be smart, not to be fooled by a weird directory name
dir = dir.replace( '\\', '/' );
if ( dir.startsWith( "./" ) )
{
dir = dir.substring( 2 );
}
while ( dir.startsWith( "/" ) )
{
dir = dir.substring( 1 );
}
int pos = dir.lastIndexOf( '/' );
if ( pos != -1 )
{
dir = dir.substring( 0, pos );
}
// name newline
writer.println( dir );
}
iter = files.iterator();
while ( iter.hasNext() )
{
writer.println( iter.next() );
}
} }
|
public class class_name {
protected final void writeIndexLikeList( List<String> dirs, List<String> files, PrintWriter writer )
{
// JarIndex is sorting the directories by ascending order.
// it has no value but cosmetic since it will be read into a
// hashtable by the classloader, but we'll do so anyway.
Collections.sort( dirs );
Collections.sort( files );
Iterator iter = dirs.iterator();
while ( iter.hasNext() )
{
String dir = (String) iter.next();
// try to be smart, not to be fooled by a weird directory name
dir = dir.replace( '\\', '/' ); // depends on control dependency: [while], data = [none]
if ( dir.startsWith( "./" ) )
{
dir = dir.substring( 2 ); // depends on control dependency: [if], data = [none]
}
while ( dir.startsWith( "/" ) )
{
dir = dir.substring( 1 ); // depends on control dependency: [while], data = [none]
}
int pos = dir.lastIndexOf( '/' );
if ( pos != -1 )
{
dir = dir.substring( 0, pos ); // depends on control dependency: [if], data = [none]
}
// name newline
writer.println( dir ); // depends on control dependency: [while], data = [none]
}
iter = files.iterator();
while ( iter.hasNext() )
{
writer.println( iter.next() ); // depends on control dependency: [while], data = [none]
}
} }
|
public class class_name {
static String escape(final String text) {
if (text == null) {
return null;
}
StringBuilder strBuilder = null;
final int offset = 0;
final int max = text.length();
int readOffset = offset;
for (int i = offset; i < max; i++) {
final char c = text.charAt(i);
/*
* Shortcut: most characters will be Alphanumeric, and we won't need to do anything at
* all for them.
*/
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
continue;
}
/*
* At this point we know for sure we will need some kind of escape, so we
* initialize the string builder.
*/
if (strBuilder == null) {
strBuilder = new StringBuilder(max + 20);
// If we need this, it's because we have non-alphanumeric chars. And that means
// we should enclose in double-quotes.
strBuilder.append(DOUBLE_QUOTE);
}
/*
* Now we copy all the contents pending up to this point.
*/
if (i - readOffset > 0) {
strBuilder.append(text, readOffset, i);
}
readOffset = i + 1;
/*
* Check whether the character is a double-quote (in which case, we escape it)
*/
if (c == DOUBLE_QUOTE) {
strBuilder.append(TWO_DOUBLE_QUOTES);
continue;
}
strBuilder.append(c);
}
/*
* -----------------------------------------------------------------------------------------------
* Final cleaning: return the original String object if no escape was actually needed. Otherwise
* append the remaining unescaped text to the string builder and return.
* -----------------------------------------------------------------------------------------------
*/
if (strBuilder == null) {
return text;
}
if (max - readOffset > 0) {
strBuilder.append(text, readOffset, max);
}
// If we reached here, it's because we had non-alphanumeric chars. And that means
// we should enclose in double-quotes.
strBuilder.append(DOUBLE_QUOTE);
return strBuilder.toString();
} }
|
public class class_name {
static String escape(final String text) {
if (text == null) {
return null; // depends on control dependency: [if], data = [none]
}
StringBuilder strBuilder = null;
final int offset = 0;
final int max = text.length();
int readOffset = offset;
for (int i = offset; i < max; i++) {
final char c = text.charAt(i);
/*
* Shortcut: most characters will be Alphanumeric, and we won't need to do anything at
* all for them.
*/
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
continue;
}
/*
* At this point we know for sure we will need some kind of escape, so we
* initialize the string builder.
*/
if (strBuilder == null) {
strBuilder = new StringBuilder(max + 20); // depends on control dependency: [if], data = [none]
// If we need this, it's because we have non-alphanumeric chars. And that means
// we should enclose in double-quotes.
strBuilder.append(DOUBLE_QUOTE); // depends on control dependency: [if], data = [none]
}
/*
* Now we copy all the contents pending up to this point.
*/
if (i - readOffset > 0) {
strBuilder.append(text, readOffset, i); // depends on control dependency: [if], data = [none]
}
readOffset = i + 1; // depends on control dependency: [for], data = [i]
/*
* Check whether the character is a double-quote (in which case, we escape it)
*/
if (c == DOUBLE_QUOTE) {
strBuilder.append(TWO_DOUBLE_QUOTES); // depends on control dependency: [if], data = [none]
continue;
}
strBuilder.append(c); // depends on control dependency: [for], data = [none]
}
/*
* -----------------------------------------------------------------------------------------------
* Final cleaning: return the original String object if no escape was actually needed. Otherwise
* append the remaining unescaped text to the string builder and return.
* -----------------------------------------------------------------------------------------------
*/
if (strBuilder == null) {
return text; // depends on control dependency: [if], data = [none]
}
if (max - readOffset > 0) {
strBuilder.append(text, readOffset, max); // depends on control dependency: [if], data = [none]
}
// If we reached here, it's because we had non-alphanumeric chars. And that means
// we should enclose in double-quotes.
strBuilder.append(DOUBLE_QUOTE);
return strBuilder.toString();
} }
|
public class class_name {
protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {
// Process elements
final List<PatchElement> elements = new ArrayList<PatchElement>();
// Process layers
for (final PatchEntry entry : getLayers()) {
final PatchElement element = createRollbackElement(entry);
elements.add(element);
}
// Process add-ons
for (final PatchEntry entry : getAddOns()) {
final PatchElement element = createRollbackElement(entry);
elements.add(element);
}
final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();
final String name = installedIdentity.getIdentity().getName();
final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());
if (patchType == Patch.PatchType.CUMULATIVE) {
identity.setPatchType(Patch.PatchType.CUMULATIVE);
identity.setResultingVersion(installedIdentity.getIdentity().getVersion());
} else if (patchType == Patch.PatchType.ONE_OFF) {
identity.setPatchType(Patch.PatchType.ONE_OFF);
}
final List<ContentModification> modifications = identityEntry.rollbackActions;
final Patch delegate = new PatchImpl(patchId, "rollback patch", identity, elements, modifications);
return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);
} }
|
public class class_name {
protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) {
// Process elements
final List<PatchElement> elements = new ArrayList<PatchElement>();
// Process layers
for (final PatchEntry entry : getLayers()) {
final PatchElement element = createRollbackElement(entry);
elements.add(element); // depends on control dependency: [for], data = [none]
}
// Process add-ons
for (final PatchEntry entry : getAddOns()) {
final PatchElement element = createRollbackElement(entry);
elements.add(element); // depends on control dependency: [for], data = [none]
}
final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState();
final String name = installedIdentity.getIdentity().getName();
final IdentityImpl identity = new IdentityImpl(name, modification.getVersion());
if (patchType == Patch.PatchType.CUMULATIVE) {
identity.setPatchType(Patch.PatchType.CUMULATIVE); // depends on control dependency: [if], data = [Patch.PatchType.CUMULATIVE)]
identity.setResultingVersion(installedIdentity.getIdentity().getVersion()); // depends on control dependency: [if], data = [none]
} else if (patchType == Patch.PatchType.ONE_OFF) {
identity.setPatchType(Patch.PatchType.ONE_OFF); // depends on control dependency: [if], data = [Patch.PatchType.ONE_OFF)]
}
final List<ContentModification> modifications = identityEntry.rollbackActions;
final Patch delegate = new PatchImpl(patchId, "rollback patch", identity, elements, modifications);
return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity);
} }
|
public class class_name {
public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyle featureStyle, float density, IconCache iconCache) {
boolean featureStyleSet = false;
if (featureStyle != null) {
featureStyleSet = setIcon(markerOptions, featureStyle.getIcon(), density, iconCache);
if (!featureStyleSet) {
featureStyleSet = setStyle(markerOptions, featureStyle.getStyle());
}
}
return featureStyleSet;
} }
|
public class class_name {
public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyle featureStyle, float density, IconCache iconCache) {
boolean featureStyleSet = false;
if (featureStyle != null) {
featureStyleSet = setIcon(markerOptions, featureStyle.getIcon(), density, iconCache); // depends on control dependency: [if], data = [none]
if (!featureStyleSet) {
featureStyleSet = setStyle(markerOptions, featureStyle.getStyle()); // depends on control dependency: [if], data = [none]
}
}
return featureStyleSet;
} }
|
public class class_name {
public ClassInfoModel readClassInfo(PropertyOwner recordOwner, String className)
{
String strParamRecord = null;
String strParamScreenType = null;
String strParamMenu = null;
String strParamHelp = null;
if (className == null)
{
strParamRecord = recordOwner.getProperty(DBParams.RECORD); // Display record
className = recordOwner.getProperty(DBParams.SCREEN); // Display screen
strParamScreenType = recordOwner.getProperty(DBParams.COMMAND); // Display record
strParamMenu = recordOwner.getProperty(DBParams.MENU); // Display record
strParamHelp = recordOwner.getProperty(DBParams.HELP); // Display record
}
if (className == null)
className = DBConstants.BLANK;
if ((className.length() == 0) || (className.equals("Screen")) || (className.equals("GridScreen")))
{
if (strParamRecord != null) if (strParamRecord.length() > 0)
className = strParamRecord; // Use desc of record class if standard screen
}
try {
this.setKeyArea(DBConstants.PRIMARY_KEY);
if (className.lastIndexOf('.') != -1)
className = className.substring(className.lastIndexOf('.') + 1);
this.getField(ClassInfo.CLASS_NAME).setString(className);
boolean bSuccess = false;
this.setKeyArea(ClassInfo.CLASS_NAME_KEY);
if (className.length() > 0)
bSuccess = this.seek("=");
if (!bSuccess)
{ // Not found, use standard screen maintenance screen
if ((strParamMenu != null) && (strParamMenu.length() > 0))
this.getField(ClassInfo.CLASS_NAME).setString("MenuScreen");
else if ((strParamRecord != null) && (strParamRecord.length() > 0))
{
if ((strParamScreenType != null) && (strParamScreenType.length() > 0) && (strParamScreenType.equalsIgnoreCase(ThinMenuConstants.FORM)))
this.getField(ClassInfo.CLASS_NAME).setString("Screen");
else
this.getField(ClassInfo.CLASS_NAME).setString("GridScreen");
}
else
this.getField(ClassInfo.CLASS_NAME).setString(strParamHelp);
if (!bSuccess)
bSuccess = this.seek("=");
}
} catch (DBException e) {
e.printStackTrace();
return null;
}
return this;
} }
|
public class class_name {
public ClassInfoModel readClassInfo(PropertyOwner recordOwner, String className)
{
String strParamRecord = null;
String strParamScreenType = null;
String strParamMenu = null;
String strParamHelp = null;
if (className == null)
{
strParamRecord = recordOwner.getProperty(DBParams.RECORD); // Display record // depends on control dependency: [if], data = [none]
className = recordOwner.getProperty(DBParams.SCREEN); // Display screen // depends on control dependency: [if], data = [none]
strParamScreenType = recordOwner.getProperty(DBParams.COMMAND); // Display record // depends on control dependency: [if], data = [none]
strParamMenu = recordOwner.getProperty(DBParams.MENU); // Display record // depends on control dependency: [if], data = [none]
strParamHelp = recordOwner.getProperty(DBParams.HELP); // Display record // depends on control dependency: [if], data = [none]
}
if (className == null)
className = DBConstants.BLANK;
if ((className.length() == 0) || (className.equals("Screen")) || (className.equals("GridScreen")))
{
if (strParamRecord != null) if (strParamRecord.length() > 0)
className = strParamRecord; // Use desc of record class if standard screen
}
try {
this.setKeyArea(DBConstants.PRIMARY_KEY); // depends on control dependency: [try], data = [none]
if (className.lastIndexOf('.') != -1)
className = className.substring(className.lastIndexOf('.') + 1);
this.getField(ClassInfo.CLASS_NAME).setString(className); // depends on control dependency: [try], data = [none]
boolean bSuccess = false;
this.setKeyArea(ClassInfo.CLASS_NAME_KEY); // depends on control dependency: [try], data = [none]
if (className.length() > 0)
bSuccess = this.seek("=");
if (!bSuccess)
{ // Not found, use standard screen maintenance screen
if ((strParamMenu != null) && (strParamMenu.length() > 0))
this.getField(ClassInfo.CLASS_NAME).setString("MenuScreen");
else if ((strParamRecord != null) && (strParamRecord.length() > 0))
{
if ((strParamScreenType != null) && (strParamScreenType.length() > 0) && (strParamScreenType.equalsIgnoreCase(ThinMenuConstants.FORM)))
this.getField(ClassInfo.CLASS_NAME).setString("Screen");
else
this.getField(ClassInfo.CLASS_NAME).setString("GridScreen");
}
else
this.getField(ClassInfo.CLASS_NAME).setString(strParamHelp);
if (!bSuccess)
bSuccess = this.seek("=");
}
} catch (DBException e) {
e.printStackTrace();
return null;
} // depends on control dependency: [catch], data = [none]
return this;
} }
|
public class class_name {
private URL getRequiredUrlParameter(String keyword,
Map<String, String> parms) {
String urlString = getRequiredParameter(keyword, parms);
try {
return new URL(urlString);
} catch (MalformedURLException e) {
throw new ValidatorProcessUsageException("Value '" + urlString
+ "' for parameter '" + keyword + "' is not a valid URL: "
+ e.getMessage());
}
} }
|
public class class_name {
private URL getRequiredUrlParameter(String keyword,
Map<String, String> parms) {
String urlString = getRequiredParameter(keyword, parms);
try {
return new URL(urlString); // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
throw new ValidatorProcessUsageException("Value '" + urlString
+ "' for parameter '" + keyword + "' is not a valid URL: "
+ e.getMessage());
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
String getContentByCardId(String cardId) {
Map<String, Object> request = new HashMap<>();
request.put("card_id", cardId);
String url = WxEndpoint.get("url.card.mpnews.gethtml");
String json = JsonMapper.defaultMapper().toJson(request);
logger.debug("get mpnews content by card id: {}", json);
String response = wxClient.post(url, json);
Map<String, Object> result = JsonMapper.defaultMapper().json2Map(response);
if (result.containsKey("content")) {
return result.get("content").toString();
} else {
throw new WxRuntimeException(999, "get html content by card id failed.");
}
} }
|
public class class_name {
String getContentByCardId(String cardId) {
Map<String, Object> request = new HashMap<>();
request.put("card_id", cardId);
String url = WxEndpoint.get("url.card.mpnews.gethtml");
String json = JsonMapper.defaultMapper().toJson(request);
logger.debug("get mpnews content by card id: {}", json);
String response = wxClient.post(url, json);
Map<String, Object> result = JsonMapper.defaultMapper().json2Map(response);
if (result.containsKey("content")) {
return result.get("content").toString();
// depends on control dependency: [if], data = [none]
} else {
throw new WxRuntimeException(999, "get html content by card id failed.");
}
} }
|
public class class_name {
public void marshall(Configuration configuration, ProtocolMarshaller protocolMarshaller) {
if (configuration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(configuration.getClassification(), CLASSIFICATION_BINDING);
protocolMarshaller.marshall(configuration.getConfigurations(), CONFIGURATIONS_BINDING);
protocolMarshaller.marshall(configuration.getProperties(), PROPERTIES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(Configuration configuration, ProtocolMarshaller protocolMarshaller) {
if (configuration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(configuration.getClassification(), CLASSIFICATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(configuration.getConfigurations(), CONFIGURATIONS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(configuration.getProperties(), PROPERTIES_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 void solve() {
while (true) {
try {
// Is our proof of work valid yet?
if (checkProofOfWork(false))
return;
// No, so increment the nonce and try again.
setNonce(getNonce() + 1);
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
} }
|
public class class_name {
public void solve() {
while (true) {
try {
// Is our proof of work valid yet?
if (checkProofOfWork(false))
return;
// No, so increment the nonce and try again.
setNonce(getNonce() + 1); // depends on control dependency: [try], data = [none]
} catch (VerificationException e) {
throw new RuntimeException(e); // Cannot happen.
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
@Override
public String resolve(HttpServletRequest request) {
String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
String parameterToken = resolveFromRequestParameters(request);
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST,
HttpStatus.BAD_REQUEST,
"Found multiple bearer tokens in the request",
"https://tools.ietf.org/html/rfc6750#section-3.1");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
else if (parameterToken != null && isParameterTokenSupportedForRequest(request)) {
return parameterToken;
}
return null;
} }
|
public class class_name {
@Override
public String resolve(HttpServletRequest request) {
String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
String parameterToken = resolveFromRequestParameters(request);
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST,
HttpStatus.BAD_REQUEST,
"Found multiple bearer tokens in the request",
"https://tools.ietf.org/html/rfc6750#section-3.1");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken; // depends on control dependency: [if], data = [none]
}
else if (parameterToken != null && isParameterTokenSupportedForRequest(request)) {
return parameterToken; // depends on control dependency: [if], data = [none]
}
return null;
} }
|
public class class_name {
public void onCompleted() {
mSerializingExecutor.execute(() -> {
Preconditions.checkState(mContext != null);
try {
completeRequest(mContext);
replySuccess();
} catch (Exception e) {
LogUtils.warnWithException(LOG, "Exception occurred while completing write request {}.",
mContext.getRequest(), e);
Throwables.throwIfUnchecked(e);
abort(new Error(AlluxioStatusException.fromCheckedException(e), true));
}
});
} }
|
public class class_name {
public void onCompleted() {
mSerializingExecutor.execute(() -> {
Preconditions.checkState(mContext != null);
try {
completeRequest(mContext); // depends on control dependency: [try], data = [none]
replySuccess(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LogUtils.warnWithException(LOG, "Exception occurred while completing write request {}.",
mContext.getRequest(), e);
Throwables.throwIfUnchecked(e);
abort(new Error(AlluxioStatusException.fromCheckedException(e), true));
} // depends on control dependency: [catch], data = [none]
});
} }
|
public class class_name {
@Override
public void endElement(String uri, String local, String raw) { //NOPMD
logger.debug("END Element: ", raw);
logger.debug(" uri: ", uri);
logger.debug(" local: ", local);
logger.debug(" raw: ", raw);
logger.debug(" chars: ", currentChars.trim());
if ("atomType".equals(local)) {
atomTypes.add(atomType);
} else if ("scalar".equals(local)) {
currentChars.trim();
try {
if (scalarType == SCALAR_BONDORDERSUM) {
atomType.setBondOrderSum(Double.parseDouble(currentChars));
} else if (scalarType == SCALAR_MAXBONDORDER) {
double scalarValue = Double.parseDouble(currentChars);
if (scalarValue == 1.0) {
atomType.setMaxBondOrder(IBond.Order.SINGLE);
} else if (scalarValue == 2.0) {
atomType.setMaxBondOrder(IBond.Order.DOUBLE);
} else if (scalarValue == 3.0) {
atomType.setMaxBondOrder(IBond.Order.TRIPLE);
} else if (scalarValue == 4.0) {
atomType.setMaxBondOrder(IBond.Order.QUADRUPLE);
}
} else if (scalarType == SCALAR_FORMALNEIGHBOURCOUNT) {
atomType.setFormalNeighbourCount(Integer.parseInt(currentChars));
} else if (scalarType == SCALAR_VALENCY) {
atomType.setValency(Integer.parseInt(currentChars));
} else if (scalarType == SCALAR_FORMALCHARGE) {
atomType.setFormalCharge(Integer.parseInt(currentChars));
} else if (scalarType == SCALAR_HYBRIDIZATION) {
if ("sp1".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP1);
} else if ("sp2".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP2);
} else if ("sp3".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP3);
} else if ("planar".equals(currentChars)) {
atomType.setHybridization(Hybridization.PLANAR3);
} else {
logger.warn("Unrecognized hybridization in config file: ", currentChars);
}
} else if (scalarType == SCALAR_DA) {
if ("A".equals(currentChars)) {
atomType.setFlag(CDKConstants.IS_HYDROGENBOND_ACCEPTOR, true);
} else if ("D".equals(currentChars)) {
atomType.setFlag(CDKConstants.IS_HYDROGENBOND_DONOR, true);
} else {
logger.warn("Unrecognized H-bond donor/acceptor pattern in config file: ", currentChars);
}
} else if (scalarType == SCALAR_SPHERICALMATCHER) {
atomType.setProperty(CDKConstants.SPHERICAL_MATCHER, currentChars);
} else if (scalarType == SCALAR_RINGSIZE) {
atomType.setProperty(CDKConstants.PART_OF_RING_OF_SIZE, Integer.valueOf(currentChars));
} else if (scalarType == SCALAR_CHEMICALGROUPCONSTANT) {
atomType.setProperty(CDKConstants.CHEMICAL_GROUP_CONSTANT, Integer.valueOf(currentChars));
} else if (scalarType == SCALAR_ISAROMATIC) {
atomType.setFlag(CDKConstants.ISAROMATIC, true);
} else if (scalarType == SCALAR_PIBONDCOUNT) {
atomType.setProperty(CDKConstants.PI_BOND_COUNT, Integer.valueOf(currentChars));
} else if (scalarType == SCALAR_LONEPAIRCOUNT) {
atomType.setProperty(CDKConstants.LONE_PAIR_COUNT, Integer.valueOf(currentChars));
}
} catch (Exception exception) {
logger.error("Value (", currentChars, ") is not off the expected type: ", exception.getMessage());
logger.debug(exception);
}
scalarType = SCALAR_UNSET;
}
currentChars = "";
} }
|
public class class_name {
@Override
public void endElement(String uri, String local, String raw) { //NOPMD
logger.debug("END Element: ", raw);
logger.debug(" uri: ", uri);
logger.debug(" local: ", local);
logger.debug(" raw: ", raw);
logger.debug(" chars: ", currentChars.trim());
if ("atomType".equals(local)) {
atomTypes.add(atomType); // depends on control dependency: [if], data = [none]
} else if ("scalar".equals(local)) {
currentChars.trim(); // depends on control dependency: [if], data = [none]
try {
if (scalarType == SCALAR_BONDORDERSUM) {
atomType.setBondOrderSum(Double.parseDouble(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_MAXBONDORDER) {
double scalarValue = Double.parseDouble(currentChars);
if (scalarValue == 1.0) {
atomType.setMaxBondOrder(IBond.Order.SINGLE); // depends on control dependency: [if], data = [none]
} else if (scalarValue == 2.0) {
atomType.setMaxBondOrder(IBond.Order.DOUBLE); // depends on control dependency: [if], data = [none]
} else if (scalarValue == 3.0) {
atomType.setMaxBondOrder(IBond.Order.TRIPLE); // depends on control dependency: [if], data = [none]
} else if (scalarValue == 4.0) {
atomType.setMaxBondOrder(IBond.Order.QUADRUPLE); // depends on control dependency: [if], data = [none]
}
} else if (scalarType == SCALAR_FORMALNEIGHBOURCOUNT) {
atomType.setFormalNeighbourCount(Integer.parseInt(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_VALENCY) {
atomType.setValency(Integer.parseInt(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_FORMALCHARGE) {
atomType.setFormalCharge(Integer.parseInt(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_HYBRIDIZATION) {
if ("sp1".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP1); // depends on control dependency: [if], data = [none]
} else if ("sp2".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP2); // depends on control dependency: [if], data = [none]
} else if ("sp3".equals(currentChars)) {
atomType.setHybridization(Hybridization.SP3); // depends on control dependency: [if], data = [none]
} else if ("planar".equals(currentChars)) {
atomType.setHybridization(Hybridization.PLANAR3); // depends on control dependency: [if], data = [none]
} else {
logger.warn("Unrecognized hybridization in config file: ", currentChars); // depends on control dependency: [if], data = [none]
}
} else if (scalarType == SCALAR_DA) {
if ("A".equals(currentChars)) {
atomType.setFlag(CDKConstants.IS_HYDROGENBOND_ACCEPTOR, true); // depends on control dependency: [if], data = [none]
} else if ("D".equals(currentChars)) {
atomType.setFlag(CDKConstants.IS_HYDROGENBOND_DONOR, true); // depends on control dependency: [if], data = [none]
} else {
logger.warn("Unrecognized H-bond donor/acceptor pattern in config file: ", currentChars); // depends on control dependency: [if], data = [none]
}
} else if (scalarType == SCALAR_SPHERICALMATCHER) {
atomType.setProperty(CDKConstants.SPHERICAL_MATCHER, currentChars); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_RINGSIZE) {
atomType.setProperty(CDKConstants.PART_OF_RING_OF_SIZE, Integer.valueOf(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_CHEMICALGROUPCONSTANT) {
atomType.setProperty(CDKConstants.CHEMICAL_GROUP_CONSTANT, Integer.valueOf(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_ISAROMATIC) {
atomType.setFlag(CDKConstants.ISAROMATIC, true); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_PIBONDCOUNT) {
atomType.setProperty(CDKConstants.PI_BOND_COUNT, Integer.valueOf(currentChars)); // depends on control dependency: [if], data = [none]
} else if (scalarType == SCALAR_LONEPAIRCOUNT) {
atomType.setProperty(CDKConstants.LONE_PAIR_COUNT, Integer.valueOf(currentChars)); // depends on control dependency: [if], data = [none]
}
} catch (Exception exception) {
logger.error("Value (", currentChars, ") is not off the expected type: ", exception.getMessage());
logger.debug(exception);
} // depends on control dependency: [catch], data = [none]
scalarType = SCALAR_UNSET; // depends on control dependency: [if], data = [none]
}
currentChars = "";
} }
|
public class class_name {
private void closeChannel() {
if (this.channel != null) {
if (this.channel.isConnected()) {
try {
this.channel.disconnect();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
if (this.channel.isOpen()) {
try {
this.channel.close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
}
} }
|
public class class_name {
private void closeChannel() {
if (this.channel != null) {
if (this.channel.isConnected()) {
try {
this.channel.disconnect(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
if (this.channel.isOpen()) {
try {
this.channel.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
} }
|
public class class_name {
public void add(String name, String... values) {
if (containsKey(name)) {
List<String> list = get(name);
for (String value: values) {
list.add(value);
}
} else {
put(name, values);
}
} }
|
public class class_name {
public void add(String name, String... values) {
if (containsKey(name)) {
List<String> list = get(name);
for (String value: values) {
list.add(value); // depends on control dependency: [for], data = [value]
}
} else {
put(name, values); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public String getXPathBase() {
String xPathBase = "";
if (this.getElement() != null) {
String locator = getLocator();
if (!locator.startsWith("link=") && !locator.startsWith("xpath=") && !locator.startsWith("/")) {
if (locator.startsWith("id=") || locator.startsWith("name=")) {
String tmp = locator.substring(locator.indexOf('=', 1) + 1);
if (locator.startsWith("id=")) {
xPathBase = "//table[@id='" + tmp + "']/tbody/";
} else {
xPathBase = "//*[@name='" + tmp + "']/tbody/";
}
} else {
xPathBase = "//*[@id='" + locator + "']/tbody/";
}
} else {
if (locator.startsWith("xpath=")) {
locator = locator.substring(locator.indexOf('=', 1) + 1);
}
if (HtmlElementUtils.locateElements(locator + "/tbody").size() > 0) {
xPathBase = locator + "/tbody/";
} else {
xPathBase = locator + "//";
}
}
} else {
throw new NoSuchElementException("Table" + this.getLocator() + " does not exist.");
}
return xPathBase;
} }
|
public class class_name {
public String getXPathBase() {
String xPathBase = "";
if (this.getElement() != null) {
String locator = getLocator();
if (!locator.startsWith("link=") && !locator.startsWith("xpath=") && !locator.startsWith("/")) {
if (locator.startsWith("id=") || locator.startsWith("name=")) {
String tmp = locator.substring(locator.indexOf('=', 1) + 1);
if (locator.startsWith("id=")) {
xPathBase = "//table[@id='" + tmp + "']/tbody/";
} else {
xPathBase = "//*[@name='" + tmp + "']/tbody/";
}
} else {
xPathBase = "//*[@id='" + locator + "']/tbody/";
}
} else {
if (locator.startsWith("xpath=")) {
locator = locator.substring(locator.indexOf('=', 1) + 1); // depends on control dependency: [if], data = [none]
}
if (HtmlElementUtils.locateElements(locator + "/tbody").size() > 0) {
xPathBase = locator + "/tbody/"; // depends on control dependency: [if], data = [none]
} else {
xPathBase = locator + "//";
}
}
} else {
throw new NoSuchElementException("Table" + this.getLocator() + " does not exist."); // depends on control dependency: [if], data = [none]
}
return xPathBase; // depends on control dependency: [if], data = [none]
} }
|
public class class_name {
public Parcelable onSaveInstanceState() {
if (isInEditMode) return null;
Parcelable superState = delegateCallback.superOnSaveInstanceState();
if (keepPresenterDuringScreenOrientationChange) {
return new MosbySavedState(superState, mosbyViewId);
} else {
return superState;
}
} }
|
public class class_name {
public Parcelable onSaveInstanceState() {
if (isInEditMode) return null;
Parcelable superState = delegateCallback.superOnSaveInstanceState();
if (keepPresenterDuringScreenOrientationChange) {
return new MosbySavedState(superState, mosbyViewId); // depends on control dependency: [if], data = [none]
} else {
return superState; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public String getName() {
String name = null;
if (webAppConfig!=null) {
name=webAppConfig.getModuleName();
}
return name;
} }
|
public class class_name {
@Override
public String getName() {
String name = null;
if (webAppConfig!=null) {
name=webAppConfig.getModuleName(); // depends on control dependency: [if], data = [none]
}
return name;
} }
|
public class class_name {
private int readCRS(JsonParser jp) throws IOException, SQLException {
int srid = 0;
jp.nextToken(); //START_OBJECT {
jp.nextToken();// crs type
jp.nextToken(); // crs name
String firstField = jp.getText();
if(firstField.equalsIgnoreCase(GeoJsonField.NAME)){
jp.nextToken(); // crs properties
jp.nextToken(); //START_OBJECT {
jp.nextToken(); // crs name
jp.nextToken(); // crs value
String crsURI = jp.getText();
String[] split = crsURI.toLowerCase().split(GeoJsonField.CRS_URN_EPSG);
if (split != null) {
srid = Integer.valueOf(split[1]);
} else {
log.warn("The CRS URN " + crsURI + " is not supported.");
}
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //Go to features
}
else if (firstField.equalsIgnoreCase(GeoJsonField.LINK)) {
log.warn("Linked CRS is not supported.");
jp.nextToken();
jp.nextToken();
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //Go to features
}
else{
throw new SQLException("Malformed GeoJSON CRS element.");
}
return srid;
} }
|
public class class_name {
private int readCRS(JsonParser jp) throws IOException, SQLException {
int srid = 0;
jp.nextToken(); //START_OBJECT {
jp.nextToken();// crs type
jp.nextToken(); // crs name
String firstField = jp.getText();
if(firstField.equalsIgnoreCase(GeoJsonField.NAME)){
jp.nextToken(); // crs properties
jp.nextToken(); //START_OBJECT {
jp.nextToken(); // crs name
jp.nextToken(); // crs value
String crsURI = jp.getText();
String[] split = crsURI.toLowerCase().split(GeoJsonField.CRS_URN_EPSG);
if (split != null) {
srid = Integer.valueOf(split[1]); // depends on control dependency: [if], data = [(split]
} else {
log.warn("The CRS URN " + crsURI + " is not supported."); // depends on control dependency: [if], data = [none]
}
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //Go to features
}
else if (firstField.equalsIgnoreCase(GeoJsonField.LINK)) {
log.warn("Linked CRS is not supported.");
jp.nextToken();
jp.nextToken();
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //END_OBJECT }
jp.nextToken(); //Go to features
}
else{
throw new SQLException("Malformed GeoJSON CRS element.");
}
return srid;
} }
|
public class class_name {
public String getInformationURL(final String locale) {
if (this.uiInfo != null) {
val informationUrl = getLocalizedValues(locale, this.uiInfo.getInformationURLs());
return informationUrl != null ? informationUrl : super.getInformationURL();
}
return super.getInformationURL();
} }
|
public class class_name {
public String getInformationURL(final String locale) {
if (this.uiInfo != null) {
val informationUrl = getLocalizedValues(locale, this.uiInfo.getInformationURLs());
return informationUrl != null ? informationUrl : super.getInformationURL(); // depends on control dependency: [if], data = [none]
}
return super.getInformationURL();
} }
|
public class class_name {
public void zmatrixChainToCartesian(IAtomContainer molecule, boolean flagBranched) {
Point3d result = null;
for (int index = 0; index < distances.length; index++) {
if (index == 0) {
result = new Point3d(0d, 0d, 0d);
} else if (index == 1) {
result = new Point3d(distances[1], 0d, 0d);
} else if (index == 2) {
result = new Point3d(-Math.cos((angles[2] / 180) * Math.PI) * distances[2] + distances[1],
Math.sin((angles[2] / 180) * Math.PI) * distances[2], 0d);
} else {
Vector3d cd = new Vector3d();
cd.sub(molecule.getAtom(thirdAtoms[index]).getPoint3d(), molecule.getAtom(secondAtoms[index])
.getPoint3d());
Vector3d bc = new Vector3d();
bc.sub(molecule.getAtom(secondAtoms[index]).getPoint3d(), molecule.getAtom(firstAtoms[index - 3])
.getPoint3d());
Vector3d n1 = new Vector3d();
n1.cross(cd, bc);
n1.normalize();
Vector3d n2 = null;
if (index == 3 && flagBranched) {
n2 = AtomTetrahedralLigandPlacer3D.rotate(n1, bc, DIHEDRAL_BRANCHED_CHAIN);
} else {
n2 = AtomTetrahedralLigandPlacer3D.rotate(n1, bc, dihedrals[index]);
}
n2.normalize();
Vector3d ba = new Vector3d();
if (index == 3 && flagBranched) {
ba = AtomTetrahedralLigandPlacer3D.rotate(cd, n2, (-angles[index] / 180) * Math.PI);
ba = AtomTetrahedralLigandPlacer3D.rotate(ba, cd, (-angles[index] / 180) * Math.PI);
} else {
ba = AtomTetrahedralLigandPlacer3D.rotate(cd, n2, (-angles[index] / 180) * Math.PI);
}
ba.normalize();
Vector3d ban = new Vector3d(ba);
ban.scale(distances[index]);
result = new Point3d();
result.add(molecule.getAtom(firstAtoms[index - 1]).getPoint3d(), ban);
}
IAtom atom = molecule.getAtom(firstAtoms[index]);
if ((atom.getPoint3d() == null || !atom.getFlag(CDKConstants.ISPLACED))
&& !atom.getFlag(CDKConstants.ISINRING) && isHeavyAtom(atom)) {
atom.setPoint3d(result);
atom.setFlag(CDKConstants.ISPLACED, true);
}
}
} }
|
public class class_name {
public void zmatrixChainToCartesian(IAtomContainer molecule, boolean flagBranched) {
Point3d result = null;
for (int index = 0; index < distances.length; index++) {
if (index == 0) {
result = new Point3d(0d, 0d, 0d); // depends on control dependency: [if], data = [none]
} else if (index == 1) {
result = new Point3d(distances[1], 0d, 0d); // depends on control dependency: [if], data = [none]
} else if (index == 2) {
result = new Point3d(-Math.cos((angles[2] / 180) * Math.PI) * distances[2] + distances[1],
Math.sin((angles[2] / 180) * Math.PI) * distances[2], 0d); // depends on control dependency: [if], data = [none]
} else {
Vector3d cd = new Vector3d();
cd.sub(molecule.getAtom(thirdAtoms[index]).getPoint3d(), molecule.getAtom(secondAtoms[index])
.getPoint3d()); // depends on control dependency: [if], data = [none]
Vector3d bc = new Vector3d();
bc.sub(molecule.getAtom(secondAtoms[index]).getPoint3d(), molecule.getAtom(firstAtoms[index - 3])
.getPoint3d()); // depends on control dependency: [if], data = [none]
Vector3d n1 = new Vector3d();
n1.cross(cd, bc); // depends on control dependency: [if], data = [none]
n1.normalize(); // depends on control dependency: [if], data = [none]
Vector3d n2 = null;
if (index == 3 && flagBranched) {
n2 = AtomTetrahedralLigandPlacer3D.rotate(n1, bc, DIHEDRAL_BRANCHED_CHAIN); // depends on control dependency: [if], data = [none]
} else {
n2 = AtomTetrahedralLigandPlacer3D.rotate(n1, bc, dihedrals[index]); // depends on control dependency: [if], data = [none]
}
n2.normalize(); // depends on control dependency: [if], data = [none]
Vector3d ba = new Vector3d();
if (index == 3 && flagBranched) {
ba = AtomTetrahedralLigandPlacer3D.rotate(cd, n2, (-angles[index] / 180) * Math.PI); // depends on control dependency: [if], data = [none]
ba = AtomTetrahedralLigandPlacer3D.rotate(ba, cd, (-angles[index] / 180) * Math.PI); // depends on control dependency: [if], data = [none]
} else {
ba = AtomTetrahedralLigandPlacer3D.rotate(cd, n2, (-angles[index] / 180) * Math.PI); // depends on control dependency: [if], data = [none]
}
ba.normalize(); // depends on control dependency: [if], data = [none]
Vector3d ban = new Vector3d(ba);
ban.scale(distances[index]); // depends on control dependency: [if], data = [none]
result = new Point3d(); // depends on control dependency: [if], data = [none]
result.add(molecule.getAtom(firstAtoms[index - 1]).getPoint3d(), ban); // depends on control dependency: [if], data = [none]
}
IAtom atom = molecule.getAtom(firstAtoms[index]);
if ((atom.getPoint3d() == null || !atom.getFlag(CDKConstants.ISPLACED))
&& !atom.getFlag(CDKConstants.ISINRING) && isHeavyAtom(atom)) {
atom.setPoint3d(result); // depends on control dependency: [if], data = [none]
atom.setFlag(CDKConstants.ISPLACED, true); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public void marshall(GetCampaignActivitiesRequest getCampaignActivitiesRequest, ProtocolMarshaller protocolMarshaller) {
if (getCampaignActivitiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getCampaignActivitiesRequest.getApplicationId(), APPLICATIONID_BINDING);
protocolMarshaller.marshall(getCampaignActivitiesRequest.getCampaignId(), CAMPAIGNID_BINDING);
protocolMarshaller.marshall(getCampaignActivitiesRequest.getPageSize(), PAGESIZE_BINDING);
protocolMarshaller.marshall(getCampaignActivitiesRequest.getToken(), TOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(GetCampaignActivitiesRequest getCampaignActivitiesRequest, ProtocolMarshaller protocolMarshaller) {
if (getCampaignActivitiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getCampaignActivitiesRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCampaignActivitiesRequest.getCampaignId(), CAMPAIGNID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCampaignActivitiesRequest.getPageSize(), PAGESIZE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCampaignActivitiesRequest.getToken(), TOKEN_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 {
@Subscribe
public void onSuiteResult(AggregatedSuiteResultEvent e) {
// Calculate summaries.
summaryListener.suiteSummary(e);
Description suiteDescription = e.getDescription();
String displayName = suiteDescription.getDisplayName();
if (displayName.trim().isEmpty()) {
junit4.log("Could not emit XML report for suite (null description).",
Project.MSG_WARN);
return;
}
if (!suiteCounts.containsKey(displayName)) {
suiteCounts.put(displayName, 1);
} else {
int newCount = suiteCounts.get(displayName) + 1;
suiteCounts.put(displayName, newCount);
if (!ignoreDuplicateSuites && newCount == 2) {
junit4.log("Duplicate suite name used with XML reports: "
+ displayName + ". This may confuse tools that process XML reports. "
+ "Set 'ignoreDuplicateSuites' to true to skip this message.", Project.MSG_WARN);
}
displayName = displayName + "-" + newCount;
}
try {
File reportFile = new File(dir, "TEST-" + displayName + ".xml");
RegistryMatcher rm = new RegistryMatcher();
rm.bind(String.class, new XmlStringTransformer());
Persister persister = new Persister(rm);
persister.write(buildModel(e), reportFile);
} catch (Exception x) {
junit4.log("Could not serialize report for suite "
+ displayName + ": " + x.toString(), x, Project.MSG_WARN);
}
} }
|
public class class_name {
@Subscribe
public void onSuiteResult(AggregatedSuiteResultEvent e) {
// Calculate summaries.
summaryListener.suiteSummary(e);
Description suiteDescription = e.getDescription();
String displayName = suiteDescription.getDisplayName();
if (displayName.trim().isEmpty()) {
junit4.log("Could not emit XML report for suite (null description).",
Project.MSG_WARN); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (!suiteCounts.containsKey(displayName)) {
suiteCounts.put(displayName, 1); // depends on control dependency: [if], data = [none]
} else {
int newCount = suiteCounts.get(displayName) + 1;
suiteCounts.put(displayName, newCount); // depends on control dependency: [if], data = [none]
if (!ignoreDuplicateSuites && newCount == 2) {
junit4.log("Duplicate suite name used with XML reports: "
+ displayName + ". This may confuse tools that process XML reports. "
+ "Set 'ignoreDuplicateSuites' to true to skip this message.", Project.MSG_WARN); // depends on control dependency: [if], data = [none]
}
displayName = displayName + "-" + newCount; // depends on control dependency: [if], data = [none]
}
try {
File reportFile = new File(dir, "TEST-" + displayName + ".xml");
RegistryMatcher rm = new RegistryMatcher();
rm.bind(String.class, new XmlStringTransformer()); // depends on control dependency: [try], data = [none]
Persister persister = new Persister(rm);
persister.write(buildModel(e), reportFile); // depends on control dependency: [try], data = [none]
} catch (Exception x) {
junit4.log("Could not serialize report for suite "
+ displayName + ": " + x.toString(), x, Project.MSG_WARN);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public synchronized T get()
{
T val;
synchronized(this)
{
if(valRef==null || (val = valRef.get())==null)
{
val = make();
valRef = new WeakReference<T>(val);
}
}
return val;
} }
|
public class class_name {
@Override
public synchronized T get()
{
T val;
synchronized(this)
{
if(valRef==null || (val = valRef.get())==null)
{
val = make(); // depends on control dependency: [if], data = [none]
valRef = new WeakReference<T>(val); // depends on control dependency: [if], data = [none]
}
}
return val;
} }
|
public class class_name {
public static double blackScholesGeneralizedOptionVega(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(forward / optionStrike) + (0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double vega = payoffUnit * NormalDistribution.density(dPlus) * forward * Math.sqrt(optionMaturity);
return vega;
}
} }
|
public class class_name {
public static double blackScholesGeneralizedOptionVega(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0; // depends on control dependency: [if], data = [none]
}
else
{
// Calculate vega
double dPlus = (Math.log(forward / optionStrike) + (0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double vega = payoffUnit * NormalDistribution.density(dPlus) * forward * Math.sqrt(optionMaturity);
return vega; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void removePropertyChangeListener(
String propertyName,
PropertyChangeListener listener) {
if (listener == null || propertyName == null) {
return;
}
listener = this.map.extract(listener);
if (listener != null) {
this.map.remove(propertyName, listener);
}
} }
|
public class class_name {
public void removePropertyChangeListener(
String propertyName,
PropertyChangeListener listener) {
if (listener == null || propertyName == null) {
return; // depends on control dependency: [if], data = [none]
}
listener = this.map.extract(listener);
if (listener != null) {
this.map.remove(propertyName, listener); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
BitSet toEdgeVector(final int[] path) {
final BitSet incidence = new BitSet(edges.size());
int len = path.length - 1;
for (int i = 0; i < len; i++) {
incidence.set(indexOfEdge(path[i], path[i + 1]));
}
return incidence;
} }
|
public class class_name {
BitSet toEdgeVector(final int[] path) {
final BitSet incidence = new BitSet(edges.size());
int len = path.length - 1;
for (int i = 0; i < len; i++) {
incidence.set(indexOfEdge(path[i], path[i + 1])); // depends on control dependency: [for], data = [i]
}
return incidence;
} }
|
public class class_name {
public String removeProperty(final String propertyName) throws DOMException {
if (null == propertyName) {
return "";
}
for (int i = 0; i < properties_.size(); i++) {
final Property p = properties_.get(i);
if (p != null && propertyName.equalsIgnoreCase(p.getName())) {
properties_.remove(i);
if (p.getValue() == null) {
return "";
}
return p.getValue().toString();
}
}
return "";
} }
|
public class class_name {
public String removeProperty(final String propertyName) throws DOMException {
if (null == propertyName) {
return "";
}
for (int i = 0; i < properties_.size(); i++) {
final Property p = properties_.get(i);
if (p != null && propertyName.equalsIgnoreCase(p.getName())) {
properties_.remove(i);
if (p.getValue() == null) {
return ""; // depends on control dependency: [if], data = [none]
}
return p.getValue().toString();
}
}
return "";
} }
|
public class class_name {
public void putDefaults(Map map) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
if (!containsKey(key)) {
put(key, entry.getValue());
}
}
} }
|
public class class_name {
public void putDefaults(Map map) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
if (!containsKey(key)) {
put(key, entry.getValue()); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@SuppressWarnings("static-method")
protected int getIssueAdornment(XtendMember element) {
final ICompositeNode node = NodeModelUtils.getNode(element);
if (node == null) {
return 0;
}
// Error markers are more important than warning markers.
// Order of checks:
// - parser error (from the resource) or semantic error (from Diagnostician)
// - parser warning or semantic warning
final Resource resource = element.eResource();
if (!resource.getURI().isArchive()) {
if (hasParserIssue(node, resource.getErrors())) {
return JavaElementImageDescriptor.ERROR;
}
final Diagnostic diagnostic = Diagnostician.INSTANCE.validate(element);
switch (diagnostic.getSeverity()) {
case Diagnostic.ERROR:
return JavaElementImageDescriptor.ERROR;
case Diagnostic.WARNING:
return JavaElementImageDescriptor.WARNING;
default:
}
if (hasParserIssue(node, resource.getWarnings())) {
return JavaElementImageDescriptor.WARNING;
}
}
return 0;
} }
|
public class class_name {
@SuppressWarnings("static-method")
protected int getIssueAdornment(XtendMember element) {
final ICompositeNode node = NodeModelUtils.getNode(element);
if (node == null) {
return 0; // depends on control dependency: [if], data = [none]
}
// Error markers are more important than warning markers.
// Order of checks:
// - parser error (from the resource) or semantic error (from Diagnostician)
// - parser warning or semantic warning
final Resource resource = element.eResource();
if (!resource.getURI().isArchive()) {
if (hasParserIssue(node, resource.getErrors())) {
return JavaElementImageDescriptor.ERROR; // depends on control dependency: [if], data = [none]
}
final Diagnostic diagnostic = Diagnostician.INSTANCE.validate(element);
switch (diagnostic.getSeverity()) {
case Diagnostic.ERROR:
return JavaElementImageDescriptor.ERROR; // depends on control dependency: [if], data = [none]
case Diagnostic.WARNING:
return JavaElementImageDescriptor.WARNING; // depends on control dependency: [if], data = [none]
default:
}
if (hasParserIssue(node, resource.getWarnings())) {
return JavaElementImageDescriptor.WARNING; // depends on control dependency: [if], data = [none]
}
}
return 0;
} }
|
public class class_name {
protected boolean validate(String text)
{
try
{
String[] strings = text.split(",");
for (int i = 0; i < strings.length; i++)
{
Integer.parseInt(strings[i].trim());
}
return true;
}
catch (NumberFormatException e)
{
return false;
}
} }
|
public class class_name {
protected boolean validate(String text)
{
try
{
String[] strings = text.split(",");
for (int i = 0; i < strings.length; i++)
{
Integer.parseInt(strings[i].trim()); // depends on control dependency: [for], data = [i]
}
return true; // depends on control dependency: [try], data = [none]
}
catch (NumberFormatException e)
{
return false;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static CmsMacroResolver getMacroResolverForProperties(
final CmsObject cms,
final I_CmsXmlContentHandler contentHandler,
final CmsXmlContent content,
final Function<String, String> stringtemplateSource,
final CmsResource containerPage) {
Locale locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(cms, content.getFile(), content);
final CmsGalleryNameMacroResolver resolver = new CmsGalleryNameMacroResolver(cms, content, locale) {
@SuppressWarnings("synthetic-access")
@Override
public String getMacroValue(String macro) {
if (macro.startsWith(PAGE_PROPERTY_PREFIX)) {
String remainder = macro.substring(PAGE_PROPERTY_PREFIX.length());
int secondColonPos = remainder.indexOf(":");
String defaultValue = "";
String propName = null;
if (secondColonPos >= 0) {
propName = remainder.substring(0, secondColonPos);
defaultValue = remainder.substring(secondColonPos + 1);
} else {
propName = remainder;
}
if (containerPage != null) {
try {
CmsProperty prop = cms.readPropertyObject(containerPage, propName, true);
String propValue = prop.getValue();
if ((propValue == null) || PROPERTY_EMPTY_MARKER.equals(propValue)) {
propValue = defaultValue;
}
return propValue;
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
return defaultValue;
}
}
}
return super.getMacroValue(macro);
}
};
resolver.setStringTemplateSource(stringtemplateSource);
Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
CmsMultiMessages messages = new CmsMultiMessages(wpLocale);
messages.addMessages(OpenCms.getWorkplaceManager().getMessages(wpLocale));
messages.addMessages(content.getContentDefinition().getContentHandler().getMessages(wpLocale));
resolver.setCmsObject(cms);
resolver.setKeepEmptyMacros(true);
resolver.setMessages(messages);
return resolver;
} }
|
public class class_name {
public static CmsMacroResolver getMacroResolverForProperties(
final CmsObject cms,
final I_CmsXmlContentHandler contentHandler,
final CmsXmlContent content,
final Function<String, String> stringtemplateSource,
final CmsResource containerPage) {
Locale locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(cms, content.getFile(), content);
final CmsGalleryNameMacroResolver resolver = new CmsGalleryNameMacroResolver(cms, content, locale) {
@SuppressWarnings("synthetic-access")
@Override
public String getMacroValue(String macro) {
if (macro.startsWith(PAGE_PROPERTY_PREFIX)) {
String remainder = macro.substring(PAGE_PROPERTY_PREFIX.length());
int secondColonPos = remainder.indexOf(":");
String defaultValue = "";
String propName = null;
if (secondColonPos >= 0) {
propName = remainder.substring(0, secondColonPos); // depends on control dependency: [if], data = [none]
defaultValue = remainder.substring(secondColonPos + 1); // depends on control dependency: [if], data = [(secondColonPos]
} else {
propName = remainder; // depends on control dependency: [if], data = [none]
}
if (containerPage != null) {
try {
CmsProperty prop = cms.readPropertyObject(containerPage, propName, true);
String propValue = prop.getValue();
if ((propValue == null) || PROPERTY_EMPTY_MARKER.equals(propValue)) {
propValue = defaultValue; // depends on control dependency: [if], data = [none]
}
return propValue; // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
return defaultValue;
} // depends on control dependency: [catch], data = [none]
}
}
return super.getMacroValue(macro);
}
};
resolver.setStringTemplateSource(stringtemplateSource);
Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
CmsMultiMessages messages = new CmsMultiMessages(wpLocale);
messages.addMessages(OpenCms.getWorkplaceManager().getMessages(wpLocale));
messages.addMessages(content.getContentDefinition().getContentHandler().getMessages(wpLocale));
resolver.setCmsObject(cms);
resolver.setKeepEmptyMacros(true);
resolver.setMessages(messages);
return resolver;
} }
|
public class class_name {
@Override
public synchronized UserTransaction getUserTransaction() {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getUserTransaction");
// Calling getUserTransaction is not allowed from setMessageDrivenContext
// per the EJB Specification. d159152
if ((state == PRE_CREATE)) {
IllegalStateException ise;
ise = new IllegalStateException("MessageDrivenBean: getUserTransaction " +
"not allowed from state = " +
getStateName(state));
if (isTraceOn && tc.isDebugEnabled())
Tr.exit(tc, "getUserTransaction", ise);
throw ise;
}
UserTransaction userTransactionWrapper = UserTransactionWrapper.INSTANCE; // d631349
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "getUserTransaction", userTransactionWrapper);
return userTransactionWrapper;
} }
|
public class class_name {
@Override
public synchronized UserTransaction getUserTransaction() {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getUserTransaction");
// Calling getUserTransaction is not allowed from setMessageDrivenContext
// per the EJB Specification. d159152
if ((state == PRE_CREATE)) {
IllegalStateException ise;
ise = new IllegalStateException("MessageDrivenBean: getUserTransaction " +
"not allowed from state = " +
getStateName(state)); // depends on control dependency: [if], data = [none]
if (isTraceOn && tc.isDebugEnabled())
Tr.exit(tc, "getUserTransaction", ise);
throw ise;
}
UserTransaction userTransactionWrapper = UserTransactionWrapper.INSTANCE; // d631349
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "getUserTransaction", userTransactionWrapper);
return userTransactionWrapper;
} }
|
public class class_name {
@Override
public String getLocalName() {
try {
collaborator.preInvoke(componentMetaData);
return request.getLocalName();
} finally {
collaborator.postInvoke();
}
} }
|
public class class_name {
@Override
public String getLocalName() {
try {
collaborator.preInvoke(componentMetaData); // depends on control dependency: [try], data = [none]
return request.getLocalName(); // depends on control dependency: [try], data = [none]
} finally {
collaborator.postInvoke();
}
} }
|
public class class_name {
public synchronized Exception getException(Conversation conversation)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getException", conversation);
checkReleased();
// The top level exception we want to return at the end
Exception topException = null;
if (receivedBuffer != null)
{
// Read the number of exceptions returned
short numberOfExceptions = getShort();
// A handle on the last exception in the chain that new ones should link to
Exception link = null;
for (int x = 0; x < numberOfExceptions; x++)
{
short exceptionId = getShort();
Exception e = parseSingleException(exceptionId);
// Is this the first exception? If so, save it away in its proper place and save the
// handle of the exception to place the link the next time (also the top level exception)
if (topException == null)
{
topException = e;
link = topException;
}
// Otherwise, link the exception we just got with the last one we just got
else
{
link.initCause(e);
link = e;
}
}
}
final HandshakeProperties handshakeProperties = conversation.getHandshakeProperties();
if ((handshakeProperties != null) &&
((CATHandshakeProperties)handshakeProperties).isFapLevelKnown())
{
// If we don't know hte FAP level, at this point in time, then assume a pre-FAP 9
// version. This could happen if an exception is thrown during handshaking.
final int fapLevel = ((CATHandshakeProperties)handshakeProperties).getFapLevel();
if (fapLevel >= JFapChannelConstants.FAP_VERSION_9)
{
// At FAP version 9 or greater, exceptions are encoded to include a reason
// and inserts. Retrieve these.
int reason = getInt();
String[] inserts = Reasonable.DEFAULT_INSERTS;
int numberOfInserts = getShort();
if (numberOfInserts > 0)
{
inserts = new String[numberOfInserts];
for (int i=0; i < numberOfInserts; ++i)
{
inserts[i] = getString();
}
}
// Stuff reason and inserts back into the chain of exceptions
setReasonableInformation(topException, reason, inserts);
}
}
if (TraceComponent.isAnyTracingEnabled() && topException != null) {
CommsLightTrace.traceException(tc, topException);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getException", topException);
return topException;
} }
|
public class class_name {
public synchronized Exception getException(Conversation conversation)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getException", conversation);
checkReleased();
// The top level exception we want to return at the end
Exception topException = null;
if (receivedBuffer != null)
{
// Read the number of exceptions returned
short numberOfExceptions = getShort();
// A handle on the last exception in the chain that new ones should link to
Exception link = null;
for (int x = 0; x < numberOfExceptions; x++)
{
short exceptionId = getShort();
Exception e = parseSingleException(exceptionId);
// Is this the first exception? If so, save it away in its proper place and save the
// handle of the exception to place the link the next time (also the top level exception)
if (topException == null)
{
topException = e; // depends on control dependency: [if], data = [none]
link = topException; // depends on control dependency: [if], data = [none]
}
// Otherwise, link the exception we just got with the last one we just got
else
{
link.initCause(e); // depends on control dependency: [if], data = [none]
link = e; // depends on control dependency: [if], data = [none]
}
}
}
final HandshakeProperties handshakeProperties = conversation.getHandshakeProperties();
if ((handshakeProperties != null) &&
((CATHandshakeProperties)handshakeProperties).isFapLevelKnown())
{
// If we don't know hte FAP level, at this point in time, then assume a pre-FAP 9
// version. This could happen if an exception is thrown during handshaking.
final int fapLevel = ((CATHandshakeProperties)handshakeProperties).getFapLevel();
if (fapLevel >= JFapChannelConstants.FAP_VERSION_9)
{
// At FAP version 9 or greater, exceptions are encoded to include a reason
// and inserts. Retrieve these.
int reason = getInt();
String[] inserts = Reasonable.DEFAULT_INSERTS;
int numberOfInserts = getShort();
if (numberOfInserts > 0)
{
inserts = new String[numberOfInserts]; // depends on control dependency: [if], data = [none]
for (int i=0; i < numberOfInserts; ++i)
{
inserts[i] = getString(); // depends on control dependency: [for], data = [i]
}
}
// Stuff reason and inserts back into the chain of exceptions
setReasonableInformation(topException, reason, inserts); // depends on control dependency: [if], data = [none]
}
}
if (TraceComponent.isAnyTracingEnabled() && topException != null) {
CommsLightTrace.traceException(tc, topException); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getException", topException);
return topException;
} }
|
public class class_name {
public static int searchLast(long[] longArray, long value, int occurrence) {
if(occurrence <= 0 || occurrence > longArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = longArray.length-1; i >=0; i--) {
if(longArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} }
|
public class class_name {
public static int searchLast(long[] longArray, long value, int occurrence) {
if(occurrence <= 0 || occurrence > longArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = longArray.length-1; i >=0; i--) {
if(longArray[i] == value) {
valuesSeen++; // depends on control dependency: [if], data = [none]
if(valuesSeen == occurrence) {
return i; // depends on control dependency: [if], data = [none]
}
}
}
return -1;
} }
|
public class class_name {
public String asString(final String format) {
try {
return format(EnglishEnums.valueOf(MapFormat.class, format), new StringBuilder()).toString();
} catch (final IllegalArgumentException ex) {
return asString();
}
} }
|
public class class_name {
public String asString(final String format) {
try {
return format(EnglishEnums.valueOf(MapFormat.class, format), new StringBuilder()).toString(); // depends on control dependency: [try], data = [none]
} catch (final IllegalArgumentException ex) {
return asString();
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static <P extends Enum<P>> boolean hasEnum(final JSONObject json,
final String key, final Class<? extends Enum> enumType) {
if (hasInstanceOf(json, key, enumType)) {
return true;
}
final Object o = json.opt(key);
if (o == null || o == JSONObject.NULL) {
return false;
}
if (o instanceof String) {
final String s = (String) o;
try {
Enum.valueOf(enumType, s);
return true;
} catch (IllegalArgumentException e) {
Log.e(Log.SUBSYSTEM.JSON, TAG, e,
"hasEnum(): failed to coerce value at '%s' to %s (%s)",
key, enumType.getSimpleName(), o);
}
}
return false;
} }
|
public class class_name {
public static <P extends Enum<P>> boolean hasEnum(final JSONObject json,
final String key, final Class<? extends Enum> enumType) {
if (hasInstanceOf(json, key, enumType)) {
return true; // depends on control dependency: [if], data = [none]
}
final Object o = json.opt(key);
if (o == null || o == JSONObject.NULL) {
return false; // depends on control dependency: [if], data = [none]
}
if (o instanceof String) {
final String s = (String) o;
try {
Enum.valueOf(enumType, s);
return true; // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
Log.e(Log.SUBSYSTEM.JSON, TAG, e,
"hasEnum(): failed to coerce value at '%s' to %s (%s)",
key, enumType.getSimpleName(), o);
} // depends on control dependency: [catch], data = [none]
}
return false;
} }
|
public class class_name {
@RequestMapping(path = "/{customerId}", method = RequestMethod.DELETE)
public ResponseEntity removeCustomer(@PathVariable("customerId") Long customerId){
boolean succeed = customerService.removeCustomer(customerId);
if(succeed){
return new ResponseEntity(HttpStatus.OK);
}else{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
} }
|
public class class_name {
@RequestMapping(path = "/{customerId}", method = RequestMethod.DELETE)
public ResponseEntity removeCustomer(@PathVariable("customerId") Long customerId){
boolean succeed = customerService.removeCustomer(customerId);
if(succeed){
return new ResponseEntity(HttpStatus.OK); // depends on control dependency: [if], data = [none]
}else{
return new ResponseEntity(HttpStatus.NOT_FOUND); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private static String[] readArgsFile(String argsFile) throws IOException {
final ArrayList<String> lines = new ArrayList<String>();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(argsFile), "UTF-8"));
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty() && !line.startsWith("#")) {
lines.add(line);
}
}
} finally {
reader.close();
}
return lines.toArray(new String [lines.size()]);
} }
|
public class class_name {
private static String[] readArgsFile(String argsFile) throws IOException {
final ArrayList<String> lines = new ArrayList<String>();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(argsFile), "UTF-8"));
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // depends on control dependency: [while], data = [none]
if (!line.isEmpty() && !line.startsWith("#")) {
lines.add(line); // depends on control dependency: [if], data = [none]
}
}
} finally {
reader.close();
}
return lines.toArray(new String [lines.size()]);
} }
|
public class class_name {
private void executeStatement(String statement) throws SQLException {
Statement stmt = null;
try {
stmt = m_con.createStatement();
stmt.execute(statement);
} finally {
if (stmt != null) {
stmt.close();
}
}
} }
|
public class class_name {
private void executeStatement(String statement) throws SQLException {
Statement stmt = null;
try {
stmt = m_con.createStatement();
stmt.execute(statement);
} finally {
if (stmt != null) {
stmt.close(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private double[] multiScore(MultiStringWrapper ms,MultiStringWrapper mt)
{
if (ms.size() != mt.size()) {
throw new IllegalArgumentException("inputs have different numbers of fields");
}
int n = ms.size();
double scores[] = new double[n];
for (int i=0; i<n; i++) {
scores[i] = getDistance(i).score(ms.get(i), mt.get(i));
}
return scores;
} }
|
public class class_name {
private double[] multiScore(MultiStringWrapper ms,MultiStringWrapper mt)
{
if (ms.size() != mt.size()) {
throw new IllegalArgumentException("inputs have different numbers of fields");
}
int n = ms.size();
double scores[] = new double[n];
for (int i=0; i<n; i++) {
scores[i] = getDistance(i).score(ms.get(i), mt.get(i)); // depends on control dependency: [for], data = [i]
}
return scores;
} }
|
public class class_name {
static public FwdPassReturn activateHelper(final BaseLayer layer, final NeuralNetConfiguration conf,
final IActivation gateActivationFn, //Activation function for the gates - sigmoid or hard sigmoid (must be found in range 0 to 1)
INDArray input, final INDArray recurrentWeights, //Shape: [hiddenLayerSize,4*hiddenLayerSize+3]; order: [wI,wF,wO,wG,wFF,wOO,wGG]
final INDArray originalInputWeights, //Shape: [n^(L-1),4*hiddenLayerSize]; order: [wi,wf,wo,wg]
final INDArray biases, //Shape: [4,hiddenLayerSize]; order: [bi,bf,bo,bg]^T
final boolean training, final INDArray originalPrevOutputActivations,
final INDArray originalPrevMemCellState, boolean forBackprop, boolean forwards,
final String inputWeightKey, INDArray maskArray, //Input mask: should only be used with bidirectional RNNs + variable length
final boolean hasPeepholeConnections, //True for GravesLSTM, false for LSTM
final LSTMHelper helper, final CacheMode cacheMode, // cacheMode for layer calling this helper
final LayerWorkspaceMgr workspaceMgr
) {
//Mini-batch data format: for mini-batch size m, nIn inputs, and T time series length
//Data has shape [m,nIn,T]. Layer activations/output has shape [m,nHiddenUnits,T]
if (input == null || input.length() == 0)
throw new IllegalArgumentException("Invalid input: not set or 0 length");
INDArray inputWeights = originalInputWeights;
INDArray prevOutputActivations = originalPrevOutputActivations;
if(maskArray != null){
maskArray = maskArray.castTo(recurrentWeights.dataType());
}
boolean is2dInput = input.rank() < 3; //Edge case of T=1, may have shape [m,nIn], equiv. to [m,nIn,1]
input = input.castTo(inputWeights.dataType()); //No-op if already correct dtype
// FIXME
int timeSeriesLength = (int) (is2dInput ? 1 : input.size(2));
int hiddenLayerSize = (int) recurrentWeights.size(0);
int miniBatchSize = (int) input.size(0);
INDArray prevMemCellState;
if (originalPrevMemCellState == null) {
prevMemCellState = Nd4j.create(inputWeights.dataType(), new long[] {miniBatchSize, hiddenLayerSize}, 'f');
} else {
prevMemCellState = originalPrevMemCellState.dup('f');
}
INDArray recurrentWeightsIFOG = recurrentWeights.get(all(), interval(0, 4 * hiddenLayerSize)).dup('f');
INDArray wFFTranspose = null;
INDArray wOOTranspose = null;
INDArray wGGTranspose = null;
if (hasPeepholeConnections) {
wFFTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize, 4 * hiddenLayerSize + 1)).reshape(1, recurrentWeights.size(0));//current
wOOTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize + 1, 4 * hiddenLayerSize + 2)).reshape(1, recurrentWeights.size(0)); //current
wGGTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize + 2, 4 * hiddenLayerSize + 3)).reshape(1, recurrentWeights.size(0)); //previous
if (timeSeriesLength > 1 || forBackprop) {
wFFTranspose = Shape.toMmulCompatible(wFFTranspose);
wOOTranspose = Shape.toMmulCompatible(wOOTranspose);
wGGTranspose = Shape.toMmulCompatible(wGGTranspose);
}
}
//Allocate arrays for activations:
boolean sigmoidGates = gateActivationFn instanceof ActivationSigmoid;
IActivation afn = layer.layerConf().getActivationFn();
INDArray outputActivations = null;
FwdPassReturn toReturn = new FwdPassReturn();
if (forBackprop) {
toReturn.fwdPassOutputAsArrays = new INDArray[timeSeriesLength];
toReturn.memCellState = new INDArray[timeSeriesLength];
toReturn.memCellActivations = new INDArray[timeSeriesLength];
toReturn.iz = new INDArray[timeSeriesLength];
toReturn.ia = new INDArray[timeSeriesLength];
toReturn.fa = new INDArray[timeSeriesLength];
toReturn.oa = new INDArray[timeSeriesLength];
toReturn.ga = new INDArray[timeSeriesLength];
if (!sigmoidGates) {
toReturn.fz = new INDArray[timeSeriesLength];
toReturn.oz = new INDArray[timeSeriesLength];
toReturn.gz = new INDArray[timeSeriesLength];
}
if (training && cacheMode != CacheMode.NONE && workspaceMgr.hasConfiguration(ArrayType.FF_CACHE) && workspaceMgr.isWorkspaceOpen(ArrayType.FF_CACHE)) {
try (MemoryWorkspace wsB = workspaceMgr.notifyScopeBorrowed(ArrayType.FF_CACHE)) {
outputActivations = Nd4j.create(inputWeights.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together
toReturn.fwdPassOutput = outputActivations;
}
} else {
outputActivations = workspaceMgr.create(ArrayType.ACTIVATIONS, input.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together
toReturn.fwdPassOutput = outputActivations;
}
} else {
outputActivations = workspaceMgr.create(ArrayType.ACTIVATIONS, input.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together
toReturn.fwdPassOutput = outputActivations;
}
//Level1 l1BLAS = Nd4j.getBlasWrapper().level1();
//Input validation: check input data matches nIn
if (input.size(1) != inputWeights.size(0)) {
throw new DL4JInvalidInputException("Received input with size(1) = " + input.size(1)
+ " (input array shape = " + Arrays.toString(input.shape())
+ "); input.size(1) must match layer nIn size (nIn = " + inputWeights.size(0) + ")");
}
//Input validation: check that if past state is provided, that it has same
//These can be different if user forgets to call rnnClearPreviousState() between calls of rnnTimeStep
if (prevOutputActivations != null && prevOutputActivations.size(0) != input.size(0)) {
throw new DL4JInvalidInputException("Previous activations (stored state) number of examples = "
+ prevOutputActivations.size(0) + " but input array number of examples = " + input.size(0)
+ ". Possible cause: using rnnTimeStep() without calling"
+ " rnnClearPreviousState() between different sequences?");
}
//initialize prevOutputActivations to zeroes
if (prevOutputActivations == null) {
prevOutputActivations = Nd4j.zeros(input.dataType(), new long[] {miniBatchSize, hiddenLayerSize});
}
if (helper != null) {
FwdPassReturn ret = helper.activate(layer, conf, gateActivationFn, input, recurrentWeights, inputWeights,
biases, training, prevOutputActivations, prevMemCellState, forBackprop, forwards,
inputWeightKey, maskArray, hasPeepholeConnections, workspaceMgr);
if (ret != null) {
return ret;
}
}
for (int iTimeIndex = 0; iTimeIndex < timeSeriesLength; iTimeIndex++) {
try(MemoryWorkspace ws = workspaceMgr.notifyScopeEntered(ArrayType.RNN_FF_LOOP_WORKING_MEM)) {
int time = iTimeIndex;
if (!forwards) {
time = timeSeriesLength - iTimeIndex - 1;
}
INDArray miniBatchData = (is2dInput ? input : input.tensorAlongDimension(time, 1, 0)); //[Expected shape: [m,nIn]. Also deals with edge case of T=1, with 'time series' data of shape [m,nIn], equiv. to [m,nIn,1]
miniBatchData = Shape.toMmulCompatible(miniBatchData);
// if we're using cache here - let's create ifogActivations within cache workspace, so all views from this array will be valid in cache
cacheEnter(training, cacheMode, workspaceMgr);
//Calculate activations for: network input + forget, output, input modulation gates. Next 3 lines are first part of those
INDArray ifogActivations = miniBatchData.mmul(inputWeights); //Shape: [miniBatch,4*layerSize]
cacheExit(training, cacheMode, workspaceMgr);
Nd4j.gemm(prevOutputActivations, recurrentWeightsIFOG, ifogActivations, false, false, 1.0, 1.0);
ifogActivations.addiRowVector(biases);
INDArray inputActivations =
ifogActivations.get(all(), interval(0, hiddenLayerSize));
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.iz[time] = inputActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.iz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, inputActivations, 'f');
}
}
layer.layerConf().getActivationFn().getActivation(inputActivations, training);
if (forBackprop){
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.ia[time] = inputActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.ia[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, inputActivations);
}
}
INDArray forgetGateActivations = ifogActivations.get(all(),
interval(hiddenLayerSize, 2 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWFF = prevMemCellState.dup('f').muliRowVector(wFFTranspose);
forgetGateActivations.addi(pmcellWFF);
}
//Above line: treats matrix as a vector. Can only do this because we're sure both pwcelWFF and forgetGateACtivations are f order, offset 0 and have same strides
if (forBackprop && !sigmoidGates) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.fz[time] = forgetGateActivations.dup('f'); //Forget gate pre-out (z)
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.fz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, forgetGateActivations, 'f'); //Forget gate pre-out (z)
}
}
gateActivationFn.getActivation(forgetGateActivations, training);
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.fa[time] = forgetGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.fa[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, forgetGateActivations);
}
}
INDArray inputModGateActivations = ifogActivations.get(all(),
interval(3 * hiddenLayerSize, 4 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWGG = prevMemCellState.dup('f').muliRowVector(wGGTranspose);
inputModGateActivations.addi(pmcellWGG);
}
if (forBackprop && !sigmoidGates) {
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.gz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, inputModGateActivations, 'f'); //Input modulation gate pre-out (z)
cacheExit(training, cacheMode, workspaceMgr);
}
gateActivationFn.getActivation(inputModGateActivations, training);
if (forBackprop){
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.ga[time] = inputModGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.ga[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, inputModGateActivations);
}
}
//Memory cell state
INDArray currentMemoryCellState;
INDArray inputModMulInput;
if (forBackprop) {
cacheEnter(training, cacheMode, workspaceMgr);
currentMemoryCellState = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, prevMemCellState, 'f').muli(forgetGateActivations);
cacheExit(training, cacheMode, workspaceMgr);
// this variable isn't stored in cache
inputModMulInput = inputModGateActivations.dup('f').muli(inputActivations);
} else {
currentMemoryCellState = workspaceMgr.leverageTo(ArrayType.FF_WORKING_MEM, forgetGateActivations.muli(prevMemCellState)); //TODO optimize without the copy
inputModMulInput = inputModGateActivations.muli(inputActivations);
}
currentMemoryCellState.addi(inputModMulInput);
INDArray outputGateActivations = ifogActivations.get(all(),
interval(2 * hiddenLayerSize, 3 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWOO = currentMemoryCellState.dup('f').muliRowVector(wOOTranspose);
outputGateActivations.addi(pmcellWOO);
}
if (forBackprop && !sigmoidGates) {
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.oz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, outputGateActivations, 'f'); //Output gate activations
cacheExit(training, cacheMode, workspaceMgr);
}
gateActivationFn.getActivation(outputGateActivations, training);
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.oa[time] = outputGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.oa[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, outputGateActivations); //TODO optimize without leverage
}
}
////////////// same as with iFogActivations - if we use cache, let's create this array right there
cacheEnter(training, cacheMode, workspaceMgr);
//LSTM unit outputs:
INDArray currMemoryCellActivation ;
currMemoryCellActivation = workspaceMgr.dup(ArrayType.FF_WORKING_MEM, currentMemoryCellState, 'f');
currMemoryCellActivation = afn.getActivation(currMemoryCellActivation, training);
cacheExit(training, cacheMode, workspaceMgr);
///////////////////
INDArray currHiddenUnitActivations;
if (forBackprop) {
cacheEnter(training, cacheMode, workspaceMgr);
currHiddenUnitActivations = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, currMemoryCellActivation, 'f').muli(outputGateActivations); //Expected shape: [m,hiddenLayerSize]
cacheExit(training, cacheMode, workspaceMgr);
} else {
currHiddenUnitActivations = currMemoryCellActivation.muli(outputGateActivations); //Expected shape: [m,hiddenLayerSize]
}
if (maskArray != null) {
//Mask array is present: bidirectional RNN -> need to zero out these activations to avoid
// incorrectly using activations from masked time steps (i.e., want 0 initialization in both directions)
//We *also* need to apply this to the memory cells, as they are carried forward
//Mask array has shape [minibatch, timeSeriesLength] -> get column
INDArray timeStepMaskColumn = maskArray.getColumn(time, true);
currHiddenUnitActivations.muliColumnVector(timeStepMaskColumn);
currentMemoryCellState.muliColumnVector(timeStepMaskColumn);
}
currentMemoryCellState = workspaceMgr.leverageTo(ArrayType.FF_WORKING_MEM, currentMemoryCellState); //TODO optimize, without the leverage
if (forBackprop) {
toReturn.fwdPassOutputAsArrays[time] = currHiddenUnitActivations;
toReturn.memCellState[time] = currentMemoryCellState;
toReturn.memCellActivations[time] = currMemoryCellActivation;
if (training && cacheMode != CacheMode.NONE && workspaceMgr.hasConfiguration(ArrayType.FF_CACHE) && workspaceMgr.isWorkspaceOpen(ArrayType.FF_CACHE)) {
toReturn.memCellActivations[time] = workspaceMgr.leverageTo(ArrayType.FF_CACHE, toReturn.memCellActivations[time]);
toReturn.memCellState[time] = workspaceMgr.leverageTo(ArrayType.FF_CACHE, toReturn.memCellState[time]);
}
if (cacheMode != CacheMode.NONE) {
outputActivations.tensorAlongDimension(time, 1, 0).assign(currHiddenUnitActivations);
}
} else {
outputActivations.tensorAlongDimension(time, 1, 0).assign(currHiddenUnitActivations);
}
prevOutputActivations = currHiddenUnitActivations;
prevMemCellState = currentMemoryCellState;
// no need to dup here, if that's cache - it's already within Cache workspace
toReturn.lastAct = currHiddenUnitActivations;
// the same as above, already in cache
toReturn.lastMemCell = currentMemoryCellState;
}
}
//toReturn.leverageTo(ComputationGraph.workspaceExternal);
toReturn.prevAct = originalPrevOutputActivations;
toReturn.prevMemCell = originalPrevMemCellState;
return toReturn;
} }
|
public class class_name {
static public FwdPassReturn activateHelper(final BaseLayer layer, final NeuralNetConfiguration conf,
final IActivation gateActivationFn, //Activation function for the gates - sigmoid or hard sigmoid (must be found in range 0 to 1)
INDArray input, final INDArray recurrentWeights, //Shape: [hiddenLayerSize,4*hiddenLayerSize+3]; order: [wI,wF,wO,wG,wFF,wOO,wGG]
final INDArray originalInputWeights, //Shape: [n^(L-1),4*hiddenLayerSize]; order: [wi,wf,wo,wg]
final INDArray biases, //Shape: [4,hiddenLayerSize]; order: [bi,bf,bo,bg]^T
final boolean training, final INDArray originalPrevOutputActivations,
final INDArray originalPrevMemCellState, boolean forBackprop, boolean forwards,
final String inputWeightKey, INDArray maskArray, //Input mask: should only be used with bidirectional RNNs + variable length
final boolean hasPeepholeConnections, //True for GravesLSTM, false for LSTM
final LSTMHelper helper, final CacheMode cacheMode, // cacheMode for layer calling this helper
final LayerWorkspaceMgr workspaceMgr
) {
//Mini-batch data format: for mini-batch size m, nIn inputs, and T time series length
//Data has shape [m,nIn,T]. Layer activations/output has shape [m,nHiddenUnits,T]
if (input == null || input.length() == 0)
throw new IllegalArgumentException("Invalid input: not set or 0 length");
INDArray inputWeights = originalInputWeights;
INDArray prevOutputActivations = originalPrevOutputActivations;
if(maskArray != null){
maskArray = maskArray.castTo(recurrentWeights.dataType()); // depends on control dependency: [if], data = [none]
}
boolean is2dInput = input.rank() < 3; //Edge case of T=1, may have shape [m,nIn], equiv. to [m,nIn,1]
input = input.castTo(inputWeights.dataType()); //No-op if already correct dtype
// FIXME
int timeSeriesLength = (int) (is2dInput ? 1 : input.size(2));
int hiddenLayerSize = (int) recurrentWeights.size(0);
int miniBatchSize = (int) input.size(0);
INDArray prevMemCellState;
if (originalPrevMemCellState == null) {
prevMemCellState = Nd4j.create(inputWeights.dataType(), new long[] {miniBatchSize, hiddenLayerSize}, 'f'); // depends on control dependency: [if], data = [none]
} else {
prevMemCellState = originalPrevMemCellState.dup('f'); // depends on control dependency: [if], data = [none]
}
INDArray recurrentWeightsIFOG = recurrentWeights.get(all(), interval(0, 4 * hiddenLayerSize)).dup('f');
INDArray wFFTranspose = null;
INDArray wOOTranspose = null;
INDArray wGGTranspose = null;
if (hasPeepholeConnections) {
wFFTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize, 4 * hiddenLayerSize + 1)).reshape(1, recurrentWeights.size(0));//current // depends on control dependency: [if], data = [none]
wOOTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize + 1, 4 * hiddenLayerSize + 2)).reshape(1, recurrentWeights.size(0)); //current // depends on control dependency: [if], data = [none]
wGGTranspose = recurrentWeights.get(all(), interval(4 * hiddenLayerSize + 2, 4 * hiddenLayerSize + 3)).reshape(1, recurrentWeights.size(0)); //previous // depends on control dependency: [if], data = [none]
if (timeSeriesLength > 1 || forBackprop) {
wFFTranspose = Shape.toMmulCompatible(wFFTranspose); // depends on control dependency: [if], data = [none]
wOOTranspose = Shape.toMmulCompatible(wOOTranspose); // depends on control dependency: [if], data = [none]
wGGTranspose = Shape.toMmulCompatible(wGGTranspose); // depends on control dependency: [if], data = [none]
}
}
//Allocate arrays for activations:
boolean sigmoidGates = gateActivationFn instanceof ActivationSigmoid;
IActivation afn = layer.layerConf().getActivationFn();
INDArray outputActivations = null;
FwdPassReturn toReturn = new FwdPassReturn();
if (forBackprop) {
toReturn.fwdPassOutputAsArrays = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.memCellState = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.memCellActivations = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.iz = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.ia = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.fa = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.oa = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.ga = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
if (!sigmoidGates) {
toReturn.fz = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.oz = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
toReturn.gz = new INDArray[timeSeriesLength]; // depends on control dependency: [if], data = [none]
}
if (training && cacheMode != CacheMode.NONE && workspaceMgr.hasConfiguration(ArrayType.FF_CACHE) && workspaceMgr.isWorkspaceOpen(ArrayType.FF_CACHE)) {
try (MemoryWorkspace wsB = workspaceMgr.notifyScopeBorrowed(ArrayType.FF_CACHE)) {
outputActivations = Nd4j.create(inputWeights.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together
toReturn.fwdPassOutput = outputActivations; // depends on control dependency: [if], data = [none]
}
} else {
outputActivations = workspaceMgr.create(ArrayType.ACTIVATIONS, input.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together // depends on control dependency: [if], data = [none]
toReturn.fwdPassOutput = outputActivations; // depends on control dependency: [if], data = [none]
}
} else {
outputActivations = workspaceMgr.create(ArrayType.ACTIVATIONS, input.dataType(), new long[] {miniBatchSize, hiddenLayerSize, timeSeriesLength}, 'f'); //F order to keep time steps together
toReturn.fwdPassOutput = outputActivations;
}
//Level1 l1BLAS = Nd4j.getBlasWrapper().level1();
//Input validation: check input data matches nIn
if (input.size(1) != inputWeights.size(0)) {
throw new DL4JInvalidInputException("Received input with size(1) = " + input.size(1)
+ " (input array shape = " + Arrays.toString(input.shape())
+ "); input.size(1) must match layer nIn size (nIn = " + inputWeights.size(0) + ")");
}
//Input validation: check that if past state is provided, that it has same
//These can be different if user forgets to call rnnClearPreviousState() between calls of rnnTimeStep
if (prevOutputActivations != null && prevOutputActivations.size(0) != input.size(0)) {
throw new DL4JInvalidInputException("Previous activations (stored state) number of examples = "
+ prevOutputActivations.size(0) + " but input array number of examples = " + input.size(0)
+ ". Possible cause: using rnnTimeStep() without calling"
+ " rnnClearPreviousState() between different sequences?");
}
//initialize prevOutputActivations to zeroes
if (prevOutputActivations == null) {
prevOutputActivations = Nd4j.zeros(input.dataType(), new long[] {miniBatchSize, hiddenLayerSize});
}
if (helper != null) {
FwdPassReturn ret = helper.activate(layer, conf, gateActivationFn, input, recurrentWeights, inputWeights,
biases, training, prevOutputActivations, prevMemCellState, forBackprop, forwards,
inputWeightKey, maskArray, hasPeepholeConnections, workspaceMgr);
if (ret != null) {
return ret;
}
}
for (int iTimeIndex = 0; iTimeIndex < timeSeriesLength; iTimeIndex++) {
try(MemoryWorkspace ws = workspaceMgr.notifyScopeEntered(ArrayType.RNN_FF_LOOP_WORKING_MEM)) {
int time = iTimeIndex;
if (!forwards) {
time = timeSeriesLength - iTimeIndex - 1;
}
INDArray miniBatchData = (is2dInput ? input : input.tensorAlongDimension(time, 1, 0)); //[Expected shape: [m,nIn]. Also deals with edge case of T=1, with 'time series' data of shape [m,nIn], equiv. to [m,nIn,1]
miniBatchData = Shape.toMmulCompatible(miniBatchData);
// if we're using cache here - let's create ifogActivations within cache workspace, so all views from this array will be valid in cache
cacheEnter(training, cacheMode, workspaceMgr);
//Calculate activations for: network input + forget, output, input modulation gates. Next 3 lines are first part of those
INDArray ifogActivations = miniBatchData.mmul(inputWeights); //Shape: [miniBatch,4*layerSize]
cacheExit(training, cacheMode, workspaceMgr);
Nd4j.gemm(prevOutputActivations, recurrentWeightsIFOG, ifogActivations, false, false, 1.0, 1.0);
ifogActivations.addiRowVector(biases);
INDArray inputActivations =
ifogActivations.get(all(), interval(0, hiddenLayerSize));
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.iz[time] = inputActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.iz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, inputActivations, 'f');
}
}
layer.layerConf().getActivationFn().getActivation(inputActivations, training);
if (forBackprop){
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.ia[time] = inputActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.ia[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, inputActivations);
}
}
INDArray forgetGateActivations = ifogActivations.get(all(),
interval(hiddenLayerSize, 2 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWFF = prevMemCellState.dup('f').muliRowVector(wFFTranspose);
forgetGateActivations.addi(pmcellWFF);
}
//Above line: treats matrix as a vector. Can only do this because we're sure both pwcelWFF and forgetGateACtivations are f order, offset 0 and have same strides
if (forBackprop && !sigmoidGates) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.fz[time] = forgetGateActivations.dup('f'); //Forget gate pre-out (z)
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.fz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, forgetGateActivations, 'f'); //Forget gate pre-out (z)
}
}
gateActivationFn.getActivation(forgetGateActivations, training);
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.fa[time] = forgetGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.fa[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, forgetGateActivations);
}
}
INDArray inputModGateActivations = ifogActivations.get(all(),
interval(3 * hiddenLayerSize, 4 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWGG = prevMemCellState.dup('f').muliRowVector(wGGTranspose);
inputModGateActivations.addi(pmcellWGG);
}
if (forBackprop && !sigmoidGates) {
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.gz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, inputModGateActivations, 'f'); //Input modulation gate pre-out (z)
cacheExit(training, cacheMode, workspaceMgr);
}
gateActivationFn.getActivation(inputModGateActivations, training);
if (forBackprop){
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.ga[time] = inputModGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.ga[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, inputModGateActivations);
}
}
//Memory cell state
INDArray currentMemoryCellState;
INDArray inputModMulInput;
if (forBackprop) {
cacheEnter(training, cacheMode, workspaceMgr);
currentMemoryCellState = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, prevMemCellState, 'f').muli(forgetGateActivations);
cacheExit(training, cacheMode, workspaceMgr);
// this variable isn't stored in cache
inputModMulInput = inputModGateActivations.dup('f').muli(inputActivations);
} else {
currentMemoryCellState = workspaceMgr.leverageTo(ArrayType.FF_WORKING_MEM, forgetGateActivations.muli(prevMemCellState)); //TODO optimize without the copy
inputModMulInput = inputModGateActivations.muli(inputActivations);
}
currentMemoryCellState.addi(inputModMulInput);
INDArray outputGateActivations = ifogActivations.get(all(),
interval(2 * hiddenLayerSize, 3 * hiddenLayerSize));
if (hasPeepholeConnections) {
INDArray pmcellWOO = currentMemoryCellState.dup('f').muliRowVector(wOOTranspose);
outputGateActivations.addi(pmcellWOO);
}
if (forBackprop && !sigmoidGates) {
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.oz[time] = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, outputGateActivations, 'f'); //Output gate activations
cacheExit(training, cacheMode, workspaceMgr);
}
gateActivationFn.getActivation(outputGateActivations, training);
if (forBackprop) {
if(shouldCache(training, cacheMode, workspaceMgr)){
cacheEnter(training, cacheMode, workspaceMgr);
toReturn.oa[time] = outputGateActivations.dup('f');
cacheExit(training, cacheMode, workspaceMgr);
} else {
toReturn.oa[time] = workspaceMgr.leverageTo(ArrayType.BP_WORKING_MEM, outputGateActivations); //TODO optimize without leverage
}
}
////////////// same as with iFogActivations - if we use cache, let's create this array right there
cacheEnter(training, cacheMode, workspaceMgr);
//LSTM unit outputs:
INDArray currMemoryCellActivation ;
currMemoryCellActivation = workspaceMgr.dup(ArrayType.FF_WORKING_MEM, currentMemoryCellState, 'f');
currMemoryCellActivation = afn.getActivation(currMemoryCellActivation, training);
cacheExit(training, cacheMode, workspaceMgr);
///////////////////
INDArray currHiddenUnitActivations;
if (forBackprop) {
cacheEnter(training, cacheMode, workspaceMgr);
currHiddenUnitActivations = workspaceMgr.dup(ArrayType.BP_WORKING_MEM, currMemoryCellActivation, 'f').muli(outputGateActivations); //Expected shape: [m,hiddenLayerSize]
cacheExit(training, cacheMode, workspaceMgr);
} else {
currHiddenUnitActivations = currMemoryCellActivation.muli(outputGateActivations); //Expected shape: [m,hiddenLayerSize]
}
if (maskArray != null) {
//Mask array is present: bidirectional RNN -> need to zero out these activations to avoid
// incorrectly using activations from masked time steps (i.e., want 0 initialization in both directions)
//We *also* need to apply this to the memory cells, as they are carried forward
//Mask array has shape [minibatch, timeSeriesLength] -> get column
INDArray timeStepMaskColumn = maskArray.getColumn(time, true);
currHiddenUnitActivations.muliColumnVector(timeStepMaskColumn);
currentMemoryCellState.muliColumnVector(timeStepMaskColumn);
}
currentMemoryCellState = workspaceMgr.leverageTo(ArrayType.FF_WORKING_MEM, currentMemoryCellState); //TODO optimize, without the leverage
if (forBackprop) {
toReturn.fwdPassOutputAsArrays[time] = currHiddenUnitActivations;
toReturn.memCellState[time] = currentMemoryCellState;
toReturn.memCellActivations[time] = currMemoryCellActivation;
if (training && cacheMode != CacheMode.NONE && workspaceMgr.hasConfiguration(ArrayType.FF_CACHE) && workspaceMgr.isWorkspaceOpen(ArrayType.FF_CACHE)) {
toReturn.memCellActivations[time] = workspaceMgr.leverageTo(ArrayType.FF_CACHE, toReturn.memCellActivations[time]);
toReturn.memCellState[time] = workspaceMgr.leverageTo(ArrayType.FF_CACHE, toReturn.memCellState[time]);
}
if (cacheMode != CacheMode.NONE) {
outputActivations.tensorAlongDimension(time, 1, 0).assign(currHiddenUnitActivations);
}
} else {
outputActivations.tensorAlongDimension(time, 1, 0).assign(currHiddenUnitActivations);
}
prevOutputActivations = currHiddenUnitActivations;
prevMemCellState = currentMemoryCellState;
// no need to dup here, if that's cache - it's already within Cache workspace
toReturn.lastAct = currHiddenUnitActivations;
// the same as above, already in cache
toReturn.lastMemCell = currentMemoryCellState;
}
}
//toReturn.leverageTo(ComputationGraph.workspaceExternal);
toReturn.prevAct = originalPrevOutputActivations;
toReturn.prevMemCell = originalPrevMemCellState;
return toReturn;
} }
|
public class class_name {
protected final Map<String,Object> readMapFrom( RawDataBuffer in )
{
int mapSize = in.readInt();
if (mapSize == 0)
return null;
Map<String,Object> map = new HashMap<>(Math.max(17,mapSize*4/3));
for (int n = 0 ; n < mapSize ; n++)
{
String propName = in.readUTF();
Object propValue = in.readGeneric();
map.put(propName,propValue);
}
return map;
} }
|
public class class_name {
protected final Map<String,Object> readMapFrom( RawDataBuffer in )
{
int mapSize = in.readInt();
if (mapSize == 0)
return null;
Map<String,Object> map = new HashMap<>(Math.max(17,mapSize*4/3));
for (int n = 0 ; n < mapSize ; n++)
{
String propName = in.readUTF();
Object propValue = in.readGeneric();
map.put(propName,propValue); // depends on control dependency: [for], data = [none]
}
return map;
} }
|
public class class_name {
public void marshall(OriginationRoute originationRoute, ProtocolMarshaller protocolMarshaller) {
if (originationRoute == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(originationRoute.getHost(), HOST_BINDING);
protocolMarshaller.marshall(originationRoute.getPort(), PORT_BINDING);
protocolMarshaller.marshall(originationRoute.getProtocol(), PROTOCOL_BINDING);
protocolMarshaller.marshall(originationRoute.getPriority(), PRIORITY_BINDING);
protocolMarshaller.marshall(originationRoute.getWeight(), WEIGHT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(OriginationRoute originationRoute, ProtocolMarshaller protocolMarshaller) {
if (originationRoute == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(originationRoute.getHost(), HOST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(originationRoute.getPort(), PORT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(originationRoute.getProtocol(), PROTOCOL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(originationRoute.getPriority(), PRIORITY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(originationRoute.getWeight(), WEIGHT_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 {
@Override
protected GeneratedData genVdmToTargetLang(List<IRStatus<PIR>> statuses) throws AnalysisException {
GeneratedData r = new GeneratedData();
try {
// Apply transformations
for (IRStatus<PIR> status : statuses) {
// make init expression an op
StateInit stateInit = new StateInit(getInfo());
generator.applyPartialTransformation(status, stateInit);
// transform away any recursion cycles
GroupMutRecs groupMR = new GroupMutRecs();
generator.applyTotalTransformation(status, groupMR);
if (status.getIrNode() instanceof AModuleDeclIR) {
AModuleDeclIR cClass = (AModuleDeclIR) status.getIrNode();
// then sort remaining dependencies
SortDependencies sortTrans = new SortDependencies(cClass.getDecls());
generator.applyPartialTransformation(status, sortTrans);
}
}
r.setClasses(prettyPrint(statuses));
} catch (org.overture.codegen.ir.analysis.AnalysisException e) {
throw new AnalysisException(e);
}
return r;
} }
|
public class class_name {
@Override
protected GeneratedData genVdmToTargetLang(List<IRStatus<PIR>> statuses) throws AnalysisException {
GeneratedData r = new GeneratedData();
try {
// Apply transformations
for (IRStatus<PIR> status : statuses) {
// make init expression an op
StateInit stateInit = new StateInit(getInfo());
generator.applyPartialTransformation(status, stateInit); // depends on control dependency: [for], data = [status]
// transform away any recursion cycles
GroupMutRecs groupMR = new GroupMutRecs();
generator.applyTotalTransformation(status, groupMR); // depends on control dependency: [for], data = [status]
if (status.getIrNode() instanceof AModuleDeclIR) {
AModuleDeclIR cClass = (AModuleDeclIR) status.getIrNode();
// then sort remaining dependencies
SortDependencies sortTrans = new SortDependencies(cClass.getDecls());
generator.applyPartialTransformation(status, sortTrans); // depends on control dependency: [if], data = [none]
}
}
r.setClasses(prettyPrint(statuses));
} catch (org.overture.codegen.ir.analysis.AnalysisException e) {
throw new AnalysisException(e);
}
return r;
} }
|
public class class_name {
private void browseForImage() {
if (emitter != null) {
int resp = chooser.showOpenDialog(this);
if (resp == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String path = file.getParentFile().getAbsolutePath();
String name = file.getName();
ConfigurableEmitter.setRelativePath(path);
emitter.setImageName(name);
imageName.setText(name);
}
}
} }
|
public class class_name {
private void browseForImage() {
if (emitter != null) {
int resp = chooser.showOpenDialog(this);
if (resp == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String path = file.getParentFile().getAbsolutePath();
String name = file.getName();
ConfigurableEmitter.setRelativePath(path);
// depends on control dependency: [if], data = [none]
emitter.setImageName(name);
// depends on control dependency: [if], data = [none]
imageName.setText(name);
// depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private void removeWorker(final Worker worker)
{
log.info("Kaboom! Worker[%s] removed!", worker.getHost());
final ZkWorker zkWorker = zkWorkers.get(worker.getHost());
if (zkWorker != null) {
try {
scheduleTasksCleanupForWorker(worker.getHost(), getAssignedTasks(worker));
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
try {
zkWorker.close();
}
catch (Exception e) {
log.error(e, "Exception closing worker[%s]!", worker.getHost());
}
zkWorkers.remove(worker.getHost());
checkBlackListedNodes();
}
}
lazyWorkers.remove(worker.getHost());
} }
|
public class class_name {
private void removeWorker(final Worker worker)
{
log.info("Kaboom! Worker[%s] removed!", worker.getHost());
final ZkWorker zkWorker = zkWorkers.get(worker.getHost());
if (zkWorker != null) {
try {
scheduleTasksCleanupForWorker(worker.getHost(), getAssignedTasks(worker)); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
finally {
try {
zkWorker.close(); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
log.error(e, "Exception closing worker[%s]!", worker.getHost());
} // depends on control dependency: [catch], data = [none]
zkWorkers.remove(worker.getHost());
checkBlackListedNodes();
}
}
lazyWorkers.remove(worker.getHost());
} }
|
public class class_name {
static Map<String, DBObject> getDocumentFromObject(Metamodel metaModel, Object obj, Set<Attribute> columns,
String tableName) throws PropertyAccessException
{
Map<String, DBObject> embeddedObjects = new HashMap<String, DBObject>();
// BasicDBObject dBObj = new BasicDBObject();
for (Attribute column : columns)
{
String collectionName = ((AbstractAttribute) column).getTableName() != null
? ((AbstractAttribute) column).getTableName() : tableName;
DBObject dbObject = embeddedObjects.get(collectionName);
if (dbObject == null)
{
dbObject = new BasicDBObject();
embeddedObjects.put(collectionName, dbObject);
}
if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) column).getBindableJavaType()))
{
DefaultMongoDBDataHandler handler = new DefaultMongoDBDataHandler();
// handler.onEmbeddable(column, obj, metaModel, dBObj,
// collectionName);
handler.onEmbeddable(column, obj, metaModel, dbObject, collectionName);
}
else
{
extractFieldValue(obj, dbObject, column);
}
}
return embeddedObjects;
} }
|
public class class_name {
static Map<String, DBObject> getDocumentFromObject(Metamodel metaModel, Object obj, Set<Attribute> columns,
String tableName) throws PropertyAccessException
{
Map<String, DBObject> embeddedObjects = new HashMap<String, DBObject>();
// BasicDBObject dBObj = new BasicDBObject();
for (Attribute column : columns)
{
String collectionName = ((AbstractAttribute) column).getTableName() != null
? ((AbstractAttribute) column).getTableName() : tableName;
DBObject dbObject = embeddedObjects.get(collectionName);
if (dbObject == null)
{
dbObject = new BasicDBObject();
// depends on control dependency: [if], data = [none]
embeddedObjects.put(collectionName, dbObject);
// depends on control dependency: [if], data = [none]
}
if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) column).getBindableJavaType()))
{
DefaultMongoDBDataHandler handler = new DefaultMongoDBDataHandler();
// handler.onEmbeddable(column, obj, metaModel, dBObj,
// collectionName);
handler.onEmbeddable(column, obj, metaModel, dbObject, collectionName);
// depends on control dependency: [if], data = [none]
}
else
{
extractFieldValue(obj, dbObject, column);
// depends on control dependency: [if], data = [none]
}
}
return embeddedObjects;
} }
|
public class class_name {
protected void initJsonWriter() {
String writerList = config.getJsonWriters();
if (writerList != null) {
String[] writers = writerList.split(",");
Set<String> supportedWriters = TreeWriterRegistry.getWritersByFormat("json");
TreeWriter selectedWriter = null;
for (String writer : writers) {
writer = writer.trim().toLowerCase();
if (!writer.isEmpty()) {
for (String supportedWriter : supportedWriters) {
int i = supportedWriter.lastIndexOf('.');
if (i > -1) {
supportedWriter = supportedWriter.substring(i + 1);
}
if (supportedWriter.toLowerCase().contains(writer)) {
selectedWriter = TreeWriterRegistry.getWriter(supportedWriter);
logger.info("Default JSON serializer/writer is \"" + selectedWriter.getClass() + "\".");
TreeWriterRegistry.setWriter("json", selectedWriter);
break;
}
}
if (selectedWriter != null) {
break;
}
}
}
}
} }
|
public class class_name {
protected void initJsonWriter() {
String writerList = config.getJsonWriters();
if (writerList != null) {
String[] writers = writerList.split(",");
Set<String> supportedWriters = TreeWriterRegistry.getWritersByFormat("json");
TreeWriter selectedWriter = null;
for (String writer : writers) {
writer = writer.trim().toLowerCase(); // depends on control dependency: [for], data = [writer]
if (!writer.isEmpty()) {
for (String supportedWriter : supportedWriters) {
int i = supportedWriter.lastIndexOf('.');
if (i > -1) {
supportedWriter = supportedWriter.substring(i + 1); // depends on control dependency: [if], data = [(i]
}
if (supportedWriter.toLowerCase().contains(writer)) {
selectedWriter = TreeWriterRegistry.getWriter(supportedWriter); // depends on control dependency: [if], data = [none]
logger.info("Default JSON serializer/writer is \"" + selectedWriter.getClass() + "\"."); // depends on control dependency: [if], data = [none]
TreeWriterRegistry.setWriter("json", selectedWriter); // depends on control dependency: [if], data = [none]
break;
}
}
if (selectedWriter != null) {
break;
}
}
}
}
} }
|
public class class_name {
private void setExternalProperties(String name, HColumnDescriptor hColumnDescriptor)
{
Properties properties = externalProperties != null ? externalProperties.get(name) : null;
if (properties != null && !properties.isEmpty())
{
for (Object obj : properties.keySet())
{
hColumnDescriptor
.setValue(Bytes.toBytes(obj.toString()), Bytes.toBytes(properties.get(obj).toString()));
}
}
} }
|
public class class_name {
private void setExternalProperties(String name, HColumnDescriptor hColumnDescriptor)
{
Properties properties = externalProperties != null ? externalProperties.get(name) : null;
if (properties != null && !properties.isEmpty())
{
for (Object obj : properties.keySet())
{
hColumnDescriptor
.setValue(Bytes.toBytes(obj.toString()), Bytes.toBytes(properties.get(obj).toString())); // depends on control dependency: [for], data = [none]
}
}
} }
|
public class class_name {
public static long parseTimestampFromUIDString(String s, final int start, final int end) {
long ret = 0;
for (int i = start; i < end && i < start + 9; i++) {
ret <<= 5;
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
ret |= c - '0';
} else if (c >= 'a' && c <= 'v') {
ret |= c - 'a' + 10;
} else if (c >= 'A' && c <= 'V') {
ret |= c - 'A' + 10;
} else {
throw new IllegalArgumentException(s.substring(start, end) + " is not a valid UID!");
}
}
return ret;
} }
|
public class class_name {
public static long parseTimestampFromUIDString(String s, final int start, final int end) {
long ret = 0;
for (int i = start; i < end && i < start + 9; i++) {
ret <<= 5; // depends on control dependency: [for], data = [none]
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
ret |= c - '0'; // depends on control dependency: [if], data = [none]
} else if (c >= 'a' && c <= 'v') {
ret |= c - 'a' + 10; // depends on control dependency: [if], data = [none]
} else if (c >= 'A' && c <= 'V') {
ret |= c - 'A' + 10; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException(s.substring(start, end) + " is not a valid UID!");
}
}
return ret;
} }
|
public class class_name {
public static void addPropertyBigInteger(
CmsCmisTypeManager typeManager,
PropertiesImpl props,
String typeId,
Set<String> filter,
String id,
BigInteger value) {
if (!checkAddProperty(typeManager, props, typeId, filter, id)) {
return;
}
props.addProperty(new PropertyIntegerImpl(id, value));
} }
|
public class class_name {
public static void addPropertyBigInteger(
CmsCmisTypeManager typeManager,
PropertiesImpl props,
String typeId,
Set<String> filter,
String id,
BigInteger value) {
if (!checkAddProperty(typeManager, props, typeId, filter, id)) {
return;
// depends on control dependency: [if], data = [none]
}
props.addProperty(new PropertyIntegerImpl(id, value));
} }
|
public class class_name {
public static String syncRestCall(final String purl) {
try {
return CACHE.get(purl);
} catch (final ExecutionException e) {
GWT.log(e.getMessage(), e);
return null;
}
} }
|
public class class_name {
public static String syncRestCall(final String purl) {
try {
return CACHE.get(purl); // depends on control dependency: [try], data = [none]
} catch (final ExecutionException e) {
GWT.log(e.getMessage(), e);
return null;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public boolean isSupported(TemporalField field) {
if (field == WEEK_OF_WEEK_BASED_YEAR || field == WEEK_BASED_YEAR) {
return true;
} else if (field instanceof ChronoField) {
return false;
}
return field != null && field.isSupportedBy(this);
} }
|
public class class_name {
@Override
public boolean isSupported(TemporalField field) {
if (field == WEEK_OF_WEEK_BASED_YEAR || field == WEEK_BASED_YEAR) {
return true; // depends on control dependency: [if], data = [none]
} else if (field instanceof ChronoField) {
return false; // depends on control dependency: [if], data = [none]
}
return field != null && field.isSupportedBy(this);
} }
|
public class class_name {
public void doIt() {
if (nodeidx == -1) {
GetLogsTask t = new GetLogsTask();
t.doIt();
bytes = t._bytes;
}
else {
H2ONode node = H2O.CLOUD._memary[nodeidx];
GetLogsTask t = new GetLogsTask();
Log.trace("GetLogsTask starting to node " + nodeidx + "...");
// Synchronous RPC call to get ticks from remote (possibly this) node.
new RPC<>(node, t).call().get();
Log.trace("GetLogsTask completed to node " + nodeidx);
bytes = t._bytes;
}
} }
|
public class class_name {
public void doIt() {
if (nodeidx == -1) {
GetLogsTask t = new GetLogsTask();
t.doIt(); // depends on control dependency: [if], data = [none]
bytes = t._bytes; // depends on control dependency: [if], data = [none]
}
else {
H2ONode node = H2O.CLOUD._memary[nodeidx];
GetLogsTask t = new GetLogsTask();
Log.trace("GetLogsTask starting to node " + nodeidx + "..."); // depends on control dependency: [if], data = [none]
// Synchronous RPC call to get ticks from remote (possibly this) node.
new RPC<>(node, t).call().get(); // depends on control dependency: [if], data = [none]
Log.trace("GetLogsTask completed to node " + nodeidx); // depends on control dependency: [if], data = [none]
bytes = t._bytes; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Object valueAtIn(int index, List aList) {
if (aList.size() > index) {
return aList.get(index);
} else {
throw new SlimFixtureException(false, "list only has " + aList.size() + " elements");
}
} }
|
public class class_name {
public Object valueAtIn(int index, List aList) {
if (aList.size() > index) {
return aList.get(index); // depends on control dependency: [if], data = [index)]
} else {
throw new SlimFixtureException(false, "list only has " + aList.size() + " elements");
}
} }
|
public class class_name {
public static List<Parameter> mergeParameters(List<Parameter> one, List<Parameter> two) {
if (isAllNull(one, two) || !isAllNotNull(one, two)) return null;
if (one.size() != two.size()) return null;
List<Parameter> result = new ArrayList<>();
for (int index = 0; index < one.size(); index++) {
Parameter p1 = one.get(index);
Parameter p2 = two.get(index);
Parameter np = new Parameter();
np.setType(mergeSelective(p1.getType(), p2.getType()));
np.setComment(mergeSelective(p1.getComment(), p2.getComment()));
np.setAnnotations(mergeListNoDuplicate(p1.getAnnotations(), p2.getAnnotations()));
np.setVarArgs(p1.isVarArgs());
np.setId(p1.getId());
result.add(np);
}
return result;
} }
|
public class class_name {
public static List<Parameter> mergeParameters(List<Parameter> one, List<Parameter> two) {
if (isAllNull(one, two) || !isAllNotNull(one, two)) return null;
if (one.size() != two.size()) return null;
List<Parameter> result = new ArrayList<>();
for (int index = 0; index < one.size(); index++) {
Parameter p1 = one.get(index);
Parameter p2 = two.get(index);
Parameter np = new Parameter();
np.setType(mergeSelective(p1.getType(), p2.getType())); // depends on control dependency: [for], data = [none]
np.setComment(mergeSelective(p1.getComment(), p2.getComment())); // depends on control dependency: [for], data = [none]
np.setAnnotations(mergeListNoDuplicate(p1.getAnnotations(), p2.getAnnotations())); // depends on control dependency: [for], data = [none]
np.setVarArgs(p1.isVarArgs()); // depends on control dependency: [for], data = [none]
np.setId(p1.getId()); // depends on control dependency: [for], data = [none]
result.add(np); // depends on control dependency: [for], data = [none]
}
return result;
} }
|
public class class_name {
private void applyFontToToolbar(final Toolbar view) {
final CharSequence previousTitle = view.getTitle();
final CharSequence previousSubtitle = view.getSubtitle();
// The toolbar inflates both the title and the subtitle views lazily but luckily they do it
// synchronously when you set a title and a subtitle programmatically.
// So we set a title and a subtitle to something, then get the views, then revert.
view.setTitle("uk.co.chrisjenx.calligraphy:toolbar_title");
view.setSubtitle("uk.co.chrisjenx.calligraphy:toolbar_subtitle");
// Iterate through the children to run post inflation on them
final int childCount = view.getChildCount();
for (int i = 0; i < childCount; i++) {
onViewCreated(view.getChildAt(i), view.getContext(), null);
}
// Remove views from view if they didn't have copy set.
view.setTitle(previousTitle);
view.setSubtitle(previousSubtitle);
} }
|
public class class_name {
private void applyFontToToolbar(final Toolbar view) {
final CharSequence previousTitle = view.getTitle();
final CharSequence previousSubtitle = view.getSubtitle();
// The toolbar inflates both the title and the subtitle views lazily but luckily they do it
// synchronously when you set a title and a subtitle programmatically.
// So we set a title and a subtitle to something, then get the views, then revert.
view.setTitle("uk.co.chrisjenx.calligraphy:toolbar_title");
view.setSubtitle("uk.co.chrisjenx.calligraphy:toolbar_subtitle");
// Iterate through the children to run post inflation on them
final int childCount = view.getChildCount();
for (int i = 0; i < childCount; i++) {
onViewCreated(view.getChildAt(i), view.getContext(), null); // depends on control dependency: [for], data = [i]
}
// Remove views from view if they didn't have copy set.
view.setTitle(previousTitle);
view.setSubtitle(previousSubtitle);
} }
|
public class class_name {
public synchronized ApiFuture<FlatRow> add(Query query) {
Preconditions.checkNotNull(query);
ReadRowsRequest request = query.toProto(requestContext);
Preconditions.checkArgument(request.getRows().getRowKeysCount() == 1);
ByteString rowKey = request.getRows().getRowKeysList().get(0);
Preconditions.checkArgument(!rowKey.equals(ByteString.EMPTY));
final RowFilter filter = request.getFilter();
Batch batch = batches.get(filter);
if (batch == null) {
batch = new Batch(filter);
batches.put(filter, batch);
}
return batch.addKey(rowKey);
} }
|
public class class_name {
public synchronized ApiFuture<FlatRow> add(Query query) {
Preconditions.checkNotNull(query);
ReadRowsRequest request = query.toProto(requestContext);
Preconditions.checkArgument(request.getRows().getRowKeysCount() == 1);
ByteString rowKey = request.getRows().getRowKeysList().get(0);
Preconditions.checkArgument(!rowKey.equals(ByteString.EMPTY));
final RowFilter filter = request.getFilter();
Batch batch = batches.get(filter);
if (batch == null) {
batch = new Batch(filter); // depends on control dependency: [if], data = [none]
batches.put(filter, batch); // depends on control dependency: [if], data = [none]
}
return batch.addKey(rowKey);
} }
|
public class class_name {
@Override
public void shutdown() throws JournalException {
synchronized (JournalWriter.SYNCHRONIZER) {
if (state == SHUTDOWN) {
return;
}
if (state == FILE_OPEN) {
closeFile();
}
logger.debug("Shutting down.");
sendRequestToAllTransports(new ShutdownRequest());
state = SHUTDOWN;
}
} }
|
public class class_name {
@Override
public void shutdown() throws JournalException {
synchronized (JournalWriter.SYNCHRONIZER) {
if (state == SHUTDOWN) {
return; // depends on control dependency: [if], data = [none]
}
if (state == FILE_OPEN) {
closeFile(); // depends on control dependency: [if], data = [none]
}
logger.debug("Shutting down.");
sendRequestToAllTransports(new ShutdownRequest());
state = SHUTDOWN;
}
} }
|
public class class_name {
public AtomicLongConfig findAtomicLongConfig(String name) {
name = getBaseName(name);
AtomicLongConfig config = lookupByPattern(configPatternMatcher, atomicLongConfigs, name);
if (config != null) {
return config.getAsReadOnly();
}
return getAtomicLongConfig("default").getAsReadOnly();
} }
|
public class class_name {
public AtomicLongConfig findAtomicLongConfig(String name) {
name = getBaseName(name);
AtomicLongConfig config = lookupByPattern(configPatternMatcher, atomicLongConfigs, name);
if (config != null) {
return config.getAsReadOnly(); // depends on control dependency: [if], data = [none]
}
return getAtomicLongConfig("default").getAsReadOnly();
} }
|
public class class_name {
@Override
public OutlierResult run(Database db, Relation<V> relation) {
DBIDs ids = relation.getDBIDs();
WritableDoubleDataStore abodvalues = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
DoubleMinMax minmaxabod = new DoubleMinMax();
if(kernelFunction.getClass() == LinearKernelFunction.class) {
if(!kNNABOD(db, relation, ids, abodvalues, minmaxabod)) {
// Fallback, if we do not have an index.
fastABOD(db, relation, ids, abodvalues, minmaxabod);
}
}
else {
fastABOD(db, relation, ids, abodvalues, minmaxabod);
}
// Build result representation.
DoubleRelation scoreResult = new MaterializedDoubleRelation("Angle-Based Outlier Degree", "abod-outlier", abodvalues, relation.getDBIDs());
OutlierScoreMeta scoreMeta = new InvertedOutlierScoreMeta(minmaxabod.getMin(), minmaxabod.getMax(), 0.0, Double.POSITIVE_INFINITY);
return new OutlierResult(scoreMeta, scoreResult);
} }
|
public class class_name {
@Override
public OutlierResult run(Database db, Relation<V> relation) {
DBIDs ids = relation.getDBIDs();
WritableDoubleDataStore abodvalues = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
DoubleMinMax minmaxabod = new DoubleMinMax();
if(kernelFunction.getClass() == LinearKernelFunction.class) {
if(!kNNABOD(db, relation, ids, abodvalues, minmaxabod)) {
// Fallback, if we do not have an index.
fastABOD(db, relation, ids, abodvalues, minmaxabod); // depends on control dependency: [if], data = [none]
}
}
else {
fastABOD(db, relation, ids, abodvalues, minmaxabod); // depends on control dependency: [if], data = [none]
}
// Build result representation.
DoubleRelation scoreResult = new MaterializedDoubleRelation("Angle-Based Outlier Degree", "abod-outlier", abodvalues, relation.getDBIDs());
OutlierScoreMeta scoreMeta = new InvertedOutlierScoreMeta(minmaxabod.getMin(), minmaxabod.getMax(), 0.0, Double.POSITIVE_INFINITY);
return new OutlierResult(scoreMeta, scoreResult);
} }
|
public class class_name {
@SuppressWarnings("unused") // used by jelly
public boolean isUsingSecurityToken() {
try {
return !Jenkins.get().getInstallState().isSetupComplete()
&& isUsingSecurityDefaults();
} catch (Exception e) {
// ignore
}
return false;
} }
|
public class class_name {
@SuppressWarnings("unused") // used by jelly
public boolean isUsingSecurityToken() {
try {
return !Jenkins.get().getInstallState().isSetupComplete()
&& isUsingSecurityDefaults(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// ignore
} // depends on control dependency: [catch], data = [none]
return false;
} }
|
public class class_name {
public static long current(Context context, String tag) {
Long appRxValue = sReceivedBytes.get(tag);
Long appTxValue = sSendBytes.get(tag);
if (appRxValue == null || appTxValue == null) {
if (DEBUG) {
LogUtils.w(TAG, "current() appRxValue or appTxValue is null.");
}
return 0;
}
final int uid = getUid(context);
long appRxValue2 = TrafficStats.getUidRxBytes(uid);
long appTxValue2 = TrafficStats.getUidTxBytes(uid);
long rxValue = appRxValue2 - appRxValue;
long txValue = appTxValue2 - appTxValue;
if (DEBUG) {
LogUtils.v(TAG, "current() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid);
}
return rxValue;
} }
|
public class class_name {
public static long current(Context context, String tag) {
Long appRxValue = sReceivedBytes.get(tag);
Long appTxValue = sSendBytes.get(tag);
if (appRxValue == null || appTxValue == null) {
if (DEBUG) {
LogUtils.w(TAG, "current() appRxValue or appTxValue is null."); // depends on control dependency: [if], data = [none]
}
return 0; // depends on control dependency: [if], data = [none]
}
final int uid = getUid(context);
long appRxValue2 = TrafficStats.getUidRxBytes(uid);
long appTxValue2 = TrafficStats.getUidTxBytes(uid);
long rxValue = appRxValue2 - appRxValue;
long txValue = appTxValue2 - appTxValue;
if (DEBUG) {
LogUtils.v(TAG, "current() rxValue=" + rxValue / 1000 + " txValue=" + txValue / 1000 + " uid=" + uid); // depends on control dependency: [if], data = [none]
}
return rxValue;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <T, R> boolean tryScalarXMapSubscribe(Publisher<T> source,
Subscriber<? super R> subscriber,
Function<? super T, ? extends Publisher<? extends R>> mapper) {
if (source instanceof Callable) {
T t;
try {
t = ((Callable<T>)source).call();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
}
if (t == null) {
EmptySubscription.complete(subscriber);
return true;
}
Publisher<? extends R> r;
try {
r = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
}
if (r instanceof Callable) {
R u;
try {
u = ((Callable<R>)r).call();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
}
if (u == null) {
EmptySubscription.complete(subscriber);
return true;
}
subscriber.onSubscribe(new ScalarSubscription<R>(subscriber, u));
} else {
r.subscribe(subscriber);
}
return true;
}
return false;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <T, R> boolean tryScalarXMapSubscribe(Publisher<T> source,
Subscriber<? super R> subscriber,
Function<? super T, ? extends Publisher<? extends R>> mapper) {
if (source instanceof Callable) {
T t;
try {
t = ((Callable<T>)source).call(); // depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
} // depends on control dependency: [catch], data = [none]
if (t == null) {
EmptySubscription.complete(subscriber); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
Publisher<? extends R> r; // depends on control dependency: [if], data = [none]
try {
r = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); // depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
} // depends on control dependency: [catch], data = [none]
if (r instanceof Callable) {
R u;
try {
u = ((Callable<R>)r).call(); // depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, subscriber);
return true;
} // depends on control dependency: [catch], data = [none]
if (u == null) {
EmptySubscription.complete(subscriber); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
subscriber.onSubscribe(new ScalarSubscription<R>(subscriber, u)); // depends on control dependency: [if], data = [none]
} else {
r.subscribe(subscriber); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
@Override
public void updateReport(AllTablesReportDelta delta) {
checkNotNull(delta, "delta");
updateMetadata(delta);
if (delta.getTable().isPresent()) {
updateTableData(delta, delta.getTable().get());
}
} }
|
public class class_name {
@Override
public void updateReport(AllTablesReportDelta delta) {
checkNotNull(delta, "delta");
updateMetadata(delta);
if (delta.getTable().isPresent()) {
updateTableData(delta, delta.getTable().get()); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private void onScrollingDown() {
if (!hidden) {
hidden = true;
if (animatedView.getAnimation() == null) {
ObjectAnimator animator = createAnimator(true);
animator.start();
}
}
} }
|
public class class_name {
private void onScrollingDown() {
if (!hidden) {
hidden = true; // depends on control dependency: [if], data = [none]
if (animatedView.getAnimation() == null) {
ObjectAnimator animator = createAnimator(true);
animator.start(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@CanIgnoreReturnValue
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next();
keyValues.set(newValues.next());
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next();
keyValues.remove();
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next());
}
return oldValues;
} }
|
public class class_name {
@CanIgnoreReturnValue
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next(); // depends on control dependency: [while], data = [none]
keyValues.set(newValues.next()); // depends on control dependency: [while], data = [none]
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next(); // depends on control dependency: [while], data = [none]
keyValues.remove(); // depends on control dependency: [while], data = [none]
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next()); // depends on control dependency: [while], data = [none]
}
return oldValues;
} }
|
public class class_name {
public ServletType<WebAppType<T>> getOrCreateServlet()
{
List<Node> nodeList = childNode.get("servlet");
if (nodeList != null && nodeList.size() > 0)
{
return new ServletTypeImpl<WebAppType<T>>(this, "servlet", childNode, nodeList.get(0));
}
return createServlet();
} }
|
public class class_name {
public ServletType<WebAppType<T>> getOrCreateServlet()
{
List<Node> nodeList = childNode.get("servlet");
if (nodeList != null && nodeList.size() > 0)
{
return new ServletTypeImpl<WebAppType<T>>(this, "servlet", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createServlet();
} }
|
public class class_name {
public Observable<ServiceResponse<Page<DiagnosticCategoryInner>>> listSiteDiagnosticCategoriesSlotWithServiceResponseAsync(final String resourceGroupName, final String siteName, final String slot) {
return listSiteDiagnosticCategoriesSlotSinglePageAsync(resourceGroupName, siteName, slot)
.concatMap(new Func1<ServiceResponse<Page<DiagnosticCategoryInner>>, Observable<ServiceResponse<Page<DiagnosticCategoryInner>>>>() {
@Override
public Observable<ServiceResponse<Page<DiagnosticCategoryInner>>> call(ServiceResponse<Page<DiagnosticCategoryInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listSiteDiagnosticCategoriesSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<Page<DiagnosticCategoryInner>>> listSiteDiagnosticCategoriesSlotWithServiceResponseAsync(final String resourceGroupName, final String siteName, final String slot) {
return listSiteDiagnosticCategoriesSlotSinglePageAsync(resourceGroupName, siteName, slot)
.concatMap(new Func1<ServiceResponse<Page<DiagnosticCategoryInner>>, Observable<ServiceResponse<Page<DiagnosticCategoryInner>>>>() {
@Override
public Observable<ServiceResponse<Page<DiagnosticCategoryInner>>> call(ServiceResponse<Page<DiagnosticCategoryInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listSiteDiagnosticCategoriesSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
private String calculateSHA256Hash(byte[] msg, int offset, int len) {
// Calculate the SHA256 digest of the Hello message
Digest digest = platform.getCrypto().createDigestSHA256();
digest.update(msg, offset, len);
int digestLen = digest.getDigestLength();
// prepare space for hexadecimal representation, store the diggest in
// the second half and then convert
byte[] hash = new byte[2 * digestLen];
digest.getDigest(hash, digestLen, true);
for (int i = 0; i != digestLen; ++i) {
byte b = hash[digestLen + i];
int d1 = (b >> 4) & 0x0f;
int d2 = b & 0x0f;
hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0');
hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0');
}
String hashStr = new String(hash);
if (platform.getLogger().isEnabled()) {
logBuffer("calculateSHA256Hash", msg, offset, len);
logString("SHA256 Hash = '" + hashStr + "'");
}
return hashStr;
} }
|
public class class_name {
private String calculateSHA256Hash(byte[] msg, int offset, int len) {
// Calculate the SHA256 digest of the Hello message
Digest digest = platform.getCrypto().createDigestSHA256();
digest.update(msg, offset, len);
int digestLen = digest.getDigestLength();
// prepare space for hexadecimal representation, store the diggest in
// the second half and then convert
byte[] hash = new byte[2 * digestLen];
digest.getDigest(hash, digestLen, true);
for (int i = 0; i != digestLen; ++i) {
byte b = hash[digestLen + i];
int d1 = (b >> 4) & 0x0f;
int d2 = b & 0x0f;
hash[i * 2] = (byte) ((d1 >= 10) ? d1 + 'a' - 10 : d1 + '0'); // depends on control dependency: [for], data = [i]
hash[i * 2 + 1] = (byte) ((d2 >= 10) ? d2 + 'a' - 10 : d2 + '0'); // depends on control dependency: [for], data = [i]
}
String hashStr = new String(hash);
if (platform.getLogger().isEnabled()) {
logBuffer("calculateSHA256Hash", msg, offset, len); // depends on control dependency: [if], data = [none]
logString("SHA256 Hash = '" + hashStr + "'"); // depends on control dependency: [if], data = [none]
}
return hashStr;
} }
|
public class class_name {
public Object getInstanceOf(String key){
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return Class.forName((String)classesMap.get(key),true,loader).newInstance();
} catch (IllegalAccessException e) {
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
} catch (InstantiationException e) {
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
} catch (ClassNotFoundException e) {
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
}
return null;
} }
|
public class class_name {
public Object getInstanceOf(String key){
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return Class.forName((String)classesMap.get(key),true,loader).newInstance(); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
} catch (InstantiationException e) { // depends on control dependency: [catch], data = [none]
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
} catch (ClassNotFoundException e) { // depends on control dependency: [catch], data = [none]
logger.logp(Level.SEVERE,"JspClassFactory","getInstanceOf","jsp.error.function.classnotfound",(String) classesMap.get(key));
} // depends on control dependency: [catch], data = [none]
return null;
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.