code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
void declarePrefix (String prefix, String uri)
{
// Lazy processing...
if (!tablesDirty) {
copyTables();
}
if (declarations == null) {
declarations = new Vector();
}
prefix = prefix.intern();
uri = uri.intern();
if ("".equals(prefix)) {
if ("".equals(uri)) {
defaultNS = null;
} else {
defaultNS = uri;
}
} else {
prefixTable.put(prefix, uri);
uriTable.put(uri, prefix); // may wipe out another prefix
}
declarations.addElement(prefix);
} }
|
public class class_name {
void declarePrefix (String prefix, String uri)
{
// Lazy processing...
if (!tablesDirty) {
copyTables(); // depends on control dependency: [if], data = [none]
}
if (declarations == null) {
declarations = new Vector(); // depends on control dependency: [if], data = [none]
}
prefix = prefix.intern();
uri = uri.intern();
if ("".equals(prefix)) {
if ("".equals(uri)) {
defaultNS = null; // depends on control dependency: [if], data = [none]
} else {
defaultNS = uri; // depends on control dependency: [if], data = [none]
}
} else {
prefixTable.put(prefix, uri); // depends on control dependency: [if], data = [none]
uriTable.put(uri, prefix); // may wipe out another prefix // depends on control dependency: [if], data = [none]
}
declarations.addElement(prefix);
} }
|
public class class_name {
protected XExpression _generate(SarlAssertExpression assertStatement, IAppendable it, IExtraLanguageGeneratorContext context) {
final boolean haveAssert = !assertStatement.isIsStatic() && assertStatement.getCondition() != null;
if (haveAssert) {
it.append("assert (lambda:"); //$NON-NLS-1$
it.increaseIndentation().newLine();
generate(assertStatement.getCondition(), it, context);
it.decreaseIndentation().newLine();
it.append(")()"); //$NON-NLS-1$
}
if (context.getExpectedExpressionType() != null) {
if (haveAssert) {
it.newLine();
}
it.append("return ").append(toDefaultValue(context.getExpectedExpressionType().toJavaCompliantTypeReference())); //$NON-NLS-1$
}
return assertStatement;
} }
|
public class class_name {
protected XExpression _generate(SarlAssertExpression assertStatement, IAppendable it, IExtraLanguageGeneratorContext context) {
final boolean haveAssert = !assertStatement.isIsStatic() && assertStatement.getCondition() != null;
if (haveAssert) {
it.append("assert (lambda:"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
it.increaseIndentation().newLine(); // depends on control dependency: [if], data = [none]
generate(assertStatement.getCondition(), it, context); // depends on control dependency: [if], data = [none]
it.decreaseIndentation().newLine(); // depends on control dependency: [if], data = [none]
it.append(")()"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
if (context.getExpectedExpressionType() != null) {
if (haveAssert) {
it.newLine(); // depends on control dependency: [if], data = [none]
}
it.append("return ").append(toDefaultValue(context.getExpectedExpressionType().toJavaCompliantTypeReference())); //$NON-NLS-1$ // depends on control dependency: [if], data = [(context.getExpectedExpressionType()]
}
return assertStatement;
} }
|
public class class_name {
public void setRecordState(java.util.Collection<StringFilter> recordState) {
if (recordState == null) {
this.recordState = null;
return;
}
this.recordState = new java.util.ArrayList<StringFilter>(recordState);
} }
|
public class class_name {
public void setRecordState(java.util.Collection<StringFilter> recordState) {
if (recordState == null) {
this.recordState = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.recordState = new java.util.ArrayList<StringFilter>(recordState);
} }
|
public class class_name {
private void checkSelection(boolean suppressEvent) {
Dateitem selectedItem = getSelectedItem();
if (selectedItem == null) {
selectedItem = lastSelectedItem;
setSelectedItem(selectedItem);
} else if (selectedItem != customItem && lastSelectedItem != selectedItem) {
lastSelectedItem = selectedItem;
if (!suppressEvent) {
EventUtil.send(new Event(ON_SELECT_RANGE, this));
}
}
updateSelection();
} }
|
public class class_name {
private void checkSelection(boolean suppressEvent) {
Dateitem selectedItem = getSelectedItem();
if (selectedItem == null) {
selectedItem = lastSelectedItem; // depends on control dependency: [if], data = [none]
setSelectedItem(selectedItem); // depends on control dependency: [if], data = [(selectedItem]
} else if (selectedItem != customItem && lastSelectedItem != selectedItem) {
lastSelectedItem = selectedItem; // depends on control dependency: [if], data = [none]
if (!suppressEvent) {
EventUtil.send(new Event(ON_SELECT_RANGE, this)); // depends on control dependency: [if], data = [none]
}
}
updateSelection();
} }
|
public class class_name {
private void buildComplexConcept(INode node, List<String> tokensOfNodeLabel, String meaningfulTokens) {
// label of node
String token;
// List of ACoLs identifiers
List<String> vec = new ArrayList<String>();
// formula for the complex concept
StringBuilder formulaOfConcept = new StringBuilder();
// logical connective
String connective = " ";
// brackets to add
String bracket = "";
// whether to insert brackets
boolean insert;
// how many left brackets do not have corresponding right ones
int bracketsBalance = 0;
// number of left brackets
int leftBrackets = 0;
// for each token of node label
for (int i = 0; i < tokensOfNodeLabel.size(); i++) {
token = (tokensOfNodeLabel.get(i));
// If logical AND or OR
if (andWords.contains(" " + token + " ") || orWords.contains(" " + token + " ")) {
insert = false;
// If non first token
if (vec != null && vec.size() > 0) {
// construct formula
if (connective.isEmpty()) {
formulaOfConcept.append(" | ").append(bracket).append(encloseWithParentheses(vec));
} else {
formulaOfConcept.append(connective).append(bracket).append(encloseWithParentheses(vec));
}
insert = true;
connective = "";
bracket = "";
vec = new ArrayList<String>();
leftBrackets = 0;
}
// If bracket
if (token.equals("(") && bracketsBalance >= 0) {
connective = " & ";
bracket = "(";
bracketsBalance = bracketsBalance + 1;
leftBrackets = leftBrackets + 1;
} else if (token.equals(")") && bracketsBalance > 0) {
if (insert) {
formulaOfConcept.append(")");
}
bracketsBalance = bracketsBalance - 1;
} else {
connective = " | ";
}
// If logical not
} else if (notWords.contains(" " + token + " ")) {
if (vec != null && vec.size() > 0) {
formulaOfConcept.append(connective).append(encloseWithParentheses(vec));
vec = new ArrayList<String>();
connective = "";
}
// What to add
if (connective.contains("&") || connective.contains("|")) {
connective = connective + " ~ ";
} else {
connective = " & ~ ";
}
} else {
if (meaningfulTokens.contains(" " + i + " ")) {
// fill list with ACoL ids
vec.add((node.getNodeData().getId() + "." + i));
}
}
}
// Dealing with first token of the node
if (vec != null && vec.size() > 0) {
//construct formula
if (connective.contains("&") || connective.contains("|") || connective.equals(" ")) {
formulaOfConcept.append(connective).append(bracket).append(encloseWithParentheses(vec));
} else {
formulaOfConcept.append(" & ").append(encloseWithParentheses(vec));
}
connective = "";
} else {
if (leftBrackets > 0) {
bracketsBalance = bracketsBalance - leftBrackets;
}
}
if (bracketsBalance > 0) {
for (int i = 0; i < bracketsBalance; i++) {
formulaOfConcept.append(")");
}
}
// dealing with brackets
String foc = formulaOfConcept.toString();
foc = foc.replace('[', '(');
foc = foc.replace(']', ')');
foc = foc.replaceAll(", ", " & ");
foc = foc.trim();
if (foc.startsWith("&")) {
StringTokenizer atoms = new StringTokenizer(foc, "&");
foc = atoms.nextToken();
}
foc = foc.trim();
if (foc.startsWith("|")) {
StringTokenizer atoms = new StringTokenizer(foc, "|");
foc = atoms.nextToken();
}
// bracket counters
StringTokenizer open = new StringTokenizer(foc, "(", true);
int openCount = 0;
while (open.hasMoreTokens()) {
String tmp = open.nextToken();
if (tmp.equals("(")) {
openCount++;
}
}
StringTokenizer closed = new StringTokenizer(foc, ")", true);
while (closed.hasMoreTokens()) {
String tmp = closed.nextToken();
if (tmp.equals(")")) {
openCount--;
}
}
formulaOfConcept = new StringBuilder(foc);
if (openCount > 0) {
for (int par = 0; par < openCount; par++) {
formulaOfConcept.append(")");
}
}
if (openCount < 0) {
for (int par = 0; par < openCount; par++) {
formulaOfConcept.insert(0, "(");
}
}
// assign formula to the node
node.getNodeData().setcLabFormula(formulaOfConcept.toString());
} }
|
public class class_name {
private void buildComplexConcept(INode node, List<String> tokensOfNodeLabel, String meaningfulTokens) {
// label of node
String token;
// List of ACoLs identifiers
List<String> vec = new ArrayList<String>();
// formula for the complex concept
StringBuilder formulaOfConcept = new StringBuilder();
// logical connective
String connective = " ";
// brackets to add
String bracket = "";
// whether to insert brackets
boolean insert;
// how many left brackets do not have corresponding right ones
int bracketsBalance = 0;
// number of left brackets
int leftBrackets = 0;
// for each token of node label
for (int i = 0; i < tokensOfNodeLabel.size(); i++) {
token = (tokensOfNodeLabel.get(i));
// depends on control dependency: [for], data = [i]
// If logical AND or OR
if (andWords.contains(" " + token + " ") || orWords.contains(" " + token + " ")) {
insert = false;
// depends on control dependency: [if], data = [none]
// If non first token
if (vec != null && vec.size() > 0) {
// construct formula
if (connective.isEmpty()) {
formulaOfConcept.append(" | ").append(bracket).append(encloseWithParentheses(vec));
// depends on control dependency: [if], data = [none]
} else {
formulaOfConcept.append(connective).append(bracket).append(encloseWithParentheses(vec));
// depends on control dependency: [if], data = [none]
}
insert = true;
// depends on control dependency: [if], data = [none]
connective = "";
bracket = "";
vec = new ArrayList<String>();
// depends on control dependency: [if], data = [none]
leftBrackets = 0;
// depends on control dependency: [if], data = [none]
}
// If bracket
if (token.equals("(") && bracketsBalance >= 0) {
connective = " & ";
// depends on control dependency: [if], data = [none]
bracket = "(";
// depends on control dependency: [if], data = [none]
bracketsBalance = bracketsBalance + 1;
// depends on control dependency: [if], data = [none]
leftBrackets = leftBrackets + 1;
// depends on control dependency: [if], data = [none]
} else if (token.equals(")") && bracketsBalance > 0) {
if (insert) {
formulaOfConcept.append(")");
// depends on control dependency: [if], data = [none]
}
bracketsBalance = bracketsBalance - 1;
// depends on control dependency: [if], data = [none]
} else {
connective = " | ";
// depends on control dependency: [if], data = [none]
}
// If logical not
} else if (notWords.contains(" " + token + " ")) {
if (vec != null && vec.size() > 0) {
formulaOfConcept.append(connective).append(encloseWithParentheses(vec));
// depends on control dependency: [if], data = [(vec]
vec = new ArrayList<String>();
// depends on control dependency: [if], data = [none]
connective = "";
// depends on control dependency: [if], data = [none]
}
// What to add
if (connective.contains("&") || connective.contains("|")) {
connective = connective + " ~ ";
// depends on control dependency: [if], data = [none]
} else {
connective = " & ~ ";
// depends on control dependency: [if], data = [none]
}
} else {
if (meaningfulTokens.contains(" " + i + " ")) {
// fill list with ACoL ids
vec.add((node.getNodeData().getId() + "." + i));
// depends on control dependency: [if], data = [none]
}
}
}
// Dealing with first token of the node
if (vec != null && vec.size() > 0) {
//construct formula
if (connective.contains("&") || connective.contains("|") || connective.equals(" ")) {
formulaOfConcept.append(connective).append(bracket).append(encloseWithParentheses(vec));
// depends on control dependency: [if], data = [none]
} else {
formulaOfConcept.append(" & ").append(encloseWithParentheses(vec));
// depends on control dependency: [if], data = [none]
}
connective = "";
// depends on control dependency: [if], data = [none]
} else {
if (leftBrackets > 0) {
bracketsBalance = bracketsBalance - leftBrackets;
// depends on control dependency: [if], data = [none]
}
}
if (bracketsBalance > 0) {
for (int i = 0; i < bracketsBalance; i++) {
formulaOfConcept.append(")");
// depends on control dependency: [for], data = [none]
}
}
// dealing with brackets
String foc = formulaOfConcept.toString();
foc = foc.replace('[', '(');
foc = foc.replace(']', ')');
foc = foc.replaceAll(", ", " & ");
foc = foc.trim();
if (foc.startsWith("&")) {
StringTokenizer atoms = new StringTokenizer(foc, "&");
foc = atoms.nextToken();
// depends on control dependency: [if], data = [none]
}
foc = foc.trim();
if (foc.startsWith("|")) {
StringTokenizer atoms = new StringTokenizer(foc, "|");
foc = atoms.nextToken();
// depends on control dependency: [if], data = [none]
}
// bracket counters
StringTokenizer open = new StringTokenizer(foc, "(", true);
int openCount = 0;
while (open.hasMoreTokens()) {
String tmp = open.nextToken();
if (tmp.equals("(")) {
openCount++;
// depends on control dependency: [if], data = [none]
}
}
StringTokenizer closed = new StringTokenizer(foc, ")", true);
while (closed.hasMoreTokens()) {
String tmp = closed.nextToken();
if (tmp.equals(")")) {
openCount--;
// depends on control dependency: [if], data = [none]
}
}
formulaOfConcept = new StringBuilder(foc);
if (openCount > 0) {
for (int par = 0; par < openCount; par++) {
formulaOfConcept.append(")");
// depends on control dependency: [for], data = [none]
}
}
if (openCount < 0) {
for (int par = 0; par < openCount; par++) {
formulaOfConcept.insert(0, "(");
// depends on control dependency: [for], data = [none]
}
}
// assign formula to the node
node.getNodeData().setcLabFormula(formulaOfConcept.toString());
} }
|
public class class_name {
private void removeExistingKeys(Collection<Data> keys) {
if (keys == null || keys.isEmpty()) {
return;
}
Storage storage = recordStore.getStorage();
keys.removeIf(storage::containsKey);
} }
|
public class class_name {
private void removeExistingKeys(Collection<Data> keys) {
if (keys == null || keys.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
Storage storage = recordStore.getStorage();
keys.removeIf(storage::containsKey);
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Override
public Set<JsonEntityBean> search(String entityType, String searchTerm) {
Set<JsonEntityBean> results = new HashSet<>();
EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType);
if (entityEnum == null) {
throw new IllegalArgumentException(
String.format("Parameter entityType has an unknown value of [%s]", entityType));
}
EntityIdentifier[] identifiers;
Class identifierType;
// if the entity type is a group, use the group service's findGroup method
// to locate it
if (entityEnum.isGroup()) {
identifiers =
GroupService.searchForGroups(
searchTerm,
GroupService.SearchMethod.CONTAINS_CI,
entityEnum.getClazz());
identifierType = IEntityGroup.class;
}
// otherwise use the getGroupMember method
else {
identifiers =
GroupService.searchForEntities(
searchTerm,
GroupService.SearchMethod.CONTAINS_CI,
entityEnum.getClazz());
identifierType = entityEnum.getClazz();
}
for (int i = 0; i < identifiers.length; i++) {
if (identifiers[i].getType().equals(identifierType)) {
IGroupMember entity = GroupService.getGroupMember(identifiers[i]);
if (entity != null) {
JsonEntityBean jsonBean = getEntity(entity);
results.add(jsonBean);
} else {
log.warn("Grouper member entity of " + identifiers[i].getKey() + " is null.");
}
}
}
return results;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Override
public Set<JsonEntityBean> search(String entityType, String searchTerm) {
Set<JsonEntityBean> results = new HashSet<>();
EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType);
if (entityEnum == null) {
throw new IllegalArgumentException(
String.format("Parameter entityType has an unknown value of [%s]", entityType));
}
EntityIdentifier[] identifiers;
Class identifierType;
// if the entity type is a group, use the group service's findGroup method
// to locate it
if (entityEnum.isGroup()) {
identifiers =
GroupService.searchForGroups(
searchTerm,
GroupService.SearchMethod.CONTAINS_CI,
entityEnum.getClazz()); // depends on control dependency: [if], data = [none]
identifierType = IEntityGroup.class; // depends on control dependency: [if], data = [none]
}
// otherwise use the getGroupMember method
else {
identifiers =
GroupService.searchForEntities(
searchTerm,
GroupService.SearchMethod.CONTAINS_CI,
entityEnum.getClazz()); // depends on control dependency: [if], data = [none]
identifierType = entityEnum.getClazz(); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < identifiers.length; i++) {
if (identifiers[i].getType().equals(identifierType)) {
IGroupMember entity = GroupService.getGroupMember(identifiers[i]);
if (entity != null) {
JsonEntityBean jsonBean = getEntity(entity);
results.add(jsonBean); // depends on control dependency: [if], data = [none]
} else {
log.warn("Grouper member entity of " + identifiers[i].getKey() + " is null."); // depends on control dependency: [if], data = [none]
}
}
}
return results;
} }
|
public class class_name {
private DataModel createDataModel()
{
Object value = getValue();
if (value == null)
{
return EMPTY_DATA_MODEL;
}
else if (value instanceof DataModel)
{
return (DataModel) value;
}
else
{
DataModel dataModel = null;
if (DATAMODEL_BUILDER_CLASS != null && value != null)
{
try
{
Object dataModelBuilderProxy = DATAMODEL_BUILDER_CLASS.newInstance();
dataModel = (DataModel) DATAMODEL_BUILDER_CREATE_DATAMODEL_METHOD.invoke(dataModelBuilderProxy,
getFacesContext(), value.getClass(), value);
}
catch (InstantiationException ex)
{
//No op
}
catch (IllegalAccessException ex)
{
//No op
}
catch (IllegalArgumentException ex)
{
//No op
}
catch (InvocationTargetException ex)
{
//No op
}
}
if (dataModel == null)
{
if (value instanceof List)
{
return new ListDataModel((List<?>) value);
}
else if (OBJECT_ARRAY_CLASS.isAssignableFrom(value.getClass()))
{
return new ArrayDataModel((Object[]) value);
}
else if (value instanceof ResultSet)
{
return new ResultSetDataModel((ResultSet) value);
}
else if (value instanceof Result)
{
return new ResultDataModel((Result) value);
}
else if (value instanceof Iterable)
{
return new IterableDataModel<>((Iterable<?>) value);
}
else if (value instanceof Map)
{
return new IterableDataModel<>(((Map<?, ?>) value).entrySet());
}
else if (value instanceof Collection)
{
return new CollectionDataModel((Collection) value);
}
else
{
return new ScalarDataModel(value);
}
}
else
{
return dataModel;
}
}
} }
|
public class class_name {
private DataModel createDataModel()
{
Object value = getValue();
if (value == null)
{
return EMPTY_DATA_MODEL; // depends on control dependency: [if], data = [none]
}
else if (value instanceof DataModel)
{
return (DataModel) value; // depends on control dependency: [if], data = [none]
}
else
{
DataModel dataModel = null;
if (DATAMODEL_BUILDER_CLASS != null && value != null)
{
try
{
Object dataModelBuilderProxy = DATAMODEL_BUILDER_CLASS.newInstance();
dataModel = (DataModel) DATAMODEL_BUILDER_CREATE_DATAMODEL_METHOD.invoke(dataModelBuilderProxy,
getFacesContext(), value.getClass(), value); // depends on control dependency: [try], data = [none]
}
catch (InstantiationException ex)
{
//No op
} // depends on control dependency: [catch], data = [none]
catch (IllegalAccessException ex)
{
//No op
} // depends on control dependency: [catch], data = [none]
catch (IllegalArgumentException ex)
{
//No op
} // depends on control dependency: [catch], data = [none]
catch (InvocationTargetException ex)
{
//No op
} // depends on control dependency: [catch], data = [none]
}
if (dataModel == null)
{
if (value instanceof List)
{
return new ListDataModel((List<?>) value); // depends on control dependency: [if], data = [none]
}
else if (OBJECT_ARRAY_CLASS.isAssignableFrom(value.getClass()))
{
return new ArrayDataModel((Object[]) value); // depends on control dependency: [if], data = [none]
}
else if (value instanceof ResultSet)
{
return new ResultSetDataModel((ResultSet) value); // depends on control dependency: [if], data = [none]
}
else if (value instanceof Result)
{
return new ResultDataModel((Result) value); // depends on control dependency: [if], data = [none]
}
else if (value instanceof Iterable)
{
return new IterableDataModel<>((Iterable<?>) value); // depends on control dependency: [if], data = [none]
}
else if (value instanceof Map)
{
return new IterableDataModel<>(((Map<?, ?>) value).entrySet()); // depends on control dependency: [if], data = [none]
}
else if (value instanceof Collection)
{
return new CollectionDataModel((Collection) value); // depends on control dependency: [if], data = [none]
}
else
{
return new ScalarDataModel(value); // depends on control dependency: [if], data = [none]
}
}
else
{
return dataModel; // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public void setPromoted(final boolean promoted) {
this.promoted = promoted;
for (final Artifact artifact : artifacts) {
artifact.setPromoted(promoted);
}
for (final Module suModule : submodules) {
suModule.setPromoted(promoted);
}
} }
|
public class class_name {
public void setPromoted(final boolean promoted) {
this.promoted = promoted;
for (final Artifact artifact : artifacts) {
artifact.setPromoted(promoted); // depends on control dependency: [for], data = [artifact]
}
for (final Module suModule : submodules) {
suModule.setPromoted(promoted); // depends on control dependency: [for], data = [suModule]
}
} }
|
public class class_name {
public void marshall(ListPlaybackConfigurationsRequest listPlaybackConfigurationsRequest, ProtocolMarshaller protocolMarshaller) {
if (listPlaybackConfigurationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listPlaybackConfigurationsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listPlaybackConfigurationsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(ListPlaybackConfigurationsRequest listPlaybackConfigurationsRequest, ProtocolMarshaller protocolMarshaller) {
if (listPlaybackConfigurationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listPlaybackConfigurationsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listPlaybackConfigurationsRequest.getNextToken(), NEXTTOKEN_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 final void putShort(int index, short value) {
final long pos = address + index;
if (index >= 0 && pos <= addressLimit - 2) {
UNSAFE.putShort(heapMemory, pos, value);
}
else if (address > addressLimit) {
throw new IllegalStateException("segment has been freed");
}
else {
// index is in fact invalid
throw new IndexOutOfBoundsException();
}
} }
|
public class class_name {
public final void putShort(int index, short value) {
final long pos = address + index;
if (index >= 0 && pos <= addressLimit - 2) {
UNSAFE.putShort(heapMemory, pos, value); // depends on control dependency: [if], data = [none]
}
else if (address > addressLimit) {
throw new IllegalStateException("segment has been freed");
}
else {
// index is in fact invalid
throw new IndexOutOfBoundsException();
}
} }
|
public class class_name {
public static boolean isCglibRenamedMethod(Method renamedMethod) {
String name = renamedMethod.getName();
if (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX)) {
int i = name.length() - 1;
while (i >= 0 && Character.isDigit(name.charAt(i))) {
i--;
}
return ((i > CGLIB_RENAMED_METHOD_PREFIX.length()) &&
(i < name.length() - 1) &&
(name.charAt(i) == '$'));
}
return false;
} }
|
public class class_name {
public static boolean isCglibRenamedMethod(Method renamedMethod) {
String name = renamedMethod.getName();
if (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX)) {
int i = name.length() - 1;
while (i >= 0 && Character.isDigit(name.charAt(i))) {
i--; // depends on control dependency: [while], data = [none]
}
return ((i > CGLIB_RENAMED_METHOD_PREFIX.length()) &&
(i < name.length() - 1) &&
(name.charAt(i) == '$')); // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
public void set(Throwable t) {
try {
lock.writeLock().lock();
this.t = t;
} finally {
lock.writeLock().unlock();
}
} }
|
public class class_name {
public void set(Throwable t) {
try {
lock.writeLock().lock(); // depends on control dependency: [try], data = [none]
this.t = t; // depends on control dependency: [try], data = [none]
} finally {
lock.writeLock().unlock();
}
} }
|
public class class_name {
public static int compareCodePoint(int codePoint, CharSequence s) {
if (s == null) {
return 1;
}
final int strLen = s.length();
if (strLen == 0) {
return 1;
}
int second = Character.codePointAt(s, 0);
int diff = codePoint - second;
if (diff != 0) {
return diff;
}
return strLen == Character.charCount(codePoint) ? 0 : -1;
} }
|
public class class_name {
public static int compareCodePoint(int codePoint, CharSequence s) {
if (s == null) {
return 1; // depends on control dependency: [if], data = [none]
}
final int strLen = s.length();
if (strLen == 0) {
return 1; // depends on control dependency: [if], data = [none]
}
int second = Character.codePointAt(s, 0);
int diff = codePoint - second;
if (diff != 0) {
return diff; // depends on control dependency: [if], data = [none]
}
return strLen == Character.charCount(codePoint) ? 0 : -1;
} }
|
public class class_name {
private String getQueryParam() {
final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);
if (param == null) {
return DEFAULT_QUERY_PARAM;
} else {
return param;
}
} }
|
public class class_name {
private String getQueryParam() {
final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);
if (param == null) {
return DEFAULT_QUERY_PARAM; // depends on control dependency: [if], data = [none]
} else {
return param; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
void generateOutboundCode(Definition def)
{
if (def.isSupportOutbound())
{
if (def.getMcfDefs() == null)
throw new IllegalStateException("Should define at least one mcf class");
for (int num = 0; num < def.getMcfDefs().size(); num++)
{
generateMultiMcfClassCode(def, "Mcf", num);
generateMultiMcfClassCode(def, "Mc", num);
generateMultiMcfClassCode(def, "McMeta", num);
if (!def.getMcfDefs().get(num).isUseCciConnection())
{
generateMultiMcfClassCode(def, "CfInterface", num);
generateMultiMcfClassCode(def, "Cf", num);
generateMultiMcfClassCode(def, "ConnInterface", num);
generateMultiMcfClassCode(def, "ConnImpl", num);
}
else
{
generateMultiMcfClassCode(def, "CciConn", num);
generateMultiMcfClassCode(def, "CciConnFactory", num);
generateMultiMcfClassCode(def, "ConnMeta", num);
generateMultiMcfClassCode(def, "ConnSpec", num);
}
}
}
} }
|
public class class_name {
void generateOutboundCode(Definition def)
{
if (def.isSupportOutbound())
{
if (def.getMcfDefs() == null)
throw new IllegalStateException("Should define at least one mcf class");
for (int num = 0; num < def.getMcfDefs().size(); num++)
{
generateMultiMcfClassCode(def, "Mcf", num); // depends on control dependency: [for], data = [num]
generateMultiMcfClassCode(def, "Mc", num); // depends on control dependency: [for], data = [num]
generateMultiMcfClassCode(def, "McMeta", num); // depends on control dependency: [for], data = [num]
if (!def.getMcfDefs().get(num).isUseCciConnection())
{
generateMultiMcfClassCode(def, "CfInterface", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "Cf", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "ConnInterface", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "ConnImpl", num); // depends on control dependency: [if], data = [none]
}
else
{
generateMultiMcfClassCode(def, "CciConn", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "CciConnFactory", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "ConnMeta", num); // depends on control dependency: [if], data = [none]
generateMultiMcfClassCode(def, "ConnSpec", num); // depends on control dependency: [if], data = [none]
}
}
}
} }
|
public class class_name {
public boolean containsKey(final K1 firstKey, final K2 secondKey) {
// existence check on inner map
final HashMap<K2, V> innerMap = map.get(firstKey);
if( innerMap == null ) {
return false;
}
return innerMap.containsKey(secondKey);
} }
|
public class class_name {
public boolean containsKey(final K1 firstKey, final K2 secondKey) {
// existence check on inner map
final HashMap<K2, V> innerMap = map.get(firstKey);
if( innerMap == null ) {
return false; // depends on control dependency: [if], data = [none]
}
return innerMap.containsKey(secondKey);
} }
|
public class class_name {
public void marshall(UpdateTaskSetRequest updateTaskSetRequest, ProtocolMarshaller protocolMarshaller) {
if (updateTaskSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateTaskSetRequest.getCluster(), CLUSTER_BINDING);
protocolMarshaller.marshall(updateTaskSetRequest.getService(), SERVICE_BINDING);
protocolMarshaller.marshall(updateTaskSetRequest.getTaskSet(), TASKSET_BINDING);
protocolMarshaller.marshall(updateTaskSetRequest.getScale(), SCALE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(UpdateTaskSetRequest updateTaskSetRequest, ProtocolMarshaller protocolMarshaller) {
if (updateTaskSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateTaskSetRequest.getCluster(), CLUSTER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateTaskSetRequest.getService(), SERVICE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateTaskSetRequest.getTaskSet(), TASKSET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateTaskSetRequest.getScale(), SCALE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static int encode(BigDecimal value, byte[] dst, int dstOffset) {
if (value == null) {
dst[dstOffset] = NULL_BYTE_HIGH;
return 1;
}
if (value.signum() == 0) {
dst[dstOffset] = (byte) 0x80;
return 1;
}
return encode(value).copyTo(dst, dstOffset);
} }
|
public class class_name {
public static int encode(BigDecimal value, byte[] dst, int dstOffset) {
if (value == null) {
dst[dstOffset] = NULL_BYTE_HIGH;
// depends on control dependency: [if], data = [none]
return 1;
// depends on control dependency: [if], data = [none]
}
if (value.signum() == 0) {
dst[dstOffset] = (byte) 0x80;
// depends on control dependency: [if], data = [none]
return 1;
// depends on control dependency: [if], data = [none]
}
return encode(value).copyTo(dst, dstOffset);
} }
|
public class class_name {
public void addChangingSimons() {
timer.schedule(new TimerTask() {
final Stopwatch tlStopwatch = SimonManager.getStopwatch("TL");
@Override
public void run() {
try {
lock.lock();
System.out.println("TL " + addStopwatchSplit(tlStopwatch));
} finally {
lock.unlock();
}
}
}, 0, 10000L);
} }
|
public class class_name {
public void addChangingSimons() {
timer.schedule(new TimerTask() {
final Stopwatch tlStopwatch = SimonManager.getStopwatch("TL");
@Override
public void run() {
try {
lock.lock(); // depends on control dependency: [try], data = [none]
System.out.println("TL " + addStopwatchSplit(tlStopwatch)); // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
}
}, 0, 10000L);
} }
|
public class class_name {
@Override
public void createStoreIfAbsent(String storeName, boolean bBinaryValues) {
DBConn dbConn = getDBConnection();
try {
synchronized (m_schemaLock) {
if (!m_schemaMgr.columnFamilyExists(dbConn, m_keyspace, storeName)) {
m_schemaMgr.createColumnFamily(dbConn, m_keyspace, storeName, bBinaryValues);
}
}
} finally {
returnDBConnection(dbConn);
}
} }
|
public class class_name {
@Override
public void createStoreIfAbsent(String storeName, boolean bBinaryValues) {
DBConn dbConn = getDBConnection();
try {
synchronized (m_schemaLock) { // depends on control dependency: [try], data = [none]
if (!m_schemaMgr.columnFamilyExists(dbConn, m_keyspace, storeName)) {
m_schemaMgr.createColumnFamily(dbConn, m_keyspace, storeName, bBinaryValues); // depends on control dependency: [if], data = [none]
}
}
} finally {
returnDBConnection(dbConn);
}
} }
|
public class class_name {
public void marshall(Participants participants, ProtocolMarshaller protocolMarshaller) {
if (participants == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(participants.getUsers(), USERS_BINDING);
protocolMarshaller.marshall(participants.getGroups(), GROUPS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(Participants participants, ProtocolMarshaller protocolMarshaller) {
if (participants == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(participants.getUsers(), USERS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(participants.getGroups(), GROUPS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private Set<Alert> getSelectedAlertsImpl(boolean allAlerts) {
TreePath[] paths = getTreeAlert().getSelectionPaths();
if (paths == null || paths.length == 0) {
return Collections.emptySet();
}
Set<Alert> alerts = new HashSet<>();
if (!allAlerts) {
DefaultMutableTreeNode alertNode = (DefaultMutableTreeNode) paths[0].getLastPathComponent();
alerts.add((Alert) alertNode.getUserObject());
return alerts;
}
for (int i = 0; i < paths.length; i++) {
DefaultMutableTreeNode alertNode = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
if (alertNode.getChildCount() == 0) {
alerts.add((Alert) alertNode.getUserObject());
continue;
}
for (int j = 0; j < alertNode.getChildCount(); j++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) alertNode.getChildAt(j);
alerts.add((Alert) node.getUserObject());
}
}
return alerts;
} }
|
public class class_name {
private Set<Alert> getSelectedAlertsImpl(boolean allAlerts) {
TreePath[] paths = getTreeAlert().getSelectionPaths();
if (paths == null || paths.length == 0) {
return Collections.emptySet();
// depends on control dependency: [if], data = [none]
}
Set<Alert> alerts = new HashSet<>();
if (!allAlerts) {
DefaultMutableTreeNode alertNode = (DefaultMutableTreeNode) paths[0].getLastPathComponent();
alerts.add((Alert) alertNode.getUserObject());
// depends on control dependency: [if], data = [none]
return alerts;
// depends on control dependency: [if], data = [none]
}
for (int i = 0; i < paths.length; i++) {
DefaultMutableTreeNode alertNode = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
if (alertNode.getChildCount() == 0) {
alerts.add((Alert) alertNode.getUserObject());
// depends on control dependency: [if], data = [none]
continue;
}
for (int j = 0; j < alertNode.getChildCount(); j++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) alertNode.getChildAt(j);
alerts.add((Alert) node.getUserObject());
// depends on control dependency: [for], data = [none]
}
}
return alerts;
} }
|
public class class_name {
public static void printSVMLightFormat(PrintWriter pw, ClassicCounter<Integer> c, int classNo) {
Integer[] features = c.keySet().toArray(new Integer[c.keySet().size()]);
Arrays.sort(features);
StringBuilder sb = new StringBuilder();
sb.append(classNo);
sb.append(' ');
for (int f: features) {
sb.append(f + 1).append(':').append(c.getCount(f)).append(' ');
}
pw.println(sb.toString());
} }
|
public class class_name {
public static void printSVMLightFormat(PrintWriter pw, ClassicCounter<Integer> c, int classNo) {
Integer[] features = c.keySet().toArray(new Integer[c.keySet().size()]);
Arrays.sort(features);
StringBuilder sb = new StringBuilder();
sb.append(classNo);
sb.append(' ');
for (int f: features) {
sb.append(f + 1).append(':').append(c.getCount(f)).append(' ');
// depends on control dependency: [for], data = [f]
}
pw.println(sb.toString());
} }
|
public class class_name {
public ServiceCall<Workspace> getWorkspace(GetWorkspaceOptions getWorkspaceOptions) {
Validator.notNull(getWorkspaceOptions, "getWorkspaceOptions cannot be null");
String[] pathSegments = { "v1/workspaces" };
String[] pathParameters = { getWorkspaceOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "getWorkspace");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
if (getWorkspaceOptions.export() != null) {
builder.query("export", String.valueOf(getWorkspaceOptions.export()));
}
if (getWorkspaceOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getWorkspaceOptions.includeAudit()));
}
if (getWorkspaceOptions.sort() != null) {
builder.query("sort", getWorkspaceOptions.sort());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Workspace.class));
} }
|
public class class_name {
public ServiceCall<Workspace> getWorkspace(GetWorkspaceOptions getWorkspaceOptions) {
Validator.notNull(getWorkspaceOptions, "getWorkspaceOptions cannot be null");
String[] pathSegments = { "v1/workspaces" };
String[] pathParameters = { getWorkspaceOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "getWorkspace");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header]
}
builder.header("Accept", "application/json");
if (getWorkspaceOptions.export() != null) {
builder.query("export", String.valueOf(getWorkspaceOptions.export())); // depends on control dependency: [if], data = [(getWorkspaceOptions.export()]
}
if (getWorkspaceOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getWorkspaceOptions.includeAudit())); // depends on control dependency: [if], data = [(getWorkspaceOptions.includeAudit()]
}
if (getWorkspaceOptions.sort() != null) {
builder.query("sort", getWorkspaceOptions.sort()); // depends on control dependency: [if], data = [none]
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Workspace.class));
} }
|
public class class_name {
@Override
public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state, LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) {
// reach the end of this layout
if (isOutOfRange(layoutState.getCurrentPosition())) {
return;
}
boolean isStartLine = false, isEndLine = false;
boolean isSecondStartLine = false, isSecondEndLine = false;
final int currentPosition = layoutState.getCurrentPosition();
GridRangeStyle rangeStyle = mRangeStyle.findRangeStyleByPosition(currentPosition);
final int itemDirection = layoutState.getItemDirection();
final boolean layingOutInPrimaryDirection =
itemDirection == LayoutStateWrapper.ITEM_DIRECTION_TAIL;
OrientationHelperEx orientationHelper = helper.getMainOrientationHelper();
final boolean layoutInVertical = helper.getOrientation() == VERTICAL;
if (layoutInVertical) {
mTotalSize = helper.getContentWidth() - helper.getPaddingRight() - helper.getPaddingLeft() - rangeStyle
.getFamilyHorizontalMargin() - rangeStyle.getFamilyHorizontalPadding();
rangeStyle.mSizePerSpan = (int) ((mTotalSize - (
rangeStyle.mSpanCount - 1) * rangeStyle.mHGap) * 1.0f / rangeStyle.mSpanCount + 0.5f);
} else {
mTotalSize = helper.getContentHeight() - helper.getPaddingBottom() - helper.getPaddingTop() - rangeStyle
.getFamilyVerticalMargin() - rangeStyle.getFamilyVerticalPadding();
rangeStyle.mSizePerSpan = (int) ((mTotalSize - (
rangeStyle.mSpanCount - 1) * rangeStyle.mVGap) * 1.0f / rangeStyle.mSpanCount + 0.5f);
}
int count = 0;
int consumedSpanCount = 0;
int remainingSpan = rangeStyle.mSpanCount;
rangeStyle.ensureSpanCount();
if (!layingOutInPrimaryDirection) {
// fill the remaining spacing this row
int itemSpanIndex = getSpanIndex(rangeStyle.mSpanSizeLookup, rangeStyle.mSpanCount, recycler, state, layoutState.getCurrentPosition());
int itemSpanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, layoutState.getCurrentPosition());
remainingSpan = itemSpanIndex + itemSpanSize;
// should find the last element of this row
if (itemSpanIndex != rangeStyle.mSpanCount - 1) {
int index = layoutState.getCurrentPosition();
int revRemainingSpan = rangeStyle.mSpanCount - remainingSpan;
while (count < rangeStyle.mSpanCount && revRemainingSpan > 0) {
// go reverse direction to find views fill current row
index -= itemDirection;
if (rangeStyle.isOutOfRange(index)) {
break;
}
final int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, index);
if (spanSize > rangeStyle.mSpanCount) {
throw new IllegalArgumentException("Item at position " + index + " requires " +
spanSize + " spans but RangeGridLayoutHelper has only " + rangeStyle.mSpanCount
+ " spans.");
}
View view = layoutState.retrieve(recycler, index);
if (view == null) {
break;
}
if (!isStartLine) {
isStartLine = helper.getReverseLayout() ? index == mRangeStyle.getRange().getUpper().intValue()
: index == mRangeStyle.getRange().getLower().intValue();
}
if (!isEndLine) {
isEndLine = helper.getReverseLayout() ? index == mRangeStyle.getRange().getLower().intValue()
: index == mRangeStyle.getRange().getUpper().intValue();
}
revRemainingSpan -= spanSize;
if (revRemainingSpan < 0) {
break;
}
consumedSpanCount += spanSize;
rangeStyle.mSet[count] = view;
count++;
}
if (count > 0) {
// reverse array
int s = 0, e = count - 1;
while (s < e) {
View temp = rangeStyle.mSet[s];
rangeStyle.mSet[s] = rangeStyle.mSet[e];
rangeStyle.mSet[e] = temp;
s++;
e--;
}
}
}
}
while (count < rangeStyle.mSpanCount && layoutState.hasMore(state) && remainingSpan > 0) {
int pos = layoutState.getCurrentPosition();
if (rangeStyle.isOutOfRange(pos)) {
if (DEBUG) {
Log.d(TAG, "pos [" + pos + "] is out of range");
}
break;
}
final int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, pos);
if (spanSize > rangeStyle.mSpanCount) {
throw new IllegalArgumentException("Item at position " + pos + " requires " +
spanSize + " spans but GridLayoutManager has only " + rangeStyle.mSpanCount
+ " spans.");
}
remainingSpan -= spanSize;
if (remainingSpan < 0) {
break; // item did not fit into this row or column
}
View view = layoutState.next(recycler);
if (view == null) {
break;
}
if (!isStartLine) {
isStartLine = helper.getReverseLayout() ? pos == mRangeStyle.getRange().getUpper().intValue()
: pos == mRangeStyle.getRange().getLower().intValue();
}
if (!isSecondStartLine) {
if (!rangeStyle.equals(mRangeStyle)) {
if (mLayoutWithAnchor) {
pos = layoutState.getCurrentPosition();
}
isSecondStartLine = helper.getReverseLayout() ? pos == rangeStyle.getRange().getUpper()
.intValue() : pos == rangeStyle.getRange().getLower().intValue();
}
}
if (!isEndLine) {
isEndLine = helper.getReverseLayout() ? pos == mRangeStyle.getRange().getLower().intValue()
: pos == mRangeStyle.getRange().getUpper().intValue();
}
if (!isSecondEndLine) {
if (!rangeStyle.equals(mRangeStyle)) {
if (mLayoutWithAnchor) {
pos = layoutState.getCurrentPosition();
}
isSecondEndLine = helper.getReverseLayout() ? pos == rangeStyle.getRange().getLower()
.intValue() : pos == rangeStyle.getRange().getUpper().intValue();
}
}
consumedSpanCount += spanSize;
rangeStyle.mSet[count] = view;
count++;
}
if (count == 0) {
return;
}
int maxSize = 0;
// we should assign spans before item decor offsets are calculated
assignSpans(rangeStyle, recycler, state, count, consumedSpanCount, layingOutInPrimaryDirection, helper);
if (remainingSpan > 0 && (count == consumedSpanCount) && rangeStyle.mIsAutoExpand) {
//autoExpand only support when each cell occupy one span.
if (layoutInVertical) {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mHGap) / count;
} else {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mVGap) / count;
}
} else if (!layingOutInPrimaryDirection && remainingSpan == 0 && (count == consumedSpanCount) && rangeStyle.mIsAutoExpand) {
//autoExpand only support when each cell occupy one span.
if (layoutInVertical) {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mHGap) / count;
} else {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mVGap) / count;
}
}
boolean weighted = false;
if (rangeStyle.mWeights != null && rangeStyle.mWeights.length > 0) {
weighted = true;
int totalSpace;
if (layoutInVertical) {
totalSpace = mTotalSize - (count - 1) * rangeStyle.mHGap;
} else {
totalSpace = mTotalSize - (count - 1) * rangeStyle.mVGap;
}
// calculate width with weight in percentage
int eqCnt = 0, remainingSpace = totalSpace;
int colCnt = (remainingSpan > 0 && rangeStyle.mIsAutoExpand) ? count : rangeStyle.mSpanCount;
for (int i = 0; i < colCnt; i++) {
if (i < rangeStyle.mWeights.length && !Float.isNaN(rangeStyle.mWeights[i]) && rangeStyle.mWeights[i] >= 0) {
float weight = rangeStyle.mWeights[i];
rangeStyle.mSpanCols[i] = (int) (weight * 1.0f / 100 * totalSpace + 0.5f);
remainingSpace -= rangeStyle.mSpanCols[i];
} else {
eqCnt++;
rangeStyle.mSpanCols[i] = -1;
}
}
if (eqCnt > 0) {
int eqLength = remainingSpace / eqCnt;
for (int i = 0; i < colCnt; i++) {
if (rangeStyle.mSpanCols[i] < 0) {
rangeStyle.mSpanCols[i] = eqLength;
}
}
}
}
for (int i = 0; i < count; i++) {
View view = rangeStyle.mSet[i];
helper.addChildView(layoutState, view, layingOutInPrimaryDirection ? -1 : 0);
int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, helper.getPosition(view)), spec;
if (weighted) {
final int index = rangeStyle.mSpanIndices[i];
int spanLength = 0;
for (int j = 0; j < spanSize; j++) {
spanLength += rangeStyle.mSpanCols[j + index];
}
spec = View.MeasureSpec.makeMeasureSpec(Math.max(0, spanLength), View.MeasureSpec.EXACTLY);
} else {
spec = View.MeasureSpec.makeMeasureSpec(rangeStyle.mSizePerSpan * spanSize +
Math.max(0, spanSize - 1) * (layoutInVertical ? rangeStyle.mHGap : rangeStyle.mVGap),
View.MeasureSpec.EXACTLY);
}
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (helper.getOrientation() == VERTICAL) {
helper.measureChildWithMargins(view, spec, getMainDirSpec(rangeStyle, lp.height, mTotalSize,
View.MeasureSpec.getSize(spec), lp.mAspectRatio));
} else {
helper.measureChildWithMargins(view,
getMainDirSpec(rangeStyle, lp.width, mTotalSize, View.MeasureSpec.getSize(spec),
lp.mAspectRatio), View.MeasureSpec.getSize(spec));
}
final int size = orientationHelper.getDecoratedMeasurement(view);
if (size > maxSize) {
maxSize = size;
}
}
// views that did not measure the maxSize has to be re-measured
final int maxMeasureSpec = getMainDirSpec(rangeStyle, maxSize, mTotalSize, 0, Float.NaN);
for (int i = 0; i < count; i++) {
final View view = rangeStyle.mSet[i];
if (orientationHelper.getDecoratedMeasurement(view) != maxSize) {
int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, helper.getPosition(view)), spec;
if (weighted) {
final int index = rangeStyle.mSpanIndices[i];
int spanLength = 0;
for (int j = 0; j < spanSize; j++) {
spanLength += rangeStyle.mSpanCols[j + index];
}
spec = View.MeasureSpec.makeMeasureSpec(Math.max(0, spanLength), View.MeasureSpec.EXACTLY);
} else {
spec = View.MeasureSpec.makeMeasureSpec(rangeStyle.mSizePerSpan * spanSize +
Math.max(0, spanSize - 1) * (layoutInVertical ? rangeStyle.mHGap : rangeStyle.mVGap),
View.MeasureSpec.EXACTLY);
}
if (helper.getOrientation() == VERTICAL) {
helper.measureChildWithMargins(view, spec, maxMeasureSpec);
} else {
helper.measureChildWithMargins(view, maxMeasureSpec, spec);
}
}
}
int startSpace = 0, endSpace = 0;
int secondStartSpace = 0, secondEndSpace = 0;
boolean isLayoutEnd = layoutState.getLayoutDirection() == VirtualLayoutManager.LayoutStateWrapper.LAYOUT_END;
final boolean isOverLapMargin = helper.isEnableMarginOverLap();
if (isStartLine) {
startSpace = computeStartSpace(helper, layoutInVertical, isLayoutEnd, isOverLapMargin);
}
if (isSecondStartLine) {
secondStartSpace = (layoutInVertical ? rangeStyle.getMarginTop() + rangeStyle.getPaddingTop()
: rangeStyle.getMarginLeft() + rangeStyle.getPaddingLeft());
}
if (isEndLine) {
endSpace = layoutInVertical ? mRangeStyle.getMarginBottom() + mRangeStyle.getPaddingBottom()
: mRangeStyle.getMarginRight() + mRangeStyle.getPaddingRight();
}
if (isSecondEndLine) {
secondEndSpace = (layoutInVertical ? rangeStyle.getMarginBottom() + rangeStyle.getPaddingBottom()
: rangeStyle.getMarginRight() + rangeStyle.getPaddingRight());
}
result.mConsumed = maxSize + startSpace + endSpace + secondStartSpace + secondEndSpace;
final boolean layoutStart = layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START;
int consumedGap = 0;
if (!mLayoutWithAnchor) {
if (!layoutStart) {
if (!isStartLine) {
if (isSecondStartLine) {
consumedGap = (layoutInVertical ? rangeStyle.mParent.mVGap : rangeStyle.mParent.mHGap);
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 1 " + consumedGap + " gap");
}
} else {
consumedGap = (layoutInVertical ? rangeStyle.mVGap : rangeStyle.mHGap);
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 2 " + consumedGap + " gap");
}
}
}
} else {
if (!isEndLine) {
if (isSecondEndLine) {
consumedGap = (layoutInVertical ? rangeStyle.mParent.mVGap : rangeStyle.mParent.mHGap);
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 3 " + consumedGap + " gap");
}
} else {
consumedGap = (layoutInVertical ? rangeStyle.mVGap : rangeStyle.mHGap);
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 4 " + consumedGap + " gap");
}
}
}
}
}
result.mConsumed += consumedGap;
if (result.mConsumed <= 0) {
result.mConsumed = 0;
}
int lastUnconsumedSpace = 0;
/** layoutView() may be triggered by layoutManager's scrollInternalBy() or onFocusSearchFailed() or onLayoutChildren()
*
* In case of scrollInternalBy() or onFocusSearchFailed(), layoutState.isRefreshLayout() == false, and layoutState.mOffset = ChildClosestToExpose + alignOffset,
* see {@link com.alibaba.android.vlayout.ExposeLinearLayoutManagerEx#updateLayoutStateExpose(int, int, boolean, State)},
* this means last line's layout padding or margin is not really consumed, so considering it before layout new line.
*
* In case of onLayoutChildren(), layoutState.isRefreshLayout() == true, and layoutState.mOffset = anchorInfo.mCoordinate = anchorChild.start + alignOffset,
* see {@link com.alibaba.android.vlayout.ExposeLinearLayoutManagerEx#updateAnchorInfoForLayoutExpose(State, AnchorInfo)},
* this means last line's layout padding or margin is consumed.
**/
if (!layoutState.isRefreshLayout()) {
if (layoutStart) {
int lastLinePosition = currentPosition + 1;
if (!isOutOfRange(lastLinePosition)) {
RangeStyle<GridRangeStyle> neighbourRange = mRangeStyle.findRangeStyleByPosition(lastLinePosition);
if (neighbourRange.isFirstPosition(lastLinePosition)) {
lastUnconsumedSpace = layoutInVertical ? neighbourRange.getMarginTop() + neighbourRange.getPaddingTop()
: neighbourRange.getMarginLeft() + neighbourRange.getPaddingLeft();
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 1 " + lastUnconsumedSpace + " last");
}
}
}
} else {
int lastLinePosition = currentPosition - 1;
if (!isOutOfRange(lastLinePosition)) {
RangeStyle<GridRangeStyle> neighbourRange = mRangeStyle.findRangeStyleByPosition(lastLinePosition);
if (neighbourRange.isLastPosition(lastLinePosition)) {
lastUnconsumedSpace = layoutInVertical ? neighbourRange.getMarginBottom() + neighbourRange.getPaddingBottom()
: neighbourRange.getMarginRight() + neighbourRange.getPaddingRight();
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 2 " + lastUnconsumedSpace + " last");
}
}
}
}
}
if (DEBUG) {
Log.d(TAG,
(layoutStart ? "⬆ " : "⬇ ") + currentPosition + " consumed " + result.mConsumed + " startSpace " + startSpace + " endSpace "
+ endSpace + " secondStartSpace " + secondStartSpace + " secondEndSpace " + secondEndSpace + " lastUnconsumedSpace " + lastUnconsumedSpace);
}
int left = 0, right = 0, top = 0, bottom = 0;
if (layoutInVertical) {
if (layoutStart) {
bottom = layoutState.getOffset() - endSpace - secondEndSpace - (consumedGap) - lastUnconsumedSpace;
top = bottom - maxSize;
} else {
top = layoutState.getOffset() + startSpace + secondStartSpace + (consumedGap) + lastUnconsumedSpace;
bottom = top + maxSize;
}
} else {
if (layoutStart) {
right = layoutState.getOffset() - endSpace - (consumedGap) - lastUnconsumedSpace;
left = right - maxSize;
} else {
left = layoutState.getOffset() + startSpace + (consumedGap) + lastUnconsumedSpace;
right = left + maxSize;
}
}
for (int i = 0; i < count; i++) {
View view = rangeStyle.mSet[i];
final int index = rangeStyle.mSpanIndices[i];
LayoutParams params = (LayoutParams) view.getLayoutParams();
if (layoutInVertical) {
if (weighted) {
left = helper.getPaddingLeft() + rangeStyle.getFamilyMarginLeft() + rangeStyle.getFamilyPaddingLeft();
for (int j = 0; j < index; j++) {
left += rangeStyle.mSpanCols[j] + rangeStyle.mHGap;
}
} else {
left = helper.getPaddingLeft() + rangeStyle.getFamilyMarginLeft() + rangeStyle
.getFamilyPaddingLeft() + rangeStyle.mSizePerSpan * index + index * rangeStyle.mHGap;
}
right = left + orientationHelper.getDecoratedMeasurementInOther(view);
} else {
if (weighted) {
top = helper.getPaddingTop() + rangeStyle.getFamilyMarginTop() + rangeStyle.getFamilyPaddingTop();
for (int j = 0; j < index; j++) {
top += rangeStyle.mSpanCols[j] + rangeStyle.mVGap;
}
} else {
top = helper.getPaddingTop() + rangeStyle.getFamilyMarginTop() + rangeStyle.getFamilyPaddingTop()
+ rangeStyle.mSizePerSpan * index + index * rangeStyle.mVGap;
}
bottom = top + orientationHelper.getDecoratedMeasurementInOther(view);
}
if (DEBUG) {
Log.d(TAG, "layout item in position: " + params.getViewPosition() + " with text with SpanIndex: " + index + " into (" +
left + ", " + top + ", " + right + ", " + bottom + " )");
}
// We calculate everything with View's bounding box (which includes decor and margins)
// To calculate correct layout position, we subtract margins.
rangeStyle.layoutChild(view, left, top, right, bottom, helper, false);
// Consume the available space if the view is not removed OR changed
if (params.isItemRemoved() || params.isItemChanged()) {
result.mIgnoreConsumed = true;
}
result.mFocusable |= view.isFocusable();
}
mLayoutWithAnchor = false;
Arrays.fill(rangeStyle.mSet, null);
Arrays.fill(rangeStyle.mSpanIndices, 0);
Arrays.fill(rangeStyle.mSpanCols, 0);
} }
|
public class class_name {
@Override
public void layoutViews(RecyclerView.Recycler recycler, RecyclerView.State state, LayoutStateWrapper layoutState, LayoutChunkResult result, LayoutManagerHelper helper) {
// reach the end of this layout
if (isOutOfRange(layoutState.getCurrentPosition())) {
return; // depends on control dependency: [if], data = [none]
}
boolean isStartLine = false, isEndLine = false;
boolean isSecondStartLine = false, isSecondEndLine = false;
final int currentPosition = layoutState.getCurrentPosition();
GridRangeStyle rangeStyle = mRangeStyle.findRangeStyleByPosition(currentPosition);
final int itemDirection = layoutState.getItemDirection();
final boolean layingOutInPrimaryDirection =
itemDirection == LayoutStateWrapper.ITEM_DIRECTION_TAIL;
OrientationHelperEx orientationHelper = helper.getMainOrientationHelper();
final boolean layoutInVertical = helper.getOrientation() == VERTICAL;
if (layoutInVertical) {
mTotalSize = helper.getContentWidth() - helper.getPaddingRight() - helper.getPaddingLeft() - rangeStyle
.getFamilyHorizontalMargin() - rangeStyle.getFamilyHorizontalPadding(); // depends on control dependency: [if], data = [none]
rangeStyle.mSizePerSpan = (int) ((mTotalSize - (
rangeStyle.mSpanCount - 1) * rangeStyle.mHGap) * 1.0f / rangeStyle.mSpanCount + 0.5f); // depends on control dependency: [if], data = [none]
} else {
mTotalSize = helper.getContentHeight() - helper.getPaddingBottom() - helper.getPaddingTop() - rangeStyle
.getFamilyVerticalMargin() - rangeStyle.getFamilyVerticalPadding(); // depends on control dependency: [if], data = [none]
rangeStyle.mSizePerSpan = (int) ((mTotalSize - (
rangeStyle.mSpanCount - 1) * rangeStyle.mVGap) * 1.0f / rangeStyle.mSpanCount + 0.5f); // depends on control dependency: [if], data = [none]
}
int count = 0;
int consumedSpanCount = 0;
int remainingSpan = rangeStyle.mSpanCount;
rangeStyle.ensureSpanCount();
if (!layingOutInPrimaryDirection) {
// fill the remaining spacing this row
int itemSpanIndex = getSpanIndex(rangeStyle.mSpanSizeLookup, rangeStyle.mSpanCount, recycler, state, layoutState.getCurrentPosition());
int itemSpanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, layoutState.getCurrentPosition());
remainingSpan = itemSpanIndex + itemSpanSize; // depends on control dependency: [if], data = [none]
// should find the last element of this row
if (itemSpanIndex != rangeStyle.mSpanCount - 1) {
int index = layoutState.getCurrentPosition();
int revRemainingSpan = rangeStyle.mSpanCount - remainingSpan;
while (count < rangeStyle.mSpanCount && revRemainingSpan > 0) {
// go reverse direction to find views fill current row
index -= itemDirection; // depends on control dependency: [while], data = [none]
if (rangeStyle.isOutOfRange(index)) {
break;
}
final int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, index);
if (spanSize > rangeStyle.mSpanCount) {
throw new IllegalArgumentException("Item at position " + index + " requires " +
spanSize + " spans but RangeGridLayoutHelper has only " + rangeStyle.mSpanCount
+ " spans.");
}
View view = layoutState.retrieve(recycler, index);
if (view == null) {
break;
}
if (!isStartLine) {
isStartLine = helper.getReverseLayout() ? index == mRangeStyle.getRange().getUpper().intValue()
: index == mRangeStyle.getRange().getLower().intValue(); // depends on control dependency: [if], data = [none]
}
if (!isEndLine) {
isEndLine = helper.getReverseLayout() ? index == mRangeStyle.getRange().getLower().intValue()
: index == mRangeStyle.getRange().getUpper().intValue(); // depends on control dependency: [if], data = [none]
}
revRemainingSpan -= spanSize; // depends on control dependency: [while], data = [none]
if (revRemainingSpan < 0) {
break;
}
consumedSpanCount += spanSize; // depends on control dependency: [while], data = [none]
rangeStyle.mSet[count] = view; // depends on control dependency: [while], data = [none]
count++; // depends on control dependency: [while], data = [none]
}
if (count > 0) {
// reverse array
int s = 0, e = count - 1;
while (s < e) {
View temp = rangeStyle.mSet[s];
rangeStyle.mSet[s] = rangeStyle.mSet[e]; // depends on control dependency: [while], data = [none]
rangeStyle.mSet[e] = temp; // depends on control dependency: [while], data = [none]
s++; // depends on control dependency: [while], data = [none]
e--; // depends on control dependency: [while], data = [none]
}
}
}
}
while (count < rangeStyle.mSpanCount && layoutState.hasMore(state) && remainingSpan > 0) {
int pos = layoutState.getCurrentPosition();
if (rangeStyle.isOutOfRange(pos)) {
if (DEBUG) {
Log.d(TAG, "pos [" + pos + "] is out of range"); // depends on control dependency: [if], data = [none]
}
break;
}
final int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, pos);
if (spanSize > rangeStyle.mSpanCount) {
throw new IllegalArgumentException("Item at position " + pos + " requires " +
spanSize + " spans but GridLayoutManager has only " + rangeStyle.mSpanCount
+ " spans.");
}
remainingSpan -= spanSize; // depends on control dependency: [while], data = [none]
if (remainingSpan < 0) {
break; // item did not fit into this row or column
}
View view = layoutState.next(recycler);
if (view == null) {
break;
}
if (!isStartLine) {
isStartLine = helper.getReverseLayout() ? pos == mRangeStyle.getRange().getUpper().intValue()
: pos == mRangeStyle.getRange().getLower().intValue(); // depends on control dependency: [if], data = [none]
}
if (!isSecondStartLine) {
if (!rangeStyle.equals(mRangeStyle)) {
if (mLayoutWithAnchor) {
pos = layoutState.getCurrentPosition(); // depends on control dependency: [if], data = [none]
}
isSecondStartLine = helper.getReverseLayout() ? pos == rangeStyle.getRange().getUpper()
.intValue() : pos == rangeStyle.getRange().getLower().intValue(); // depends on control dependency: [if], data = [none]
}
}
if (!isEndLine) {
isEndLine = helper.getReverseLayout() ? pos == mRangeStyle.getRange().getLower().intValue()
: pos == mRangeStyle.getRange().getUpper().intValue(); // depends on control dependency: [if], data = [none]
}
if (!isSecondEndLine) {
if (!rangeStyle.equals(mRangeStyle)) {
if (mLayoutWithAnchor) {
pos = layoutState.getCurrentPosition(); // depends on control dependency: [if], data = [none]
}
isSecondEndLine = helper.getReverseLayout() ? pos == rangeStyle.getRange().getLower()
.intValue() : pos == rangeStyle.getRange().getUpper().intValue(); // depends on control dependency: [if], data = [none]
}
}
consumedSpanCount += spanSize; // depends on control dependency: [while], data = [none]
rangeStyle.mSet[count] = view; // depends on control dependency: [while], data = [none]
count++; // depends on control dependency: [while], data = [none]
}
if (count == 0) {
return; // depends on control dependency: [if], data = [none]
}
int maxSize = 0;
// we should assign spans before item decor offsets are calculated
assignSpans(rangeStyle, recycler, state, count, consumedSpanCount, layingOutInPrimaryDirection, helper);
if (remainingSpan > 0 && (count == consumedSpanCount) && rangeStyle.mIsAutoExpand) {
//autoExpand only support when each cell occupy one span.
if (layoutInVertical) {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mHGap) / count; // depends on control dependency: [if], data = [none]
} else {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mVGap) / count; // depends on control dependency: [if], data = [none]
}
} else if (!layingOutInPrimaryDirection && remainingSpan == 0 && (count == consumedSpanCount) && rangeStyle.mIsAutoExpand) {
//autoExpand only support when each cell occupy one span.
if (layoutInVertical) {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mHGap) / count; // depends on control dependency: [if], data = [none]
} else {
rangeStyle.mSizePerSpan = (mTotalSize - (count - 1) * rangeStyle.mVGap) / count; // depends on control dependency: [if], data = [none]
}
}
boolean weighted = false;
if (rangeStyle.mWeights != null && rangeStyle.mWeights.length > 0) {
weighted = true; // depends on control dependency: [if], data = [none]
int totalSpace;
if (layoutInVertical) {
totalSpace = mTotalSize - (count - 1) * rangeStyle.mHGap; // depends on control dependency: [if], data = [none]
} else {
totalSpace = mTotalSize - (count - 1) * rangeStyle.mVGap; // depends on control dependency: [if], data = [none]
}
// calculate width with weight in percentage
int eqCnt = 0, remainingSpace = totalSpace;
int colCnt = (remainingSpan > 0 && rangeStyle.mIsAutoExpand) ? count : rangeStyle.mSpanCount;
for (int i = 0; i < colCnt; i++) {
if (i < rangeStyle.mWeights.length && !Float.isNaN(rangeStyle.mWeights[i]) && rangeStyle.mWeights[i] >= 0) {
float weight = rangeStyle.mWeights[i];
rangeStyle.mSpanCols[i] = (int) (weight * 1.0f / 100 * totalSpace + 0.5f); // depends on control dependency: [if], data = [none]
remainingSpace -= rangeStyle.mSpanCols[i]; // depends on control dependency: [if], data = [none]
} else {
eqCnt++; // depends on control dependency: [if], data = [none]
rangeStyle.mSpanCols[i] = -1; // depends on control dependency: [if], data = [none]
}
}
if (eqCnt > 0) {
int eqLength = remainingSpace / eqCnt;
for (int i = 0; i < colCnt; i++) {
if (rangeStyle.mSpanCols[i] < 0) {
rangeStyle.mSpanCols[i] = eqLength; // depends on control dependency: [if], data = [none]
}
}
}
}
for (int i = 0; i < count; i++) {
View view = rangeStyle.mSet[i];
helper.addChildView(layoutState, view, layingOutInPrimaryDirection ? -1 : 0); // depends on control dependency: [for], data = [none]
int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, helper.getPosition(view)), spec;
if (weighted) {
final int index = rangeStyle.mSpanIndices[i];
int spanLength = 0;
for (int j = 0; j < spanSize; j++) {
spanLength += rangeStyle.mSpanCols[j + index]; // depends on control dependency: [for], data = [j]
}
spec = View.MeasureSpec.makeMeasureSpec(Math.max(0, spanLength), View.MeasureSpec.EXACTLY); // depends on control dependency: [if], data = [none]
} else {
spec = View.MeasureSpec.makeMeasureSpec(rangeStyle.mSizePerSpan * spanSize +
Math.max(0, spanSize - 1) * (layoutInVertical ? rangeStyle.mHGap : rangeStyle.mVGap),
View.MeasureSpec.EXACTLY); // depends on control dependency: [if], data = [none]
}
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (helper.getOrientation() == VERTICAL) {
helper.measureChildWithMargins(view, spec, getMainDirSpec(rangeStyle, lp.height, mTotalSize,
View.MeasureSpec.getSize(spec), lp.mAspectRatio)); // depends on control dependency: [if], data = [none]
} else {
helper.measureChildWithMargins(view,
getMainDirSpec(rangeStyle, lp.width, mTotalSize, View.MeasureSpec.getSize(spec),
lp.mAspectRatio), View.MeasureSpec.getSize(spec)); // depends on control dependency: [if], data = [none]
}
final int size = orientationHelper.getDecoratedMeasurement(view);
if (size > maxSize) {
maxSize = size; // depends on control dependency: [if], data = [none]
}
}
// views that did not measure the maxSize has to be re-measured
final int maxMeasureSpec = getMainDirSpec(rangeStyle, maxSize, mTotalSize, 0, Float.NaN);
for (int i = 0; i < count; i++) {
final View view = rangeStyle.mSet[i];
if (orientationHelper.getDecoratedMeasurement(view) != maxSize) {
int spanSize = getSpanSize(rangeStyle.mSpanSizeLookup, recycler, state, helper.getPosition(view)), spec;
if (weighted) {
final int index = rangeStyle.mSpanIndices[i];
int spanLength = 0;
for (int j = 0; j < spanSize; j++) {
spanLength += rangeStyle.mSpanCols[j + index]; // depends on control dependency: [for], data = [j]
}
spec = View.MeasureSpec.makeMeasureSpec(Math.max(0, spanLength), View.MeasureSpec.EXACTLY); // depends on control dependency: [if], data = [none]
} else {
spec = View.MeasureSpec.makeMeasureSpec(rangeStyle.mSizePerSpan * spanSize +
Math.max(0, spanSize - 1) * (layoutInVertical ? rangeStyle.mHGap : rangeStyle.mVGap),
View.MeasureSpec.EXACTLY); // depends on control dependency: [if], data = [none]
}
if (helper.getOrientation() == VERTICAL) {
helper.measureChildWithMargins(view, spec, maxMeasureSpec); // depends on control dependency: [if], data = [none]
} else {
helper.measureChildWithMargins(view, maxMeasureSpec, spec); // depends on control dependency: [if], data = [none]
}
}
}
int startSpace = 0, endSpace = 0;
int secondStartSpace = 0, secondEndSpace = 0;
boolean isLayoutEnd = layoutState.getLayoutDirection() == VirtualLayoutManager.LayoutStateWrapper.LAYOUT_END;
final boolean isOverLapMargin = helper.isEnableMarginOverLap();
if (isStartLine) {
startSpace = computeStartSpace(helper, layoutInVertical, isLayoutEnd, isOverLapMargin); // depends on control dependency: [if], data = [none]
}
if (isSecondStartLine) {
secondStartSpace = (layoutInVertical ? rangeStyle.getMarginTop() + rangeStyle.getPaddingTop()
: rangeStyle.getMarginLeft() + rangeStyle.getPaddingLeft()); // depends on control dependency: [if], data = [none]
}
if (isEndLine) {
endSpace = layoutInVertical ? mRangeStyle.getMarginBottom() + mRangeStyle.getPaddingBottom()
: mRangeStyle.getMarginRight() + mRangeStyle.getPaddingRight(); // depends on control dependency: [if], data = [none]
}
if (isSecondEndLine) {
secondEndSpace = (layoutInVertical ? rangeStyle.getMarginBottom() + rangeStyle.getPaddingBottom()
: rangeStyle.getMarginRight() + rangeStyle.getPaddingRight()); // depends on control dependency: [if], data = [none]
}
result.mConsumed = maxSize + startSpace + endSpace + secondStartSpace + secondEndSpace;
final boolean layoutStart = layoutState.getLayoutDirection() == LayoutStateWrapper.LAYOUT_START;
int consumedGap = 0;
if (!mLayoutWithAnchor) {
if (!layoutStart) {
if (!isStartLine) {
if (isSecondStartLine) {
consumedGap = (layoutInVertical ? rangeStyle.mParent.mVGap : rangeStyle.mParent.mHGap); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 1 " + consumedGap + " gap"); // depends on control dependency: [if], data = [none]
}
} else {
consumedGap = (layoutInVertical ? rangeStyle.mVGap : rangeStyle.mHGap); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 2 " + consumedGap + " gap"); // depends on control dependency: [if], data = [none]
}
}
}
} else {
if (!isEndLine) {
if (isSecondEndLine) {
consumedGap = (layoutInVertical ? rangeStyle.mParent.mVGap : rangeStyle.mParent.mHGap); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 3 " + consumedGap + " gap"); // depends on control dependency: [if], data = [none]
}
} else {
consumedGap = (layoutInVertical ? rangeStyle.mVGap : rangeStyle.mHGap); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 4 " + consumedGap + " gap"); // depends on control dependency: [if], data = [none]
}
}
}
}
}
result.mConsumed += consumedGap;
if (result.mConsumed <= 0) {
result.mConsumed = 0; // depends on control dependency: [if], data = [none]
}
int lastUnconsumedSpace = 0;
/** layoutView() may be triggered by layoutManager's scrollInternalBy() or onFocusSearchFailed() or onLayoutChildren()
*
* In case of scrollInternalBy() or onFocusSearchFailed(), layoutState.isRefreshLayout() == false, and layoutState.mOffset = ChildClosestToExpose + alignOffset,
* see {@link com.alibaba.android.vlayout.ExposeLinearLayoutManagerEx#updateLayoutStateExpose(int, int, boolean, State)},
* this means last line's layout padding or margin is not really consumed, so considering it before layout new line.
*
* In case of onLayoutChildren(), layoutState.isRefreshLayout() == true, and layoutState.mOffset = anchorInfo.mCoordinate = anchorChild.start + alignOffset,
* see {@link com.alibaba.android.vlayout.ExposeLinearLayoutManagerEx#updateAnchorInfoForLayoutExpose(State, AnchorInfo)},
* this means last line's layout padding or margin is consumed.
**/
if (!layoutState.isRefreshLayout()) {
if (layoutStart) {
int lastLinePosition = currentPosition + 1;
if (!isOutOfRange(lastLinePosition)) {
RangeStyle<GridRangeStyle> neighbourRange = mRangeStyle.findRangeStyleByPosition(lastLinePosition);
if (neighbourRange.isFirstPosition(lastLinePosition)) {
lastUnconsumedSpace = layoutInVertical ? neighbourRange.getMarginTop() + neighbourRange.getPaddingTop()
: neighbourRange.getMarginLeft() + neighbourRange.getPaddingLeft(); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬆ " + currentPosition + " 1 " + lastUnconsumedSpace + " last"); // depends on control dependency: [if], data = [none]
}
}
}
} else {
int lastLinePosition = currentPosition - 1;
if (!isOutOfRange(lastLinePosition)) {
RangeStyle<GridRangeStyle> neighbourRange = mRangeStyle.findRangeStyleByPosition(lastLinePosition);
if (neighbourRange.isLastPosition(lastLinePosition)) {
lastUnconsumedSpace = layoutInVertical ? neighbourRange.getMarginBottom() + neighbourRange.getPaddingBottom()
: neighbourRange.getMarginRight() + neighbourRange.getPaddingRight(); // depends on control dependency: [if], data = [none]
if (DEBUG) {
Log.d(TAG, "⬇ " + currentPosition + " 2 " + lastUnconsumedSpace + " last"); // depends on control dependency: [if], data = [none]
}
}
}
}
}
if (DEBUG) {
Log.d(TAG,
(layoutStart ? "⬆ " : "⬇ ") + currentPosition + " consumed " + result.mConsumed + " startSpace " + startSpace + " endSpace "
+ endSpace + " secondStartSpace " + secondStartSpace + " secondEndSpace " + secondEndSpace + " lastUnconsumedSpace " + lastUnconsumedSpace); // depends on control dependency: [if], data = [none]
}
int left = 0, right = 0, top = 0, bottom = 0;
if (layoutInVertical) {
if (layoutStart) {
bottom = layoutState.getOffset() - endSpace - secondEndSpace - (consumedGap) - lastUnconsumedSpace; // depends on control dependency: [if], data = [none]
top = bottom - maxSize; // depends on control dependency: [if], data = [none]
} else {
top = layoutState.getOffset() + startSpace + secondStartSpace + (consumedGap) + lastUnconsumedSpace; // depends on control dependency: [if], data = [none]
bottom = top + maxSize; // depends on control dependency: [if], data = [none]
}
} else {
if (layoutStart) {
right = layoutState.getOffset() - endSpace - (consumedGap) - lastUnconsumedSpace; // depends on control dependency: [if], data = [none]
left = right - maxSize; // depends on control dependency: [if], data = [none]
} else {
left = layoutState.getOffset() + startSpace + (consumedGap) + lastUnconsumedSpace; // depends on control dependency: [if], data = [none]
right = left + maxSize; // depends on control dependency: [if], data = [none]
}
}
for (int i = 0; i < count; i++) {
View view = rangeStyle.mSet[i];
final int index = rangeStyle.mSpanIndices[i];
LayoutParams params = (LayoutParams) view.getLayoutParams();
if (layoutInVertical) {
if (weighted) {
left = helper.getPaddingLeft() + rangeStyle.getFamilyMarginLeft() + rangeStyle.getFamilyPaddingLeft(); // depends on control dependency: [if], data = [none]
for (int j = 0; j < index; j++) {
left += rangeStyle.mSpanCols[j] + rangeStyle.mHGap; // depends on control dependency: [for], data = [j]
}
} else {
left = helper.getPaddingLeft() + rangeStyle.getFamilyMarginLeft() + rangeStyle
.getFamilyPaddingLeft() + rangeStyle.mSizePerSpan * index + index * rangeStyle.mHGap; // depends on control dependency: [if], data = [none]
}
right = left + orientationHelper.getDecoratedMeasurementInOther(view); // depends on control dependency: [if], data = [none]
} else {
if (weighted) {
top = helper.getPaddingTop() + rangeStyle.getFamilyMarginTop() + rangeStyle.getFamilyPaddingTop(); // depends on control dependency: [if], data = [none]
for (int j = 0; j < index; j++) {
top += rangeStyle.mSpanCols[j] + rangeStyle.mVGap; // depends on control dependency: [for], data = [j]
}
} else {
top = helper.getPaddingTop() + rangeStyle.getFamilyMarginTop() + rangeStyle.getFamilyPaddingTop()
+ rangeStyle.mSizePerSpan * index + index * rangeStyle.mVGap; // depends on control dependency: [if], data = [none]
}
bottom = top + orientationHelper.getDecoratedMeasurementInOther(view); // depends on control dependency: [if], data = [none]
}
if (DEBUG) {
Log.d(TAG, "layout item in position: " + params.getViewPosition() + " with text with SpanIndex: " + index + " into (" +
left + ", " + top + ", " + right + ", " + bottom + " )");
}
// We calculate everything with View's bounding box (which includes decor and margins)
// To calculate correct layout position, we subtract margins.
rangeStyle.layoutChild(view, left, top, right, bottom, helper, false);
// Consume the available space if the view is not removed OR changed
if (params.isItemRemoved() || params.isItemChanged()) {
result.mIgnoreConsumed = true;
}
result.mFocusable |= view.isFocusable();
}
mLayoutWithAnchor = false;
Arrays.fill(rangeStyle.mSet, null);
Arrays.fill(rangeStyle.mSpanIndices, 0);
Arrays.fill(rangeStyle.mSpanCols, 0);
} }
|
public class class_name {
public static <T, K> List<T> move(List<T> list, K key, K ref,
Function<T, K> keyMapper, boolean before,
Function<T, Integer> orderGet, OrderSetter<T> orderSet, int orderGap) {
if (key == ref)
return null;
// { 找到要移动的项和参考项所在位置
int keyidx = -1;
int refidx = -1;
int idx = 0;
for (T t : list) {
K id = keyMapper.apply(t);
if (id.equals(key))
keyidx = idx;
if (id.equals(ref))
refidx = idx;
if (keyidx != -1 && refidx != -1)
break;
idx++;
}
if (keyidx == -1 || refidx == -1)
return null;
// }
// { 拿走要移动的项
T t = list.remove(keyidx);
if (refidx >= keyidx)
refidx--;
if (!before)
refidx++;
// }
// 放回要移动的项
list.add(refidx, t);
// { 设置排序位置
ArrayList<T> moved = new ArrayList<T>();
int startOrder = 0;
if (refidx > 0)
startOrder = orderGet.apply(list.get(refidx - 1));
for (int i = refidx + 1; i < list.size(); i++) {
int order = orderGet.apply(list.get(i));
if (order - startOrder >= i - refidx + 1) {
int gap = (order - startOrder) / (i - refidx + 1);
for (int j = refidx; j < i; j++) {
T move = list.get(j);
orderSet.apply(move, startOrder + (j - refidx + 1) * gap);
moved.add(move);
}
return moved;
}
}
for (int i = refidx; i < list.size(); i++) {
T move = list.get(i);
orderSet.apply(move, startOrder + (i - refidx + 1) * orderGap);
moved.add(move);
}
return moved;
// }
} }
|
public class class_name {
public static <T, K> List<T> move(List<T> list, K key, K ref,
Function<T, K> keyMapper, boolean before,
Function<T, Integer> orderGet, OrderSetter<T> orderSet, int orderGap) {
if (key == ref)
return null;
// { 找到要移动的项和参考项所在位置
int keyidx = -1;
int refidx = -1;
int idx = 0;
for (T t : list) {
K id = keyMapper.apply(t);
if (id.equals(key))
keyidx = idx;
if (id.equals(ref))
refidx = idx;
if (keyidx != -1 && refidx != -1)
break;
idx++;
// depends on control dependency: [for], data = [none]
}
if (keyidx == -1 || refidx == -1)
return null;
// }
// { 拿走要移动的项
T t = list.remove(keyidx);
if (refidx >= keyidx)
refidx--;
if (!before)
refidx++;
// }
// 放回要移动的项
list.add(refidx, t);
// { 设置排序位置
ArrayList<T> moved = new ArrayList<T>();
int startOrder = 0;
if (refidx > 0)
startOrder = orderGet.apply(list.get(refidx - 1));
for (int i = refidx + 1; i < list.size(); i++) {
int order = orderGet.apply(list.get(i));
if (order - startOrder >= i - refidx + 1) {
int gap = (order - startOrder) / (i - refidx + 1);
for (int j = refidx; j < i; j++) {
T move = list.get(j);
orderSet.apply(move, startOrder + (j - refidx + 1) * gap);
// depends on control dependency: [for], data = [j]
moved.add(move);
// depends on control dependency: [for], data = [none]
}
return moved;
// depends on control dependency: [if], data = [none]
}
}
for (int i = refidx; i < list.size(); i++) {
T move = list.get(i);
orderSet.apply(move, startOrder + (i - refidx + 1) * orderGap);
// depends on control dependency: [for], data = [i]
moved.add(move);
// depends on control dependency: [for], data = [none]
}
return moved;
// }
} }
|
public class class_name {
public <E> Iterable<E> searchForAll(final Object searchableAnnotatedObject) {
try {
return searchForAll(this.<E>asList(searchableAnnotatedObject, configureMatcher(getSearchableMetaData(
searchableAnnotatedObject))));
}
finally {
MatcherHolder.unset();
}
} }
|
public class class_name {
public <E> Iterable<E> searchForAll(final Object searchableAnnotatedObject) {
try {
return searchForAll(this.<E>asList(searchableAnnotatedObject, configureMatcher(getSearchableMetaData(
searchableAnnotatedObject)))); // depends on control dependency: [try], data = [none]
}
finally {
MatcherHolder.unset();
}
} }
|
public class class_name {
private static synchronized Long generateGuid() {
StringBuilder builder = new StringBuilder();
builder.append(System.currentTimeMillis());
builder.append(guidCounter++);
// Reset the counter if it gets too high. It's always a number
// between 100 and 999 so that the # of digits in the guid is
// always the same.
if (guidCounter > 999) {
guidCounter = 100;
}
return Long.parseLong(builder.toString());
} }
|
public class class_name {
private static synchronized Long generateGuid() {
StringBuilder builder = new StringBuilder();
builder.append(System.currentTimeMillis());
builder.append(guidCounter++);
// Reset the counter if it gets too high. It's always a number
// between 100 and 999 so that the # of digits in the guid is
// always the same.
if (guidCounter > 999) {
guidCounter = 100; // depends on control dependency: [if], data = [none]
}
return Long.parseLong(builder.toString());
} }
|
public class class_name {
public T setLogDirectory(final String path) {
if (path == null) {
logDir = null;
return getThis();
}
return setLogDirectory(Paths.get(path));
} }
|
public class class_name {
public T setLogDirectory(final String path) {
if (path == null) {
logDir = null; // depends on control dependency: [if], data = [none]
return getThis(); // depends on control dependency: [if], data = [none]
}
return setLogDirectory(Paths.get(path));
} }
|
public class class_name {
public void createProdInstance() {
// Checks if instance exists, creates instance if does not exists.
if (!adminClient.exists(instanceId)) {
System.out.println("Instance does not exist, creating a PRODUCTION instance");
// [START bigtable_create_prod_instance]
// Creates a Production Instance with the ID "ssd-instance",
// cluster id "ssd-cluster", 3 nodes and location "us-central1-f".
CreateInstanceRequest createInstanceRequest =
CreateInstanceRequest.of(instanceId)
.addCluster(clusterId, "us-central1-f", 3, StorageType.SSD)
.setType(Instance.Type.PRODUCTION)
.addLabel("department", "accounting");
// Creates a production instance with the given request.
try {
Instance instance = adminClient.createInstance(createInstanceRequest);
System.out.printf("PRODUCTION type instance %s created successfully%n", instance.getId());
} catch (Exception e) {
System.err.println("Failed to create instance: " + e.getMessage());
throw e;
}
// [END bigtable_create_prod_instance]
}
} }
|
public class class_name {
public void createProdInstance() {
// Checks if instance exists, creates instance if does not exists.
if (!adminClient.exists(instanceId)) {
System.out.println("Instance does not exist, creating a PRODUCTION instance"); // depends on control dependency: [if], data = [none]
// [START bigtable_create_prod_instance]
// Creates a Production Instance with the ID "ssd-instance",
// cluster id "ssd-cluster", 3 nodes and location "us-central1-f".
CreateInstanceRequest createInstanceRequest =
CreateInstanceRequest.of(instanceId)
.addCluster(clusterId, "us-central1-f", 3, StorageType.SSD)
.setType(Instance.Type.PRODUCTION)
.addLabel("department", "accounting");
// Creates a production instance with the given request.
try {
Instance instance = adminClient.createInstance(createInstanceRequest);
System.out.printf("PRODUCTION type instance %s created successfully%n", instance.getId()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
System.err.println("Failed to create instance: " + e.getMessage());
throw e;
} // depends on control dependency: [catch], data = [none]
// [END bigtable_create_prod_instance]
}
} }
|
public class class_name {
public static void updateLocale(final HasComponents ui, final Locale locale,
final ResourceBundle rb) {
// locale may not be null, however the current UI Locale may be null!
if (locale.equals(ui.getLocale())) {
return;
}
final long time = System.currentTimeMillis();
walkComponentTree(ui, (Component c) -> {
String id = c.getId();
String caption;
if (c instanceof Property
&& ((Property) c).getValue() instanceof String) {
caption = (String) ((Property) c).getValue();
} else {
caption = c.getCaption();
}
if (id != null && !id.trim().isEmpty()) {
if (rb.containsKey(id)) {
try {
c.setCaption(new String(rb.getString(id)
.getBytes("ISO-8859-1"), "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
} else if (caption != null && !caption.trim().isEmpty()) {
/**
* This is a more complex scenario where the caption uses more
* than one key for translation. Sort the keys in reverse so
* substitutions are correct.
*/
final SortedSet<String> ss = new TreeSet<>(Collections.reverseOrder());
for (Enumeration<String> e = rb.getKeys(); e.hasMoreElements();) {
try {
String key = e.nextElement();
ss.add(key);
caption = caption.replaceAll(key, new String(rb.getString(key)
.getBytes("ISO-8859-1"), "UTF-8"));
}
catch (UnsupportedEncodingException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
if (c instanceof Property) {
((Property) c).setValue(caption);
} else {
c.setCaption(caption);
}
}
});
LOG.log(Level.FINE, "Locale updated: {0} -> {1} in {2} ms.",
new Object[]{ui.getLocale(), locale,
System.currentTimeMillis() - time});
} }
|
public class class_name {
public static void updateLocale(final HasComponents ui, final Locale locale,
final ResourceBundle rb) {
// locale may not be null, however the current UI Locale may be null!
if (locale.equals(ui.getLocale())) {
return;
// depends on control dependency: [if], data = [none]
}
final long time = System.currentTimeMillis();
walkComponentTree(ui, (Component c) -> {
String id = c.getId();
String caption;
if (c instanceof Property
&& ((Property) c).getValue() instanceof String) {
caption = (String) ((Property) c).getValue();
// depends on control dependency: [if], data = [none]
} else {
caption = c.getCaption();
// depends on control dependency: [if], data = [none]
}
if (id != null && !id.trim().isEmpty()) {
if (rb.containsKey(id)) {
try {
c.setCaption(new String(rb.getString(id)
.getBytes("ISO-8859-1"), "UTF-8"));
// depends on control dependency: [try], data = [none]
}
catch (UnsupportedEncodingException ex) {
LOG.log(Level.SEVERE, null, ex);
}
// depends on control dependency: [catch], data = [none]
}
} else if (caption != null && !caption.trim().isEmpty()) {
/**
* This is a more complex scenario where the caption uses more
* than one key for translation. Sort the keys in reverse so
* substitutions are correct.
*/
final SortedSet<String> ss = new TreeSet<>(Collections.reverseOrder());
for (Enumeration<String> e = rb.getKeys(); e.hasMoreElements();) {
try {
String key = e.nextElement();
ss.add(key);
// depends on control dependency: [try], data = [none]
caption = caption.replaceAll(key, new String(rb.getString(key)
.getBytes("ISO-8859-1"), "UTF-8"));
// depends on control dependency: [try], data = [none]
}
catch (UnsupportedEncodingException ex) {
LOG.log(Level.SEVERE, null, ex);
}
// depends on control dependency: [catch], data = [none]
}
if (c instanceof Property) {
((Property) c).setValue(caption);
// depends on control dependency: [if], data = [none]
} else {
c.setCaption(caption);
// depends on control dependency: [if], data = [none]
}
}
});
LOG.log(Level.FINE, "Locale updated: {0} -> {1} in {2} ms.",
new Object[]{ui.getLocale(), locale,
System.currentTimeMillis() - time});
} }
|
public class class_name {
public static void bufferedToPlanar_F32(BufferedImage src, Planar<GrayF32> dst) {
final int width = src.getWidth();
final int height = src.getHeight();
if (dst.getNumBands() == 3) {
final float[] band1 = dst.getBand(0).data;
final float[] band2 = dst.getBand(1).data;
final float[] band3 = dst.getBand(2).data;
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> {
for (int y = 0; y < height; y++) {
int index = dst.startIndex + y * dst.stride;
for (int x = 0; x < width; x++, index++) {
int argb = src.getRGB(x, y);
band1[index] = (argb >>> 16) & 0xFF;
band2[index] = (argb >>> 8) & 0xFF;
band3[index] = argb & 0xFF;
}
}
//CONCURRENT_ABOVE });
} else if (dst.getNumBands() == 4) {
final float[] band1 = dst.getBand(0).data;
final float[] band2 = dst.getBand(1).data;
final float[] band3 = dst.getBand(2).data;
final float[] band4 = dst.getBand(3).data;
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> {
for (int y = 0; y < height; y++) {
int index = dst.startIndex + y * dst.stride;
for (int x = 0; x < width; x++, index++) {
int argb = src.getRGB(x, y);
band1[index] = (argb >>> 24) & 0xFF;
band2[index] = (argb >>> 16) & 0xFF;
band3[index] = (argb >>> 8) & 0xFF;
band4[index] = argb & 0xFF;
}
}
//CONCURRENT_ABOVE });
} else if( dst.getNumBands() == 1 ){
bufferedToGray(src, dst.getBand(0).data, dst.startIndex, dst.stride);
} else {
throw new IllegalArgumentException("Unsupported number of input bands");
}
} }
|
public class class_name {
public static void bufferedToPlanar_F32(BufferedImage src, Planar<GrayF32> dst) {
final int width = src.getWidth();
final int height = src.getHeight();
if (dst.getNumBands() == 3) {
final float[] band1 = dst.getBand(0).data;
final float[] band2 = dst.getBand(1).data;
final float[] band3 = dst.getBand(2).data;
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> {
for (int y = 0; y < height; y++) {
int index = dst.startIndex + y * dst.stride;
for (int x = 0; x < width; x++, index++) {
int argb = src.getRGB(x, y);
band1[index] = (argb >>> 16) & 0xFF; // depends on control dependency: [for], data = [none]
band2[index] = (argb >>> 8) & 0xFF; // depends on control dependency: [for], data = [none]
band3[index] = argb & 0xFF; // depends on control dependency: [for], data = [none]
}
}
//CONCURRENT_ABOVE });
} else if (dst.getNumBands() == 4) {
final float[] band1 = dst.getBand(0).data;
final float[] band2 = dst.getBand(1).data;
final float[] band3 = dst.getBand(2).data;
final float[] band4 = dst.getBand(3).data;
//CONCURRENT_BELOW BoofConcurrency.loopFor(0, height, y -> {
for (int y = 0; y < height; y++) {
int index = dst.startIndex + y * dst.stride;
for (int x = 0; x < width; x++, index++) {
int argb = src.getRGB(x, y);
band1[index] = (argb >>> 24) & 0xFF; // depends on control dependency: [for], data = [none]
band2[index] = (argb >>> 16) & 0xFF; // depends on control dependency: [for], data = [none]
band3[index] = (argb >>> 8) & 0xFF; // depends on control dependency: [for], data = [none]
band4[index] = argb & 0xFF; // depends on control dependency: [for], data = [none]
}
}
//CONCURRENT_ABOVE });
} else if( dst.getNumBands() == 1 ){
bufferedToGray(src, dst.getBand(0).data, dst.startIndex, dst.stride); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unsupported number of input bands");
}
} }
|
public class class_name {
public void marshall(KeyValue keyValue, ProtocolMarshaller protocolMarshaller) {
if (keyValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(keyValue.getKey(), KEY_BINDING);
protocolMarshaller.marshall(keyValue.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(KeyValue keyValue, ProtocolMarshaller protocolMarshaller) {
if (keyValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(keyValue.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(keyValue.getValue(), VALUE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static String abbreviateInt(Number number, int decPlaces) {
if (number == null) {
return "";
}
String abbrevn = number.toString();
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = (int) Math.pow(10, decPlaces);
// Enumerate number abbreviations
String[] abbrev = {"K", "M", "B", "T"};
boolean done = false;
// Go through the array backwards, so we do the largest first
for (int i = abbrev.length - 1; i >= 0 && !done; i--) {
// Convert array index to "1000", "1000000", etc
int size = (int) Math.pow(10, (double) (i + 1) * 3);
// If the number is bigger or equal do the abbreviation
if (size <= number.intValue()) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number.intValue() * decPlaces / (float) size) / decPlaces;
// Add the letter for the abbreviation
abbrevn = number + abbrev[i];
// We are done... stop
done = true;
}
}
return abbrevn;
} }
|
public class class_name {
public static String abbreviateInt(Number number, int decPlaces) {
if (number == null) {
return ""; // depends on control dependency: [if], data = [none]
}
String abbrevn = number.toString();
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = (int) Math.pow(10, decPlaces);
// Enumerate number abbreviations
String[] abbrev = {"K", "M", "B", "T"};
boolean done = false;
// Go through the array backwards, so we do the largest first
for (int i = abbrev.length - 1; i >= 0 && !done; i--) {
// Convert array index to "1000", "1000000", etc
int size = (int) Math.pow(10, (double) (i + 1) * 3);
// If the number is bigger or equal do the abbreviation
if (size <= number.intValue()) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number.intValue() * decPlaces / (float) size) / decPlaces; // depends on control dependency: [if], data = [none]
// Add the letter for the abbreviation
abbrevn = number + abbrev[i]; // depends on control dependency: [if], data = [none]
// We are done... stop
done = true; // depends on control dependency: [if], data = [none]
}
}
return abbrevn;
} }
|
public class class_name {
public void internalNodeRemoved( String internalNodeKey ) {
if (this.snapshot.get().containsProjectionForInternalNode(internalNodeKey)) {
// identify all the projections which from this internal (aka. federated node) and remove them
synchronized (this) {
Snapshot current = this.snapshot.get();
Snapshot updated = current;
for (Projection projection : current.getProjections()) {
if (internalNodeKey.equalsIgnoreCase(projection.getProjectedNodeKey())) {
String externalNodeKey = projection.getExternalNodeKey();
removeStoredProjection(externalNodeKey);
updated = updated.withoutProjection(externalNodeKey);
}
}
if (current != updated) {
this.snapshot.compareAndSet(current, updated);
}
}
}
} }
|
public class class_name {
public void internalNodeRemoved( String internalNodeKey ) {
if (this.snapshot.get().containsProjectionForInternalNode(internalNodeKey)) {
// identify all the projections which from this internal (aka. federated node) and remove them
synchronized (this) { // depends on control dependency: [if], data = [none]
Snapshot current = this.snapshot.get();
Snapshot updated = current;
for (Projection projection : current.getProjections()) {
if (internalNodeKey.equalsIgnoreCase(projection.getProjectedNodeKey())) {
String externalNodeKey = projection.getExternalNodeKey();
removeStoredProjection(externalNodeKey); // depends on control dependency: [if], data = [none]
updated = updated.withoutProjection(externalNodeKey); // depends on control dependency: [if], data = [none]
}
}
if (current != updated) {
this.snapshot.compareAndSet(current, updated); // depends on control dependency: [if], data = [(current]
}
}
}
} }
|
public class class_name {
public RandomVariableInterface expand(int numberOfPaths) {
if(isDeterministic()) {
// Expand random variable to a vector of path values
double[] clone = new double[numberOfPaths];
java.util.Arrays.fill(clone,valueIfNonStochastic);
return new RandomVariableLowMemory(time,clone);
}
return new RandomVariableLowMemory(time,realizations.clone());
} }
|
public class class_name {
public RandomVariableInterface expand(int numberOfPaths) {
if(isDeterministic()) {
// Expand random variable to a vector of path values
double[] clone = new double[numberOfPaths];
java.util.Arrays.fill(clone,valueIfNonStochastic); // depends on control dependency: [if], data = [none]
return new RandomVariableLowMemory(time,clone); // depends on control dependency: [if], data = [none]
}
return new RandomVariableLowMemory(time,realizations.clone());
} }
|
public class class_name {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> clazz = findLoadedClass(name);
if (clazz == null) {
if (inExceptedPackage(name)) {
clazz = super.loadClass(name, false);
} else {
try {
clazz = findClass(name);
} catch (ClassNotFoundException e) {
clazz = super.loadClass(name, false);
if (!clazz.isAnnotation()) { // Annotations are always safe to load
logger.log(Type.WARN, String.format(
"Class %s is used in Gin, but not available in GWT client code.", name));
}
}
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
} }
|
public class class_name {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> clazz = findLoadedClass(name);
if (clazz == null) {
if (inExceptedPackage(name)) {
clazz = super.loadClass(name, false);
} else {
try {
clazz = findClass(name); // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e) {
clazz = super.loadClass(name, false);
if (!clazz.isAnnotation()) { // Annotations are always safe to load
logger.log(Type.WARN, String.format(
"Class %s is used in Gin, but not available in GWT client code.", name)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
} }
|
public class class_name {
public EClass getIfcOutletType() {
if (ifcOutletTypeEClass == null) {
ifcOutletTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(342);
}
return ifcOutletTypeEClass;
} }
|
public class class_name {
public EClass getIfcOutletType() {
if (ifcOutletTypeEClass == null) {
ifcOutletTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(342);
// depends on control dependency: [if], data = [none]
}
return ifcOutletTypeEClass;
} }
|
public class class_name {
private Visualization embedOrThumbnail(final int thumbsize, PlotItem it, VisualizationTask task, Element parent) {
final Visualization vis;
if(!single) {
vis = task.getFactory().makeVisualizationOrThumbnail(context, task, plot, it.w, it.h, it.proj, thumbsize);
}
else {
vis = task.getFactory().makeVisualization(context, task, plot, it.w, it.h, it.proj);
}
if(vis == null || vis.getLayer() == null) {
LOG.warning("Visualization returned empty layer: " + vis);
return vis;
}
if(task.has(RenderFlag.NO_EXPORT)) {
vis.getLayer().setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE, SVGPlot.NO_EXPORT_ATTRIBUTE);
}
parent.appendChild(vis.getLayer());
return vis;
} }
|
public class class_name {
private Visualization embedOrThumbnail(final int thumbsize, PlotItem it, VisualizationTask task, Element parent) {
final Visualization vis;
if(!single) {
vis = task.getFactory().makeVisualizationOrThumbnail(context, task, plot, it.w, it.h, it.proj, thumbsize); // depends on control dependency: [if], data = [none]
}
else {
vis = task.getFactory().makeVisualization(context, task, plot, it.w, it.h, it.proj); // depends on control dependency: [if], data = [none]
}
if(vis == null || vis.getLayer() == null) {
LOG.warning("Visualization returned empty layer: " + vis); // depends on control dependency: [if], data = [none]
return vis; // depends on control dependency: [if], data = [none]
}
if(task.has(RenderFlag.NO_EXPORT)) {
vis.getLayer().setAttribute(SVGPlot.NO_EXPORT_ATTRIBUTE, SVGPlot.NO_EXPORT_ATTRIBUTE); // depends on control dependency: [if], data = [none]
}
parent.appendChild(vis.getLayer());
return vis;
} }
|
public class class_name {
protected void appendCapacityContextAwareWrapper(SarlCapacity source, JvmGenericType inferredJvmType) {
final JvmGenericType innerType = this.typesFactory.createJvmGenericType();
innerType.setInterface(false);
innerType.setAbstract(false);
innerType.setVisibility(JvmVisibility.PUBLIC);
innerType.setStatic(true);
innerType.setStrictFloatingPoint(false);
innerType.setFinal(false);
final String innerTypeName = Capacity.ContextAwareCapacityWrapper.class.getSimpleName();
innerType.setSimpleName(innerTypeName);
inferredJvmType.getMembers().add(innerType);
this.typeBuilder.setDocumentation(innerType, "@ExcludeFromApidoc"); //$NON-NLS-1$
final JvmTypeParameter typeParameter = this.typesFactory.createJvmTypeParameter();
typeParameter.setName("C"); //$NON-NLS-1$
final JvmUpperBound constraint = this.typesFactory.createJvmUpperBound();
constraint.setTypeReference(this._typeReferenceBuilder.typeRef(inferredJvmType));
typeParameter.getConstraints().add(constraint);
innerType.getTypeParameters().add(typeParameter);
final Iterator<JvmTypeReference> extendedTypeIterator = inferredJvmType.getExtendedInterfaces().iterator();
if (extendedTypeIterator.hasNext()) {
final JvmTypeReference extendedType = extendedTypeIterator.next();
final JvmTypeReference superType = this._typeReferenceBuilder.typeRef(
extendedType.getQualifiedName() + "$" + innerTypeName, //$NON-NLS-1$
this._typeReferenceBuilder.typeRef(typeParameter));
innerType.getSuperTypes().add(superType);
}
innerType.getSuperTypes().add(this._typeReferenceBuilder.typeRef(inferredJvmType));
final JvmConstructor constructor = this.typesFactory.createJvmConstructor();
constructor.setVisibility(JvmVisibility.PUBLIC);
innerType.getMembers().add(constructor);
final JvmFormalParameter parameter1 = this.typesFactory.createJvmFormalParameter();
parameter1.setName("capacity"); //$NON-NLS-1$
parameter1.setParameterType(this._typeReferenceBuilder.typeRef(typeParameter));
constructor.getParameters().add(parameter1);
final JvmFormalParameter parameter2 = this.typesFactory.createJvmFormalParameter();
parameter2.setName("caller"); //$NON-NLS-1$
parameter2.setParameterType(this._typeReferenceBuilder.typeRef(AgentTrait.class));
constructor.getParameters().add(parameter2);
setBody(constructor, it -> {
it.append("super(capacity, caller);"); //$NON-NLS-1$
});
final Set<ActionPrototype> createdActions = new TreeSet<>();
for (final JvmGenericType sourceType : Iterables.concat(
Collections.singletonList(inferredJvmType),
Iterables.transform(Iterables.skip(inferredJvmType.getExtendedInterfaces(), 1), it -> {
return (JvmGenericType) it.getType();
}))) {
copyNonStaticPublicJvmOperations(sourceType, innerType, createdActions, (operation, it) -> {
it.append("try {"); //$NON-NLS-1$
it.newLine();
it.append(" ensureCallerInLocalThread();"); //$NON-NLS-1$
it.newLine();
it.append(" "); //$NON-NLS-1$
if (operation.getReturnType() != null && !Objects.equal("void", operation.getReturnType().getIdentifier())) { //$NON-NLS-1$
it.append("return "); //$NON-NLS-1$
}
it.append("this.capacity."); //$NON-NLS-1$
it.append(operation.getSimpleName());
it.append("("); //$NON-NLS-1$
boolean first = true;
for (final JvmFormalParameter fparam : operation.getParameters()) {
if (first) {
first = false;
} else {
it.append(", "); //$NON-NLS-1$
}
it.append(fparam.getName());
}
it.append(");"); //$NON-NLS-1$
it.newLine();
it.append("} finally {"); //$NON-NLS-1$
it.newLine();
it.append(" resetCallerInLocalThread();"); //$NON-NLS-1$
it.newLine();
it.append("}"); //$NON-NLS-1$
});
}
} }
|
public class class_name {
protected void appendCapacityContextAwareWrapper(SarlCapacity source, JvmGenericType inferredJvmType) {
final JvmGenericType innerType = this.typesFactory.createJvmGenericType();
innerType.setInterface(false);
innerType.setAbstract(false);
innerType.setVisibility(JvmVisibility.PUBLIC);
innerType.setStatic(true);
innerType.setStrictFloatingPoint(false);
innerType.setFinal(false);
final String innerTypeName = Capacity.ContextAwareCapacityWrapper.class.getSimpleName();
innerType.setSimpleName(innerTypeName);
inferredJvmType.getMembers().add(innerType);
this.typeBuilder.setDocumentation(innerType, "@ExcludeFromApidoc"); //$NON-NLS-1$
final JvmTypeParameter typeParameter = this.typesFactory.createJvmTypeParameter();
typeParameter.setName("C"); //$NON-NLS-1$
final JvmUpperBound constraint = this.typesFactory.createJvmUpperBound();
constraint.setTypeReference(this._typeReferenceBuilder.typeRef(inferredJvmType));
typeParameter.getConstraints().add(constraint);
innerType.getTypeParameters().add(typeParameter);
final Iterator<JvmTypeReference> extendedTypeIterator = inferredJvmType.getExtendedInterfaces().iterator();
if (extendedTypeIterator.hasNext()) {
final JvmTypeReference extendedType = extendedTypeIterator.next();
final JvmTypeReference superType = this._typeReferenceBuilder.typeRef(
extendedType.getQualifiedName() + "$" + innerTypeName, //$NON-NLS-1$
this._typeReferenceBuilder.typeRef(typeParameter));
innerType.getSuperTypes().add(superType); // depends on control dependency: [if], data = [none]
}
innerType.getSuperTypes().add(this._typeReferenceBuilder.typeRef(inferredJvmType));
final JvmConstructor constructor = this.typesFactory.createJvmConstructor();
constructor.setVisibility(JvmVisibility.PUBLIC);
innerType.getMembers().add(constructor);
final JvmFormalParameter parameter1 = this.typesFactory.createJvmFormalParameter();
parameter1.setName("capacity"); //$NON-NLS-1$
parameter1.setParameterType(this._typeReferenceBuilder.typeRef(typeParameter));
constructor.getParameters().add(parameter1);
final JvmFormalParameter parameter2 = this.typesFactory.createJvmFormalParameter();
parameter2.setName("caller"); //$NON-NLS-1$
parameter2.setParameterType(this._typeReferenceBuilder.typeRef(AgentTrait.class));
constructor.getParameters().add(parameter2);
setBody(constructor, it -> {
it.append("super(capacity, caller);"); //$NON-NLS-1$
});
final Set<ActionPrototype> createdActions = new TreeSet<>();
for (final JvmGenericType sourceType : Iterables.concat(
Collections.singletonList(inferredJvmType),
Iterables.transform(Iterables.skip(inferredJvmType.getExtendedInterfaces(), 1), it -> {
return (JvmGenericType) it.getType();
}))) {
copyNonStaticPublicJvmOperations(sourceType, innerType, createdActions, (operation, it) -> {
it.append("try {"); //$NON-NLS-1$
it.newLine();
it.append(" ensureCallerInLocalThread();"); //$NON-NLS-1$
it.newLine();
it.append(" "); //$NON-NLS-1$
if (operation.getReturnType() != null && !Objects.equal("void", operation.getReturnType().getIdentifier())) { //$NON-NLS-1$
it.append("return "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.append("this.capacity."); //$NON-NLS-1$
it.append(operation.getSimpleName());
it.append("("); //$NON-NLS-1$
boolean first = true;
for (final JvmFormalParameter fparam : operation.getParameters()) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
it.append(", "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.append(fparam.getName()); // depends on control dependency: [for], data = [fparam]
}
it.append(");"); //$NON-NLS-1$
it.newLine();
it.append("} finally {"); //$NON-NLS-1$
it.newLine();
it.append(" resetCallerInLocalThread();"); //$NON-NLS-1$
it.newLine();
it.append("}"); //$NON-NLS-1$
});
}
} }
|
public class class_name {
public void updateOptionBarPosition() {
// only if attached to the DOM
if ((m_elementOptionBar != null) && RootPanel.getBodyElement().isOrHasChild(getElement())) {
int absoluteTop = getElement().getAbsoluteTop();
int absoluteRight = getElement().getAbsoluteRight();
CmsPositionBean dimensions = CmsPositionBean.getBoundingClientRect(getElement());
int top = 0;
int right = 0;
int offsetLeft = 0;
int offsetTop = 0;
final Style style = m_elementOptionBar.getElement().getStyle();
if (m_positioningInstructionParser.tryParse(getElement().getClassName())) {
offsetLeft = m_positioningInstructionParser.getOffsetLeft();
offsetTop = m_positioningInstructionParser.getOffsetTop();
}
if (Math.abs(absoluteTop - dimensions.getTop()) > 20) {
absoluteTop = (dimensions.getTop() - absoluteTop) + 2;
top = absoluteTop;
}
if (Math.abs(absoluteRight - dimensions.getLeft() - dimensions.getWidth()) > 20) {
absoluteRight = (absoluteRight - dimensions.getLeft() - dimensions.getWidth()) + 2;
right = absoluteRight;
}
top += offsetTop;
right -= offsetLeft;
if (top != 0) {
style.setTop(top, Unit.PX);
} else {
style.clearTop();
}
if (right != 0) {
style.setRight(right, Unit.PX);
} else {
style.clearRight();
}
if (isOptionbarIFrameCollision(absoluteTop, m_elementOptionBar.getCalculatedWidth())) {
style.setPosition(Position.RELATIVE);
int marginLeft = getElement().getClientWidth() - m_elementOptionBar.getCalculatedWidth();
if (marginLeft > 0) {
style.setMarginLeft(marginLeft, Unit.PX);
}
} else {
style.clearPosition();
style.clearMarginLeft();
}
}
} }
|
public class class_name {
public void updateOptionBarPosition() {
// only if attached to the DOM
if ((m_elementOptionBar != null) && RootPanel.getBodyElement().isOrHasChild(getElement())) {
int absoluteTop = getElement().getAbsoluteTop();
int absoluteRight = getElement().getAbsoluteRight();
CmsPositionBean dimensions = CmsPositionBean.getBoundingClientRect(getElement());
int top = 0;
int right = 0;
int offsetLeft = 0;
int offsetTop = 0;
final Style style = m_elementOptionBar.getElement().getStyle();
if (m_positioningInstructionParser.tryParse(getElement().getClassName())) {
offsetLeft = m_positioningInstructionParser.getOffsetLeft(); // depends on control dependency: [if], data = [none]
offsetTop = m_positioningInstructionParser.getOffsetTop(); // depends on control dependency: [if], data = [none]
}
if (Math.abs(absoluteTop - dimensions.getTop()) > 20) {
absoluteTop = (dimensions.getTop() - absoluteTop) + 2; // depends on control dependency: [if], data = [none]
top = absoluteTop; // depends on control dependency: [if], data = [none]
}
if (Math.abs(absoluteRight - dimensions.getLeft() - dimensions.getWidth()) > 20) {
absoluteRight = (absoluteRight - dimensions.getLeft() - dimensions.getWidth()) + 2; // depends on control dependency: [if], data = [none]
right = absoluteRight; // depends on control dependency: [if], data = [none]
}
top += offsetTop; // depends on control dependency: [if], data = [none]
right -= offsetLeft; // depends on control dependency: [if], data = [none]
if (top != 0) {
style.setTop(top, Unit.PX); // depends on control dependency: [if], data = [(top]
} else {
style.clearTop(); // depends on control dependency: [if], data = [none]
}
if (right != 0) {
style.setRight(right, Unit.PX); // depends on control dependency: [if], data = [(right]
} else {
style.clearRight(); // depends on control dependency: [if], data = [none]
}
if (isOptionbarIFrameCollision(absoluteTop, m_elementOptionBar.getCalculatedWidth())) {
style.setPosition(Position.RELATIVE); // depends on control dependency: [if], data = [none]
int marginLeft = getElement().getClientWidth() - m_elementOptionBar.getCalculatedWidth();
if (marginLeft > 0) {
style.setMarginLeft(marginLeft, Unit.PX); // depends on control dependency: [if], data = [(marginLeft]
}
} else {
style.clearPosition(); // depends on control dependency: [if], data = [none]
style.clearMarginLeft(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Override
public void onCreate(Context context) {
if(logger != null && logger.isDebugEnabled()) {
logger.debug("SocializeC2DMReceiver creating..");
}
try {
container.onCreate(context);
initBeans();
}
catch (Exception e) {
logError("Error initializing GCM receiver!", e);
}
} }
|
public class class_name {
@Override
public void onCreate(Context context) {
if(logger != null && logger.isDebugEnabled()) {
logger.debug("SocializeC2DMReceiver creating.."); // depends on control dependency: [if], data = [none]
}
try {
container.onCreate(context); // depends on control dependency: [try], data = [none]
initBeans(); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
logError("Error initializing GCM receiver!", e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void rollback() {
if (!active)
throw error("Inactive micro-transaction on rollback");
if (level < 1)
throw error("Unbalanced micro-transaction, level = " + level);
--level;
if (level == 0) {
active = false;
doRollback();
}
} }
|
public class class_name {
public void rollback() {
if (!active)
throw error("Inactive micro-transaction on rollback");
if (level < 1)
throw error("Unbalanced micro-transaction, level = " + level);
--level;
if (level == 0) {
active = false; // depends on control dependency: [if], data = [none]
doRollback(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void setDiscreteSeconds(boolean DISCRETE) {
if (null == discreteSeconds) {
_discreteSeconds = DISCRETE;
stopTask(periodicTickTask);
if (isAnimated()) return;
scheduleTickTask();
} else {
discreteSeconds.set(DISCRETE);
}
} }
|
public class class_name {
public void setDiscreteSeconds(boolean DISCRETE) {
if (null == discreteSeconds) {
_discreteSeconds = DISCRETE; // depends on control dependency: [if], data = [none]
stopTask(periodicTickTask); // depends on control dependency: [if], data = [none]
if (isAnimated()) return;
scheduleTickTask(); // depends on control dependency: [if], data = [none]
} else {
discreteSeconds.set(DISCRETE); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void processNack(ControlNack nm) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "processNack", nm);
boolean sendPending = false;
List sendList = new ArrayList();
boolean sendLeadingSilence = false;
long lsstart = 0;
long lsend = 0;
boolean sendTrailingSilence = false;
long tsstart = 0;
long tsend = 0;
long startstamp = nm.getStartTick();
long endstamp = nm.getEndTick();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack from: " + startstamp + " to " + endstamp + " on Stream " + stream);
}
long completedPrefix;
// the TickRange to hold information discovered as we traverse stream
TickRange r = null;
// Go through oststream and see which ticks in the Nack range are
// Completed or Value or Uncommitted and send appropriate messages
// for these ticks.
synchronized (this)
{
// SIB0105
// Update the health state of this stream
getControlAdapter().getHealthState().updateHealth(HealthStateListener.NACK_RECEIVED_STATE,
HealthState.AMBER);
lastNackReceivedTick = endstamp;
inboundFlow = true;
completedPrefix = oststream.getCompletedPrefix();
// If some of the ticks in the Nack range are before the completedPrefix
// of our Stream we send a Silence message from the startstamp
// to the completedPrefix.
if (startstamp <= completedPrefix)
{
sendLeadingSilence = true;
lsstart = startstamp;
lsend = completedPrefix;
//Some of the ticks in the Nack range are before the completedPrefix
//of our Stream so start from there
startstamp = completedPrefix + 1;
}
// If there are any tick in the Nack range which are not yet
// complete process these now
if( endstamp > completedPrefix)
{
oststream.setCursor(startstamp);
// Get the first TickRange
TickRange tr = oststream.getNext();
TickRange tr2 = null;
while ((tr.startstamp <= endstamp) && (tr != tr2))
{
if ((tr.type == TickRange.Unknown)
|| (tr.type == TickRange.Requested))
{
break;
}
else if (tr.type == TickRange.Value)
{
// Do we have a previous Value message to add
// to the list
if (sendPending)
{
sendList.add(r);
}
// If message is inside sendWindow
// copy the Value tick range into r
if (msgCanBeSent(tr.valuestamp, true))
{
r = (TickRange)tr.clone();
sendPending = true;
}
else
{
// If this message is outside the sendWindow we should stop
break;
}
}
else if (tr.type == TickRange.Uncommitted)
{
// If there is a previous Value message in the list
// we can put any Completed ticks between that and this
// Uncommitted tick into it.
if (sendPending)
{
// If there are Completed ticks between
// the Value and Uncommitted ticks
// Add them to the end of the Value message
if (tr.valuestamp > (r.valuestamp + 1))
{
r.endstamp = tr.valuestamp - 1;
}
sendList.add(r);
sendPending = false;
}
}
tr2 = tr;
tr = oststream.getNext();
} // end while
// If we finish on a Completed range then add this to the
// last Value in our list
// Check for null as we may have dropped out first time round loop
// above without ever initialising tr2
if ((tr2 != null) && (tr2.type == TickRange.Completed))
{
if (sendPending)
{
r.endstamp = tr2.endstamp;
}
else
{
// Need to send this Completed range in a Silence
// message as there is no Value to add it to
// This may be because the whole Nack range is Completed or
// because the previous range was Uncommitted
// or because the previous range was outside the sendWindow
if (msgCanBeSent(tr2.startstamp, true))
{
sendTrailingSilence = true;
tsstart = tr2.startstamp;
tsend = tr2.endstamp;
}
}
}
if (sendPending)
{
sendList.add(r);
}
}
} // end sync
// Send any Silence at start of Nack range
if (sendLeadingSilence)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack sending Silence from: " + lsstart + " to " + lsend + " on Stream " + stream);
}
try
{
downControl.sendSilenceMessage(lsstart, lsend, completedPrefix, true,
nm.getPriority().intValue(),
nm.getReliability(), stream);
}
catch (SIResourceException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.gd.SourceStream.processNack",
"1:1222:1.138",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack", e);
throw e;
}
}
// send and messages in Nack range
if (sendList.size() != 0)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack resending Value messages on Stream " + stream);
}
// second parameter indicates that this is a resend in response to a Nack
sendMsgs( sendList, true );
}
// send any Silence at end of Nack range
if (sendTrailingSilence)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack sending Silence from: " + tsstart + " to " + tsend + " on Stream " + stream);
}
try
{
downControl.sendSilenceMessage(tsstart, tsend, completedPrefix, true,
nm.getPriority().intValue(),
nm.getReliability(), stream);
}
catch (SIResourceException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.gd.SourceStream.processNack",
"1:1267:1.138",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack", e);
throw e;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack");
} }
|
public class class_name {
public void processNack(ControlNack nm) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "processNack", nm);
boolean sendPending = false;
List sendList = new ArrayList();
boolean sendLeadingSilence = false;
long lsstart = 0;
long lsend = 0;
boolean sendTrailingSilence = false;
long tsstart = 0;
long tsend = 0;
long startstamp = nm.getStartTick();
long endstamp = nm.getEndTick();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack from: " + startstamp + " to " + endstamp + " on Stream " + stream);
}
long completedPrefix;
// the TickRange to hold information discovered as we traverse stream
TickRange r = null;
// Go through oststream and see which ticks in the Nack range are
// Completed or Value or Uncommitted and send appropriate messages
// for these ticks.
synchronized (this)
{
// SIB0105
// Update the health state of this stream
getControlAdapter().getHealthState().updateHealth(HealthStateListener.NACK_RECEIVED_STATE,
HealthState.AMBER);
lastNackReceivedTick = endstamp;
inboundFlow = true;
completedPrefix = oststream.getCompletedPrefix();
// If some of the ticks in the Nack range are before the completedPrefix
// of our Stream we send a Silence message from the startstamp
// to the completedPrefix.
if (startstamp <= completedPrefix)
{
sendLeadingSilence = true; // depends on control dependency: [if], data = [none]
lsstart = startstamp; // depends on control dependency: [if], data = [none]
lsend = completedPrefix; // depends on control dependency: [if], data = [none]
//Some of the ticks in the Nack range are before the completedPrefix
//of our Stream so start from there
startstamp = completedPrefix + 1; // depends on control dependency: [if], data = [none]
}
// If there are any tick in the Nack range which are not yet
// complete process these now
if( endstamp > completedPrefix)
{
oststream.setCursor(startstamp); // depends on control dependency: [if], data = [none]
// Get the first TickRange
TickRange tr = oststream.getNext();
TickRange tr2 = null;
while ((tr.startstamp <= endstamp) && (tr != tr2))
{
if ((tr.type == TickRange.Unknown)
|| (tr.type == TickRange.Requested))
{
break;
}
else if (tr.type == TickRange.Value)
{
// Do we have a previous Value message to add
// to the list
if (sendPending)
{
sendList.add(r); // depends on control dependency: [if], data = [none]
}
// If message is inside sendWindow
// copy the Value tick range into r
if (msgCanBeSent(tr.valuestamp, true))
{
r = (TickRange)tr.clone(); // depends on control dependency: [if], data = [none]
sendPending = true; // depends on control dependency: [if], data = [none]
}
else
{
// If this message is outside the sendWindow we should stop
break;
}
}
else if (tr.type == TickRange.Uncommitted)
{
// If there is a previous Value message in the list
// we can put any Completed ticks between that and this
// Uncommitted tick into it.
if (sendPending)
{
// If there are Completed ticks between
// the Value and Uncommitted ticks
// Add them to the end of the Value message
if (tr.valuestamp > (r.valuestamp + 1))
{
r.endstamp = tr.valuestamp - 1; // depends on control dependency: [if], data = [none]
}
sendList.add(r); // depends on control dependency: [if], data = [none]
sendPending = false; // depends on control dependency: [if], data = [none]
}
}
tr2 = tr; // depends on control dependency: [while], data = [none]
tr = oststream.getNext(); // depends on control dependency: [while], data = [none]
} // end while
// If we finish on a Completed range then add this to the
// last Value in our list
// Check for null as we may have dropped out first time round loop
// above without ever initialising tr2
if ((tr2 != null) && (tr2.type == TickRange.Completed))
{
if (sendPending)
{
r.endstamp = tr2.endstamp; // depends on control dependency: [if], data = [none]
}
else
{
// Need to send this Completed range in a Silence
// message as there is no Value to add it to
// This may be because the whole Nack range is Completed or
// because the previous range was Uncommitted
// or because the previous range was outside the sendWindow
if (msgCanBeSent(tr2.startstamp, true))
{
sendTrailingSilence = true; // depends on control dependency: [if], data = [none]
tsstart = tr2.startstamp; // depends on control dependency: [if], data = [none]
tsend = tr2.endstamp; // depends on control dependency: [if], data = [none]
}
}
}
if (sendPending)
{
sendList.add(r); // depends on control dependency: [if], data = [none]
}
}
} // end sync
// Send any Silence at start of Nack range
if (sendLeadingSilence)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack sending Silence from: " + lsstart + " to " + lsend + " on Stream " + stream); // depends on control dependency: [if], data = [none]
}
try
{
downControl.sendSilenceMessage(lsstart, lsend, completedPrefix, true,
nm.getPriority().intValue(),
nm.getReliability(), stream); // depends on control dependency: [try], data = [none]
}
catch (SIResourceException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.gd.SourceStream.processNack",
"1:1222:1.138",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack", e);
throw e;
} // depends on control dependency: [catch], data = [none]
}
// send and messages in Nack range
if (sendList.size() != 0)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack resending Value messages on Stream " + stream); // depends on control dependency: [if], data = [none]
}
// second parameter indicates that this is a resend in response to a Nack
sendMsgs( sendList, true );
}
// send any Silence at end of Nack range
if (sendTrailingSilence)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "processNack sending Silence from: " + tsstart + " to " + tsend + " on Stream " + stream); // depends on control dependency: [if], data = [none]
}
try
{
downControl.sendSilenceMessage(tsstart, tsend, completedPrefix, true,
nm.getPriority().intValue(),
nm.getReliability(), stream); // depends on control dependency: [try], data = [none]
}
catch (SIResourceException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.gd.SourceStream.processNack",
"1:1267:1.138",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack", e);
throw e;
} // depends on control dependency: [catch], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "processNack");
} }
|
public class class_name {
static private <T extends Collection<String>> JSONObject aggregateDisjunctiveFacetingResults(@NonNull JSONObject answers, @NonNull Collection<String> disjunctiveFacets, @NonNull Map<String, T> refinements) throws AlgoliaException
{
Map<String, T> disjunctiveRefinements = filterDisjunctiveRefinements(disjunctiveFacets, refinements);
// aggregate answers
// first answer stores the hits + regular facets
try {
boolean nonExhaustiveFacetsCount = false;
JSONArray results = answers.getJSONArray("results");
JSONObject aggregatedAnswer = results.getJSONObject(0);
JSONObject disjunctiveFacetsJSON = new JSONObject();
for (int i = 1; i < results.length(); ++i) {
if (!results.getJSONObject(i).optBoolean("exhaustiveFacetsCount")) {
nonExhaustiveFacetsCount = true;
}
JSONObject facets = results.getJSONObject(i).getJSONObject("facets");
@SuppressWarnings("unchecked")
Iterator<String> keys = facets.keys();
while (keys.hasNext()) {
String key = keys.next();
// Add the facet to the disjunctive facet hash
disjunctiveFacetsJSON.put(key, facets.getJSONObject(key));
// concatenate missing refinements
if (!disjunctiveRefinements.containsKey(key)) {
continue;
}
for (String refine : disjunctiveRefinements.get(key)) {
if (!disjunctiveFacetsJSON.getJSONObject(key).has(refine)) {
disjunctiveFacetsJSON.getJSONObject(key).put(refine, 0);
}
}
}
}
aggregatedAnswer.put("disjunctiveFacets", disjunctiveFacetsJSON);
if (nonExhaustiveFacetsCount) {
aggregatedAnswer.put("exhaustiveFacetsCount", false);
}
return aggregatedAnswer;
} catch (JSONException e) {
throw new AlgoliaException("Failed to aggregate results", e);
}
} }
|
public class class_name {
static private <T extends Collection<String>> JSONObject aggregateDisjunctiveFacetingResults(@NonNull JSONObject answers, @NonNull Collection<String> disjunctiveFacets, @NonNull Map<String, T> refinements) throws AlgoliaException
{
Map<String, T> disjunctiveRefinements = filterDisjunctiveRefinements(disjunctiveFacets, refinements);
// aggregate answers
// first answer stores the hits + regular facets
try {
boolean nonExhaustiveFacetsCount = false;
JSONArray results = answers.getJSONArray("results");
JSONObject aggregatedAnswer = results.getJSONObject(0);
JSONObject disjunctiveFacetsJSON = new JSONObject();
for (int i = 1; i < results.length(); ++i) {
if (!results.getJSONObject(i).optBoolean("exhaustiveFacetsCount")) {
nonExhaustiveFacetsCount = true; // depends on control dependency: [if], data = [none]
}
JSONObject facets = results.getJSONObject(i).getJSONObject("facets");
@SuppressWarnings("unchecked")
Iterator<String> keys = facets.keys();
while (keys.hasNext()) {
String key = keys.next();
// Add the facet to the disjunctive facet hash
disjunctiveFacetsJSON.put(key, facets.getJSONObject(key)); // depends on control dependency: [while], data = [none]
// concatenate missing refinements
if (!disjunctiveRefinements.containsKey(key)) {
continue;
}
for (String refine : disjunctiveRefinements.get(key)) {
if (!disjunctiveFacetsJSON.getJSONObject(key).has(refine)) {
disjunctiveFacetsJSON.getJSONObject(key).put(refine, 0); // depends on control dependency: [if], data = [none]
}
}
}
}
aggregatedAnswer.put("disjunctiveFacets", disjunctiveFacetsJSON);
if (nonExhaustiveFacetsCount) {
aggregatedAnswer.put("exhaustiveFacetsCount", false); // depends on control dependency: [if], data = [none]
}
return aggregatedAnswer;
} catch (JSONException e) {
throw new AlgoliaException("Failed to aggregate results", e);
}
} }
|
public class class_name {
public void setPolicies(java.util.Collection<Policy> policies) {
if (policies == null) {
this.policies = null;
return;
}
this.policies = new com.amazonaws.internal.SdkInternalList<Policy>(policies);
} }
|
public class class_name {
public void setPolicies(java.util.Collection<Policy> policies) {
if (policies == null) {
this.policies = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.policies = new com.amazonaws.internal.SdkInternalList<Policy>(policies);
} }
|
public class class_name {
private Stack<QuickSortSet.Cell> forwardPath(QuickSortSet.Cell lexemeCell , LexemePath option){
//发生冲突的Lexeme栈
Stack<QuickSortSet.Cell> conflictStack = new Stack<QuickSortSet.Cell>();
QuickSortSet.Cell c = lexemeCell;
//迭代遍历Lexeme链表
while(c != null && c.getLexeme() != null){
if(!option.addNotCrossLexeme(c.getLexeme())){
//词元交叉,添加失败则加入lexemeStack栈
conflictStack.push(c);
}
c = c.getNext();
}
return conflictStack;
} }
|
public class class_name {
private Stack<QuickSortSet.Cell> forwardPath(QuickSortSet.Cell lexemeCell , LexemePath option){
//发生冲突的Lexeme栈
Stack<QuickSortSet.Cell> conflictStack = new Stack<QuickSortSet.Cell>();
QuickSortSet.Cell c = lexemeCell;
//迭代遍历Lexeme链表
while(c != null && c.getLexeme() != null){
if(!option.addNotCrossLexeme(c.getLexeme())){
//词元交叉,添加失败则加入lexemeStack栈
conflictStack.push(c);
// depends on control dependency: [if], data = [none]
}
c = c.getNext();
// depends on control dependency: [while], data = [none]
}
return conflictStack;
} }
|
public class class_name {
@Override
public boolean hasNext() {
if (iterationsCounter.get() >= totalIterations)
return false;
if (newEpoch) {
log.info("Epoch " + epochs + ", number of batches completed " + lastBatch);
newEpoch = false;
}
if (iter == null)
return (epochs < numEpochs) && ((!batchedDS.isEmpty() && batchedDS.size() > batch) || batchedDS.isEmpty());
else
// either there are still epochs to complete or its the first epoch
return (epochs < numEpochs) || (iter.hasNext() && (epochs == 0 || epochs == numEpochs));
} }
|
public class class_name {
@Override
public boolean hasNext() {
if (iterationsCounter.get() >= totalIterations)
return false;
if (newEpoch) {
log.info("Epoch " + epochs + ", number of batches completed " + lastBatch); // depends on control dependency: [if], data = [none]
newEpoch = false; // depends on control dependency: [if], data = [none]
}
if (iter == null)
return (epochs < numEpochs) && ((!batchedDS.isEmpty() && batchedDS.size() > batch) || batchedDS.isEmpty());
else
// either there are still epochs to complete or its the first epoch
return (epochs < numEpochs) || (iter.hasNext() && (epochs == 0 || epochs == numEpochs));
} }
|
public class class_name {
public void setSrcdir(Path srcDir) {
if (src == null) {
src = srcDir;
} else {
src.append(srcDir);
}
} }
|
public class class_name {
public void setSrcdir(Path srcDir) {
if (src == null) {
src = srcDir; // depends on control dependency: [if], data = [none]
} else {
src.append(srcDir); // depends on control dependency: [if], data = [(src]
}
} }
|
public class class_name {
static String normalize(@NonNull String name) {
StringBuilder toReturn = new StringBuilder();
boolean previousSpace = false;
for( char c : name.toCharArray()){
if( Character.isWhitespace(c) ){
if( !previousSpace ){
toReturn.append('_');
}
previousSpace = true;
} else {
previousSpace = false;
toReturn.append(Character.toUpperCase(c));
}
}
return toReturn.toString();//name.toUpperCase().replaceAll("\\s+", "_");
} }
|
public class class_name {
static String normalize(@NonNull String name) {
StringBuilder toReturn = new StringBuilder();
boolean previousSpace = false;
for( char c : name.toCharArray()){
if( Character.isWhitespace(c) ){
if( !previousSpace ){
toReturn.append('_'); // depends on control dependency: [if], data = [none]
}
previousSpace = true; // depends on control dependency: [if], data = [none]
} else {
previousSpace = false; // depends on control dependency: [if], data = [none]
toReturn.append(Character.toUpperCase(c)); // depends on control dependency: [if], data = [none]
}
}
return toReturn.toString();//name.toUpperCase().replaceAll("\\s+", "_");
} }
|
public class class_name {
public static List<String> toPathParts(String encodedPath) {
if (encodedPath == null || encodedPath.length() == 0) {
return null;
}
List<String> result = new ArrayList<String>();
int cur = 0;
boolean notDone = true;
while (notDone) {
int slash = encodedPath.indexOf('/', cur);
notDone = slash != -1;
String sub;
if (notDone) {
sub = encodedPath.substring(cur, slash);
} else {
sub = encodedPath.substring(cur);
}
result.add(CharEscapers.decodeUri(sub));
cur = slash + 1;
}
return result;
} }
|
public class class_name {
public static List<String> toPathParts(String encodedPath) {
if (encodedPath == null || encodedPath.length() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
List<String> result = new ArrayList<String>();
int cur = 0;
boolean notDone = true;
while (notDone) {
int slash = encodedPath.indexOf('/', cur);
notDone = slash != -1; // depends on control dependency: [while], data = [none]
String sub;
if (notDone) {
sub = encodedPath.substring(cur, slash); // depends on control dependency: [if], data = [none]
} else {
sub = encodedPath.substring(cur); // depends on control dependency: [if], data = [none]
}
result.add(CharEscapers.decodeUri(sub)); // depends on control dependency: [while], data = [none]
cur = slash + 1; // depends on control dependency: [while], data = [none]
}
return result;
} }
|
public class class_name {
public Instances samoaInstancesInformation(weka.core.Instances instances) {
Instances samoaInstances;
List<Attribute> attInfo = new ArrayList<Attribute>();
for (int i = 0; i < instances.numAttributes(); i++) {
attInfo.add(samoaAttribute(i, instances.attribute(i)));
}
samoaInstances = new Instances(instances.relationName(), attInfo, 0);
if(instances.classIndex() >= 0) { // class attribute is present
samoaInstances.setClassIndex(instances.classIndex());
}
return samoaInstances;
} }
|
public class class_name {
public Instances samoaInstancesInformation(weka.core.Instances instances) {
Instances samoaInstances;
List<Attribute> attInfo = new ArrayList<Attribute>();
for (int i = 0; i < instances.numAttributes(); i++) {
attInfo.add(samoaAttribute(i, instances.attribute(i))); // depends on control dependency: [for], data = [i]
}
samoaInstances = new Instances(instances.relationName(), attInfo, 0);
if(instances.classIndex() >= 0) { // class attribute is present
samoaInstances.setClassIndex(instances.classIndex()); // depends on control dependency: [if], data = [(instances.classIndex()]
}
return samoaInstances;
} }
|
public class class_name {
public Datatype.Builder mutateGeneratedBuilderAnnotations(
Consumer<? super List<Excerpt>> mutator) {
if (generatedBuilderAnnotations instanceof ImmutableList) {
generatedBuilderAnnotations = new ArrayList<>(generatedBuilderAnnotations);
}
// If addGeneratedBuilderAnnotations is overridden, this method will be updated to delegate to it
mutator.accept(generatedBuilderAnnotations);
return (Datatype.Builder) this;
} }
|
public class class_name {
public Datatype.Builder mutateGeneratedBuilderAnnotations(
Consumer<? super List<Excerpt>> mutator) {
if (generatedBuilderAnnotations instanceof ImmutableList) {
generatedBuilderAnnotations = new ArrayList<>(generatedBuilderAnnotations); // depends on control dependency: [if], data = [none]
}
// If addGeneratedBuilderAnnotations is overridden, this method will be updated to delegate to it
mutator.accept(generatedBuilderAnnotations);
return (Datatype.Builder) this;
} }
|
public class class_name {
@Override
public IPortletWindowId getPortletForFolderName(
HttpServletRequest request, String targetedLayoutNodeId, String folderName) {
final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
final String fname;
final IPortletEntity portletEntity;
final int seperatorIndex = folderName.indexOf(PORTLET_PATH_ELEMENT_SEPERATOR);
if (seperatorIndex <= 0 || seperatorIndex + 1 == folderName.length()) {
fname = folderName;
portletEntity =
this.portletEntityRegistry.getOrCreatePortletEntityByFname(
request, userInstance, fname);
} else {
fname = folderName.substring(0, seperatorIndex);
final String subscribeId = folderName.substring(seperatorIndex + 1);
portletEntity =
this.portletEntityRegistry.getOrCreatePortletEntityByFname(
request, userInstance, fname, subscribeId);
}
if (portletEntity != null) {
final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId();
final IPortletWindow portletWindow =
this.portletWindowRegistry.getOrCreateDefaultPortletWindow(
request, portletEntityId);
return portletWindow.getPortletWindowId();
} else {
this.logger.warn(
targetedLayoutNodeId
+ " node for portlet of folder "
+ folderName
+ " can't be targeted by the request.");
return null;
}
} }
|
public class class_name {
@Override
public IPortletWindowId getPortletForFolderName(
HttpServletRequest request, String targetedLayoutNodeId, String folderName) {
final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
final String fname;
final IPortletEntity portletEntity;
final int seperatorIndex = folderName.indexOf(PORTLET_PATH_ELEMENT_SEPERATOR);
if (seperatorIndex <= 0 || seperatorIndex + 1 == folderName.length()) {
fname = folderName; // depends on control dependency: [if], data = [none]
portletEntity =
this.portletEntityRegistry.getOrCreatePortletEntityByFname(
request, userInstance, fname); // depends on control dependency: [if], data = [none]
} else {
fname = folderName.substring(0, seperatorIndex); // depends on control dependency: [if], data = [none]
final String subscribeId = folderName.substring(seperatorIndex + 1);
portletEntity =
this.portletEntityRegistry.getOrCreatePortletEntityByFname(
request, userInstance, fname, subscribeId); // depends on control dependency: [if], data = [none]
}
if (portletEntity != null) {
final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId();
final IPortletWindow portletWindow =
this.portletWindowRegistry.getOrCreateDefaultPortletWindow(
request, portletEntityId);
return portletWindow.getPortletWindowId(); // depends on control dependency: [if], data = [none]
} else {
this.logger.warn(
targetedLayoutNodeId
+ " node for portlet of folder "
+ folderName
+ " can't be targeted by the request."); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@NonNull
public static CqlIdentifier fromCql(@NonNull String cql) {
Preconditions.checkNotNull(cql, "cql must not be null");
final String internal;
if (Strings.isDoubleQuoted(cql)) {
internal = Strings.unDoubleQuote(cql);
} else {
internal = cql.toLowerCase();
Preconditions.checkArgument(
!Strings.needsDoubleQuotes(internal), "Invalid CQL form [%s]: needs double quotes", cql);
}
return fromInternal(internal);
} }
|
public class class_name {
@NonNull
public static CqlIdentifier fromCql(@NonNull String cql) {
Preconditions.checkNotNull(cql, "cql must not be null");
final String internal;
if (Strings.isDoubleQuoted(cql)) {
internal = Strings.unDoubleQuote(cql); // depends on control dependency: [if], data = [none]
} else {
internal = cql.toLowerCase(); // depends on control dependency: [if], data = [none]
Preconditions.checkArgument(
!Strings.needsDoubleQuotes(internal), "Invalid CQL form [%s]: needs double quotes", cql); // depends on control dependency: [if], data = [none]
}
return fromInternal(internal);
} }
|
public class class_name {
public void restoreState(FacesContext context, Object state)
{
if (state != null)
{
//Since pattern is required, if state is null
//nothing has changed
this.pattern = (String) state;
}
} }
|
public class class_name {
public void restoreState(FacesContext context, Object state)
{
if (state != null)
{
//Since pattern is required, if state is null
//nothing has changed
this.pattern = (String) state; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static double[] flatten(double[][] array) {
int size = 0;
for (double[] a : array) {
size += a.length;
}
double[] newArray = new double[size];
int i = 0;
for (double[] a : array) {
for (double d : a) {
newArray[i++] = d;
}
}
return newArray;
} }
|
public class class_name {
public static double[] flatten(double[][] array) {
int size = 0;
for (double[] a : array) {
size += a.length;
// depends on control dependency: [for], data = [a]
}
double[] newArray = new double[size];
int i = 0;
for (double[] a : array) {
for (double d : a) {
newArray[i++] = d;
// depends on control dependency: [for], data = [d]
}
}
return newArray;
} }
|
public class class_name {
public synchronized void lockExclusive()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "lockExclusive", this);
boolean interrupted = false;
// If another thread is attempting to lock exclusive,
// wait for it to finish first.
while (!tryLockExclusive())
{
try
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Waiting to get exclusive lock");
wait(1000);
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
}
}
// Wait for existing locks to be released
while (iLockCount > 0)
{
try
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Waiting for lock count to reach 0 " + iLockCount);
wait(1000);
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
}
}
if (interrupted)
{
Thread.currentThread().interrupt();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "lockExclusive");
} }
|
public class class_name {
public synchronized void lockExclusive()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "lockExclusive", this);
boolean interrupted = false;
// If another thread is attempting to lock exclusive,
// wait for it to finish first.
while (!tryLockExclusive())
{
try
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Waiting to get exclusive lock");
wait(1000); // depends on control dependency: [try], data = [none]
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
} // depends on control dependency: [catch], data = [none]
}
// Wait for existing locks to be released
while (iLockCount > 0)
{
try
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Waiting for lock count to reach 0 " + iLockCount);
wait(1000); // depends on control dependency: [try], data = [none]
}
catch (InterruptedException e)
{
// No FFDC code needed
interrupted = true;
} // depends on control dependency: [catch], data = [none]
}
if (interrupted)
{
Thread.currentThread().interrupt(); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "lockExclusive");
} }
|
public class class_name {
private void checkAndLogInvariants() {
if (m_pendingTxnCount < 0 || m_pendingTxnBytes < 0) {
boolean badTxnCount = m_pendingTxnCount < 0 ? true : false;
boolean badPendingBytes = m_pendingTxnBytes < 0 ? true : false;
if (!m_haveLoggedACGNegativeFailure) {
m_haveLoggedACGNegativeFailure = true;
if (badTxnCount) {
networkLog.error("Admission control error, negative outstanding transaction count. " +
"This is error is not fatal, but it does indicate that admission control " +
"is not correctly tracking transaction resource usage. This message will not repeat " +
"the next time the condition occurs to avoid log spam");
}
if (badPendingBytes) {
networkLog.error(
"Backpressure reports a negative outstanding transaction byte count (" +
m_pendingTxnBytes +
"). No action required.", new RuntimeException("for stack trace purposes"));
}
}
/*
* Repair both. It's possible that repairing it will trigger a repair cascade
* effectively rendering the ACG always permissive, but it should right itself
* once all requests associated with the ACG have left the system and the correct values are indeed 0.
*/
m_pendingTxnCount = 0;
m_pendingTxnBytes = 0;
}
} }
|
public class class_name {
private void checkAndLogInvariants() {
if (m_pendingTxnCount < 0 || m_pendingTxnBytes < 0) {
boolean badTxnCount = m_pendingTxnCount < 0 ? true : false;
boolean badPendingBytes = m_pendingTxnBytes < 0 ? true : false;
if (!m_haveLoggedACGNegativeFailure) {
m_haveLoggedACGNegativeFailure = true; // depends on control dependency: [if], data = [none]
if (badTxnCount) {
networkLog.error("Admission control error, negative outstanding transaction count. " +
"This is error is not fatal, but it does indicate that admission control " +
"is not correctly tracking transaction resource usage. This message will not repeat " +
"the next time the condition occurs to avoid log spam"); // depends on control dependency: [if], data = [none]
}
if (badPendingBytes) {
networkLog.error(
"Backpressure reports a negative outstanding transaction byte count (" +
m_pendingTxnBytes +
"). No action required.", new RuntimeException("for stack trace purposes")); // depends on control dependency: [if], data = [none]
}
}
/*
* Repair both. It's possible that repairing it will trigger a repair cascade
* effectively rendering the ACG always permissive, but it should right itself
* once all requests associated with the ACG have left the system and the correct values are indeed 0.
*/
m_pendingTxnCount = 0; // depends on control dependency: [if], data = [none]
m_pendingTxnBytes = 0; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
protected boolean handleUnmatchedRoute(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, HttpMethod httpMethod, String requestPath) {
// If this resource matches a different method[s], error out specially
List<HttpMethod> otherHttpMethods = new ArrayList<>(HttpMethod.values().length);
for (HttpMethod otherHttpMethod : HttpMethod.values())
if (httpMethod != otherHttpMethod && routeMatcher.match(otherHttpMethod, requestPath).isPresent())
otherHttpMethods.add(otherHttpMethod);
// Handle OPTIONS specially by indicating we don't want to invoke the response handler
// Otherwise, throw an exception indicating a 405
if (otherHttpMethods.size() > 0) {
// Always write the Allow header
httpServletResponse.setHeader("Allow",
otherHttpMethods.stream().map(method -> method.name()).collect(joining(", ")));
if (httpMethod == HttpMethod.OPTIONS)
return false;
throw new MethodNotAllowedException(format("%s is not supported for this resource. Supported method%s %s",
httpMethod, (otherHttpMethods.size() == 1 ? " is" : "s are"),
otherHttpMethods.stream().map(method -> method.name()).collect(joining(", "))));
}
// No matching route, and no possible alternatives? It's a 404
throw new NotFoundException(format("No route was found for %s %s", httpMethod.name(), requestPath));
} }
|
public class class_name {
protected boolean handleUnmatchedRoute(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, HttpMethod httpMethod, String requestPath) {
// If this resource matches a different method[s], error out specially
List<HttpMethod> otherHttpMethods = new ArrayList<>(HttpMethod.values().length);
for (HttpMethod otherHttpMethod : HttpMethod.values())
if (httpMethod != otherHttpMethod && routeMatcher.match(otherHttpMethod, requestPath).isPresent())
otherHttpMethods.add(otherHttpMethod);
// Handle OPTIONS specially by indicating we don't want to invoke the response handler
// Otherwise, throw an exception indicating a 405
if (otherHttpMethods.size() > 0) {
// Always write the Allow header
httpServletResponse.setHeader("Allow",
otherHttpMethods.stream().map(method -> method.name()).collect(joining(", "))); // depends on control dependency: [if], data = [none]
if (httpMethod == HttpMethod.OPTIONS)
return false;
throw new MethodNotAllowedException(format("%s is not supported for this resource. Supported method%s %s",
httpMethod, (otherHttpMethods.size() == 1 ? " is" : "s are"),
otherHttpMethods.stream().map(method -> method.name()).collect(joining(", "))));
}
// No matching route, and no possible alternatives? It's a 404
throw new NotFoundException(format("No route was found for %s %s", httpMethod.name(), requestPath));
} }
|
public class class_name {
@Override
protected void afterRemoveChild(ElementBase child) {
if (child == activePane) {
setActivePane((ElementTreePane) getFirstChild());
}
super.afterRemoveChild(child);
} }
|
public class class_name {
@Override
protected void afterRemoveChild(ElementBase child) {
if (child == activePane) {
setActivePane((ElementTreePane) getFirstChild()); // depends on control dependency: [if], data = [none]
}
super.afterRemoveChild(child);
} }
|
public class class_name {
public static Integer parseHistoryTimeToLive(String historyTimeToLive) {
Integer timeToLive = null;
if (historyTimeToLive != null && !historyTimeToLive.isEmpty()) {
Matcher matISO = REGEX_TTL_ISO.matcher(historyTimeToLive);
if (matISO.find()) {
historyTimeToLive = matISO.group(1);
}
timeToLive = parseIntegerAttribute("historyTimeToLive", historyTimeToLive);
}
if (timeToLive != null && timeToLive < 0) {
throw new NotValidException("Cannot parse historyTimeToLive: negative value is not allowed");
}
return timeToLive;
} }
|
public class class_name {
public static Integer parseHistoryTimeToLive(String historyTimeToLive) {
Integer timeToLive = null;
if (historyTimeToLive != null && !historyTimeToLive.isEmpty()) {
Matcher matISO = REGEX_TTL_ISO.matcher(historyTimeToLive);
if (matISO.find()) {
historyTimeToLive = matISO.group(1); // depends on control dependency: [if], data = [none]
}
timeToLive = parseIntegerAttribute("historyTimeToLive", historyTimeToLive); // depends on control dependency: [if], data = [none]
}
if (timeToLive != null && timeToLive < 0) {
throw new NotValidException("Cannot parse historyTimeToLive: negative value is not allowed");
}
return timeToLive;
} }
|
public class class_name {
public static void unqueue(Task task) {
if(THREAD != null) {
synchronized(THREAD) {
THREAD.queue.remove(task);
}
}
} }
|
public class class_name {
public static void unqueue(Task task) {
if(THREAD != null) {
synchronized(THREAD) { // depends on control dependency: [if], data = [(THREAD]
THREAD.queue.remove(task);
}
}
} }
|
public class class_name {
protected FraggleFragment peek(String tag) {
if (fm != null) {
return (FraggleFragment) fm.findFragmentByTag(tag);
}
return new EmptyFragment();
} }
|
public class class_name {
protected FraggleFragment peek(String tag) {
if (fm != null) {
return (FraggleFragment) fm.findFragmentByTag(tag); // depends on control dependency: [if], data = [none]
}
return new EmptyFragment();
} }
|
public class class_name {
private static float getAutofitTextSize(CharSequence text, TextPaint paint,
float targetWidth, int maxLines, float low, float high, float precision,
DisplayMetrics displayMetrics) {
float mid = (low + high) / 2.0f;
int lineCount = 1;
StaticLayout layout = null;
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid,
displayMetrics));
if (maxLines != 1) {
layout = new StaticLayout(text, paint, (int)targetWidth, Layout.Alignment.ALIGN_NORMAL,
1.0f, 0.0f, true);
lineCount = layout.getLineCount();
}
if (SPEW) Log.d(TAG, "low=" + low + " high=" + high + " mid=" + mid +
" target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount);
if (lineCount > maxLines) {
// For the case that `text` has more newline characters than `maxLines`.
if ((high - low) < precision) {
return low;
}
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics);
}
else if (lineCount < maxLines) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics);
}
else {
float maxLineWidth = 0;
if (maxLines == 1) {
maxLineWidth = paint.measureText(text, 0, text.length());
} else {
for (int i = 0; i < lineCount; i++) {
if (layout.getLineWidth(i) > maxLineWidth) {
maxLineWidth = layout.getLineWidth(i);
}
}
}
if ((high - low) < precision) {
return low;
} else if (maxLineWidth > targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics);
} else if (maxLineWidth < targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics);
} else {
return mid;
}
}
} }
|
public class class_name {
private static float getAutofitTextSize(CharSequence text, TextPaint paint,
float targetWidth, int maxLines, float low, float high, float precision,
DisplayMetrics displayMetrics) {
float mid = (low + high) / 2.0f;
int lineCount = 1;
StaticLayout layout = null;
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid,
displayMetrics));
if (maxLines != 1) {
layout = new StaticLayout(text, paint, (int)targetWidth, Layout.Alignment.ALIGN_NORMAL,
1.0f, 0.0f, true); // depends on control dependency: [if], data = [none]
lineCount = layout.getLineCount(); // depends on control dependency: [if], data = [none]
}
if (SPEW) Log.d(TAG, "low=" + low + " high=" + high + " mid=" + mid +
" target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount);
if (lineCount > maxLines) {
// For the case that `text` has more newline characters than `maxLines`.
if ((high - low) < precision) {
return low; // depends on control dependency: [if], data = [none]
}
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics); // depends on control dependency: [if], data = [none]
}
else if (lineCount < maxLines) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics); // depends on control dependency: [if], data = [none]
}
else {
float maxLineWidth = 0;
if (maxLines == 1) {
maxLineWidth = paint.measureText(text, 0, text.length()); // depends on control dependency: [if], data = [none]
} else {
for (int i = 0; i < lineCount; i++) {
if (layout.getLineWidth(i) > maxLineWidth) {
maxLineWidth = layout.getLineWidth(i); // depends on control dependency: [if], data = [none]
}
}
}
if ((high - low) < precision) {
return low; // depends on control dependency: [if], data = [none]
} else if (maxLineWidth > targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics); // depends on control dependency: [if], data = [none]
} else if (maxLineWidth < targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics); // depends on control dependency: [if], data = [none]
} else {
return mid; // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public static Provider withUrl(Provider provider, String url) {
checkNotNull(provider, "provider");
checkNotNull(url, "url");
try {
Constructor<?> ctor = provider.getClass().getDeclaredConstructor(String.class);
// allow private or package protected ctors
ctor.setAccessible(true);
return Provider.class.cast(ctor.newInstance(url));
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
provider.getClass() + " does not have a String parameter constructor", e);
} catch (Exception e) {
throw new IllegalArgumentException(
"exception attempting to instantiate " + provider.getClass()
+ " for provider " + provider, e);
}
} }
|
public class class_name {
public static Provider withUrl(Provider provider, String url) {
checkNotNull(provider, "provider");
checkNotNull(url, "url");
try {
Constructor<?> ctor = provider.getClass().getDeclaredConstructor(String.class);
// allow private or package protected ctors
ctor.setAccessible(true); // depends on control dependency: [try], data = [none]
return Provider.class.cast(ctor.newInstance(url)); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
provider.getClass() + " does not have a String parameter constructor", e);
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
throw new IllegalArgumentException(
"exception attempting to instantiate " + provider.getClass()
+ " for provider " + provider, e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
int walkHash(HashtableAction action, int retrieveMode, int index, int length)
throws IOException,
EOFException,
FileManagerException,
ClassNotFoundException,
HashtableOnDiskException {
iterationLock.p();
int tindex = -1;
int tableSize = header.tablesize();
//System.out.println("*** table size= " + tableSize + " index=" + index + " length=" + length);
try {
for (int i = index, j = 0; i < tableSize; i++) {
//
// We want to drop the lock between each iteration so that other
// threads can continue to work
//
boolean result = true;
synchronized (this) {
long location = getHtindex(i, header.currentTableId());
long previous = 0;
long next = 0;
int hash = 0;
initReadBuffer(location);
next = headerin.readLong();
hash = headerin.readInt();
while (location != 0) {
HashtableEntry e = readEntry2(location, next, hash, previous, retrieveMode, !CHECK_EXPIRED, header.currentTableId(), null, null);
if (e != null) {
j++;
try {
Object id = e.getKey();
result = action.execute(e);
// if result is false, do not continue
if (result == false) { // LI4337-17
traceDebug("walkHash()", "cacheName=" + this.htoddc.cacheName + " id=" + id + " action.execute() returns false.");
break;
}
} catch (Exception xcp) {
throw new HashtableOnDiskException("HashtableAction: " + xcp.toString());
}
previous = location;
location = next;
if (location != 0) {
initReadBuffer(location);
next = headerin.readLong();
hash = headerin.readInt();
}
}
}
// if result is false, do not continue
if (result == false) { // LI4337-17
break;
}
if (j >= length) {
tindex = i + 1;
break;
}
}
}
} finally {
iterationLock.v();
}
if (tindex == -1) {
tindex = tableSize;
}
//System.out.println("*** HTOD return index=" + tindex + " tableSize=" + tableSize);
return tindex;
} }
|
public class class_name {
int walkHash(HashtableAction action, int retrieveMode, int index, int length)
throws IOException,
EOFException,
FileManagerException,
ClassNotFoundException,
HashtableOnDiskException {
iterationLock.p();
int tindex = -1;
int tableSize = header.tablesize();
//System.out.println("*** table size= " + tableSize + " index=" + index + " length=" + length);
try {
for (int i = index, j = 0; i < tableSize; i++) {
//
// We want to drop the lock between each iteration so that other
// threads can continue to work
//
boolean result = true;
synchronized (this) { // depends on control dependency: [for], data = [none]
long location = getHtindex(i, header.currentTableId());
long previous = 0;
long next = 0;
int hash = 0;
initReadBuffer(location);
next = headerin.readLong();
hash = headerin.readInt();
while (location != 0) {
HashtableEntry e = readEntry2(location, next, hash, previous, retrieveMode, !CHECK_EXPIRED, header.currentTableId(), null, null);
if (e != null) {
j++; // depends on control dependency: [if], data = [none]
try {
Object id = e.getKey();
result = action.execute(e); // depends on control dependency: [try], data = [none]
// if result is false, do not continue
if (result == false) { // LI4337-17
traceDebug("walkHash()", "cacheName=" + this.htoddc.cacheName + " id=" + id + " action.execute() returns false."); // depends on control dependency: [if], data = [none]
break;
}
} catch (Exception xcp) {
throw new HashtableOnDiskException("HashtableAction: " + xcp.toString());
} // depends on control dependency: [catch], data = [none]
previous = location; // depends on control dependency: [if], data = [none]
location = next; // depends on control dependency: [if], data = [none]
if (location != 0) {
initReadBuffer(location); // depends on control dependency: [if], data = [(location]
next = headerin.readLong(); // depends on control dependency: [if], data = [none]
hash = headerin.readInt(); // depends on control dependency: [if], data = [none]
}
}
}
// if result is false, do not continue
if (result == false) { // LI4337-17
break;
}
if (j >= length) {
tindex = i + 1; // depends on control dependency: [if], data = [none]
break;
}
}
}
} finally {
iterationLock.v();
}
if (tindex == -1) {
tindex = tableSize;
}
//System.out.println("*** HTOD return index=" + tindex + " tableSize=" + tableSize);
return tindex;
} }
|
public class class_name {
public void setResourceAdaptorContext(javax.slee.resource.ResourceAdaptorContext raContext) {
this.raContext = raContext;
this.tracer = raContext.getTracer("XCAPClientResourceAdaptor");
sbbInterface = new XCAPClientResourceAdaptorSbbInterfaceImpl(this);
this.sleeEndpoint = raContext.getSleeEndpoint();
this.eventLookupFacility = raContext.getEventLookupFacility();
try {
this.getResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("GetResponseEvent", "org.restcomm", "2.0"));
this.putResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("PutResponseEvent", "org.restcomm", "2.0"));
this.deleteResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("DeleteResponseEvent", "org.restcomm", "2.0"));
}
catch(Exception e) {
if(tracer.isWarningEnabled())
tracer.warning("Could not look up Response Event",e);
}
} }
|
public class class_name {
public void setResourceAdaptorContext(javax.slee.resource.ResourceAdaptorContext raContext) {
this.raContext = raContext;
this.tracer = raContext.getTracer("XCAPClientResourceAdaptor");
sbbInterface = new XCAPClientResourceAdaptorSbbInterfaceImpl(this);
this.sleeEndpoint = raContext.getSleeEndpoint();
this.eventLookupFacility = raContext.getEventLookupFacility();
try {
this.getResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("GetResponseEvent", "org.restcomm", "2.0"));
// depends on control dependency: [try], data = [none]
this.putResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("PutResponseEvent", "org.restcomm", "2.0"));
// depends on control dependency: [try], data = [none]
this.deleteResponseEvent = eventLookupFacility.getFireableEventType(new EventTypeID("DeleteResponseEvent", "org.restcomm", "2.0"));
// depends on control dependency: [try], data = [none]
}
catch(Exception e) {
if(tracer.isWarningEnabled())
tracer.warning("Could not look up Response Event",e);
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private static void printRealm(ArrayList<String> realm, String name) {
System.out.println(name + ":");
for (String s : realm) {
System.out.println(" " + s);
}
} }
|
public class class_name {
private static void printRealm(ArrayList<String> realm, String name) {
System.out.println(name + ":");
for (String s : realm) {
System.out.println(" " + s); // depends on control dependency: [for], data = [s]
}
} }
|
public class class_name {
public InetAddress replicaNodeForId(final String id, int replicaNum) {
if (replicaNum < 1 || replicaNum > 3) {
throw new IllegalArgumentException("Replica number must be between 1 and 3.");
}
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
if (nodeId == -2) {
throw new IllegalStateException("Replica not configured for this bucket.");
}
try {
return InetAddress.getByName(cbc.nodeAtIndex(nodeId).hostname().address());
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
} }
|
public class class_name {
public InetAddress replicaNodeForId(final String id, int replicaNum) {
if (replicaNum < 1 || replicaNum > 3) {
throw new IllegalArgumentException("Replica number must be between 1 and 3.");
}
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
if (nodeId == -2) {
throw new IllegalStateException("Replica not configured for this bucket.");
}
try {
return InetAddress.getByName(cbc.nodeAtIndex(nodeId).hostname().address()); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
} }
|
public class class_name {
public final hqlParser.path_return path() throws RecognitionException {
hqlParser.path_return retval = new hqlParser.path_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token DOT303=null;
ParserRuleReturnScope identifier302 =null;
ParserRuleReturnScope identifier304 =null;
CommonTree DOT303_tree=null;
// TODO - need to clean up DotIdent - suspect that DotIdent2 supersedes the other one, but need to do the analysis
//HandleDotIdent2();
try {
// hql.g:714:2: ( identifier ( DOT ^ identifier )* )
// hql.g:714:4: identifier ( DOT ^ identifier )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_identifier_in_path3609);
identifier302=identifier();
state._fsp--;
adaptor.addChild(root_0, identifier302.getTree());
// hql.g:714:15: ( DOT ^ identifier )*
loop108:
while (true) {
int alt108=2;
int LA108_0 = input.LA(1);
if ( (LA108_0==DOT) ) {
alt108=1;
}
switch (alt108) {
case 1 :
// hql.g:714:17: DOT ^ identifier
{
DOT303=(Token)match(input,DOT,FOLLOW_DOT_in_path3613);
DOT303_tree = (CommonTree)adaptor.create(DOT303);
root_0 = (CommonTree)adaptor.becomeRoot(DOT303_tree, root_0);
WeakKeywords();
pushFollow(FOLLOW_identifier_in_path3618);
identifier304=identifier();
state._fsp--;
adaptor.addChild(root_0, identifier304.getTree());
}
break;
default :
break loop108;
}
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} }
|
public class class_name {
public final hqlParser.path_return path() throws RecognitionException {
hqlParser.path_return retval = new hqlParser.path_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token DOT303=null;
ParserRuleReturnScope identifier302 =null;
ParserRuleReturnScope identifier304 =null;
CommonTree DOT303_tree=null;
// TODO - need to clean up DotIdent - suspect that DotIdent2 supersedes the other one, but need to do the analysis
//HandleDotIdent2();
try {
// hql.g:714:2: ( identifier ( DOT ^ identifier )* )
// hql.g:714:4: identifier ( DOT ^ identifier )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_identifier_in_path3609);
identifier302=identifier();
state._fsp--;
adaptor.addChild(root_0, identifier302.getTree());
// hql.g:714:15: ( DOT ^ identifier )*
loop108:
while (true) {
int alt108=2;
int LA108_0 = input.LA(1);
if ( (LA108_0==DOT) ) {
alt108=1; // depends on control dependency: [if], data = [none]
}
switch (alt108) {
case 1 :
// hql.g:714:17: DOT ^ identifier
{
DOT303=(Token)match(input,DOT,FOLLOW_DOT_in_path3613);
DOT303_tree = (CommonTree)adaptor.create(DOT303);
root_0 = (CommonTree)adaptor.becomeRoot(DOT303_tree, root_0);
WeakKeywords();
pushFollow(FOLLOW_identifier_in_path3618);
identifier304=identifier();
state._fsp--;
adaptor.addChild(root_0, identifier304.getTree());
}
break;
default :
break loop108;
}
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} }
|
public class class_name {
@ConditionalOnExpression("'${joinfaces.primefaces.uploader}' != 'commons'")
@Bean
public ServletContextInitializer primefacesFileUploadServletContextInitializer(MultipartConfigElement multipartConfigElement) {
return servletContext -> {
ServletRegistration servletRegistration = servletContext.getServletRegistration(FACES_SERVLET_NAME);
if (servletRegistration instanceof ServletRegistration.Dynamic) {
((ServletRegistration.Dynamic) servletRegistration).setMultipartConfig(multipartConfigElement);
}
};
} }
|
public class class_name {
@ConditionalOnExpression("'${joinfaces.primefaces.uploader}' != 'commons'")
@Bean
public ServletContextInitializer primefacesFileUploadServletContextInitializer(MultipartConfigElement multipartConfigElement) {
return servletContext -> {
ServletRegistration servletRegistration = servletContext.getServletRegistration(FACES_SERVLET_NAME);
if (servletRegistration instanceof ServletRegistration.Dynamic) {
((ServletRegistration.Dynamic) servletRegistration).setMultipartConfig(multipartConfigElement); // depends on control dependency: [if], data = [none]
}
};
} }
|
public class class_name {
@Nullable
public static CalendarDate parseUdunitsOrIso(String calendarName, String isoOrUdunits) {
CalendarDate result;
try {
result = parseISOformat(calendarName, isoOrUdunits);
} catch (Exception e) {
try {
result = parseUdunits(calendarName, isoOrUdunits);
} catch (Exception e2) {
return null;
}
}
return result;
} }
|
public class class_name {
@Nullable
public static CalendarDate parseUdunitsOrIso(String calendarName, String isoOrUdunits) {
CalendarDate result;
try {
result = parseISOformat(calendarName, isoOrUdunits);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
try {
result = parseUdunits(calendarName, isoOrUdunits);
// depends on control dependency: [try], data = [none]
} catch (Exception e2) {
return null;
}
// depends on control dependency: [catch], data = [none]
}
// depends on control dependency: [catch], data = [none]
return result;
} }
|
public class class_name {
private void doInterruptAllWaitingThreads() {
//Interrupt all the threads
for (int i=0; i<nThreads; i++) {
threads[i].interrupt();
}
synchronized(lock) {
lock.notify();
}
} }
|
public class class_name {
private void doInterruptAllWaitingThreads() {
//Interrupt all the threads
for (int i=0; i<nThreads; i++) {
threads[i].interrupt();
// depends on control dependency: [for], data = [i]
}
synchronized(lock) {
lock.notify();
}
} }
|
public class class_name {
@Override
public final ColumnsValues convert(final Map<String, Object> pAddParam,
final T pObject) throws Exception {
ColumnsValues result = new ColumnsValues();
TableSql tableSql = this.tablesMap.get(this.objectClass.getSimpleName());
result.setIdColumnsNames(tableSql.getIdColumnsNames());
if (pAddParam.get("isOnlyId") != null) {
if (tableSql.getIdColumnsNames().length > 0 && tableSql.getFieldsMap()
.get(tableSql.getIdColumnsNames()[0]).getTypeField()
.equals(ETypeField.DERIVED_FROM_COMPOSITE)) {
// it's also composite foreign ID
for (Map.Entry<String, FieldSql> entry : tableSql
.getFieldsMap().entrySet()) {
if (entry.getValue().getTypeField()
.equals(ETypeField.COMPOSITE_FK_PK)) {
convertField(pAddParam, entry.getKey(), pObject,
true, result, tableSql);
break;
}
}
} else { // simple or foreign entity or composite ID (not also foreign):
for (String idFldNm : tableSql.getIdColumnsNames()) {
convertField(pAddParam, idFldNm, pObject, true, result, tableSql);
}
}
} else if (pAddParam.get("fieldsNames") != null) {
String[] fieldsNames = (String[]) pAddParam.get("fieldsNames");
for (String fldNm : fieldsNames) {
convertField(pAddParam, fldNm, pObject,
false, result, tableSql);
}
} else {
for (Map.Entry<String, FieldSql> entry : tableSql
.getFieldsMap().entrySet()) {
if (!entry.getValue().getTypeField()
.equals(ETypeField.DERIVED_FROM_COMPOSITE)) {
// Foreign entity with composite ID will be represented
// as several ID fields, e.g. {itsName='admin', itsRole='role'}.
convertField(pAddParam, entry.getKey(), pObject,
false, result, tableSql);
}
}
}
return result;
} }
|
public class class_name {
@Override
public final ColumnsValues convert(final Map<String, Object> pAddParam,
final T pObject) throws Exception {
ColumnsValues result = new ColumnsValues();
TableSql tableSql = this.tablesMap.get(this.objectClass.getSimpleName());
result.setIdColumnsNames(tableSql.getIdColumnsNames());
if (pAddParam.get("isOnlyId") != null) {
if (tableSql.getIdColumnsNames().length > 0 && tableSql.getFieldsMap()
.get(tableSql.getIdColumnsNames()[0]).getTypeField()
.equals(ETypeField.DERIVED_FROM_COMPOSITE)) {
// it's also composite foreign ID
for (Map.Entry<String, FieldSql> entry : tableSql
.getFieldsMap().entrySet()) {
if (entry.getValue().getTypeField()
.equals(ETypeField.COMPOSITE_FK_PK)) {
convertField(pAddParam, entry.getKey(), pObject,
true, result, tableSql); // depends on control dependency: [if], data = [none]
break;
}
}
} else { // simple or foreign entity or composite ID (not also foreign):
for (String idFldNm : tableSql.getIdColumnsNames()) {
convertField(pAddParam, idFldNm, pObject, true, result, tableSql); // depends on control dependency: [for], data = [idFldNm]
}
}
} else if (pAddParam.get("fieldsNames") != null) {
String[] fieldsNames = (String[]) pAddParam.get("fieldsNames");
for (String fldNm : fieldsNames) {
convertField(pAddParam, fldNm, pObject,
false, result, tableSql); // depends on control dependency: [for], data = [none]
}
} else {
for (Map.Entry<String, FieldSql> entry : tableSql
.getFieldsMap().entrySet()) {
if (!entry.getValue().getTypeField()
.equals(ETypeField.DERIVED_FROM_COMPOSITE)) {
// Foreign entity with composite ID will be represented
// as several ID fields, e.g. {itsName='admin', itsRole='role'}.
convertField(pAddParam, entry.getKey(), pObject,
false, result, tableSql); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} }
|
public class class_name {
public List<JobInfo> findJobs(final Optional<String> type, final int count) {
if (type.isPresent()) {
return jobRepository.findLatestBy(type.get(), count);
} else {
return jobRepository.findLatest(count);
}
} }
|
public class class_name {
public List<JobInfo> findJobs(final Optional<String> type, final int count) {
if (type.isPresent()) {
return jobRepository.findLatestBy(type.get(), count); // depends on control dependency: [if], data = [none]
} else {
return jobRepository.findLatest(count); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public HadoopServer performFinish() {
try {
if (this.original == null) {
// New location
Display.getDefault().syncExec(new Runnable() {
public void run() {
ServerRegistry.getInstance().addServer(
HadoopLocationWizard.this.location);
}
});
return this.location;
} else {
// Update location
final String originalName = this.original.getLocationName();
this.original.load(this.location);
Display.getDefault().syncExec(new Runnable() {
public void run() {
ServerRegistry.getInstance().updateServer(originalName,
HadoopLocationWizard.this.location);
}
});
return this.original;
}
} catch (Exception e) {
e.printStackTrace();
setMessage("Invalid server location values", IMessageProvider.ERROR);
return null;
}
} }
|
public class class_name {
public HadoopServer performFinish() {
try {
if (this.original == null) {
// New location
Display.getDefault().syncExec(new Runnable() {
public void run() {
ServerRegistry.getInstance().addServer(
HadoopLocationWizard.this.location);
}
}); // depends on control dependency: [if], data = [none]
return this.location; // depends on control dependency: [if], data = [none]
} else {
// Update location
final String originalName = this.original.getLocationName();
this.original.load(this.location); // depends on control dependency: [if], data = [none]
Display.getDefault().syncExec(new Runnable() {
public void run() {
ServerRegistry.getInstance().updateServer(originalName,
HadoopLocationWizard.this.location);
}
}); // depends on control dependency: [if], data = [none]
return this.original; // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
e.printStackTrace();
setMessage("Invalid server location values", IMessageProvider.ERROR);
return null;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void release() {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException ex) {
LOGGER.debug("Failed to release lock", ex);
}
}
if (file != null) {
try {
file.close();
file = null;
} catch (IOException ex) {
LOGGER.debug("Unable to delete lock file", ex);
}
}
if (lockFile != null && lockFile.isFile()) {
final String msg = readLockFile();
if (msg != null && msg.equals(magic) && !lockFile.delete()) {
LOGGER.error("Lock file '{}' was unable to be deleted. Please manually delete this file.", lockFile.toString());
lockFile.deleteOnExit();
}
}
lockFile = null;
removeShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock released ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
} }
|
public class class_name {
public void release() {
if (lock != null) {
try {
lock.release(); // depends on control dependency: [try], data = [none]
lock = null; // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
LOGGER.debug("Failed to release lock", ex);
} // depends on control dependency: [catch], data = [none]
}
if (file != null) {
try {
file.close(); // depends on control dependency: [try], data = [none]
file = null; // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
LOGGER.debug("Unable to delete lock file", ex);
} // depends on control dependency: [catch], data = [none]
}
if (lockFile != null && lockFile.isFile()) {
final String msg = readLockFile();
if (msg != null && msg.equals(magic) && !lockFile.delete()) {
LOGGER.error("Lock file '{}' was unable to be deleted. Please manually delete this file.", lockFile.toString()); // depends on control dependency: [if], data = [none]
lockFile.deleteOnExit(); // depends on control dependency: [if], data = [none]
}
}
lockFile = null;
removeShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock released ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
} }
|
public class class_name {
protected Node<ElkClass> queryEquivalentClasses(
final ElkClassExpression classExpression)
throws ElkInconsistentOntologyException, ElkException {
final Node<ElkClass> result;
if (computeQuery(classExpression, false)) {
final Node<ElkClass> r = classExpressionQueryState_
.getEquivalentClasses(classExpression);
if (r == null) {
result = classTaxonomyState.getTaxonomy().getBottomNode();
} else {
result = r;
}
} else {
// classExpression couldn't be indexed; pretend it is a fresh class
result = new QueryNode<ElkClass>(ElkClassKeyProvider.INSTANCE);
}
incompleteness_.log(
incompleteness_.getIncompletenessMonitorForClassExpressionQuery(
classExpressionQueryState_
.getOccurrenceStore(classExpression)));
return result;
} }
|
public class class_name {
protected Node<ElkClass> queryEquivalentClasses(
final ElkClassExpression classExpression)
throws ElkInconsistentOntologyException, ElkException {
final Node<ElkClass> result;
if (computeQuery(classExpression, false)) {
final Node<ElkClass> r = classExpressionQueryState_
.getEquivalentClasses(classExpression);
if (r == null) {
result = classTaxonomyState.getTaxonomy().getBottomNode(); // depends on control dependency: [if], data = [none]
} else {
result = r; // depends on control dependency: [if], data = [none]
}
} else {
// classExpression couldn't be indexed; pretend it is a fresh class
result = new QueryNode<ElkClass>(ElkClassKeyProvider.INSTANCE);
}
incompleteness_.log(
incompleteness_.getIncompletenessMonitorForClassExpressionQuery(
classExpressionQueryState_
.getOccurrenceStore(classExpression)));
return result;
} }
|
public class class_name {
public boolean changeSubScreen(Container parent, JBasePanel baseScreen, String strCommandToPush, int options)
{
if ((parent == null) || (parent == this))
parent = m_parent;
boolean bScreenChange = false;
if (!this.checkSecurity(baseScreen))
{
baseScreen.free();
return false;
}
this.freeSubComponents(parent);
if (parent.getComponentCount() > 0)
{ // Remove all the old components
parent.removeAll();
bScreenChange = true;
}
JComponent screen = baseScreen;
if (!(parent.getLayout() instanceof BoxLayout))
parent.setLayout(new BorderLayout()); // If default layout, use box layout!
screen = baseScreen.setupNewScreen(baseScreen);
screen.setMinimumSize(new Dimension(100, 100));
screen.setAlignmentX(LEFT_ALIGNMENT);
screen.setAlignmentY(TOP_ALIGNMENT);
parent.add(screen);
if (bScreenChange)
{
this.invalidate();
this.validate();
this.repaint();
baseScreen.resetFocus();
}
if (parent == m_parent)
{
if (strCommandToPush == null)
strCommandToPush = baseScreen.getScreenCommand();
if (strCommandToPush != null)
if ((options & Constants.DONT_PUSH_HISTORY) == 0)
this.pushHistory(strCommandToPush, ((options & Constants.DONT_PUSH_TO_BROWSER) == Constants.PUSH_TO_BROWSER));
}
return true; // Success
} }
|
public class class_name {
public boolean changeSubScreen(Container parent, JBasePanel baseScreen, String strCommandToPush, int options)
{
if ((parent == null) || (parent == this))
parent = m_parent;
boolean bScreenChange = false;
if (!this.checkSecurity(baseScreen))
{
baseScreen.free(); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
this.freeSubComponents(parent);
if (parent.getComponentCount() > 0)
{ // Remove all the old components
parent.removeAll(); // depends on control dependency: [if], data = [none]
bScreenChange = true; // depends on control dependency: [if], data = [none]
}
JComponent screen = baseScreen;
if (!(parent.getLayout() instanceof BoxLayout))
parent.setLayout(new BorderLayout()); // If default layout, use box layout!
screen = baseScreen.setupNewScreen(baseScreen);
screen.setMinimumSize(new Dimension(100, 100));
screen.setAlignmentX(LEFT_ALIGNMENT);
screen.setAlignmentY(TOP_ALIGNMENT);
parent.add(screen);
if (bScreenChange)
{
this.invalidate(); // depends on control dependency: [if], data = [none]
this.validate(); // depends on control dependency: [if], data = [none]
this.repaint(); // depends on control dependency: [if], data = [none]
baseScreen.resetFocus(); // depends on control dependency: [if], data = [none]
}
if (parent == m_parent)
{
if (strCommandToPush == null)
strCommandToPush = baseScreen.getScreenCommand();
if (strCommandToPush != null)
if ((options & Constants.DONT_PUSH_HISTORY) == 0)
this.pushHistory(strCommandToPush, ((options & Constants.DONT_PUSH_TO_BROWSER) == Constants.PUSH_TO_BROWSER));
}
return true; // Success
} }
|
public class class_name {
public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory)
{
if (metricsTrackerFactory != null) {
this.metricsTracker = new MetricsTrackerDelegate(metricsTrackerFactory.create(config.getPoolName(), getPoolStats()));
}
else {
this.metricsTracker = new NopMetricsTrackerDelegate();
}
} }
|
public class class_name {
public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory)
{
if (metricsTrackerFactory != null) {
this.metricsTracker = new MetricsTrackerDelegate(metricsTrackerFactory.create(config.getPoolName(), getPoolStats())); // depends on control dependency: [if], data = [(metricsTrackerFactory]
}
else {
this.metricsTracker = new NopMetricsTrackerDelegate(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public Set<Service> getServices(Set<URI> serviceUris) throws ServiceException {
ImmutableSet.Builder<Service> result = ImmutableSet.builder();
Service svc;
for (URI svcUri : serviceUris) {
svc = this.getService(svcUri);
if (svc != null) {
result.add(svc);
}
}
return result.build();
} }
|
public class class_name {
@Override
public Set<Service> getServices(Set<URI> serviceUris) throws ServiceException {
ImmutableSet.Builder<Service> result = ImmutableSet.builder();
Service svc;
for (URI svcUri : serviceUris) {
svc = this.getService(svcUri);
if (svc != null) {
result.add(svc); // depends on control dependency: [if], data = [(svc]
}
}
return result.build();
} }
|
public class class_name {
public static Map<String, Object> loadSequenceResources(
final TrainingParameters params) throws IOException {
final Map<String, Object> resources = new HashMap<String, Object>();
@SuppressWarnings("rawtypes")
final Map<String, ArtifactSerializer> artifactSerializers = SequenceLabelerModel
.createArtifactSerializers();
if (Flags.isBrownFeatures(params)) {
final String ClusterLexiconPath = Flags.getBrownFeatures(params);
final String serializerId = "brownserializer";
final List<File> ClusterLexiconFiles = Flags
.getClusterLexiconFiles(ClusterLexiconPath);
for (final File ClusterLexiconFile : ClusterLexiconFiles) {
final String brownFilePath = ClusterLexiconFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer());
loadResource(serializerId, artifactSerializers, brownFilePath,
resources);
}
}
if (Flags.isClarkFeatures(params)) {
final String clarkClusterPath = Flags.getClarkFeatures(params);
final String serializerId = "clarkserializer";
final List<File> clarkClusterFiles = Flags
.getClusterLexiconFiles(clarkClusterPath);
for (final File clarkClusterFile : clarkClusterFiles) {
final String clarkFilePath = clarkClusterFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer());
loadResource(serializerId, artifactSerializers, clarkFilePath,
resources);
}
}
if (Flags.isWord2VecClusterFeatures(params)) {
final String ClusterLexiconPath = Flags
.getWord2VecClusterFeatures(params);
final String serializerId = "word2vecserializer";
final List<File> ClusterLexiconFiles = Flags
.getClusterLexiconFiles(ClusterLexiconPath);
for (final File ClusterLexiconFile : ClusterLexiconFiles) {
final String word2vecFilePath = ClusterLexiconFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer());
loadResource(serializerId, artifactSerializers, word2vecFilePath,
resources);
}
}
if (Flags.isDictionaryFeatures(params)) {
final String dictDir = Flags.getDictionaryFeatures(params);
final String serializerId = "dictionaryserializer";
final List<File> fileList = StringUtils.getFilesInDir(new File(dictDir));
for (final File dictFile : fileList) {
final String dictionaryPath = dictFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new Dictionary.DictionarySerializer());
loadResource(serializerId, artifactSerializers, dictionaryPath,
resources);
}
}
if (Flags.isPOSTagModelFeatures(params)) {
final String morphoResourcesPath = Flags.getPOSTagModelFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, morphoResourcesPath,
resources);
}
if (Flags.isPOSDictionaryFeatures(params)) {
final String posDictPath = Flags.getPOSDictionaryFeatures(params);
final String posSerializerId = "posdictserializer";
artifactSerializers.put(posSerializerId,
new POSDictionary.POSDictionarySerializer());
loadResource(posSerializerId, artifactSerializers, posDictPath,
resources);
}
if (Flags.isLemmaModelFeatures(params)) {
final String lemmaModelPath = Flags.getLemmaModelFeatures(params);
final String lemmaSerializerId = "seqmodelserializer";
artifactSerializers.put(lemmaSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(lemmaSerializerId, artifactSerializers, lemmaModelPath,
resources);
}
if (Flags.isLemmaDictionaryFeatures(params)) {
final String lemmaDictPath = Flags.getLemmaDictionaryFeatures(params);
final String[] lemmaDictResources = Flags
.getLemmaDictionaryResources(lemmaDictPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaDictSerializerId = "lemmadictserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, lemmaDictResources[0],
resources);
artifactSerializers.put(lemmaDictSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaDictSerializerId, artifactSerializers,
lemmaDictResources[1], resources);
}
if (Flags.isSuperSenseFeatures(params)) {
final String mfsResourcesPath = Flags.getSuperSenseFeatures(params);
final String[] mfsResources = Flags
.getSuperSenseResources(mfsResourcesPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaSerializerId = "lemmadictserializer";
final String mfsSerializerId = "mfsserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, mfsResources[0],
resources);
artifactSerializers.put(lemmaSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaSerializerId, artifactSerializers, mfsResources[1],
resources);
artifactSerializers.put(mfsSerializerId,
new MFSResource.MFSResourceSerializer());
loadResource(mfsSerializerId, artifactSerializers, mfsResources[2],
resources);
}
if (Flags.isMFSFeatures(params)) {
final String mfsResourcesPath = Flags.getMFSFeatures(params);
final String[] mfsResources = Flags.getMFSResources(mfsResourcesPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaSerializerId = "lemmadictserializer";
final String mfsSerializerId = "mfsserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, mfsResources[0],
resources);
artifactSerializers.put(lemmaSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaSerializerId, artifactSerializers, mfsResources[1],
resources);
artifactSerializers.put(mfsSerializerId,
new MFSResource.MFSResourceSerializer());
loadResource(mfsSerializerId, artifactSerializers, mfsResources[2],
resources);
}
if (Flags.isLemmaBaselineFeatures(params)) {
final String lemmaBaselineFeatures = Flags
.getLemmaBaselineFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, lemmaBaselineFeatures,
resources);
}
if (Flags.isChunkBaselineFeatures(params)) {
final String chunkBaselineFeatures = Flags
.getChunkBaselineFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, chunkBaselineFeatures,
resources);
}
if (Flags.isPredicateContextFeatures(params)) {
final String predicateContextFeatures = Flags
.getPredicateContextFeatures(params);
final String posSerializerId = "predicatecontextserializer";
artifactSerializers.put(posSerializerId,
new PredicateContext.PredicateContextSerializer());
loadResource(posSerializerId, artifactSerializers,
predicateContextFeatures, resources);
}
return resources;
} }
|
public class class_name {
public static Map<String, Object> loadSequenceResources(
final TrainingParameters params) throws IOException {
final Map<String, Object> resources = new HashMap<String, Object>();
@SuppressWarnings("rawtypes")
final Map<String, ArtifactSerializer> artifactSerializers = SequenceLabelerModel
.createArtifactSerializers();
if (Flags.isBrownFeatures(params)) {
final String ClusterLexiconPath = Flags.getBrownFeatures(params);
final String serializerId = "brownserializer";
final List<File> ClusterLexiconFiles = Flags
.getClusterLexiconFiles(ClusterLexiconPath);
for (final File ClusterLexiconFile : ClusterLexiconFiles) {
final String brownFilePath = ClusterLexiconFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer()); // depends on control dependency: [for], data = [none]
loadResource(serializerId, artifactSerializers, brownFilePath,
resources); // depends on control dependency: [for], data = [none]
}
}
if (Flags.isClarkFeatures(params)) {
final String clarkClusterPath = Flags.getClarkFeatures(params);
final String serializerId = "clarkserializer";
final List<File> clarkClusterFiles = Flags
.getClusterLexiconFiles(clarkClusterPath);
for (final File clarkClusterFile : clarkClusterFiles) {
final String clarkFilePath = clarkClusterFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer()); // depends on control dependency: [for], data = [none]
loadResource(serializerId, artifactSerializers, clarkFilePath,
resources); // depends on control dependency: [for], data = [none]
}
}
if (Flags.isWord2VecClusterFeatures(params)) {
final String ClusterLexiconPath = Flags
.getWord2VecClusterFeatures(params);
final String serializerId = "word2vecserializer";
final List<File> ClusterLexiconFiles = Flags
.getClusterLexiconFiles(ClusterLexiconPath);
for (final File ClusterLexiconFile : ClusterLexiconFiles) {
final String word2vecFilePath = ClusterLexiconFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new WordCluster.WordClusterSerializer()); // depends on control dependency: [for], data = [none]
loadResource(serializerId, artifactSerializers, word2vecFilePath,
resources); // depends on control dependency: [for], data = [none]
}
}
if (Flags.isDictionaryFeatures(params)) {
final String dictDir = Flags.getDictionaryFeatures(params);
final String serializerId = "dictionaryserializer";
final List<File> fileList = StringUtils.getFilesInDir(new File(dictDir));
for (final File dictFile : fileList) {
final String dictionaryPath = dictFile.getCanonicalPath();
artifactSerializers.put(serializerId,
new Dictionary.DictionarySerializer()); // depends on control dependency: [for], data = [none]
loadResource(serializerId, artifactSerializers, dictionaryPath,
resources); // depends on control dependency: [for], data = [none]
}
}
if (Flags.isPOSTagModelFeatures(params)) {
final String morphoResourcesPath = Flags.getPOSTagModelFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, morphoResourcesPath,
resources);
}
if (Flags.isPOSDictionaryFeatures(params)) {
final String posDictPath = Flags.getPOSDictionaryFeatures(params);
final String posSerializerId = "posdictserializer";
artifactSerializers.put(posSerializerId,
new POSDictionary.POSDictionarySerializer());
loadResource(posSerializerId, artifactSerializers, posDictPath,
resources);
}
if (Flags.isLemmaModelFeatures(params)) {
final String lemmaModelPath = Flags.getLemmaModelFeatures(params);
final String lemmaSerializerId = "seqmodelserializer";
artifactSerializers.put(lemmaSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(lemmaSerializerId, artifactSerializers, lemmaModelPath,
resources);
}
if (Flags.isLemmaDictionaryFeatures(params)) {
final String lemmaDictPath = Flags.getLemmaDictionaryFeatures(params);
final String[] lemmaDictResources = Flags
.getLemmaDictionaryResources(lemmaDictPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaDictSerializerId = "lemmadictserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, lemmaDictResources[0],
resources);
artifactSerializers.put(lemmaDictSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaDictSerializerId, artifactSerializers,
lemmaDictResources[1], resources);
}
if (Flags.isSuperSenseFeatures(params)) {
final String mfsResourcesPath = Flags.getSuperSenseFeatures(params);
final String[] mfsResources = Flags
.getSuperSenseResources(mfsResourcesPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaSerializerId = "lemmadictserializer";
final String mfsSerializerId = "mfsserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, mfsResources[0],
resources);
artifactSerializers.put(lemmaSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaSerializerId, artifactSerializers, mfsResources[1],
resources);
artifactSerializers.put(mfsSerializerId,
new MFSResource.MFSResourceSerializer());
loadResource(mfsSerializerId, artifactSerializers, mfsResources[2],
resources);
}
if (Flags.isMFSFeatures(params)) {
final String mfsResourcesPath = Flags.getMFSFeatures(params);
final String[] mfsResources = Flags.getMFSResources(mfsResourcesPath);
final String posSerializerId = "seqmodelserializer";
final String lemmaSerializerId = "lemmadictserializer";
final String mfsSerializerId = "mfsserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, mfsResources[0],
resources);
artifactSerializers.put(lemmaSerializerId,
new DictionaryLemmatizer.DictionaryLemmatizerSerializer());
loadResource(lemmaSerializerId, artifactSerializers, mfsResources[1],
resources);
artifactSerializers.put(mfsSerializerId,
new MFSResource.MFSResourceSerializer());
loadResource(mfsSerializerId, artifactSerializers, mfsResources[2],
resources);
}
if (Flags.isLemmaBaselineFeatures(params)) {
final String lemmaBaselineFeatures = Flags
.getLemmaBaselineFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, lemmaBaselineFeatures,
resources);
}
if (Flags.isChunkBaselineFeatures(params)) {
final String chunkBaselineFeatures = Flags
.getChunkBaselineFeatures(params);
final String posSerializerId = "seqmodelserializer";
artifactSerializers.put(posSerializerId,
new SequenceModelResource.SequenceModelResourceSerializer());
loadResource(posSerializerId, artifactSerializers, chunkBaselineFeatures,
resources);
}
if (Flags.isPredicateContextFeatures(params)) {
final String predicateContextFeatures = Flags
.getPredicateContextFeatures(params);
final String posSerializerId = "predicatecontextserializer";
artifactSerializers.put(posSerializerId,
new PredicateContext.PredicateContextSerializer());
loadResource(posSerializerId, artifactSerializers,
predicateContextFeatures, resources);
}
return resources;
} }
|
public class class_name {
public void updateModelPageDisabledState(CmsUUID entryId, boolean disabled) {
if (m_modelPageTreeItems.containsKey(entryId)) {
m_modelPageTreeItems.get(entryId).setDisabled(disabled);
} else if (m_parentModelPageTreeItems.containsKey(entryId)) {
m_parentModelPageTreeItems.get(entryId).setDisabled(disabled);
}
} }
|
public class class_name {
public void updateModelPageDisabledState(CmsUUID entryId, boolean disabled) {
if (m_modelPageTreeItems.containsKey(entryId)) {
m_modelPageTreeItems.get(entryId).setDisabled(disabled); // depends on control dependency: [if], data = [none]
} else if (m_parentModelPageTreeItems.containsKey(entryId)) {
m_parentModelPageTreeItems.get(entryId).setDisabled(disabled); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private static boolean linearPathIntersectsEnvelope_(MultiPath multipath_a,
Envelope2D env_b, double tolerance, ProgressTracker progress_tracker) {
if (!multipath_a.hasNonLinearSegments()) {
Envelope2D env_b_inflated = new Envelope2D();
env_b_inflated.setCoords(env_b);
env_b_inflated.inflate(tolerance, tolerance);
MultiPathImpl mimpl_a = (MultiPathImpl) multipath_a._getImpl();
AttributeStreamOfDbl xy = (AttributeStreamOfDbl) (mimpl_a
.getAttributeStreamRef(VertexDescription.Semantics.POSITION));
Point2D pt = new Point2D();
Point2D pt_prev = new Point2D();
Point2D pt_1 = new Point2D();
Point2D pt_2 = new Point2D();
for (int ipath = 0, npath = mimpl_a.getPathCount(); ipath < npath; ipath++) {
boolean b_first = true;
for (int i = mimpl_a.getPathStart(ipath), n = mimpl_a
.getPathEnd(ipath); i < n; i++) {
if (b_first) {
xy.read(2 * i, pt_prev);
b_first = false;
continue;
}
xy.read(2 * i, pt);
pt_1.setCoords(pt_prev);
pt_2.setCoords(pt);
if (env_b_inflated.clipLine(pt_1, pt_2) != 0)
return true;
pt_prev.setCoords(pt);
}
}
} else {
Line line_1 = new Line(env_b.xmin, env_b.ymin, env_b.xmin,
env_b.ymax);
Line line_2 = new Line(env_b.xmin, env_b.ymax, env_b.xmax,
env_b.ymax);
Line line3 = new Line(env_b.xmax, env_b.ymax, env_b.xmax,
env_b.ymin);
Line line4 = new Line(env_b.xmax, env_b.ymin, env_b.xmin,
env_b.ymin);
SegmentIterator iter = multipath_a.querySegmentIterator();
while (iter.nextPath()) {
while (iter.hasNextSegment()) {
Segment polySeg = iter.nextSegment();
if (polySeg.isIntersecting(line_1, tolerance))
return true;
if (polySeg.isIntersecting(line_2, tolerance))
return true;
if (polySeg.isIntersecting(line3, tolerance))
return true;
if (polySeg.isIntersecting(line4, tolerance))
return true;
}
}
}
return false;
} }
|
public class class_name {
private static boolean linearPathIntersectsEnvelope_(MultiPath multipath_a,
Envelope2D env_b, double tolerance, ProgressTracker progress_tracker) {
if (!multipath_a.hasNonLinearSegments()) {
Envelope2D env_b_inflated = new Envelope2D();
env_b_inflated.setCoords(env_b); // depends on control dependency: [if], data = [none]
env_b_inflated.inflate(tolerance, tolerance); // depends on control dependency: [if], data = [none]
MultiPathImpl mimpl_a = (MultiPathImpl) multipath_a._getImpl();
AttributeStreamOfDbl xy = (AttributeStreamOfDbl) (mimpl_a
.getAttributeStreamRef(VertexDescription.Semantics.POSITION));
Point2D pt = new Point2D();
Point2D pt_prev = new Point2D();
Point2D pt_1 = new Point2D();
Point2D pt_2 = new Point2D();
for (int ipath = 0, npath = mimpl_a.getPathCount(); ipath < npath; ipath++) {
boolean b_first = true;
for (int i = mimpl_a.getPathStart(ipath), n = mimpl_a
.getPathEnd(ipath); i < n; i++) {
if (b_first) {
xy.read(2 * i, pt_prev); // depends on control dependency: [if], data = [none]
b_first = false; // depends on control dependency: [if], data = [none]
continue;
}
xy.read(2 * i, pt); // depends on control dependency: [for], data = [i]
pt_1.setCoords(pt_prev); // depends on control dependency: [for], data = [none]
pt_2.setCoords(pt); // depends on control dependency: [for], data = [none]
if (env_b_inflated.clipLine(pt_1, pt_2) != 0)
return true;
pt_prev.setCoords(pt); // depends on control dependency: [for], data = [none]
}
}
} else {
Line line_1 = new Line(env_b.xmin, env_b.ymin, env_b.xmin,
env_b.ymax);
Line line_2 = new Line(env_b.xmin, env_b.ymax, env_b.xmax,
env_b.ymax);
Line line3 = new Line(env_b.xmax, env_b.ymax, env_b.xmax,
env_b.ymin);
Line line4 = new Line(env_b.xmax, env_b.ymin, env_b.xmin,
env_b.ymin);
SegmentIterator iter = multipath_a.querySegmentIterator();
while (iter.nextPath()) {
while (iter.hasNextSegment()) {
Segment polySeg = iter.nextSegment();
if (polySeg.isIntersecting(line_1, tolerance))
return true;
if (polySeg.isIntersecting(line_2, tolerance))
return true;
if (polySeg.isIntersecting(line3, tolerance))
return true;
if (polySeg.isIntersecting(line4, tolerance))
return true;
}
}
}
return false;
} }
|
public class class_name {
static int getConversionWeight(Object fromObj, Class<?> to) {
int fromCode = getJSTypeCode(fromObj);
switch (fromCode) {
case JSTYPE_UNDEFINED:
if (to == ScriptRuntime.StringClass ||
to == ScriptRuntime.ObjectClass) {
return 1;
}
break;
case JSTYPE_NULL:
if (!to.isPrimitive()) {
return 1;
}
break;
case JSTYPE_BOOLEAN:
// "boolean" is #1
if (to == Boolean.TYPE) {
return 1;
}
else if (to == ScriptRuntime.BooleanClass) {
return 2;
}
else if (to == ScriptRuntime.ObjectClass) {
return 3;
}
else if (to == ScriptRuntime.StringClass) {
return 4;
}
break;
case JSTYPE_NUMBER:
if (to.isPrimitive()) {
if (to == Double.TYPE) {
return 1;
}
else if (to != Boolean.TYPE) {
return 1 + getSizeRank(to);
}
}
else {
if (to == ScriptRuntime.StringClass) {
// native numbers are #1-8
return 9;
}
else if (to == ScriptRuntime.ObjectClass) {
return 10;
}
else if (ScriptRuntime.NumberClass.isAssignableFrom(to)) {
// "double" is #1
return 2;
}
}
break;
case JSTYPE_STRING:
if (to == ScriptRuntime.StringClass) {
return 1;
}
else if (to.isInstance(fromObj)) {
return 2;
}
else if (to.isPrimitive()) {
if (to == Character.TYPE) {
return 3;
} else if (to != Boolean.TYPE) {
return 4;
}
}
break;
case JSTYPE_JAVA_CLASS:
if (to == ScriptRuntime.ClassClass) {
return 1;
}
else if (to == ScriptRuntime.ObjectClass) {
return 3;
}
else if (to == ScriptRuntime.StringClass) {
return 4;
}
break;
case JSTYPE_JAVA_OBJECT:
case JSTYPE_JAVA_ARRAY:
Object javaObj = fromObj;
if (javaObj instanceof Wrapper) {
javaObj = ((Wrapper)javaObj).unwrap();
}
if (to.isInstance(javaObj)) {
return CONVERSION_NONTRIVIAL;
}
if (to == ScriptRuntime.StringClass) {
return 2;
}
else if (to.isPrimitive() && to != Boolean.TYPE) {
return (fromCode == JSTYPE_JAVA_ARRAY)
? CONVERSION_NONE : 2 + getSizeRank(to);
}
break;
case JSTYPE_OBJECT:
// Other objects takes #1-#3 spots
if (to != ScriptRuntime.ObjectClass && to.isInstance(fromObj)) {
// No conversion required, but don't apply for java.lang.Object
return 1;
}
if (to.isArray()) {
if (fromObj instanceof NativeArray) {
// This is a native array conversion to a java array
// Array conversions are all equal, and preferable to object
// and string conversion, per LC3.
return 2;
}
}
else if (to == ScriptRuntime.ObjectClass) {
return 3;
}
else if (to == ScriptRuntime.StringClass) {
return 4;
}
else if (to == ScriptRuntime.DateClass) {
if (fromObj instanceof NativeDate) {
// This is a native date to java date conversion
return 1;
}
}
else if (to.isInterface()) {
if (fromObj instanceof NativeFunction) {
// See comments in createInterfaceAdapter
return 1;
}
if (fromObj instanceof NativeObject) {
return 2;
}
return 12;
}
else if (to.isPrimitive() && to != Boolean.TYPE) {
return 4 + getSizeRank(to);
}
break;
}
return CONVERSION_NONE;
} }
|
public class class_name {
static int getConversionWeight(Object fromObj, Class<?> to) {
int fromCode = getJSTypeCode(fromObj);
switch (fromCode) {
case JSTYPE_UNDEFINED:
if (to == ScriptRuntime.StringClass ||
to == ScriptRuntime.ObjectClass) {
return 1; // depends on control dependency: [if], data = [none]
}
break;
case JSTYPE_NULL:
if (!to.isPrimitive()) {
return 1; // depends on control dependency: [if], data = [none]
}
break;
case JSTYPE_BOOLEAN:
// "boolean" is #1
if (to == Boolean.TYPE) {
return 1; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.BooleanClass) {
return 2; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.ObjectClass) {
return 3; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.StringClass) {
return 4; // depends on control dependency: [if], data = [none]
}
break;
case JSTYPE_NUMBER:
if (to.isPrimitive()) {
if (to == Double.TYPE) {
return 1; // depends on control dependency: [if], data = [none]
}
else if (to != Boolean.TYPE) {
return 1 + getSizeRank(to); // depends on control dependency: [if], data = [(to]
}
}
else {
if (to == ScriptRuntime.StringClass) {
// native numbers are #1-8
return 9; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.ObjectClass) {
return 10; // depends on control dependency: [if], data = [none]
}
else if (ScriptRuntime.NumberClass.isAssignableFrom(to)) {
// "double" is #1
return 2; // depends on control dependency: [if], data = [none]
}
}
break;
case JSTYPE_STRING:
if (to == ScriptRuntime.StringClass) {
return 1; // depends on control dependency: [if], data = [none]
}
else if (to.isInstance(fromObj)) {
return 2; // depends on control dependency: [if], data = [none]
}
else if (to.isPrimitive()) {
if (to == Character.TYPE) {
return 3; // depends on control dependency: [if], data = [none]
} else if (to != Boolean.TYPE) {
return 4; // depends on control dependency: [if], data = [none]
}
}
break;
case JSTYPE_JAVA_CLASS:
if (to == ScriptRuntime.ClassClass) {
return 1; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.ObjectClass) {
return 3; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.StringClass) {
return 4; // depends on control dependency: [if], data = [none]
}
break;
case JSTYPE_JAVA_OBJECT:
case JSTYPE_JAVA_ARRAY:
Object javaObj = fromObj;
if (javaObj instanceof Wrapper) {
javaObj = ((Wrapper)javaObj).unwrap(); // depends on control dependency: [if], data = [none]
}
if (to.isInstance(javaObj)) {
return CONVERSION_NONTRIVIAL; // depends on control dependency: [if], data = [none]
}
if (to == ScriptRuntime.StringClass) {
return 2; // depends on control dependency: [if], data = [none]
}
else if (to.isPrimitive() && to != Boolean.TYPE) {
return (fromCode == JSTYPE_JAVA_ARRAY)
? CONVERSION_NONE : 2 + getSizeRank(to); // depends on control dependency: [if], data = [none]
}
break;
case JSTYPE_OBJECT:
// Other objects takes #1-#3 spots
if (to != ScriptRuntime.ObjectClass && to.isInstance(fromObj)) {
// No conversion required, but don't apply for java.lang.Object
return 1; // depends on control dependency: [if], data = [none]
}
if (to.isArray()) {
if (fromObj instanceof NativeArray) {
// This is a native array conversion to a java array
// Array conversions are all equal, and preferable to object
// and string conversion, per LC3.
return 2; // depends on control dependency: [if], data = [none]
}
}
else if (to == ScriptRuntime.ObjectClass) {
return 3; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.StringClass) {
return 4; // depends on control dependency: [if], data = [none]
}
else if (to == ScriptRuntime.DateClass) {
if (fromObj instanceof NativeDate) {
// This is a native date to java date conversion
return 1; // depends on control dependency: [if], data = [none]
}
}
else if (to.isInterface()) {
if (fromObj instanceof NativeFunction) {
// See comments in createInterfaceAdapter
return 1; // depends on control dependency: [if], data = [none]
}
if (fromObj instanceof NativeObject) {
return 2; // depends on control dependency: [if], data = [none]
}
return 12; // depends on control dependency: [if], data = [none]
}
else if (to.isPrimitive() && to != Boolean.TYPE) {
return 4 + getSizeRank(to); // depends on control dependency: [if], data = [none]
}
break;
}
return CONVERSION_NONE;
} }
|
public class class_name {
protected void addPackagesList(Collection<PackageDoc> packages, Content tbody) {
boolean altColor = true;
for (PackageDoc pkg : packages) {
if (pkg != null && !pkg.name().isEmpty()) {
if (!(configuration.nodeprecated && utils.isDeprecated(pkg))) {
Content packageLinkContent = getPackageLink(pkg, getPackageName(pkg));
Content tdPackage = HtmlTree.TD(HtmlStyle.colFirst, packageLinkContent);
HtmlTree tdSummary = new HtmlTree(HtmlTag.TD);
tdSummary.addStyle(HtmlStyle.colLast);
addSummaryComment(pkg, tdSummary);
HtmlTree tr = HtmlTree.TR(tdPackage);
tr.addContent(tdSummary);
tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor);
tbody.addContent(tr);
}
}
altColor = !altColor;
}
} }
|
public class class_name {
protected void addPackagesList(Collection<PackageDoc> packages, Content tbody) {
boolean altColor = true;
for (PackageDoc pkg : packages) {
if (pkg != null && !pkg.name().isEmpty()) {
if (!(configuration.nodeprecated && utils.isDeprecated(pkg))) {
Content packageLinkContent = getPackageLink(pkg, getPackageName(pkg));
Content tdPackage = HtmlTree.TD(HtmlStyle.colFirst, packageLinkContent);
HtmlTree tdSummary = new HtmlTree(HtmlTag.TD);
tdSummary.addStyle(HtmlStyle.colLast); // depends on control dependency: [if], data = [none]
addSummaryComment(pkg, tdSummary); // depends on control dependency: [if], data = [none]
HtmlTree tr = HtmlTree.TR(tdPackage);
tr.addContent(tdSummary); // depends on control dependency: [if], data = [none]
tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor); // depends on control dependency: [if], data = [none]
tbody.addContent(tr); // depends on control dependency: [if], data = [none]
}
}
altColor = !altColor; // depends on control dependency: [for], data = [none]
}
} }
|
public class class_name {
private void visitArrayLitOrCallWithSpread(Node spreadParent) {
if (spreadParent.isArrayLit()) {
visitArrayLitContainingSpread(spreadParent);
} else if (spreadParent.isCall()) {
visitCallContainingSpread(spreadParent);
} else {
checkArgument(spreadParent.isNew(), spreadParent);
visitNewWithSpread(spreadParent);
}
} }
|
public class class_name {
private void visitArrayLitOrCallWithSpread(Node spreadParent) {
if (spreadParent.isArrayLit()) {
visitArrayLitContainingSpread(spreadParent); // depends on control dependency: [if], data = [none]
} else if (spreadParent.isCall()) {
visitCallContainingSpread(spreadParent); // depends on control dependency: [if], data = [none]
} else {
checkArgument(spreadParent.isNew(), spreadParent); // depends on control dependency: [if], data = [none]
visitNewWithSpread(spreadParent); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) {
if (checkNotifyWaiters()) {
notifyListeners();
}
return true;
}
return false;
} }
|
public class class_name {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) {
if (checkNotifyWaiters()) {
notifyListeners(); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
public static <T extends Comparable<T>> List<T> lcs(List<T> arg0, List<T> arg1) {
if (arg0 == null || arg1 == null) {
return Collections.emptyList();
}
return lcs(arg0, arg1, 0, 0);
} }
|
public class class_name {
public static <T extends Comparable<T>> List<T> lcs(List<T> arg0, List<T> arg1) {
if (arg0 == null || arg1 == null) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
return lcs(arg0, arg1, 0, 0);
} }
|
public class class_name {
public static long parseLong(String s) {
//quickly reject most non-numbers
//This is a huge speed improvement when parsing ASCII data files
// because Java is very slow at filling in the stack trace when an exception is thrown.
if (s == null)
return Long.MAX_VALUE;
s = s.trim();
if (s.length() == 0)
return Long.MAX_VALUE;
char ch = s.charAt(0);
if ((ch < '0' || ch > '9') && ch != '-' && ch != '+')
return Long.MAX_VALUE;
try {
if (s.startsWith("0x"))
return Long.parseLong(s.substring(2), 16);
return Long.parseLong(s);
} catch (Exception e) {
return Long.MAX_VALUE;
}
} }
|
public class class_name {
public static long parseLong(String s) {
//quickly reject most non-numbers
//This is a huge speed improvement when parsing ASCII data files
// because Java is very slow at filling in the stack trace when an exception is thrown.
if (s == null)
return Long.MAX_VALUE;
s = s.trim();
if (s.length() == 0)
return Long.MAX_VALUE;
char ch = s.charAt(0);
if ((ch < '0' || ch > '9') && ch != '-' && ch != '+')
return Long.MAX_VALUE;
try {
if (s.startsWith("0x"))
return Long.parseLong(s.substring(2), 16);
return Long.parseLong(s); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return Long.MAX_VALUE;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static <T> String join(final Collection<T> collection, final String separator) {
if (isEmpty(collection)) {
return "";
}
StringBuffer stringBuffer = new StringBuffer();
boolean isFirstVisited = true;
for (Object object : collection) {
if (isFirstVisited) {
isFirstVisited = false;
} else {
stringBuffer.append(separator);
}
stringBuffer.append(ObjectUtils.toString(object));
}
return stringBuffer.toString();
} }
|
public class class_name {
public static <T> String join(final Collection<T> collection, final String separator) {
if (isEmpty(collection)) {
return ""; // depends on control dependency: [if], data = [none]
}
StringBuffer stringBuffer = new StringBuffer();
boolean isFirstVisited = true;
for (Object object : collection) {
if (isFirstVisited) {
isFirstVisited = false; // depends on control dependency: [if], data = [none]
} else {
stringBuffer.append(separator); // depends on control dependency: [if], data = [none]
}
stringBuffer.append(ObjectUtils.toString(object)); // depends on control dependency: [for], data = [object]
}
return stringBuffer.toString();
} }
|
public class class_name {
public String getSafariSDKVersion() {
validateSafariSDKVersionMethodCall();
Matcher sdkVersionMatcher = SAFARI_SDK_VERSION.matcher(app.getAbsolutePath());
if (sdkVersionMatcher.matches()) {
return sdkVersionMatcher.group(1) != null ? sdkVersionMatcher.group(1) : sdkVersionMatcher.group(2);
} else {
throw new WebDriverException("Cannot identify the version of Safari from application: " + app.getAbsolutePath());
}
} }
|
public class class_name {
public String getSafariSDKVersion() {
validateSafariSDKVersionMethodCall();
Matcher sdkVersionMatcher = SAFARI_SDK_VERSION.matcher(app.getAbsolutePath());
if (sdkVersionMatcher.matches()) {
return sdkVersionMatcher.group(1) != null ? sdkVersionMatcher.group(1) : sdkVersionMatcher.group(2); // depends on control dependency: [if], data = [none]
} else {
throw new WebDriverException("Cannot identify the version of Safari from application: " + app.getAbsolutePath());
}
} }
|
public class class_name {
public static MethodInvoker getMethodInvokerByName(Object object, String methodName,
boolean paramsRequired, Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName,
paramTypes);
if (method == null) {
String errorMsg = "no method found with name [" + methodName + "] on class ["
+ object.getClass().getSimpleName()
+ "] compatable with the signature ["
+ getParamTypesString(paramTypes) + "].";
Assert.isTrue(!paramsRequired, errorMsg);
// if no method was found for the given parameters, and the
// parameters aren't required, then try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName,
new Class[] {});
Assert.notNull(method, errorMsg);
}
return new SimpleMethodInvoker(object, method);
} }
|
public class class_name {
public static MethodInvoker getMethodInvokerByName(Object object, String methodName,
boolean paramsRequired, Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName,
paramTypes);
if (method == null) {
String errorMsg = "no method found with name [" + methodName + "] on class ["
+ object.getClass().getSimpleName()
+ "] compatable with the signature ["
+ getParamTypesString(paramTypes) + "]."; // depends on control dependency: [if], data = [none]
Assert.isTrue(!paramsRequired, errorMsg); // depends on control dependency: [if], data = [none]
// if no method was found for the given parameters, and the
// parameters aren't required, then try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName,
new Class[] {}); // depends on control dependency: [if], data = [none]
Assert.notNull(method, errorMsg); // depends on control dependency: [if], data = [(method]
}
return new SimpleMethodInvoker(object, method);
} }
|
public class class_name {
void add(MutableBigInteger addend) {
int x = intLen;
int y = addend.intLen;
int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
int[] result = (value.length < resultLen ? new int[resultLen] : value);
int rstart = result.length-1;
long sum;
long carry = 0;
// Add common parts of both numbers
while(x > 0 && y > 0) {
x--; y--;
sum = (value[x+offset] & LONG_MASK) +
(addend.value[y+addend.offset] & LONG_MASK) + carry;
result[rstart--] = (int)sum;
carry = sum >>> 32;
}
// Add remainder of the longer number
while(x > 0) {
x--;
if (carry == 0 && result == value && rstart == (x + offset))
return;
sum = (value[x+offset] & LONG_MASK) + carry;
result[rstart--] = (int)sum;
carry = sum >>> 32;
}
while(y > 0) {
y--;
sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
result[rstart--] = (int)sum;
carry = sum >>> 32;
}
if (carry > 0) { // Result must grow in length
resultLen++;
if (result.length < resultLen) {
int temp[] = new int[resultLen];
// Result one word longer from carry-out; copy low-order
// bits into new result.
System.arraycopy(result, 0, temp, 1, result.length);
temp[0] = 1;
result = temp;
} else {
result[rstart--] = 1;
}
}
value = result;
intLen = resultLen;
offset = result.length - resultLen;
} }
|
public class class_name {
void add(MutableBigInteger addend) {
int x = intLen;
int y = addend.intLen;
int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
int[] result = (value.length < resultLen ? new int[resultLen] : value);
int rstart = result.length-1;
long sum;
long carry = 0;
// Add common parts of both numbers
while(x > 0 && y > 0) {
x--; y--; // depends on control dependency: [while], data = [none] // depends on control dependency: [while], data = [none]
sum = (value[x+offset] & LONG_MASK) +
(addend.value[y+addend.offset] & LONG_MASK) + carry; // depends on control dependency: [while], data = [none]
result[rstart--] = (int)sum; // depends on control dependency: [while], data = [none]
carry = sum >>> 32; // depends on control dependency: [while], data = [none]
}
// Add remainder of the longer number
while(x > 0) {
x--; // depends on control dependency: [while], data = [none]
if (carry == 0 && result == value && rstart == (x + offset))
return;
sum = (value[x+offset] & LONG_MASK) + carry; // depends on control dependency: [while], data = [none]
result[rstart--] = (int)sum; // depends on control dependency: [while], data = [none]
carry = sum >>> 32; // depends on control dependency: [while], data = [none]
}
while(y > 0) {
y--; // depends on control dependency: [while], data = [none]
sum = (addend.value[y+addend.offset] & LONG_MASK) + carry; // depends on control dependency: [while], data = [none]
result[rstart--] = (int)sum; // depends on control dependency: [while], data = [none]
carry = sum >>> 32; // depends on control dependency: [while], data = [none]
}
if (carry > 0) { // Result must grow in length
resultLen++; // depends on control dependency: [if], data = [none]
if (result.length < resultLen) {
int temp[] = new int[resultLen];
// Result one word longer from carry-out; copy low-order
// bits into new result.
System.arraycopy(result, 0, temp, 1, result.length); // depends on control dependency: [if], data = [none]
temp[0] = 1; // depends on control dependency: [if], data = [none]
result = temp; // depends on control dependency: [if], data = [none]
} else {
result[rstart--] = 1; // depends on control dependency: [if], data = [none]
}
}
value = result;
intLen = resultLen;
offset = result.length - resultLen;
} }
|
public class class_name {
@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
protected TypeInformation<?> createInfo(Type fieldType) {
if (fieldType.equals(this.type)) {
return this;
}
if (fieldType instanceof Class) {
return new ClassTypeInformation((Class<?>) fieldType);
}
Class<S> resolveType = resolveClass(fieldType);
Map<TypeVariable, Type> variableMap = new HashMap<TypeVariable, Type>();
variableMap.putAll(GenericTypeResolver.getTypeVariableMap(resolveType));
if (fieldType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) fieldType;
TypeVariable<Class<S>>[] typeParameters = resolveType.getTypeParameters();
Type[] arguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < typeParameters.length; i++) {
variableMap.put(typeParameters[i], arguments[i]);
}
return new ParametrizedTypeInformation(parameterizedType, this, variableMap);
}
if (fieldType instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) fieldType;
return new TypeVariableTypeInformation(variable, type, this, variableMap);
}
if (fieldType instanceof GenericArrayType) {
return new GenericArrayTypeInformation((GenericArrayType) fieldType, this, variableMap);
}
if (fieldType instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) fieldType;
return new WildcardTypeInformation(wildcardType, variableMap);
}
throw new IllegalArgumentException();
} }
|
public class class_name {
@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
protected TypeInformation<?> createInfo(Type fieldType) {
if (fieldType.equals(this.type)) {
return this; // depends on control dependency: [if], data = [none]
}
if (fieldType instanceof Class) {
return new ClassTypeInformation((Class<?>) fieldType); // depends on control dependency: [if], data = [none]
}
Class<S> resolveType = resolveClass(fieldType);
Map<TypeVariable, Type> variableMap = new HashMap<TypeVariable, Type>();
variableMap.putAll(GenericTypeResolver.getTypeVariableMap(resolveType));
if (fieldType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) fieldType;
TypeVariable<Class<S>>[] typeParameters = resolveType.getTypeParameters();
Type[] arguments = parameterizedType.getActualTypeArguments();
for (int i = 0; i < typeParameters.length; i++) {
variableMap.put(typeParameters[i], arguments[i]); // depends on control dependency: [for], data = [i]
}
return new ParametrizedTypeInformation(parameterizedType, this, variableMap); // depends on control dependency: [if], data = [none]
}
if (fieldType instanceof TypeVariable) {
TypeVariable<?> variable = (TypeVariable<?>) fieldType;
return new TypeVariableTypeInformation(variable, type, this, variableMap); // depends on control dependency: [if], data = [none]
}
if (fieldType instanceof GenericArrayType) {
return new GenericArrayTypeInformation((GenericArrayType) fieldType, this, variableMap); // depends on control dependency: [if], data = [none]
}
if (fieldType instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) fieldType;
return new WildcardTypeInformation(wildcardType, variableMap); // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException();
} }
|
public class class_name {
public PolymerNotation getSimplePolymer(String string) {
for (PolymerNotation polymer : listOfPolymers) {
if (polymer.getPolymerID().getId().equals(string)) {
return polymer;
}
}
return null;
} }
|
public class class_name {
public PolymerNotation getSimplePolymer(String string) {
for (PolymerNotation polymer : listOfPolymers) {
if (polymer.getPolymerID().getId().equals(string)) {
return polymer;
// depends on control dependency: [if], data = [none]
}
}
return null;
} }
|
public class class_name {
protected void writeCsv(final MBasicTable table, final OutputStream outputStream,
final DateFormat dateFormat) throws IOException {
// récupération des informations utiles
final int columnCount = table.getColumnModel().getColumnCount();
final int rowCount = table.getRowCount();
final String charset = System.getProperty("file.encoding");
final Writer out = new OutputStreamWriter(outputStream, charset);
final char csvSeparator = CSV_SEPARATOR;
// le séparateur des .csv (',' à l'américaine)
final NumberFormat decimalFormat = NumberFormat.getInstance(Locale.US);
decimalFormat.setGroupingUsed(false);
final String eol = System.getProperty("line.separator");
// titres des colonnes
writeCsvHeader(table, out, csvSeparator);
// les données proprement dites (ligne par ligne puis colonne par colonne)
Object value;
String text;
for (int k = 0; k < rowCount; k++) {
for (int i = 0; i < columnCount; i++) {
value = getValueAt(table, k, i);
if (value instanceof Number) {
text = decimalFormat.format(value);
} else if (value instanceof Date) {
text = dateFormat.format(value);
} else if (value instanceof Boolean) {
text = value.toString();
} else {
text = getTextAt(table, k, i);
text = formatCsv(text, csvSeparator);
}
out.write(text);
if (i < columnCount - 1) {
out.write(csvSeparator);
}
}
if (k < rowCount - 1) {
out.write(eol);
}
}
out.flush();
} }
|
public class class_name {
protected void writeCsv(final MBasicTable table, final OutputStream outputStream,
final DateFormat dateFormat) throws IOException {
// récupération des informations utiles
final int columnCount = table.getColumnModel().getColumnCount();
final int rowCount = table.getRowCount();
final String charset = System.getProperty("file.encoding");
final Writer out = new OutputStreamWriter(outputStream, charset);
final char csvSeparator = CSV_SEPARATOR;
// le séparateur des .csv (',' à l'américaine)
final NumberFormat decimalFormat = NumberFormat.getInstance(Locale.US);
decimalFormat.setGroupingUsed(false);
final String eol = System.getProperty("line.separator");
// titres des colonnes
writeCsvHeader(table, out, csvSeparator);
// les données proprement dites (ligne par ligne puis colonne par colonne)
Object value;
String text;
for (int k = 0; k < rowCount; k++) {
for (int i = 0; i < columnCount; i++) {
value = getValueAt(table, k, i);
// depends on control dependency: [for], data = [i]
if (value instanceof Number) {
text = decimalFormat.format(value);
// depends on control dependency: [if], data = [none]
} else if (value instanceof Date) {
text = dateFormat.format(value);
// depends on control dependency: [if], data = [none]
} else if (value instanceof Boolean) {
text = value.toString();
// depends on control dependency: [if], data = [none]
} else {
text = getTextAt(table, k, i);
// depends on control dependency: [if], data = [none]
text = formatCsv(text, csvSeparator);
// depends on control dependency: [if], data = [none]
}
out.write(text);
// depends on control dependency: [for], data = [none]
if (i < columnCount - 1) {
out.write(csvSeparator);
// depends on control dependency: [if], data = [none]
}
}
if (k < rowCount - 1) {
out.write(eol);
// depends on control dependency: [if], data = [none]
}
}
out.flush();
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.