code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public void marshall(ListPolicyAttachmentsRequest listPolicyAttachmentsRequest, ProtocolMarshaller protocolMarshaller) {
if (listPolicyAttachmentsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getDirectoryArn(), DIRECTORYARN_BINDING);
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getPolicyReference(), POLICYREFERENCE_BINDING);
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getConsistencyLevel(), CONSISTENCYLEVEL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListPolicyAttachmentsRequest listPolicyAttachmentsRequest, ProtocolMarshaller protocolMarshaller) {
if (listPolicyAttachmentsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getDirectoryArn(), DIRECTORYARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getPolicyReference(), POLICYREFERENCE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listPolicyAttachmentsRequest.getConsistencyLevel(), CONSISTENCYLEVEL_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void requestCompleteCallback(CompletableFuture<ConnectionWrapper> connectionFuture,
Throwable e) {
// when processing completes, return the connection back to connection manager asynchronously.
// Note: If result future is complete, connectionFuture is definitely complete. if connectionFuture had failed,
// we would not have received a connection object anyway.
if (e != null) {
Throwable unwrap = Exceptions.unwrap(e);
if (hasConnectionFailed(unwrap)) {
connectionFuture.thenAccept(connectionObject -> {
connectionObject.failConnection();
connectionObject.close();
});
} else {
connectionFuture.thenAccept(ConnectionWrapper::close);
}
} else {
connectionFuture.thenAccept(ConnectionWrapper::close);
}
} } | public class class_name {
private void requestCompleteCallback(CompletableFuture<ConnectionWrapper> connectionFuture,
Throwable e) {
// when processing completes, return the connection back to connection manager asynchronously.
// Note: If result future is complete, connectionFuture is definitely complete. if connectionFuture had failed,
// we would not have received a connection object anyway.
if (e != null) {
Throwable unwrap = Exceptions.unwrap(e);
if (hasConnectionFailed(unwrap)) {
connectionFuture.thenAccept(connectionObject -> {
connectionObject.failConnection(); // depends on control dependency: [if], data = [none]
connectionObject.close(); // depends on control dependency: [if], data = [none]
});
} else {
connectionFuture.thenAccept(ConnectionWrapper::close); // depends on control dependency: [if], data = [none]
}
} else {
connectionFuture.thenAccept(ConnectionWrapper::close);
}
} } |
public class class_name {
public void reply(Object message) {
if (context.sender() != null) {
context.sender().send(message, self());
}
} } | public class class_name {
public void reply(Object message) {
if (context.sender() != null) {
context.sender().send(message, self()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addComment(Comment comment) {
if (comments == null || comments.size() == 0) {
comments = new ArrayList<Comment>();
}
comments.add((CommentImpl) comment);
} } | public class class_name {
public void addComment(Comment comment) {
if (comments == null || comments.size() == 0) {
comments = new ArrayList<Comment>(); // depends on control dependency: [if], data = [none]
}
comments.add((CommentImpl) comment);
} } |
public class class_name {
public static <T extends Enum<T>> T convert(Class<T> type, String name, T defaultValue) {
if (name == null) {
return defaultValue;
}
for (T e : type.getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return e;
}
}
return defaultValue;
} } | public class class_name {
public static <T extends Enum<T>> T convert(Class<T> type, String name, T defaultValue) {
if (name == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
for (T e : type.getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return e; // depends on control dependency: [if], data = [none]
}
}
return defaultValue;
} } |
public class class_name {
public static Object getValue(Result result, int index,
GeoPackageDataType dataType) {
Object value = null;
int type = result.getType(index);
switch (type) {
case FIELD_TYPE_INTEGER:
value = getIntegerValue(result, index, dataType);
break;
case FIELD_TYPE_FLOAT:
value = getFloatValue(result, index, dataType);
break;
case FIELD_TYPE_STRING:
String stringValue = result.getString(index);
if (dataType != null
&& (dataType == GeoPackageDataType.DATE || dataType == GeoPackageDataType.DATETIME)) {
DateConverter converter = DateConverter.converter(dataType);
try {
value = converter.dateValue(stringValue);
} catch (Exception e) {
logger.log(Level.WARNING,
"Invalid " + dataType + " format: " + stringValue
+ ", String value used", e);
value = stringValue;
}
} else {
value = stringValue;
}
break;
case FIELD_TYPE_BLOB:
value = result.getBlob(index);
break;
case FIELD_TYPE_NULL:
// leave value as null
}
return value;
} } | public class class_name {
public static Object getValue(Result result, int index,
GeoPackageDataType dataType) {
Object value = null;
int type = result.getType(index);
switch (type) {
case FIELD_TYPE_INTEGER:
value = getIntegerValue(result, index, dataType);
break;
case FIELD_TYPE_FLOAT:
value = getFloatValue(result, index, dataType);
break;
case FIELD_TYPE_STRING:
String stringValue = result.getString(index);
if (dataType != null
&& (dataType == GeoPackageDataType.DATE || dataType == GeoPackageDataType.DATETIME)) {
DateConverter converter = DateConverter.converter(dataType);
try {
value = converter.dateValue(stringValue); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.log(Level.WARNING,
"Invalid " + dataType + " format: " + stringValue
+ ", String value used", e);
value = stringValue;
} // depends on control dependency: [catch], data = [none]
} else {
value = stringValue; // depends on control dependency: [if], data = [none]
}
break;
case FIELD_TYPE_BLOB:
value = result.getBlob(index);
break;
case FIELD_TYPE_NULL:
// leave value as null
}
return value;
} } |
public class class_name {
private String generateMultidots(String line) {
line = multiDots.matcher(line).replaceAll(" DOTMULTI$1 ");
final Matcher dotMultiDot = dotmultiDot.matcher(line);
while (dotMultiDot.find()) {
line = dotmultiDotAny.matcher(line).replaceAll("DOTDOTMULTI $1");
line = dotMultiDot.replaceAll("DOTDOTMULTI");
// reset the matcher otherwise the while will stop after one run
dotMultiDot.reset(line);
}
return line;
} } | public class class_name {
private String generateMultidots(String line) {
line = multiDots.matcher(line).replaceAll(" DOTMULTI$1 ");
final Matcher dotMultiDot = dotmultiDot.matcher(line);
while (dotMultiDot.find()) {
line = dotmultiDotAny.matcher(line).replaceAll("DOTDOTMULTI $1"); // depends on control dependency: [while], data = [none]
line = dotMultiDot.replaceAll("DOTDOTMULTI"); // depends on control dependency: [while], data = [none]
// reset the matcher otherwise the while will stop after one run
dotMultiDot.reset(line); // depends on control dependency: [while], data = [none]
}
return line;
} } |
public class class_name {
@VisibleForTesting
static void updateRecordForHDFS(
Record record,
boolean roll,
String avroSchema,
String location
){
if(roll){
record.getHeader().setAttribute(HDFS_HEADER_ROLL, "true");
}
record.getHeader().setAttribute(HDFS_HEADER_AVROSCHEMA, avroSchema);
record.getHeader().setAttribute(HDFS_HEADER_TARGET_DIRECTORY, location);
LOG.trace("Record {} will be stored in {} path: roll({}), avro schema: {}", record.getHeader().getSourceId(), location, roll, avroSchema);
} } | public class class_name {
@VisibleForTesting
static void updateRecordForHDFS(
Record record,
boolean roll,
String avroSchema,
String location
){
if(roll){
record.getHeader().setAttribute(HDFS_HEADER_ROLL, "true"); // depends on control dependency: [if], data = [none]
}
record.getHeader().setAttribute(HDFS_HEADER_AVROSCHEMA, avroSchema);
record.getHeader().setAttribute(HDFS_HEADER_TARGET_DIRECTORY, location);
LOG.trace("Record {} will be stored in {} path: roll({}), avro schema: {}", record.getHeader().getSourceId(), location, roll, avroSchema);
} } |
public class class_name {
public Long getId() {
if (this.genericRecordAttributes.getId() != null) {
return this.genericRecordAttributes.getId();
} else if (this.typeARecordAttributes.getId() != null) {
return this.typeARecordAttributes.getId();
} else if (this.typeAAAARecordAttributes.getId() != null) {
return this.typeAAAARecordAttributes.getId();
} else if (this.typeNSRecordAttributes.getId() != null) {
return this.typeNSRecordAttributes.getId();
} else if (this.typeSOARecordAttributes.getId() != null) {
return this.typeSOARecordAttributes.getId();
} else if (this.typeMXRecordAttributes.getId() != null) {
return this.typeMXRecordAttributes.getId();
} else if (this.typePTRRecordAttributes.getId() != null) {
return this.typePTRRecordAttributes.getId();
} else if (this.typeTXTRecordAttributes.getId() != null) {
return this.typeTXTRecordAttributes.getId();
} else {
return null;
}
} } | public class class_name {
public Long getId() {
if (this.genericRecordAttributes.getId() != null) {
return this.genericRecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeARecordAttributes.getId() != null) {
return this.typeARecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeAAAARecordAttributes.getId() != null) {
return this.typeAAAARecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeNSRecordAttributes.getId() != null) {
return this.typeNSRecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeSOARecordAttributes.getId() != null) {
return this.typeSOARecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeMXRecordAttributes.getId() != null) {
return this.typeMXRecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typePTRRecordAttributes.getId() != null) {
return this.typePTRRecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else if (this.typeTXTRecordAttributes.getId() != null) {
return this.typeTXTRecordAttributes.getId(); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(Output output, ProtocolMarshaller protocolMarshaller) {
if (output == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(output.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(output.getDestination(), DESTINATION_BINDING);
protocolMarshaller.marshall(output.getEncryption(), ENCRYPTION_BINDING);
protocolMarshaller.marshall(output.getEntitlementArn(), ENTITLEMENTARN_BINDING);
protocolMarshaller.marshall(output.getMediaLiveInputArn(), MEDIALIVEINPUTARN_BINDING);
protocolMarshaller.marshall(output.getName(), NAME_BINDING);
protocolMarshaller.marshall(output.getOutputArn(), OUTPUTARN_BINDING);
protocolMarshaller.marshall(output.getPort(), PORT_BINDING);
protocolMarshaller.marshall(output.getTransport(), TRANSPORT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Output output, ProtocolMarshaller protocolMarshaller) {
if (output == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(output.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getDestination(), DESTINATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getEncryption(), ENCRYPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getEntitlementArn(), ENTITLEMENTARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getMediaLiveInputArn(), MEDIALIVEINPUTARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getOutputArn(), OUTPUTARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getPort(), PORT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(output.getTransport(), TRANSPORT_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 State<O> updateSignature(State<O> state, int idx, State<O> succ) {
StateSignature<O> sig = state.getSignature();
if (sig.successors.array[idx] == succ) {
return state;
}
register.remove(sig);
if (sig.successors.array[idx] != null) {
sig.successors.array[idx].decreaseIncoming();
}
sig.successors.array[idx] = succ;
succ.increaseIncoming();
sig.updateHashCode();
return replaceOrRegister(state);
} } | public class class_name {
private State<O> updateSignature(State<O> state, int idx, State<O> succ) {
StateSignature<O> sig = state.getSignature();
if (sig.successors.array[idx] == succ) {
return state; // depends on control dependency: [if], data = [none]
}
register.remove(sig);
if (sig.successors.array[idx] != null) {
sig.successors.array[idx].decreaseIncoming(); // depends on control dependency: [if], data = [none]
}
sig.successors.array[idx] = succ;
succ.increaseIncoming();
sig.updateHashCode();
return replaceOrRegister(state);
} } |
public class class_name {
public static void loadProperties(Properties properties) {
if (instance == null) {
instance = getConfigInstance();
}
ConfigurationUtils.loadProperties(properties, instance);
} } | public class class_name {
public static void loadProperties(Properties properties) {
if (instance == null) {
instance = getConfigInstance(); // depends on control dependency: [if], data = [none]
}
ConfigurationUtils.loadProperties(properties, instance);
} } |
public class class_name {
public final void mRIGHT_JOIN() throws RecognitionException {
try {
int _type = RIGHT_JOIN;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:655:13: ( ( 'RIGHT_JOIN' | 'right_join' ) )
// druidG.g:655:15: ( 'RIGHT_JOIN' | 'right_join' )
{
// druidG.g:655:15: ( 'RIGHT_JOIN' | 'right_join' )
int alt36=2;
int LA36_0 = input.LA(1);
if ( (LA36_0=='R') ) {
alt36=1;
}
else if ( (LA36_0=='r') ) {
alt36=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 36, 0, input);
throw nvae;
}
switch (alt36) {
case 1 :
// druidG.g:655:16: 'RIGHT_JOIN'
{
match("RIGHT_JOIN");
}
break;
case 2 :
// druidG.g:655:31: 'right_join'
{
match("right_join");
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mRIGHT_JOIN() throws RecognitionException {
try {
int _type = RIGHT_JOIN;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:655:13: ( ( 'RIGHT_JOIN' | 'right_join' ) )
// druidG.g:655:15: ( 'RIGHT_JOIN' | 'right_join' )
{
// druidG.g:655:15: ( 'RIGHT_JOIN' | 'right_join' )
int alt36=2;
int LA36_0 = input.LA(1);
if ( (LA36_0=='R') ) {
alt36=1; // depends on control dependency: [if], data = [none]
}
else if ( (LA36_0=='r') ) {
alt36=2; // depends on control dependency: [if], data = [none]
}
else {
NoViableAltException nvae =
new NoViableAltException("", 36, 0, input);
throw nvae;
}
switch (alt36) {
case 1 :
// druidG.g:655:16: 'RIGHT_JOIN'
{
match("RIGHT_JOIN");
}
break;
case 2 :
// druidG.g:655:31: 'right_join'
{
match("right_join");
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public void sendAuditEvent(AuditEventMessage[] msgs) throws Exception
{
if (!EventUtils.isEmptyOrNull(msgs)) {
DatagramSocket socket = new DatagramSocket();
for (int i=0; i<msgs.length; i++) {
if (!EventUtils.isEmptyOrNull(msgs[i])) {
send(msgs[i], socket, msgs[i].getDestinationAddress(), msgs[i].getDestinationPort());
}
}
socket.close();
}
} } | public class class_name {
public void sendAuditEvent(AuditEventMessage[] msgs) throws Exception
{
if (!EventUtils.isEmptyOrNull(msgs)) {
DatagramSocket socket = new DatagramSocket();
for (int i=0; i<msgs.length; i++) {
if (!EventUtils.isEmptyOrNull(msgs[i])) {
send(msgs[i], socket, msgs[i].getDestinationAddress(), msgs[i].getDestinationPort()); // depends on control dependency: [if], data = [none]
}
}
socket.close();
}
} } |
public class class_name {
private boolean startSettingsRequest(Activity activity, Fragment fragment) {
boolean isSuccessful = false;
// State transition.
mLinkRequestState = STATE_SETTINGS_REQUEST;
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Start activity for result.
Intent intent = new Intent(activity, FacebookSettingsActivity.class);
if (fragment == null) {
activity.startActivityForResult(intent, SETTINGS_REQUEST_CODE);
} else {
fragment.startActivityForResult(intent, SETTINGS_REQUEST_CODE);
}
isSuccessful = true;
}
return isSuccessful;
} } | public class class_name {
private boolean startSettingsRequest(Activity activity, Fragment fragment) {
boolean isSuccessful = false;
// State transition.
mLinkRequestState = STATE_SETTINGS_REQUEST;
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Start activity for result.
Intent intent = new Intent(activity, FacebookSettingsActivity.class);
if (fragment == null) {
activity.startActivityForResult(intent, SETTINGS_REQUEST_CODE); // depends on control dependency: [if], data = [none]
} else {
fragment.startActivityForResult(intent, SETTINGS_REQUEST_CODE); // depends on control dependency: [if], data = [none]
}
isSuccessful = true; // depends on control dependency: [if], data = [none]
}
return isSuccessful;
} } |
public class class_name {
private int checkSecurity(String strClassResource, String strSecurityMap, int iAccessType, int iLevel)
{
int iAccessAllowed = Constants.ACCESS_DENIED;
if (strSecurityMap == null)
return iAccessAllowed; // Denied
if (LOGIN_REQUIRED.equalsIgnoreCase(strSecurityMap))
return Constants.LOGIN_REQUIRED; // Denied
if (CREATE_USER_REQUIRED.equalsIgnoreCase(strSecurityMap))
return Constants.CREATE_USER_REQUIRED; // Denied
int startThin = strClassResource.indexOf(Constants.THIN_SUBPACKAGE, 0);
if (startThin != -1) // Remove the ".thin" reference
strClassResource = strClassResource.substring(0, startThin) + strClassResource.substring(startThin + Constants.THIN_SUBPACKAGE.length());
if (this.classMatch(strClassResource, BASE_CLASS))
return Constants.NORMAL_RETURN; // Allow access to all base classes
StringTokenizer tokenizer = new StringTokenizer(strSecurityMap, TOKENS);
try {
while (tokenizer.hasMoreTokens())
{
String strClass = tokenizer.nextToken();
String strAccess = tokenizer.nextToken();
int iClassAccessType = Constants.READ_ACCESS;
iClassAccessType = Integer.parseInt(strAccess);
String strLevel = tokenizer.nextToken();
int iClassLevel = Constants.LOGIN_USER;
iClassLevel = Integer.parseInt(strLevel);
if (this.classMatch(strClassResource, strClass))
if (iAccessType <= iClassAccessType)
if (iLevel >= iClassLevel)
{
iAccessAllowed = Constants.NORMAL_RETURN;
}
}
} catch (NoSuchElementException ex) {
// Done
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
if (("1"/*DBConstants.ANON_USER_ID*/.equals(this.getProperty(Params.USER_ID)))
|| (this.getProperty(Params.USER_ID) == null))
if (iAccessAllowed == Constants.ACCESS_DENIED)
iAccessAllowed = Constants.LOGIN_REQUIRED; // For anonymous access, logging in will always get you more
return iAccessAllowed;
} } | public class class_name {
private int checkSecurity(String strClassResource, String strSecurityMap, int iAccessType, int iLevel)
{
int iAccessAllowed = Constants.ACCESS_DENIED;
if (strSecurityMap == null)
return iAccessAllowed; // Denied
if (LOGIN_REQUIRED.equalsIgnoreCase(strSecurityMap))
return Constants.LOGIN_REQUIRED; // Denied
if (CREATE_USER_REQUIRED.equalsIgnoreCase(strSecurityMap))
return Constants.CREATE_USER_REQUIRED; // Denied
int startThin = strClassResource.indexOf(Constants.THIN_SUBPACKAGE, 0);
if (startThin != -1) // Remove the ".thin" reference
strClassResource = strClassResource.substring(0, startThin) + strClassResource.substring(startThin + Constants.THIN_SUBPACKAGE.length());
if (this.classMatch(strClassResource, BASE_CLASS))
return Constants.NORMAL_RETURN; // Allow access to all base classes
StringTokenizer tokenizer = new StringTokenizer(strSecurityMap, TOKENS);
try {
while (tokenizer.hasMoreTokens())
{
String strClass = tokenizer.nextToken();
String strAccess = tokenizer.nextToken();
int iClassAccessType = Constants.READ_ACCESS;
iClassAccessType = Integer.parseInt(strAccess); // depends on control dependency: [while], data = [none]
String strLevel = tokenizer.nextToken();
int iClassLevel = Constants.LOGIN_USER;
iClassLevel = Integer.parseInt(strLevel); // depends on control dependency: [while], data = [none]
if (this.classMatch(strClassResource, strClass))
if (iAccessType <= iClassAccessType)
if (iLevel >= iClassLevel)
{
iAccessAllowed = Constants.NORMAL_RETURN; // depends on control dependency: [if], data = [none]
}
}
} catch (NoSuchElementException ex) {
// Done
} catch (NumberFormatException ex) { // depends on control dependency: [catch], data = [none]
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
if (("1"/*DBConstants.ANON_USER_ID*/.equals(this.getProperty(Params.USER_ID)))
|| (this.getProperty(Params.USER_ID) == null))
if (iAccessAllowed == Constants.ACCESS_DENIED)
iAccessAllowed = Constants.LOGIN_REQUIRED; // For anonymous access, logging in will always get you more
return iAccessAllowed;
} } |
public class class_name {
public void close() {
if (connected) {
try {
transport.close();
socket.close();
}
catch (IOException ex) {
logger.warn("Could not close socket", ex);
}
connected = false;
}
} } | public class class_name {
public void close() {
if (connected) {
try {
transport.close(); // depends on control dependency: [try], data = [none]
socket.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException ex) {
logger.warn("Could not close socket", ex);
} // depends on control dependency: [catch], data = [none]
connected = false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void stopPageReadFromCacheTimer() {
final long endTs = nanoTimer.getNano();
final long timeDiff = (endTs - timeStamps.pop());
performanceCountersHolder.pageReadFromCacheTime += timeDiff;
performanceCountersHolder.pageReadFromCacheCount++;
for (Component component : componentsStack) {
final String componentName = component.name;
PerformanceCountersHolder cHolder = countersByComponent
.computeIfAbsent(componentName, k -> component.type.newCountersHolder());
cHolder.pageReadFromCacheTime += timeDiff;
cHolder.pageReadFromCacheCount++;
}
final Component currentComponent = componentsStack.peek();
if (currentComponent != null) {
PerformanceCountersHolder currentHolder = countersByComponent.get(currentComponent.name);
if (currentHolder.currentOperation != null) {
currentHolder.currentOperation.incrementOperationsCounter(1, 0);
}
}
makeSnapshotIfNeeded(endTs);
} } | public class class_name {
public void stopPageReadFromCacheTimer() {
final long endTs = nanoTimer.getNano();
final long timeDiff = (endTs - timeStamps.pop());
performanceCountersHolder.pageReadFromCacheTime += timeDiff;
performanceCountersHolder.pageReadFromCacheCount++;
for (Component component : componentsStack) {
final String componentName = component.name;
PerformanceCountersHolder cHolder = countersByComponent
.computeIfAbsent(componentName, k -> component.type.newCountersHolder());
cHolder.pageReadFromCacheTime += timeDiff; // depends on control dependency: [for], data = [none]
cHolder.pageReadFromCacheCount++; // depends on control dependency: [for], data = [none]
}
final Component currentComponent = componentsStack.peek();
if (currentComponent != null) {
PerformanceCountersHolder currentHolder = countersByComponent.get(currentComponent.name);
if (currentHolder.currentOperation != null) {
currentHolder.currentOperation.incrementOperationsCounter(1, 0); // depends on control dependency: [if], data = [none]
}
}
makeSnapshotIfNeeded(endTs);
} } |
public class class_name {
public LinkedHashSet<Class<?>> getRegisteredKryoTypes() {
if (isForceKryoEnabled()) {
// if we force kryo, we must also return all the types that
// were previously only registered as POJO
LinkedHashSet<Class<?>> result = new LinkedHashSet<>();
result.addAll(registeredKryoTypes);
for(Class<?> t : registeredPojoTypes) {
if (!result.contains(t)) {
result.add(t);
}
}
return result;
} else {
return registeredKryoTypes;
}
} } | public class class_name {
public LinkedHashSet<Class<?>> getRegisteredKryoTypes() {
if (isForceKryoEnabled()) {
// if we force kryo, we must also return all the types that
// were previously only registered as POJO
LinkedHashSet<Class<?>> result = new LinkedHashSet<>(); // depends on control dependency: [if], data = [none]
result.addAll(registeredKryoTypes); // depends on control dependency: [if], data = [none]
for(Class<?> t : registeredPojoTypes) {
if (!result.contains(t)) {
result.add(t); // depends on control dependency: [if], data = [none]
}
}
return result; // depends on control dependency: [if], data = [none]
} else {
return registeredKryoTypes; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void refineOperandType(VoltType valueType) {
if (m_valueType != VoltType.NUMERIC) {
return;
}
if (valueType == VoltType.DECIMAL) {
m_valueType = VoltType.DECIMAL;
m_valueSize = VoltType.DECIMAL.getLengthInBytesForFixedTypes();
}
else {
m_valueType = VoltType.FLOAT;
m_valueSize = VoltType.FLOAT.getLengthInBytesForFixedTypes();
}
} } | public class class_name {
void refineOperandType(VoltType valueType) {
if (m_valueType != VoltType.NUMERIC) {
return; // depends on control dependency: [if], data = [none]
}
if (valueType == VoltType.DECIMAL) {
m_valueType = VoltType.DECIMAL; // depends on control dependency: [if], data = [none]
m_valueSize = VoltType.DECIMAL.getLengthInBytesForFixedTypes(); // depends on control dependency: [if], data = [none]
}
else {
m_valueType = VoltType.FLOAT; // depends on control dependency: [if], data = [none]
m_valueSize = VoltType.FLOAT.getLengthInBytesForFixedTypes(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(DeleteAppRequest deleteAppRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteAppRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteAppRequest.getAppId(), APPID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteAppRequest deleteAppRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteAppRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteAppRequest.getAppId(), APPID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void zoomPrevious() {
if (hasPrevious()) {
next.addFirst(previous.remove());
MapViewChangedEvent data = previous.peek();
active = false;
mapView.applyBounds(data.getBounds(), MapView.ZoomOption.LEVEL_CLOSEST);
updateActionsAbility();
}
} } | public class class_name {
public void zoomPrevious() {
if (hasPrevious()) {
next.addFirst(previous.remove()); // depends on control dependency: [if], data = [none]
MapViewChangedEvent data = previous.peek();
active = false; // depends on control dependency: [if], data = [none]
mapView.applyBounds(data.getBounds(), MapView.ZoomOption.LEVEL_CLOSEST); // depends on control dependency: [if], data = [none]
updateActionsAbility(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void generateSheet(Workbook workbook, List<?> data, Class clazz,
boolean isWriteHeader, String sheetName)
throws Excel4JException {
Sheet sheet;
if (null != sheetName && !"".equals(sheetName)) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet();
}
Row row = sheet.createRow(0);
List<ExcelHeader> headers = Utils.getHeaderList(clazz);
if (isWriteHeader) {
// 写标题
for (int i = 0; i < headers.size(); i++) {
row.createCell(i).setCellValue(headers.get(i).getTitle());
}
}
// 写数据
Object _data;
for (int i = 0; i < data.size(); i++) {
row = sheet.createRow(i + 1);
_data = data.get(i);
for (int j = 0; j < headers.size(); j++) {
row.createCell(j).setCellValue(Utils.getProperty(_data,
headers.get(j).getFiled(),
headers.get(j).getWriteConverter()));
}
}
} } | public class class_name {
private void generateSheet(Workbook workbook, List<?> data, Class clazz,
boolean isWriteHeader, String sheetName)
throws Excel4JException {
Sheet sheet;
if (null != sheetName && !"".equals(sheetName)) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet();
}
Row row = sheet.createRow(0);
List<ExcelHeader> headers = Utils.getHeaderList(clazz);
if (isWriteHeader) {
// 写标题
for (int i = 0; i < headers.size(); i++) {
row.createCell(i).setCellValue(headers.get(i).getTitle()); // depends on control dependency: [for], data = [i]
}
}
// 写数据
Object _data;
for (int i = 0; i < data.size(); i++) {
row = sheet.createRow(i + 1);
_data = data.get(i);
for (int j = 0; j < headers.size(); j++) {
row.createCell(j).setCellValue(Utils.getProperty(_data,
headers.get(j).getFiled(),
headers.get(j).getWriteConverter()));
}
}
} } |
public class class_name {
public void marshall(DescribeMountTargetSecurityGroupsRequest describeMountTargetSecurityGroupsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeMountTargetSecurityGroupsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeMountTargetSecurityGroupsRequest.getMountTargetId(), MOUNTTARGETID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeMountTargetSecurityGroupsRequest describeMountTargetSecurityGroupsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeMountTargetSecurityGroupsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeMountTargetSecurityGroupsRequest.getMountTargetId(), MOUNTTARGETID_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 List<Workflow> getWorkflowsByCorrelationId(String correlationId, boolean includeTasks) {
if (!executionDAO.canSearchAcrossWorkflows()) {
List<Workflow> workflows = new LinkedList<>();
SearchResult<String> result = indexDAO.searchWorkflows("correlationId='" + correlationId + "'", "*", 0, 10000, null);
result.getResults().forEach(workflowId -> {
try {
Workflow workflow = getWorkflowById(workflowId, includeTasks);
workflows.add(workflow);
} catch (ApplicationException e) {
//This might happen when the workflow archival failed and the workflow was removed from dynomite
LOGGER.error("Error getting the workflowId: {} for correlationId: {} from Dynomite/Archival", workflowId, correlationId, e);
}
});
return workflows;
}
return executionDAO.getWorkflowsByCorrelationId(correlationId, includeTasks);
} } | public class class_name {
public List<Workflow> getWorkflowsByCorrelationId(String correlationId, boolean includeTasks) {
if (!executionDAO.canSearchAcrossWorkflows()) {
List<Workflow> workflows = new LinkedList<>();
SearchResult<String> result = indexDAO.searchWorkflows("correlationId='" + correlationId + "'", "*", 0, 10000, null);
result.getResults().forEach(workflowId -> {
try {
Workflow workflow = getWorkflowById(workflowId, includeTasks); // depends on control dependency: [if], data = [none]
workflows.add(workflow); // depends on control dependency: [if], data = [none]
} catch (ApplicationException e) {
//This might happen when the workflow archival failed and the workflow was removed from dynomite
LOGGER.error("Error getting the workflowId: {} for correlationId: {} from Dynomite/Archival", workflowId, correlationId, e);
}
});
return workflows;
}
return executionDAO.getWorkflowsByCorrelationId(correlationId, includeTasks);
} } |
public class class_name {
public ServiceCall<Expansions> createExpansions(CreateExpansionsOptions createExpansionsOptions) {
Validator.notNull(createExpansionsOptions, "createExpansionsOptions cannot be null");
String[] pathSegments = { "v1/environments", "collections", "expansions" };
String[] pathParameters = { createExpansionsOptions.environmentId(), createExpansionsOptions.collectionId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "createExpansions");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
contentJson.add("expansions", GsonSingleton.getGson().toJsonTree(createExpansionsOptions.expansions()));
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Expansions.class));
} } | public class class_name {
public ServiceCall<Expansions> createExpansions(CreateExpansionsOptions createExpansionsOptions) {
Validator.notNull(createExpansionsOptions, "createExpansionsOptions cannot be null");
String[] pathSegments = { "v1/environments", "collections", "expansions" };
String[] pathParameters = { createExpansionsOptions.environmentId(), createExpansionsOptions.collectionId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "createExpansions");
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");
final JsonObject contentJson = new JsonObject();
contentJson.add("expansions", GsonSingleton.getGson().toJsonTree(createExpansionsOptions.expansions()));
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Expansions.class));
} } |
public class class_name {
private ImmutableList<TargetAtom> prepareTargetQuery(MapItem predicateSubjectMap, List<MapItem> predicateObjectMapsList) {
// Create the body of the CQ
ImmutableList.Builder<TargetAtom> bodyBuilder = ImmutableList.builder();
// Store concept in the body, if any
ImmutableTerm subjectTerm = createSubjectTerm(predicateSubjectMap);
if (!predicateSubjectMap.getPredicateIRI().equals(OWL.THING)) {
TargetAtom concept = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateSubjectMap.getPredicateIRI());
bodyBuilder.add(concept);
}
// Store attributes and roles in the body
//List<Term> distinguishVariables = new ArrayList<Term>();
for (MapItem predicateObjectMap : predicateObjectMapsList) {
if (predicateObjectMap.isObjectMap()) { // if an attribute
ImmutableTerm objectTerm = createObjectTerm(getColumnName(predicateObjectMap), predicateObjectMap.getDataType());
TargetAtom attribute = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectTerm);
bodyBuilder.add(attribute);
//distinguishVariables.add(objectTerm);
} else if (predicateObjectMap.isRefObjectMap()) { // if a role
ImmutableFunctionalTerm objectRefTerm = createRefObjectTerm(predicateObjectMap);
TargetAtom role = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectRefTerm);
bodyBuilder.add(role);
}
}
// Create the head
//int arity = distinguishVariables.size();
//Function head = termFactory.getFunction(termFactory.getTermType(OBDALibConstants.QUERY_HEAD, arity), distinguishVariables);
// Create and return the conjunctive query
return bodyBuilder.build();
} } | public class class_name {
private ImmutableList<TargetAtom> prepareTargetQuery(MapItem predicateSubjectMap, List<MapItem> predicateObjectMapsList) {
// Create the body of the CQ
ImmutableList.Builder<TargetAtom> bodyBuilder = ImmutableList.builder();
// Store concept in the body, if any
ImmutableTerm subjectTerm = createSubjectTerm(predicateSubjectMap);
if (!predicateSubjectMap.getPredicateIRI().equals(OWL.THING)) {
TargetAtom concept = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateSubjectMap.getPredicateIRI());
bodyBuilder.add(concept); // depends on control dependency: [if], data = [none]
}
// Store attributes and roles in the body
//List<Term> distinguishVariables = new ArrayList<Term>();
for (MapItem predicateObjectMap : predicateObjectMapsList) {
if (predicateObjectMap.isObjectMap()) { // if an attribute
ImmutableTerm objectTerm = createObjectTerm(getColumnName(predicateObjectMap), predicateObjectMap.getDataType());
TargetAtom attribute = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectTerm);
bodyBuilder.add(attribute); // depends on control dependency: [if], data = [none]
//distinguishVariables.add(objectTerm);
} else if (predicateObjectMap.isRefObjectMap()) { // if a role
ImmutableFunctionalTerm objectRefTerm = createRefObjectTerm(predicateObjectMap);
TargetAtom role = targetAtomFactory.getTripleTargetAtom(subjectTerm, predicateObjectMap.getPredicateIRI(), objectRefTerm);
bodyBuilder.add(role); // depends on control dependency: [if], data = [none]
}
}
// Create the head
//int arity = distinguishVariables.size();
//Function head = termFactory.getFunction(termFactory.getTermType(OBDALibConstants.QUERY_HEAD, arity), distinguishVariables);
// Create and return the conjunctive query
return bodyBuilder.build();
} } |
public class class_name {
private void addSuperBlockStart(int pc) {
if (GenerateStackMap) {
if (itsSuperBlockStarts == null) {
itsSuperBlockStarts = new int[SuperBlockStartsSize];
} else if (itsSuperBlockStarts.length == itsSuperBlockStartsTop) {
int[] tmp = new int[itsSuperBlockStartsTop * 2];
System.arraycopy(itsSuperBlockStarts, 0, tmp, 0,
itsSuperBlockStartsTop);
itsSuperBlockStarts = tmp;
}
itsSuperBlockStarts[itsSuperBlockStartsTop++] = pc;
}
} } | public class class_name {
private void addSuperBlockStart(int pc) {
if (GenerateStackMap) {
if (itsSuperBlockStarts == null) {
itsSuperBlockStarts = new int[SuperBlockStartsSize]; // depends on control dependency: [if], data = [none]
} else if (itsSuperBlockStarts.length == itsSuperBlockStartsTop) {
int[] tmp = new int[itsSuperBlockStartsTop * 2];
System.arraycopy(itsSuperBlockStarts, 0, tmp, 0,
itsSuperBlockStartsTop); // depends on control dependency: [if], data = [none]
itsSuperBlockStarts = tmp; // depends on control dependency: [if], data = [none]
}
itsSuperBlockStarts[itsSuperBlockStartsTop++] = pc; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Object resetHardState(FacesContext context)
{
if (_transientState != null)
{
_transientState.clear();
}
if (_deltas != null && !_deltas.isEmpty() && isInitialStateMarked())
{
clearFullStateMap(context);
}
return saveState(context);
} } | public class class_name {
public Object resetHardState(FacesContext context)
{
if (_transientState != null)
{
_transientState.clear(); // depends on control dependency: [if], data = [none]
}
if (_deltas != null && !_deltas.isEmpty() && isInitialStateMarked())
{
clearFullStateMap(context); // depends on control dependency: [if], data = [none]
}
return saveState(context);
} } |
public class class_name {
public boolean cancelTimer(final long timerId)
{
final int wheelIndex = tickForTimerId(timerId);
final int arrayIndex = indexInTickArray(timerId);
if (wheelIndex < wheel.length)
{
final long[] array = wheel[wheelIndex];
if (arrayIndex < array.length && NULL_TIMER != array[arrayIndex])
{
array[arrayIndex] = NULL_TIMER;
timerCount--;
return true;
}
}
return false;
} } | public class class_name {
public boolean cancelTimer(final long timerId)
{
final int wheelIndex = tickForTimerId(timerId);
final int arrayIndex = indexInTickArray(timerId);
if (wheelIndex < wheel.length)
{
final long[] array = wheel[wheelIndex];
if (arrayIndex < array.length && NULL_TIMER != array[arrayIndex])
{
array[arrayIndex] = NULL_TIMER; // depends on control dependency: [if], data = [none]
timerCount--; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
protected void checkForOldRestStyleError(JsonNode node) {
JsonNode errorCode = node.get("error_code");
if (errorCode != null) {
int code = errorCode.intValue();
String msg = node.path("error_msg").asText();
this.throwCodeAndMessage(code, msg);
}
} } | public class class_name {
protected void checkForOldRestStyleError(JsonNode node) {
JsonNode errorCode = node.get("error_code");
if (errorCode != null) {
int code = errorCode.intValue();
String msg = node.path("error_msg").asText();
this.throwCodeAndMessage(code, msg);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean isValidGitRepository(Path folder) {
if (Files.exists(folder) && Files.isDirectory(folder)) {
// If it has been at least initialized
if (RepositoryCache.FileKey.isGitRepository(folder.toFile(), FS.DETECTED)) {
// we are assuming that the clone worked at that time, caller should call hasAtLeastOneReference
return true;
} else {
return false;
}
} else {
return false;
}
} } | public class class_name {
public boolean isValidGitRepository(Path folder) {
if (Files.exists(folder) && Files.isDirectory(folder)) {
// If it has been at least initialized
if (RepositoryCache.FileKey.isGitRepository(folder.toFile(), FS.DETECTED)) {
// we are assuming that the clone worked at that time, caller should call hasAtLeastOneReference
return true; // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private IntervalListener getListener(String intervalName){
IntervalListener listener = listeners.get(intervalName);
if (listener!=null)
return listener;
try {
Interval interval = IntervalRegistry.getInstance().getIntervalOnlyIfExisting(intervalName);
listener = new IntervalListener();
IntervalListener old = listeners.putIfAbsent(intervalName, listener);
if (old!=null)
return old;
interval.addSecondaryIntervalListener(listener);
return listener;
}catch(UnknownIntervalException e){
return NoIntervalListener.INSTANCE;
}
} } | public class class_name {
private IntervalListener getListener(String intervalName){
IntervalListener listener = listeners.get(intervalName);
if (listener!=null)
return listener;
try {
Interval interval = IntervalRegistry.getInstance().getIntervalOnlyIfExisting(intervalName);
listener = new IntervalListener(); // depends on control dependency: [try], data = [none]
IntervalListener old = listeners.putIfAbsent(intervalName, listener);
if (old!=null)
return old;
interval.addSecondaryIntervalListener(listener); // depends on control dependency: [try], data = [none]
return listener; // depends on control dependency: [try], data = [none]
}catch(UnknownIntervalException e){
return NoIntervalListener.INSTANCE;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Constraint future() {
return new Constraint("future", simplePayload("future")) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
long now = System.currentTimeMillis();
if ((actualValue instanceof Date && ((Date) actualValue).getTime() <= now)
|| (actualValue instanceof Number && ((Number) actualValue).longValue() <= now)) {
return false;
}
}
return true;
}
};
} } | public class class_name {
public static Constraint future() {
return new Constraint("future", simplePayload("future")) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
long now = System.currentTimeMillis();
if ((actualValue instanceof Date && ((Date) actualValue).getTime() <= now)
|| (actualValue instanceof Number && ((Number) actualValue).longValue() <= now)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
}
};
} } |
public class class_name {
@Override
public Attribute createAttribute(final GedObject ged, final String string) {
if (ged == null || string == null) {
return new Attribute();
}
final Attribute attribute = new Attribute(ged, string);
ged.insert(attribute);
return attribute;
} } | public class class_name {
@Override
public Attribute createAttribute(final GedObject ged, final String string) {
if (ged == null || string == null) {
return new Attribute(); // depends on control dependency: [if], data = [none]
}
final Attribute attribute = new Attribute(ged, string);
ged.insert(attribute);
return attribute;
} } |
public class class_name {
protected String getDefaultTimeFormatIfNull(Member c2jMemberDefinition, Map<String, Shape> allC2jShapes, String protocolString, Shape parentShape) {
String timestampFormat = c2jMemberDefinition.getTimestampFormat();
if (!StringUtils.isNullOrEmpty(timestampFormat)) {
failIfInCollection(c2jMemberDefinition, parentShape);
return TimestampFormat.fromValue(timestampFormat).getFormat();
}
String shapeName = c2jMemberDefinition.getShape();
Shape shape = allC2jShapes.get(shapeName);
if (!StringUtils.isNullOrEmpty(shape.getTimestampFormat())) {
failIfInCollection(c2jMemberDefinition, parentShape);
return TimestampFormat.fromValue(shape.getTimestampFormat()).getFormat();
}
String location = c2jMemberDefinition.getLocation();
if (Location.HEADER.toString().equals(location)) {
return defaultHeaderTimestamp();
}
if (Location.QUERY_STRING.toString().equals(location)) {
return TimestampFormat.ISO_8601.getFormat();
}
Protocol protocol = Protocol.fromValue(protocolString);
switch (protocol) {
case REST_XML:
case QUERY:
case EC2:
case API_GATEWAY:
return TimestampFormat.ISO_8601.getFormat();
case ION:
case REST_JSON:
case AWS_JSON:
return TimestampFormat.UNIX_TIMESTAMP.getFormat();
case CBOR:
return TimestampFormat.UNIX_TIMESTAMP_IN_MILLIS.getFormat();
}
throw new RuntimeException("Cannot determine timestamp format for protocol " + protocol);
} } | public class class_name {
protected String getDefaultTimeFormatIfNull(Member c2jMemberDefinition, Map<String, Shape> allC2jShapes, String protocolString, Shape parentShape) {
String timestampFormat = c2jMemberDefinition.getTimestampFormat();
if (!StringUtils.isNullOrEmpty(timestampFormat)) {
failIfInCollection(c2jMemberDefinition, parentShape); // depends on control dependency: [if], data = [none]
return TimestampFormat.fromValue(timestampFormat).getFormat(); // depends on control dependency: [if], data = [none]
}
String shapeName = c2jMemberDefinition.getShape();
Shape shape = allC2jShapes.get(shapeName);
if (!StringUtils.isNullOrEmpty(shape.getTimestampFormat())) {
failIfInCollection(c2jMemberDefinition, parentShape); // depends on control dependency: [if], data = [none]
return TimestampFormat.fromValue(shape.getTimestampFormat()).getFormat(); // depends on control dependency: [if], data = [none]
}
String location = c2jMemberDefinition.getLocation();
if (Location.HEADER.toString().equals(location)) {
return defaultHeaderTimestamp(); // depends on control dependency: [if], data = [none]
}
if (Location.QUERY_STRING.toString().equals(location)) {
return TimestampFormat.ISO_8601.getFormat(); // depends on control dependency: [if], data = [none]
}
Protocol protocol = Protocol.fromValue(protocolString);
switch (protocol) {
case REST_XML:
case QUERY:
case EC2:
case API_GATEWAY:
return TimestampFormat.ISO_8601.getFormat();
case ION:
case REST_JSON:
case AWS_JSON:
return TimestampFormat.UNIX_TIMESTAMP.getFormat();
case CBOR:
return TimestampFormat.UNIX_TIMESTAMP_IN_MILLIS.getFormat();
}
throw new RuntimeException("Cannot determine timestamp format for protocol " + protocol);
} } |
public class class_name {
public static File getBundleFile(Bundle bundle) throws IOException {
URL rootEntry = bundle.getEntry("/"); //$NON-NLS-1$
rootEntry = FileLocator.resolve(rootEntry);
if ("file".equals(rootEntry.getProtocol())) //$NON-NLS-1$
return new File(rootEntry.getPath());
if ("jar".equals(rootEntry.getProtocol())) { //$NON-NLS-1$
String path = rootEntry.getPath();
if (path.startsWith("file:")) {
// strip off the file: and the !/
path = path.substring(5, path.length() - 2);
return new File(path);
}
}
throw new IOException("Unknown protocol"); //$NON-NLS-1$
} } | public class class_name {
public static File getBundleFile(Bundle bundle) throws IOException {
URL rootEntry = bundle.getEntry("/"); //$NON-NLS-1$
rootEntry = FileLocator.resolve(rootEntry);
if ("file".equals(rootEntry.getProtocol())) //$NON-NLS-1$
return new File(rootEntry.getPath());
if ("jar".equals(rootEntry.getProtocol())) { //$NON-NLS-1$
String path = rootEntry.getPath();
if (path.startsWith("file:")) {
// strip off the file: and the !/
path = path.substring(5, path.length() - 2); // depends on control dependency: [if], data = [none]
return new File(path); // depends on control dependency: [if], data = [none]
}
}
throw new IOException("Unknown protocol"); //$NON-NLS-1$
} } |
public class class_name {
private AuthenticationService getAuthenticationService(String id) {
AuthenticationService service = authentication.getService(id);
if (service == null) {
throwIllegalArgumentExceptionInvalidAttributeValue(SecurityConfiguration.CFG_KEY_AUTHENTICATION_REF, id);
}
return service;
} } | public class class_name {
private AuthenticationService getAuthenticationService(String id) {
AuthenticationService service = authentication.getService(id);
if (service == null) {
throwIllegalArgumentExceptionInvalidAttributeValue(SecurityConfiguration.CFG_KEY_AUTHENTICATION_REF, id); // depends on control dependency: [if], data = [none]
}
return service;
} } |
public class class_name {
protected void addIndexContents(PackageDoc[] packages, String text,
String tableSummary, Content body) {
if (packages.length > 0) {
Arrays.sort(packages);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.indexHeader);
addAllClassesLink(div);
if (configuration.showProfiles) {
addAllProfilesLink(div);
}
body.addContent(div);
if (configuration.showProfiles && configuration.profilePackages.size() > 0) {
Content profileSummary = configuration.getResource("doclet.Profiles");
addProfilesList(profileSummary, body);
}
addPackagesList(packages, text, tableSummary, body);
}
} } | public class class_name {
protected void addIndexContents(PackageDoc[] packages, String text,
String tableSummary, Content body) {
if (packages.length > 0) {
Arrays.sort(packages); // depends on control dependency: [if], data = [none]
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.indexHeader); // depends on control dependency: [if], data = [none]
addAllClassesLink(div); // depends on control dependency: [if], data = [none]
if (configuration.showProfiles) {
addAllProfilesLink(div); // depends on control dependency: [if], data = [none]
}
body.addContent(div); // depends on control dependency: [if], data = [none]
if (configuration.showProfiles && configuration.profilePackages.size() > 0) {
Content profileSummary = configuration.getResource("doclet.Profiles");
addProfilesList(profileSummary, body); // depends on control dependency: [if], data = [none]
}
addPackagesList(packages, text, tableSummary, body); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void finish() {
try {
if (switcher.getCurrentMode() == STTYMode.RAW && lineCount > 0) {
out.write('\r');
out.write('\n');
out.flush();
}
lineCount = 0;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} } | public class class_name {
public void finish() {
try {
if (switcher.getCurrentMode() == STTYMode.RAW && lineCount > 0) {
out.write('\r'); // depends on control dependency: [if], data = [none]
out.write('\n'); // depends on control dependency: [if], data = [none]
out.flush(); // depends on control dependency: [if], data = [none]
}
lineCount = 0; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new UncheckedIOException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final EObject ruleContinueExpression() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
enterRule();
try {
// InternalSARL.g:7492:2: ( ( () otherlv_1= 'continue' ) )
// InternalSARL.g:7493:2: ( () otherlv_1= 'continue' )
{
// InternalSARL.g:7493:2: ( () otherlv_1= 'continue' )
// InternalSARL.g:7494:3: () otherlv_1= 'continue'
{
// InternalSARL.g:7494:3: ()
// InternalSARL.g:7495:4:
{
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getContinueExpressionAccess().getSarlContinueExpressionAction_0(),
current);
}
}
otherlv_1=(Token)match(input,61,FOLLOW_2); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getContinueExpressionAccess().getContinueKeyword_1());
}
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject ruleContinueExpression() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
enterRule();
try {
// InternalSARL.g:7492:2: ( ( () otherlv_1= 'continue' ) )
// InternalSARL.g:7493:2: ( () otherlv_1= 'continue' )
{
// InternalSARL.g:7493:2: ( () otherlv_1= 'continue' )
// InternalSARL.g:7494:3: () otherlv_1= 'continue'
{
// InternalSARL.g:7494:3: ()
// InternalSARL.g:7495:4:
{
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getContinueExpressionAccess().getSarlContinueExpressionAction_0(),
current); // depends on control dependency: [if], data = [none]
}
}
otherlv_1=(Token)match(input,61,FOLLOW_2); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getContinueExpressionAccess().getContinueKeyword_1()); // depends on control dependency: [if], data = [none]
}
}
}
if ( state.backtracking==0 ) {
leaveRule(); // depends on control dependency: [if], data = [none]
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) {
if (clientDetailsService != null) {
ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
Integer validity = client.getRefreshTokenValiditySeconds();
if (validity != null) {
return validity;
}
}
return refreshTokenValiditySeconds;
} } | public class class_name {
protected int getRefreshTokenValiditySeconds(OAuth2Request clientAuth) {
if (clientDetailsService != null) {
ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
Integer validity = client.getRefreshTokenValiditySeconds();
if (validity != null) {
return validity; // depends on control dependency: [if], data = [none]
}
}
return refreshTokenValiditySeconds;
} } |
public class class_name {
public void setLedType(final LedType LED_TYPE) {
if (ledType == LED_TYPE) {return;}
ledType = LED_TYPE;
final boolean LED_WAS_ON = currentLedImage.equals(ledImageOn) ? true : false;
flushImages();
ledImageOff = create_LED_Image(getWidth(), 0, ledColor, ledType);
ledImageOn = create_LED_Image(getWidth(), 1, ledColor, ledType);
currentLedImage = LED_WAS_ON == true ? ledImageOn : ledImageOff;
repaint();
} } | public class class_name {
public void setLedType(final LedType LED_TYPE) {
if (ledType == LED_TYPE) {return;} // depends on control dependency: [if], data = [none]
ledType = LED_TYPE;
final boolean LED_WAS_ON = currentLedImage.equals(ledImageOn) ? true : false;
flushImages();
ledImageOff = create_LED_Image(getWidth(), 0, ledColor, ledType);
ledImageOn = create_LED_Image(getWidth(), 1, ledColor, ledType);
currentLedImage = LED_WAS_ON == true ? ledImageOn : ledImageOff;
repaint();
} } |
public class class_name {
public static synchronized Router getRouterFor(ServletContext con) {
// log.info( "getting router for context path '" + givenContextPath + "'" );
String contextPath = EldaRouterRestletSupport.flatContextPath(con.getContextPath());
TimestampedRouter r = routers.get(contextPath);
long timeNow = System.currentTimeMillis();
//
if (r == null) {
log.info("creating router for '" + contextPath + "'");
long interval = getRefreshInterval(contextPath);
r = new TimestampedRouter(EldaRouterRestletSupport.createRouterFor(con), timeNow, interval);
routers.put(contextPath, r);
} else if (r.nextCheck < timeNow) {
long latestTime = EldaRouterRestletSupport.latestConfigTime(con, contextPath);
if (latestTime > r.timestamp) {
log.info("reloading router for '" + contextPath + "'");
long interval = getRefreshInterval(contextPath);
r = new TimestampedRouter(EldaRouterRestletSupport.createRouterFor(con), timeNow, interval);
DOMUtils.clearCache();
Cache.Registry.clearAll();
routers.put(contextPath, r);
} else {
// checked, but no change to reload
// log.info("don't need to reload router, will check again later." );
r.deferCheck();
}
} else {
// Don't need to check yet, still in waiting period
// log.info( "Using existing router, not time to check yet." );
}
//
return r.router;
} } | public class class_name {
public static synchronized Router getRouterFor(ServletContext con) {
// log.info( "getting router for context path '" + givenContextPath + "'" );
String contextPath = EldaRouterRestletSupport.flatContextPath(con.getContextPath());
TimestampedRouter r = routers.get(contextPath);
long timeNow = System.currentTimeMillis();
//
if (r == null) {
log.info("creating router for '" + contextPath + "'"); // depends on control dependency: [if], data = [none]
long interval = getRefreshInterval(contextPath);
r = new TimestampedRouter(EldaRouterRestletSupport.createRouterFor(con), timeNow, interval); // depends on control dependency: [if], data = [none]
routers.put(contextPath, r); // depends on control dependency: [if], data = [none]
} else if (r.nextCheck < timeNow) {
long latestTime = EldaRouterRestletSupport.latestConfigTime(con, contextPath);
if (latestTime > r.timestamp) {
log.info("reloading router for '" + contextPath + "'"); // depends on control dependency: [if], data = [none]
long interval = getRefreshInterval(contextPath);
r = new TimestampedRouter(EldaRouterRestletSupport.createRouterFor(con), timeNow, interval); // depends on control dependency: [if], data = [none]
DOMUtils.clearCache(); // depends on control dependency: [if], data = [none]
Cache.Registry.clearAll(); // depends on control dependency: [if], data = [none]
routers.put(contextPath, r); // depends on control dependency: [if], data = [none]
} else {
// checked, but no change to reload
// log.info("don't need to reload router, will check again later." );
r.deferCheck(); // depends on control dependency: [if], data = [none]
}
} else {
// Don't need to check yet, still in waiting period
// log.info( "Using existing router, not time to check yet." );
}
//
return r.router;
} } |
public class class_name {
public static boolean writeObjectToFile(Object obj, File f) {
try {
FileOutputStream fout = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(obj);
oos.close();
} catch (Exception e) {
System.out.println("Error writing Object to file: "
+ e.getMessage());
return false;
}
return true;
} } | public class class_name {
public static boolean writeObjectToFile(Object obj, File f) {
try {
FileOutputStream fout = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(obj);
// depends on control dependency: [try], data = [none]
oos.close();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
System.out.println("Error writing Object to file: "
+ e.getMessage());
return false;
}
// depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public static <T extends Enum<T>> ConfigurationOptionBuilder<T> enumOption(Class<T> clazz) {
final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(new EnumValueConverter<T>(clazz), clazz);
for (T enumConstant : clazz.getEnumConstants()) {
optionBuilder.addValidOption(enumConstant);
}
optionBuilder.sealValidOptions();
return optionBuilder;
} } | public class class_name {
public static <T extends Enum<T>> ConfigurationOptionBuilder<T> enumOption(Class<T> clazz) {
final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(new EnumValueConverter<T>(clazz), clazz);
for (T enumConstant : clazz.getEnumConstants()) {
optionBuilder.addValidOption(enumConstant); // depends on control dependency: [for], data = [enumConstant]
}
optionBuilder.sealValidOptions();
return optionBuilder;
} } |
public class class_name {
public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
BeanUtil.requireNonNull(url, "请传入当前网页的URL,不包含#及其后面部分");
GetSignatureResponse response = new GetSignatureResponse();
String jsApiTicket = this.config.getJsApiTicket();
String sign;
try {
sign = JsApiUtil.sign(jsApiTicket, nonceStr, timestame, url);
} catch (Exception e) {
LOG.error("获取签名异常:", e);
response.setErrcode(ResultType.OTHER_ERROR.getCode().toString());
response.setErrmsg("获取签名异常");
return response;
}
response.setNoncestr(nonceStr);
response.setSignature(sign);
response.setTimestamp(timestame);
response.setUrl(url);
response.setErrcode(ResultType.SUCCESS.getCode().toString());
return response;
} } | public class class_name {
public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
BeanUtil.requireNonNull(url, "请传入当前网页的URL,不包含#及其后面部分");
GetSignatureResponse response = new GetSignatureResponse();
String jsApiTicket = this.config.getJsApiTicket();
String sign;
try {
sign = JsApiUtil.sign(jsApiTicket, nonceStr, timestame, url); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.error("获取签名异常:", e);
response.setErrcode(ResultType.OTHER_ERROR.getCode().toString());
response.setErrmsg("获取签名异常");
return response;
} // depends on control dependency: [catch], data = [none]
response.setNoncestr(nonceStr);
response.setSignature(sign);
response.setTimestamp(timestame);
response.setUrl(url);
response.setErrcode(ResultType.SUCCESS.getCode().toString());
return response;
} } |
public class class_name {
public void setAttributeMap( Map savedAttrs )
{
assert savedAttrs != null : "Map of attributes must be non-null";
Map currentAttrs = _scopedContainer.getAttrMap();
Map attrs = new HashMap();
attrs.putAll( savedAttrs );
if ( currentAttrs != null )
{
attrs.putAll( currentAttrs );
}
_scopedContainer.setAttrMap( attrs );
} } | public class class_name {
public void setAttributeMap( Map savedAttrs )
{
assert savedAttrs != null : "Map of attributes must be non-null";
Map currentAttrs = _scopedContainer.getAttrMap();
Map attrs = new HashMap();
attrs.putAll( savedAttrs );
if ( currentAttrs != null )
{
attrs.putAll( currentAttrs ); // depends on control dependency: [if], data = [( currentAttrs]
}
_scopedContainer.setAttrMap( attrs );
} } |
public class class_name {
public JSONObject similarSearch(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return similarSearch(data, options);
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
}
} } | public class class_name {
public JSONObject similarSearch(String image, HashMap<String, String> options) {
try {
byte[] data = Util.readFileByBytes(image);
return similarSearch(data, options); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
return AipError.IMAGE_READ_ERROR.toJsonResult();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean checkPermissions() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)
return true;
for (String permission : mRequiredPermissions) {
if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
mPermissionsToRequest.add(permission);
}
}
if (mPermissionsToRequest.isEmpty()) {
return true;
}
return false;
} } | public class class_name {
public boolean checkPermissions() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)
return true;
for (String permission : mRequiredPermissions) {
if (ContextCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
mPermissionsToRequest.add(permission); // depends on control dependency: [if], data = [none]
}
}
if (mPermissionsToRequest.isEmpty()) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void generatePotentialMenuTimes(ArrayList<LocalTime> desiredTimes) {
potentialMenuTimes = new ArrayList<LocalTime>();
if (desiredTimes == null || desiredTimes.isEmpty()) {
return;
}
TreeSet<LocalTime> timeSet = new TreeSet<LocalTime>();
for (LocalTime desiredTime : desiredTimes) {
if (desiredTime != null) {
timeSet.add(desiredTime);
}
}
for (LocalTime timeSetEntry : timeSet) {
potentialMenuTimes.add(timeSetEntry);
}
} } | public class class_name {
public void generatePotentialMenuTimes(ArrayList<LocalTime> desiredTimes) {
potentialMenuTimes = new ArrayList<LocalTime>();
if (desiredTimes == null || desiredTimes.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
TreeSet<LocalTime> timeSet = new TreeSet<LocalTime>();
for (LocalTime desiredTime : desiredTimes) {
if (desiredTime != null) {
timeSet.add(desiredTime); // depends on control dependency: [if], data = [(desiredTime]
}
}
for (LocalTime timeSetEntry : timeSet) {
potentialMenuTimes.add(timeSetEntry); // depends on control dependency: [for], data = [timeSetEntry]
}
} } |
public class class_name {
public static List<String> getLocaleVariants(
String basename,
Locale locale,
boolean wantBase,
boolean defaultAsBase) {
List<String> result = new ArrayList<String>();
if (null == basename) {
return result;
} else {
String localeString = null == locale ? "" : "_" + locale.toString();
boolean wantDefaultAsBase = defaultAsBase
&& !(localeString.startsWith("_" + getDefaultLocale().toString()));
while (!localeString.isEmpty()) {
result.add(basename + localeString);
localeString = localeString.substring(0, localeString.lastIndexOf('_'));
}
if (wantBase) {
result.add(basename);
}
if (wantDefaultAsBase) {
result.add(basename + "_" + getDefaultLocale().toString());
}
return result;
}
} } | public class class_name {
public static List<String> getLocaleVariants(
String basename,
Locale locale,
boolean wantBase,
boolean defaultAsBase) {
List<String> result = new ArrayList<String>();
if (null == basename) {
return result; // depends on control dependency: [if], data = [none]
} else {
String localeString = null == locale ? "" : "_" + locale.toString();
boolean wantDefaultAsBase = defaultAsBase
&& !(localeString.startsWith("_" + getDefaultLocale().toString()));
while (!localeString.isEmpty()) {
result.add(basename + localeString); // depends on control dependency: [while], data = [none]
localeString = localeString.substring(0, localeString.lastIndexOf('_')); // depends on control dependency: [while], data = [none]
}
if (wantBase) {
result.add(basename); // depends on control dependency: [if], data = [none]
}
if (wantDefaultAsBase) {
result.add(basename + "_" + getDefaultLocale().toString()); // depends on control dependency: [if], data = [none]
}
return result; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public PackageResourceTable newFrameworkResourceTable(ResourcePath resourcePath) {
return PerfStatsCollector.getInstance()
.measure(
"load legacy framework resources",
() -> {
PackageResourceTable resourceTable = new PackageResourceTable("android");
if (resourcePath.getRClass() != null) {
addRClassValues(resourceTable, resourcePath.getRClass());
addMissingStyleableAttributes(resourceTable, resourcePath.getRClass());
}
if (resourcePath.getInternalRClass() != null) {
addRClassValues(resourceTable, resourcePath.getInternalRClass());
addMissingStyleableAttributes(resourceTable, resourcePath.getInternalRClass());
}
parseResourceFiles(resourcePath, resourceTable);
return resourceTable;
});
} } | public class class_name {
public PackageResourceTable newFrameworkResourceTable(ResourcePath resourcePath) {
return PerfStatsCollector.getInstance()
.measure(
"load legacy framework resources",
() -> {
PackageResourceTable resourceTable = new PackageResourceTable("android");
if (resourcePath.getRClass() != null) {
addRClassValues(resourceTable, resourcePath.getRClass()); // depends on control dependency: [if], data = [none]
addMissingStyleableAttributes(resourceTable, resourcePath.getRClass()); // depends on control dependency: [if], data = [none]
}
if (resourcePath.getInternalRClass() != null) {
addRClassValues(resourceTable, resourcePath.getInternalRClass()); // depends on control dependency: [if], data = [none]
addMissingStyleableAttributes(resourceTable, resourcePath.getInternalRClass()); // depends on control dependency: [if], data = [none]
}
parseResourceFiles(resourcePath, resourceTable);
return resourceTable;
});
} } |
public class class_name {
public void setNamespaceProperty(String key, Object value, String namespace)
{
try {
this.propertiesLock.lock();
Map<String, Object> namespaceProperties = getNamespaceProperties(namespace);
if (namespaceProperties != null) {
namespaceProperties.put(key, value);
}
} finally {
this.propertiesLock.unlock();
}
} } | public class class_name {
public void setNamespaceProperty(String key, Object value, String namespace)
{
try {
this.propertiesLock.lock(); // depends on control dependency: [try], data = [none]
Map<String, Object> namespaceProperties = getNamespaceProperties(namespace);
if (namespaceProperties != null) {
namespaceProperties.put(key, value); // depends on control dependency: [if], data = [none]
}
} finally {
this.propertiesLock.unlock();
}
} } |
public class class_name {
void closeAllPaths(int geometry) {
if (getGeometryType(geometry) == Geometry.GeometryType.Polygon)
return;
if (!Geometry.isLinear(getGeometryType(geometry)))
throw GeometryException.GeometryInternalError();
for (int path = getFirstPath(geometry); path != -1; path = getNextPath(path)) {
setClosedPath(path, true);
}
} } | public class class_name {
void closeAllPaths(int geometry) {
if (getGeometryType(geometry) == Geometry.GeometryType.Polygon)
return;
if (!Geometry.isLinear(getGeometryType(geometry)))
throw GeometryException.GeometryInternalError();
for (int path = getFirstPath(geometry); path != -1; path = getNextPath(path)) {
setClosedPath(path, true); // depends on control dependency: [for], data = [path]
}
} } |
public class class_name {
public String getProxyFile() {
String location;
location = System.getProperty("X509_USER_PROXY");
if (location != null) {
return location;
}
location = getProperty("proxy");
if (location != null) {
return location;
}
return ConfigUtil.discoverProxyLocation();
} } | public class class_name {
public String getProxyFile() {
String location;
location = System.getProperty("X509_USER_PROXY");
if (location != null) {
return location; // depends on control dependency: [if], data = [none]
}
location = getProperty("proxy");
if (location != null) {
return location; // depends on control dependency: [if], data = [none]
}
return ConfigUtil.discoverProxyLocation();
} } |
public class class_name {
public OutputStream getModificHistory(final String resourceName, // NOPMD this method needs alls these
// functions
final String revisionRange, final boolean nodeid, final OutputStream output, final boolean wrap)
throws JaxRxException, TTException {
// extract both revision from given String value
final StringTokenizer tokenizer = new StringTokenizer(revisionRange, "-");
final long revision1 = Long.valueOf(tokenizer.nextToken());
final long revision2 = Long.valueOf(tokenizer.nextToken());
if (revision1 < revision2 && revision2 <= getLastRevision(resourceName)) {
// variables for highest rest-id in respectively revision
long maxRestidRev1 = 0;
long maxRestidRev2 = 0;
// Connection to treetank, creating a session
AbsAxis axis = null;
INodeReadTrx rtx = null;
ISession session = null;
// List for all restIds of modifications
final List<Long> modificRestids = new LinkedList<Long>();
// List of all restIds of revision 1
final List<Long> restIdsRev1 = new LinkedList<Long>();
try {
session = mDatabase.getSession(new SessionConfiguration(resourceName, StandardSettings.KEY));
// get highest rest-id from given revision 1
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
axis = new XPathAxis(rtx, ".//*");
while (axis.hasNext()) {
if (rtx.getNode().getDataKey() > maxRestidRev1) {
maxRestidRev1 = rtx.getNode().getDataKey();
}
// stores all restids from revision 1 into a list
restIdsRev1.add(rtx.getNode().getDataKey());
}
rtx.moveTo(ROOT_NODE);
rtx.close();
// get highest rest-id from given revision 2
rtx = new NodeReadTrx(session.beginBucketRtx(revision2));
axis = new XPathAxis(rtx, ".//*");
while (axis.hasNext()) {
final Long nodeKey = rtx.getNode().getDataKey();
if (nodeKey > maxRestidRev2) {
maxRestidRev2 = rtx.getNode().getDataKey();
}
if (nodeKey > maxRestidRev1) {
/*
* writes all restids of revision 2 higher than the
* highest restid of revision 1 into the list
*/
modificRestids.add(nodeKey);
}
/*
* removes all restids from restIdsRev1 that appears in
* revision 2 all remaining restids in the list can be seen
* as deleted nodes
*/
restIdsRev1.remove(nodeKey);
}
rtx.moveTo(ROOT_NODE);
rtx.close();
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
// linked list for holding unique restids from revision 1
final List<Long> restIdsRev1New = new LinkedList<Long>();
/*
* Checks if a deleted node has a parent node that was deleted
* too. If so, only the parent node is stored in new list to
* avoid double print of node modification
*/
for (Long nodeKey : restIdsRev1) {
rtx.moveTo(nodeKey);
final long parentKey = rtx.getNode().getParentKey();
if (!restIdsRev1.contains(parentKey)) {
restIdsRev1New.add(nodeKey);
}
}
rtx.moveTo(ROOT_NODE);
rtx.close();
if (wrap) {
output.write(beginResult.getBytes());
}
/*
* Shred modified restids from revision 2 to xml fragment Just
* modifications done by post commands
*/
rtx = new NodeReadTrx(session.beginBucketRtx(revision2));
for (Long nodeKey : modificRestids) {
rtx.moveTo(nodeKey);
WorkerHelper.serializeXML(session, output, false, nodeid, nodeKey, revision2).call();
}
rtx.moveTo(ROOT_NODE);
rtx.close();
/*
* Shred modified restids from revision 1 to xml fragment Just
* modifications done by put and deletes
*/
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
for (Long nodeKey : restIdsRev1New) {
rtx.moveTo(nodeKey);
WorkerHelper.serializeXML(session, output, false, nodeid, nodeKey, revision1).call();
}
if (wrap) {
output.write(endResult.getBytes());
}
rtx.moveTo(ROOT_NODE);
} catch (final Exception globExcep) {
throw new JaxRxException(globExcep);
} finally {
WorkerHelper.closeRTX(rtx, session);
}
} else {
throw new JaxRxException(400, "Bad user request");
}
return output;
} } | public class class_name {
public OutputStream getModificHistory(final String resourceName, // NOPMD this method needs alls these
// functions
final String revisionRange, final boolean nodeid, final OutputStream output, final boolean wrap)
throws JaxRxException, TTException {
// extract both revision from given String value
final StringTokenizer tokenizer = new StringTokenizer(revisionRange, "-");
final long revision1 = Long.valueOf(tokenizer.nextToken());
final long revision2 = Long.valueOf(tokenizer.nextToken());
if (revision1 < revision2 && revision2 <= getLastRevision(resourceName)) {
// variables for highest rest-id in respectively revision
long maxRestidRev1 = 0;
long maxRestidRev2 = 0;
// Connection to treetank, creating a session
AbsAxis axis = null;
INodeReadTrx rtx = null;
ISession session = null;
// List for all restIds of modifications
final List<Long> modificRestids = new LinkedList<Long>();
// List of all restIds of revision 1
final List<Long> restIdsRev1 = new LinkedList<Long>();
try {
session = mDatabase.getSession(new SessionConfiguration(resourceName, StandardSettings.KEY));
// get highest rest-id from given revision 1
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
axis = new XPathAxis(rtx, ".//*");
while (axis.hasNext()) {
if (rtx.getNode().getDataKey() > maxRestidRev1) {
maxRestidRev1 = rtx.getNode().getDataKey();
}
// stores all restids from revision 1 into a list
restIdsRev1.add(rtx.getNode().getDataKey());
}
rtx.moveTo(ROOT_NODE);
rtx.close();
// get highest rest-id from given revision 2
rtx = new NodeReadTrx(session.beginBucketRtx(revision2));
axis = new XPathAxis(rtx, ".//*");
while (axis.hasNext()) {
final Long nodeKey = rtx.getNode().getDataKey();
if (nodeKey > maxRestidRev2) {
maxRestidRev2 = rtx.getNode().getDataKey();
}
if (nodeKey > maxRestidRev1) {
/*
* writes all restids of revision 2 higher than the
* highest restid of revision 1 into the list
*/
modificRestids.add(nodeKey);
}
/*
* removes all restids from restIdsRev1 that appears in
* revision 2 all remaining restids in the list can be seen
* as deleted nodes
*/
restIdsRev1.remove(nodeKey);
}
rtx.moveTo(ROOT_NODE);
rtx.close();
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
// linked list for holding unique restids from revision 1
final List<Long> restIdsRev1New = new LinkedList<Long>();
/*
* Checks if a deleted node has a parent node that was deleted
* too. If so, only the parent node is stored in new list to
* avoid double print of node modification
*/
for (Long nodeKey : restIdsRev1) {
rtx.moveTo(nodeKey); // depends on control dependency: [for], data = [nodeKey]
final long parentKey = rtx.getNode().getParentKey();
if (!restIdsRev1.contains(parentKey)) {
restIdsRev1New.add(nodeKey); // depends on control dependency: [if], data = [none]
}
}
rtx.moveTo(ROOT_NODE);
rtx.close();
if (wrap) {
output.write(beginResult.getBytes()); // depends on control dependency: [if], data = [none]
}
/*
* Shred modified restids from revision 2 to xml fragment Just
* modifications done by post commands
*/
rtx = new NodeReadTrx(session.beginBucketRtx(revision2));
for (Long nodeKey : modificRestids) {
rtx.moveTo(nodeKey); // depends on control dependency: [for], data = [nodeKey]
WorkerHelper.serializeXML(session, output, false, nodeid, nodeKey, revision2).call(); // depends on control dependency: [for], data = [nodeKey]
}
rtx.moveTo(ROOT_NODE);
rtx.close();
/*
* Shred modified restids from revision 1 to xml fragment Just
* modifications done by put and deletes
*/
rtx = new NodeReadTrx(session.beginBucketRtx(revision1));
for (Long nodeKey : restIdsRev1New) {
rtx.moveTo(nodeKey); // depends on control dependency: [for], data = [nodeKey]
WorkerHelper.serializeXML(session, output, false, nodeid, nodeKey, revision1).call(); // depends on control dependency: [for], data = [nodeKey]
}
if (wrap) {
output.write(endResult.getBytes()); // depends on control dependency: [if], data = [none]
}
rtx.moveTo(ROOT_NODE);
} catch (final Exception globExcep) {
throw new JaxRxException(globExcep);
} finally {
WorkerHelper.closeRTX(rtx, session);
}
} else {
throw new JaxRxException(400, "Bad user request");
}
return output;
} } |
public class class_name {
public long toLong () {
long result = 0;
byte[] uuidBytes = super.toByteArray();
for (int i = 0; i < 8; i++)
{
result = result << 8;
result += (int) uuidBytes[i];
}
return result;
} } | public class class_name {
public long toLong () {
long result = 0;
byte[] uuidBytes = super.toByteArray();
for (int i = 0; i < 8; i++)
{
result = result << 8; // depends on control dependency: [for], data = [none]
result += (int) uuidBytes[i]; // depends on control dependency: [for], data = [i]
}
return result;
} } |
public class class_name {
private static Node getNextSiblingOfType(Node first, Token ... types) {
for (Node c = first; c != null; c = c.getNext()) {
for (Token type : types) {
if (c.getToken() == type) {
return c;
}
}
}
return null;
} } | public class class_name {
private static Node getNextSiblingOfType(Node first, Token ... types) {
for (Node c = first; c != null; c = c.getNext()) {
for (Token type : types) {
if (c.getToken() == type) {
return c; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public Object getObjectByQuery(Query query) throws PersistenceBrokerException
{
Object result = null;
if (query instanceof QueryByIdentity)
{
// example obj may be an entity or an Identity
Object obj = query.getExampleObject();
if (obj instanceof Identity)
{
Identity oid = (Identity) obj;
result = getObjectByIdentity(oid);
}
else
{
// TODO: This workaround doesn't allow 'null' for PK fields
if (!serviceBrokerHelper().hasNullPKField(getClassDescriptor(obj.getClass()), obj))
{
Identity oid = serviceIdentity().buildIdentity(obj);
result = getObjectByIdentity(oid);
}
}
}
else
{
Class itemClass = query.getSearchClass();
ClassDescriptor cld = getClassDescriptor(itemClass);
/*
use OJB intern Iterator, thus we are able to close used
resources instantly
*/
OJBIterator it = getIteratorFromQuery(query, cld);
/*
arminw:
patch by Andre Clute, instead of taking the first found result
try to get the first found none null result.
He wrote:
I have a situation where an item with a certain criteria is in my
database twice -- once deleted, and then a non-deleted version of it.
When I do a PB.getObjectByQuery(), the RsIterator get's both results
from the database, but the first row is the deleted row, so my RowReader
filters it out, and do not get the right result.
*/
try
{
while (result==null && it.hasNext())
{
result = it.next();
}
} // make sure that we close the used resources
finally
{
if(it != null) it.releaseDbResources();
}
}
return result;
} } | public class class_name {
public Object getObjectByQuery(Query query) throws PersistenceBrokerException
{
Object result = null;
if (query instanceof QueryByIdentity)
{
// example obj may be an entity or an Identity
Object obj = query.getExampleObject();
if (obj instanceof Identity)
{
Identity oid = (Identity) obj;
result = getObjectByIdentity(oid); // depends on control dependency: [if], data = [none]
}
else
{
// TODO: This workaround doesn't allow 'null' for PK fields
if (!serviceBrokerHelper().hasNullPKField(getClassDescriptor(obj.getClass()), obj))
{
Identity oid = serviceIdentity().buildIdentity(obj);
result = getObjectByIdentity(oid); // depends on control dependency: [if], data = [none]
}
}
}
else
{
Class itemClass = query.getSearchClass();
ClassDescriptor cld = getClassDescriptor(itemClass);
/*
use OJB intern Iterator, thus we are able to close used
resources instantly
*/
OJBIterator it = getIteratorFromQuery(query, cld);
/*
arminw:
patch by Andre Clute, instead of taking the first found result
try to get the first found none null result.
He wrote:
I have a situation where an item with a certain criteria is in my
database twice -- once deleted, and then a non-deleted version of it.
When I do a PB.getObjectByQuery(), the RsIterator get's both results
from the database, but the first row is the deleted row, so my RowReader
filters it out, and do not get the right result.
*/
try
{
while (result==null && it.hasNext())
{
result = it.next(); // depends on control dependency: [while], data = [none]
}
} // make sure that we close the used resources
finally
{
if(it != null) it.releaseDbResources();
}
}
return result;
} } |
public class class_name {
public static final long parseDuration(String durationStr, long defaultValue) {
durationStr = durationStr.toLowerCase().trim();
Matcher matcher = DURATION_NUMBER_AND_UNIT_PATTERN.matcher(durationStr);
long millis = 0;
boolean matched = false;
while (matcher.find()) {
long number = Long.valueOf(matcher.group(1)).longValue();
String unit = matcher.group(2);
long multiplier = 0;
for (int j = 0; j < DURATION_UNTIS.length; j++) {
if (unit.equals(DURATION_UNTIS[j])) {
multiplier = DURATION_MULTIPLIERS[j];
break;
}
}
if (multiplier == 0) {
LOG.warn("parseDuration: Unknown unit " + unit);
} else {
matched = true;
}
millis += number * multiplier;
}
if (!matched) {
millis = defaultValue;
}
return millis;
} } | public class class_name {
public static final long parseDuration(String durationStr, long defaultValue) {
durationStr = durationStr.toLowerCase().trim();
Matcher matcher = DURATION_NUMBER_AND_UNIT_PATTERN.matcher(durationStr);
long millis = 0;
boolean matched = false;
while (matcher.find()) {
long number = Long.valueOf(matcher.group(1)).longValue();
String unit = matcher.group(2);
long multiplier = 0;
for (int j = 0; j < DURATION_UNTIS.length; j++) {
if (unit.equals(DURATION_UNTIS[j])) {
multiplier = DURATION_MULTIPLIERS[j]; // depends on control dependency: [if], data = [none]
break;
}
}
if (multiplier == 0) {
LOG.warn("parseDuration: Unknown unit " + unit); // depends on control dependency: [if], data = [none]
} else {
matched = true; // depends on control dependency: [if], data = [none]
}
millis += number * multiplier; // depends on control dependency: [while], data = [none]
}
if (!matched) {
millis = defaultValue; // depends on control dependency: [if], data = [none]
}
return millis;
} } |
public class class_name {
private Element writeCoordTransform(CoverageTransform ct) {
Element ctElem = new Element("coordTransform");
ctElem.setAttribute("name", ct.getName());
ctElem.setAttribute("transformType", ct.isHoriz() ? "Projection" : "Vertical");
for (Attribute param : ct.getAttributes()) {
Element pElem = ncmlWriter.makeAttributeElement(param);
pElem.setName("parameter");
ctElem.addContent(pElem);
}
return ctElem;
} } | public class class_name {
private Element writeCoordTransform(CoverageTransform ct) {
Element ctElem = new Element("coordTransform");
ctElem.setAttribute("name", ct.getName());
ctElem.setAttribute("transformType", ct.isHoriz() ? "Projection" : "Vertical");
for (Attribute param : ct.getAttributes()) {
Element pElem = ncmlWriter.makeAttributeElement(param);
pElem.setName("parameter"); // depends on control dependency: [for], data = [param]
ctElem.addContent(pElem); // depends on control dependency: [for], data = [none]
}
return ctElem;
} } |
public class class_name {
public JType getGenericReturnType()
{
SignatureAttribute sigAttr = (SignatureAttribute) getAttribute("Signature");
if (sigAttr != null) {
String sig = sigAttr.getSignature();
int t = sig.lastIndexOf(')');
return _loader.parseParameterizedType(sig.substring(t + 1));
}
return getReturnType();
} } | public class class_name {
public JType getGenericReturnType()
{
SignatureAttribute sigAttr = (SignatureAttribute) getAttribute("Signature");
if (sigAttr != null) {
String sig = sigAttr.getSignature();
int t = sig.lastIndexOf(')');
return _loader.parseParameterizedType(sig.substring(t + 1)); // depends on control dependency: [if], data = [none]
}
return getReturnType();
} } |
public class class_name {
public static String urlDecode(final String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new ImpossibleException(e);
}
} } | public class class_name {
public static String urlDecode(final String part) {
try {
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
// depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new ImpossibleException(e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
protected List<ConfigIssue> init() {
// Validate configuration values and open any required resources.
List<ConfigIssue> issues = super.init();
errorRecordHandler = new DefaultErrorRecordHandler(getContext());
elEvals.init(getContext());
Processor.Context context = getContext();
issues.addAll(hikariConfigBean.validateConfigs(context, issues));
if (issues.isEmpty() && null == dataSource) {
try {
dataSource = jdbcUtil.createDataSourceForWrite(hikariConfigBean, null, null,
false,
issues,
Collections.emptyList(),
getContext()
);
} catch (RuntimeException | SQLException | StageException e) {
LOG.debug("Could not connect to data source", e);
issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, JdbcErrors.JDBC_00, e.toString()));
}
}
if (issues.isEmpty()) {
try {
schemaWriter = JdbcSchemaWriterFactory.create(hikariConfigBean.getConnectionString(), dataSource);
} catch (JdbcStageCheckedException e) {
issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, e.getErrorCode(), e.getParams()));
}
schemaReader = new JdbcSchemaReader(dataSource, schemaWriter);
tableCache = CacheBuilder.newBuilder().maximumSize(50).build(new CacheLoader<Pair<String, String>, LinkedHashMap<String, JdbcTypeInfo>>() {
@Override
public LinkedHashMap<String, JdbcTypeInfo> load(Pair<String, String> pair) throws Exception {
return schemaReader.getTableSchema(pair.getLeft(), pair.getRight());
}
});
}
// If issues is not empty, the UI will inform the user of each configuration issue in the list.
return issues;
} } | public class class_name {
@Override
protected List<ConfigIssue> init() {
// Validate configuration values and open any required resources.
List<ConfigIssue> issues = super.init();
errorRecordHandler = new DefaultErrorRecordHandler(getContext());
elEvals.init(getContext());
Processor.Context context = getContext();
issues.addAll(hikariConfigBean.validateConfigs(context, issues));
if (issues.isEmpty() && null == dataSource) {
try {
dataSource = jdbcUtil.createDataSourceForWrite(hikariConfigBean, null, null,
false,
issues,
Collections.emptyList(),
getContext()
); // depends on control dependency: [try], data = [none]
} catch (RuntimeException | SQLException | StageException e) {
LOG.debug("Could not connect to data source", e);
issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, JdbcErrors.JDBC_00, e.toString()));
} // depends on control dependency: [catch], data = [none]
}
if (issues.isEmpty()) {
try {
schemaWriter = JdbcSchemaWriterFactory.create(hikariConfigBean.getConnectionString(), dataSource); // depends on control dependency: [try], data = [none]
} catch (JdbcStageCheckedException e) {
issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, e.getErrorCode(), e.getParams()));
} // depends on control dependency: [catch], data = [none]
schemaReader = new JdbcSchemaReader(dataSource, schemaWriter); // depends on control dependency: [if], data = [none]
tableCache = CacheBuilder.newBuilder().maximumSize(50).build(new CacheLoader<Pair<String, String>, LinkedHashMap<String, JdbcTypeInfo>>() {
@Override
public LinkedHashMap<String, JdbcTypeInfo> load(Pair<String, String> pair) throws Exception {
return schemaReader.getTableSchema(pair.getLeft(), pair.getRight());
}
}); // depends on control dependency: [if], data = [none]
}
// If issues is not empty, the UI will inform the user of each configuration issue in the list.
return issues;
} } |
public class class_name {
private static boolean
isASCIIOkBiDi(CharSequence s, int length) {
int labelStart=0;
for(int i=0; i<length; ++i) {
char c=s.charAt(i);
if(c=='.') { // dot
if(i>labelStart) {
c=s.charAt(i-1);
if(!('a'<=c && c<='z') && !('0'<=c && c<='9')) {
// Last character in the label is not an L or EN.
return false;
}
}
labelStart=i+1;
} else if(i==labelStart) {
if(!('a'<=c && c<='z')) {
// First character in the label is not an L.
return false;
}
} else {
if(c<=0x20 && (c>=0x1c || (9<=c && c<=0xd))) {
// Intermediate character in the label is a B, S or WS.
return false;
}
}
}
return true;
} } | public class class_name {
private static boolean
isASCIIOkBiDi(CharSequence s, int length) {
int labelStart=0;
for(int i=0; i<length; ++i) {
char c=s.charAt(i);
if(c=='.') { // dot
if(i>labelStart) {
c=s.charAt(i-1); // depends on control dependency: [if], data = [(i]
if(!('a'<=c && c<='z') && !('0'<=c && c<='9')) {
// Last character in the label is not an L or EN.
return false; // depends on control dependency: [if], data = [none]
}
}
labelStart=i+1; // depends on control dependency: [if], data = [none]
} else if(i==labelStart) {
if(!('a'<=c && c<='z')) {
// First character in the label is not an L.
return false; // depends on control dependency: [if], data = [none]
}
} else {
if(c<=0x20 && (c>=0x1c || (9<=c && c<=0xd))) {
// Intermediate character in the label is a B, S or WS.
return false; // depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {
for (InternetAddress address : addresses) {
greenMail.setUser(address.getAddress(), address.getAddress());
}
} } | public class class_name {
public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {
for (InternetAddress address : addresses) {
greenMail.setUser(address.getAddress(), address.getAddress()); // depends on control dependency: [for], data = [address]
}
} } |
public class class_name {
protected String ensureMemberDeclarationKeyword(CodeElementExtractor.ElementDescription memberDescription) {
final List<String> modifiers = getCodeBuilderConfig().getModifiers().get(memberDescription.getName());
if (modifiers != null && !modifiers.isEmpty()) {
return modifiers.get(0);
}
return null;
} } | public class class_name {
protected String ensureMemberDeclarationKeyword(CodeElementExtractor.ElementDescription memberDescription) {
final List<String> modifiers = getCodeBuilderConfig().getModifiers().get(memberDescription.getName());
if (modifiers != null && !modifiers.isEmpty()) {
return modifiers.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static Set<Integer> differences(BitSet s, BitSet t) {
BitSet u = (BitSet) s.clone();
u.xor(t);
Set<Integer> differences = new TreeSet<Integer>();
for (int i = u.nextSetBit(0); i >= 0; i = u.nextSetBit(i + 1)) {
differences.add(i);
}
return differences;
} } | public class class_name {
public static Set<Integer> differences(BitSet s, BitSet t) {
BitSet u = (BitSet) s.clone();
u.xor(t);
Set<Integer> differences = new TreeSet<Integer>();
for (int i = u.nextSetBit(0); i >= 0; i = u.nextSetBit(i + 1)) {
differences.add(i); // depends on control dependency: [for], data = [i]
}
return differences;
} } |
public class class_name {
@Nullable
public String[] calculateRemainingWaypointNames(RouteProgress routeProgress) {
RouteOptions routeOptions = routeProgress.directionsRoute().routeOptions();
if (routeOptions == null || TextUtils.isEmpty(routeOptions.waypointNames())) {
return null;
}
String allWaypointNames = routeOptions.waypointNames();
String[] names = allWaypointNames.split(SEMICOLON);
int coordinatesSize = routeProgress.directionsRoute().routeOptions().coordinates().size();
String[] remainingWaypointNames = Arrays.copyOfRange(names,
coordinatesSize - routeProgress.remainingWaypoints(), coordinatesSize);
String[] waypointNames = new String[remainingWaypointNames.length + ORIGIN_WAYPOINT_NAME_THRESHOLD];
waypointNames[ORIGIN_WAYPOINT_NAME] = names[ORIGIN_WAYPOINT_NAME];
System.arraycopy(remainingWaypointNames, FIRST_POSITION, waypointNames, SECOND_POSITION,
remainingWaypointNames.length);
return waypointNames;
} } | public class class_name {
@Nullable
public String[] calculateRemainingWaypointNames(RouteProgress routeProgress) {
RouteOptions routeOptions = routeProgress.directionsRoute().routeOptions();
if (routeOptions == null || TextUtils.isEmpty(routeOptions.waypointNames())) {
return null; // depends on control dependency: [if], data = [none]
}
String allWaypointNames = routeOptions.waypointNames();
String[] names = allWaypointNames.split(SEMICOLON);
int coordinatesSize = routeProgress.directionsRoute().routeOptions().coordinates().size();
String[] remainingWaypointNames = Arrays.copyOfRange(names,
coordinatesSize - routeProgress.remainingWaypoints(), coordinatesSize);
String[] waypointNames = new String[remainingWaypointNames.length + ORIGIN_WAYPOINT_NAME_THRESHOLD];
waypointNames[ORIGIN_WAYPOINT_NAME] = names[ORIGIN_WAYPOINT_NAME];
System.arraycopy(remainingWaypointNames, FIRST_POSITION, waypointNames, SECOND_POSITION,
remainingWaypointNames.length);
return waypointNames;
} } |
public class class_name {
public void marshall(ExclusionPreview exclusionPreview, ProtocolMarshaller protocolMarshaller) {
if (exclusionPreview == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(exclusionPreview.getTitle(), TITLE_BINDING);
protocolMarshaller.marshall(exclusionPreview.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(exclusionPreview.getRecommendation(), RECOMMENDATION_BINDING);
protocolMarshaller.marshall(exclusionPreview.getScopes(), SCOPES_BINDING);
protocolMarshaller.marshall(exclusionPreview.getAttributes(), ATTRIBUTES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ExclusionPreview exclusionPreview, ProtocolMarshaller protocolMarshaller) {
if (exclusionPreview == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(exclusionPreview.getTitle(), TITLE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(exclusionPreview.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(exclusionPreview.getRecommendation(), RECOMMENDATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(exclusionPreview.getScopes(), SCOPES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(exclusionPreview.getAttributes(), ATTRIBUTES_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 {
void populateClientProperties(Map properties)
{
if (properties != null && !properties.isEmpty())
{
Map<String, Client> clientMap = getDelegate();
if (!clientMap.isEmpty())
{
// TODO If we have two pu for same client then? Need to discuss
// with Amresh.
for (Client client : clientMap.values())
{
if (client instanceof ClientPropertiesSetter)
{
ClientPropertiesSetter cps = (ClientPropertiesSetter) client;
cps.populateClientProperties(client, properties);
}
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("Can't set Client properties as None/ Null was supplied");
}
}
} } | public class class_name {
void populateClientProperties(Map properties)
{
if (properties != null && !properties.isEmpty())
{
Map<String, Client> clientMap = getDelegate();
if (!clientMap.isEmpty())
{
// TODO If we have two pu for same client then? Need to discuss
// with Amresh.
for (Client client : clientMap.values())
{
if (client instanceof ClientPropertiesSetter)
{
ClientPropertiesSetter cps = (ClientPropertiesSetter) client;
cps.populateClientProperties(client, properties); // depends on control dependency: [if], data = [none]
}
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("Can't set Client properties as None/ Null was supplied"); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(QueryCompileErrorLocation queryCompileErrorLocation, ProtocolMarshaller protocolMarshaller) {
if (queryCompileErrorLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(queryCompileErrorLocation.getStartCharOffset(), STARTCHAROFFSET_BINDING);
protocolMarshaller.marshall(queryCompileErrorLocation.getEndCharOffset(), ENDCHAROFFSET_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(QueryCompileErrorLocation queryCompileErrorLocation, ProtocolMarshaller protocolMarshaller) {
if (queryCompileErrorLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(queryCompileErrorLocation.getStartCharOffset(), STARTCHAROFFSET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(queryCompileErrorLocation.getEndCharOffset(), ENDCHAROFFSET_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 {
@Bean(name = "portalRenderingPipeline")
@Qualifier(value = "main")
public IPortalRenderingPipeline getPortalRenderingPipeline() {
// Rendering Pipeline Branches (adopter extension point)
final List<RenderingPipelineBranchPoint> sortedList =
(branchPoints != null) ? new LinkedList<>(branchPoints) : Collections.emptyList();
Collections.sort(sortedList);
final List<RenderingPipelineBranchPoint> branches =
Collections.unmodifiableList(sortedList);
/*
* Sanity check: if you have multiple RenderingPipelineBranchPoint beans, you can specify
* an 'order' property on some or all of them to control the sequence of processing.
* Having 2 RenderingPipelineBranchPoint beans with the same order value will produce
* non-deterministic results and is a likely source of misconfiguration.
*/
final Set<Integer> usedOderValues = new HashSet<>();
boolean hasCollision =
branches.stream()
.anyMatch(
branchPoint -> {
final boolean rslt =
usedOderValues.contains(branchPoint.getOrder());
usedOderValues.add(branchPoint.getOrder());
return rslt;
});
if (hasCollision) {
throw new RenderingPipelineConfigurationException(
"Multiple RenderingPipelineBranchPoint beans have the same 'order' value, which likely a misconfiguration");
}
// "Standard" Pipeline
final IPortalRenderingPipeline standardRenderingPipeline = getStandardRenderingPipeline();
return new IPortalRenderingPipeline() {
@Override
public void renderState(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
for (RenderingPipelineBranchPoint branchPoint : branches) {
if (branchPoint.renderStateIfApplicable(req, res)) {
/*
* Rendering bas been processed by the branch point -- no need to continue.
*/
return;
}
}
/*
* Reaching this point means that a branch was not followed; use the "standard"
* pipeline.
*/
standardRenderingPipeline.renderState(req, res);
}
};
} } | public class class_name {
@Bean(name = "portalRenderingPipeline")
@Qualifier(value = "main")
public IPortalRenderingPipeline getPortalRenderingPipeline() {
// Rendering Pipeline Branches (adopter extension point)
final List<RenderingPipelineBranchPoint> sortedList =
(branchPoints != null) ? new LinkedList<>(branchPoints) : Collections.emptyList();
Collections.sort(sortedList);
final List<RenderingPipelineBranchPoint> branches =
Collections.unmodifiableList(sortedList);
/*
* Sanity check: if you have multiple RenderingPipelineBranchPoint beans, you can specify
* an 'order' property on some or all of them to control the sequence of processing.
* Having 2 RenderingPipelineBranchPoint beans with the same order value will produce
* non-deterministic results and is a likely source of misconfiguration.
*/
final Set<Integer> usedOderValues = new HashSet<>();
boolean hasCollision =
branches.stream()
.anyMatch(
branchPoint -> {
final boolean rslt =
usedOderValues.contains(branchPoint.getOrder());
usedOderValues.add(branchPoint.getOrder());
return rslt;
});
if (hasCollision) {
throw new RenderingPipelineConfigurationException(
"Multiple RenderingPipelineBranchPoint beans have the same 'order' value, which likely a misconfiguration");
}
// "Standard" Pipeline
final IPortalRenderingPipeline standardRenderingPipeline = getStandardRenderingPipeline();
return new IPortalRenderingPipeline() {
@Override
public void renderState(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
for (RenderingPipelineBranchPoint branchPoint : branches) {
if (branchPoint.renderStateIfApplicable(req, res)) {
/*
* Rendering bas been processed by the branch point -- no need to continue.
*/
return; // depends on control dependency: [if], data = [none]
}
}
/*
* Reaching this point means that a branch was not followed; use the "standard"
* pipeline.
*/
standardRenderingPipeline.renderState(req, res);
}
};
} } |
public class class_name {
public Node getNextSiblingElement() {
parentNode.initChildElementNodes();
if (siblingElementIndex == -1) {
int max = parentNode.getChildNodesCount();
for (int i = siblingIndex; i < max; i++) {
Node sibling = parentNode.childNodes.get(i);
if (sibling.getNodeType() == NodeType.ELEMENT) {
return sibling;
}
}
return null;
}
int index = siblingElementIndex + 1;
if (index >= parentNode.childElementNodesCount) {
return null;
}
return parentNode.childElementNodes[index];
} } | public class class_name {
public Node getNextSiblingElement() {
parentNode.initChildElementNodes();
if (siblingElementIndex == -1) {
int max = parentNode.getChildNodesCount();
for (int i = siblingIndex; i < max; i++) {
Node sibling = parentNode.childNodes.get(i);
if (sibling.getNodeType() == NodeType.ELEMENT) {
return sibling; // depends on control dependency: [if], data = [none]
}
}
return null; // depends on control dependency: [if], data = [none]
}
int index = siblingElementIndex + 1;
if (index >= parentNode.childElementNodesCount) {
return null; // depends on control dependency: [if], data = [none]
}
return parentNode.childElementNodes[index];
} } |
public class class_name {
protected int getSearchEndIndex(final @NonNull Spanned text, int cursor) {
if (cursor < 0 || cursor > text.length()) {
cursor = 0;
}
// Get index of the start of the first span after the cursor (or text.length() if does not exist)
MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class);
int closestAfterCursor = text.length();
for (MentionSpan span : spans) {
int start = text.getSpanStart(span);
if (start < closestAfterCursor && start >= cursor) {
closestAfterCursor = start;
}
}
// Get the index of the end of the line
String textString = text.toString().substring(cursor, text.length());
int lineEndIndex = text.length();
if (textString.contains(mConfig.LINE_SEPARATOR)) {
lineEndIndex = cursor + textString.indexOf(mConfig.LINE_SEPARATOR);
}
// Return whichever is closest after the cursor
return Math.min(closestAfterCursor, lineEndIndex);
} } | public class class_name {
protected int getSearchEndIndex(final @NonNull Spanned text, int cursor) {
if (cursor < 0 || cursor > text.length()) {
cursor = 0; // depends on control dependency: [if], data = [none]
}
// Get index of the start of the first span after the cursor (or text.length() if does not exist)
MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class);
int closestAfterCursor = text.length();
for (MentionSpan span : spans) {
int start = text.getSpanStart(span);
if (start < closestAfterCursor && start >= cursor) {
closestAfterCursor = start; // depends on control dependency: [if], data = [none]
}
}
// Get the index of the end of the line
String textString = text.toString().substring(cursor, text.length());
int lineEndIndex = text.length();
if (textString.contains(mConfig.LINE_SEPARATOR)) {
lineEndIndex = cursor + textString.indexOf(mConfig.LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
}
// Return whichever is closest after the cursor
return Math.min(closestAfterCursor, lineEndIndex);
} } |
public class class_name {
@Override
public void close() {
if (isDefaultManager() && getClass().getClassLoader() == classLoader) {
log.info("Closing default CacheManager");
}
Iterable<Cache> _caches;
synchronized (lock) {
if (closing) {
return;
}
_caches = cachesCopy();
closing = true;
}
logPhase("close");
List<Throwable> _suppressedExceptions = new ArrayList<Throwable>();
for (Cache c : _caches) {
((InternalCache) c).cancelTimerJobs();
}
for (Cache c : _caches) {
try {
c.close();
} catch (Throwable t) {
_suppressedExceptions.add(t);
}
}
try {
for (CacheManagerLifeCycleListener lc : cacheManagerLifeCycleListeners) {
lc.managerDestroyed(this);
}
} catch (Throwable t) {
_suppressedExceptions.add(t);
}
((Cache2kCoreProviderImpl) PROVIDER).removeManager(this);
synchronized (lock) {
for (Cache c : cacheNames.values()) {
log.warn("unable to close cache: " + c.getName());
}
}
eventuallyThrowException(_suppressedExceptions);
cacheNames = null;
} } | public class class_name {
@Override
public void close() {
if (isDefaultManager() && getClass().getClassLoader() == classLoader) {
log.info("Closing default CacheManager"); // depends on control dependency: [if], data = [none]
}
Iterable<Cache> _caches;
synchronized (lock) {
if (closing) {
return; // depends on control dependency: [if], data = [none]
}
_caches = cachesCopy();
closing = true;
}
logPhase("close");
List<Throwable> _suppressedExceptions = new ArrayList<Throwable>();
for (Cache c : _caches) {
((InternalCache) c).cancelTimerJobs(); // depends on control dependency: [for], data = [c]
}
for (Cache c : _caches) {
try {
c.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
_suppressedExceptions.add(t);
} // depends on control dependency: [catch], data = [none]
}
try {
for (CacheManagerLifeCycleListener lc : cacheManagerLifeCycleListeners) {
lc.managerDestroyed(this); // depends on control dependency: [for], data = [lc]
}
} catch (Throwable t) {
_suppressedExceptions.add(t);
} // depends on control dependency: [catch], data = [none]
((Cache2kCoreProviderImpl) PROVIDER).removeManager(this);
synchronized (lock) {
for (Cache c : cacheNames.values()) {
log.warn("unable to close cache: " + c.getName()); // depends on control dependency: [for], data = [c]
}
}
eventuallyThrowException(_suppressedExceptions);
cacheNames = null;
} } |
public class class_name {
@Override
public void declineCheckpoint(DeclineCheckpoint decline) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveDeclineMessage(decline);
} catch (Exception e) {
log.error("Error in CheckpointCoordinator while processing {}", decline, e);
}
});
} else {
String errorMessage = "Received DeclineCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID());
} else {
log.debug(errorMessage, jobGraph.getJobID());
}
}
} } | public class class_name {
@Override
public void declineCheckpoint(DeclineCheckpoint decline) {
final CheckpointCoordinator checkpointCoordinator = executionGraph.getCheckpointCoordinator();
if (checkpointCoordinator != null) {
getRpcService().execute(() -> {
try {
checkpointCoordinator.receiveDeclineMessage(decline); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.error("Error in CheckpointCoordinator while processing {}", decline, e);
} // depends on control dependency: [catch], data = [none]
});
} else {
String errorMessage = "Received DeclineCheckpoint message for job {} with no CheckpointCoordinator";
if (executionGraph.getState() == JobStatus.RUNNING) {
log.error(errorMessage, jobGraph.getJobID()); // depends on control dependency: [if], data = [none]
} else {
log.debug(errorMessage, jobGraph.getJobID()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public JavaFileObject writeClass(ClassSymbol c)
throws IOException, PoolOverflow, StringOverflow
{
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
c.flatname.toString(),
JavaFileObject.Kind.CLASS,
c.sourcefile);
OutputStream out = outFile.openOutputStream();
try {
writeClassFile(out, c);
if (verbose)
log.printVerbose("wrote.file", outFile);
out.close();
out = null;
} finally {
if (out != null) {
// if we are propagating an exception, delete the file
out.close();
outFile.delete();
outFile = null;
}
}
return outFile; // may be null if write failed
} } | public class class_name {
public JavaFileObject writeClass(ClassSymbol c)
throws IOException, PoolOverflow, StringOverflow
{
JavaFileObject outFile
= fileManager.getJavaFileForOutput(CLASS_OUTPUT,
c.flatname.toString(),
JavaFileObject.Kind.CLASS,
c.sourcefile);
OutputStream out = outFile.openOutputStream();
try {
writeClassFile(out, c);
if (verbose)
log.printVerbose("wrote.file", outFile);
out.close();
out = null;
} finally {
if (out != null) {
// if we are propagating an exception, delete the file
out.close(); // depends on control dependency: [if], data = [none]
outFile.delete(); // depends on control dependency: [if], data = [none]
outFile = null; // depends on control dependency: [if], data = [none]
}
}
return outFile; // may be null if write failed
} } |
public class class_name {
public ActionRuntime createActionRuntime(
final ActionHandler actionHandler,
final Class actionClass,
final Method actionClassMethod,
final Class<? extends ActionResult> actionResult,
final Class<? extends ActionResult> defaultActionResult,
final ActionFilter[] filters,
final ActionInterceptor[] interceptors,
final ActionDefinition actionDefinition,
final boolean async,
final boolean auth)
{
if (actionHandler != null) {
return new ActionRuntime(
actionHandler,
actionClass,
actionClassMethod,
filters,
interceptors,
actionDefinition,
NoneActionResult.class,
NoneActionResult.class,
async,
auth,
null,
null);
}
final ScopeData scopeData = scopeDataInspector.inspectClassScopes(actionClass);
// find ins and outs
final Class[] paramTypes = actionClassMethod.getParameterTypes();
final MethodParam[] params = new MethodParam[paramTypes.length];
final Annotation[][] paramAnns = actionClassMethod.getParameterAnnotations();
String[] methodParamNames = null;
// for all elements: action and method arguments...
for (int ndx = 0; ndx < paramTypes.length; ndx++) {
Class paramType = paramTypes[ndx];
// lazy init to postpone bytecode usage, when method has no arguments
if (methodParamNames == null) {
methodParamNames = actionMethodParamNameResolver.resolveParamNames(actionClassMethod);
}
final String paramName = methodParamNames[ndx];
final Annotation[] parameterAnnotations = paramAnns[ndx];
final ScopeData paramsScopeData = scopeDataInspector.inspectMethodParameterScopes(paramName, paramType, parameterAnnotations);
MapperFunction mapperFunction = null;
for (final Annotation annotation : parameterAnnotations) {
if (annotation instanceof Mapper) {
mapperFunction = MapperFunctionInstances.get().lookup(((Mapper) annotation).value());
break;
}
}
params[ndx] = new MethodParam(
paramTypes[ndx],
paramName,
scopeDataInspector.detectAnnotationType(parameterAnnotations),
paramsScopeData,
mapperFunction
);
}
return new ActionRuntime(
null,
actionClass,
actionClassMethod,
filters,
interceptors,
actionDefinition,
actionResult,
defaultActionResult,
async,
auth,
scopeData,
params);
} } | public class class_name {
public ActionRuntime createActionRuntime(
final ActionHandler actionHandler,
final Class actionClass,
final Method actionClassMethod,
final Class<? extends ActionResult> actionResult,
final Class<? extends ActionResult> defaultActionResult,
final ActionFilter[] filters,
final ActionInterceptor[] interceptors,
final ActionDefinition actionDefinition,
final boolean async,
final boolean auth)
{
if (actionHandler != null) {
return new ActionRuntime(
actionHandler,
actionClass,
actionClassMethod,
filters,
interceptors,
actionDefinition,
NoneActionResult.class,
NoneActionResult.class,
async,
auth,
null,
null); // depends on control dependency: [if], data = [none]
}
final ScopeData scopeData = scopeDataInspector.inspectClassScopes(actionClass);
// find ins and outs
final Class[] paramTypes = actionClassMethod.getParameterTypes();
final MethodParam[] params = new MethodParam[paramTypes.length];
final Annotation[][] paramAnns = actionClassMethod.getParameterAnnotations();
String[] methodParamNames = null;
// for all elements: action and method arguments...
for (int ndx = 0; ndx < paramTypes.length; ndx++) {
Class paramType = paramTypes[ndx];
// lazy init to postpone bytecode usage, when method has no arguments
if (methodParamNames == null) {
methodParamNames = actionMethodParamNameResolver.resolveParamNames(actionClassMethod); // depends on control dependency: [if], data = [none]
}
final String paramName = methodParamNames[ndx];
final Annotation[] parameterAnnotations = paramAnns[ndx];
final ScopeData paramsScopeData = scopeDataInspector.inspectMethodParameterScopes(paramName, paramType, parameterAnnotations);
MapperFunction mapperFunction = null;
for (final Annotation annotation : parameterAnnotations) {
if (annotation instanceof Mapper) {
mapperFunction = MapperFunctionInstances.get().lookup(((Mapper) annotation).value()); // depends on control dependency: [if], data = [none]
break;
}
}
params[ndx] = new MethodParam(
paramTypes[ndx],
paramName,
scopeDataInspector.detectAnnotationType(parameterAnnotations),
paramsScopeData,
mapperFunction
); // depends on control dependency: [for], data = [none]
}
return new ActionRuntime(
null,
actionClass,
actionClassMethod,
filters,
interceptors,
actionDefinition,
actionResult,
defaultActionResult,
async,
auth,
scopeData,
params);
} } |
public class class_name {
public InitiateMultipartUploadResponse initiateMultipartUpload(InitiateMultipartUploadRequest request) {
checkNotNull(request, "request should not be null.");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST);
internalRequest.addParameter("uploads", null);
if (request.getStorageClass() != null) {
internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass());
}
this.setZeroContentLength(internalRequest);
if (request.getObjectMetadata() != null) {
populateRequestMetadata(internalRequest, request.getObjectMetadata());
}
return this.invokeHttpClient(internalRequest, InitiateMultipartUploadResponse.class);
} } | public class class_name {
public InitiateMultipartUploadResponse initiateMultipartUpload(InitiateMultipartUploadRequest request) {
checkNotNull(request, "request should not be null.");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST);
internalRequest.addParameter("uploads", null);
if (request.getStorageClass() != null) {
internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass()); // depends on control dependency: [if], data = [none]
}
this.setZeroContentLength(internalRequest);
if (request.getObjectMetadata() != null) {
populateRequestMetadata(internalRequest, request.getObjectMetadata()); // depends on control dependency: [if], data = [none]
}
return this.invokeHttpClient(internalRequest, InitiateMultipartUploadResponse.class);
} } |
public class class_name {
private void doDocumentTypeDefinition(Node received, Node source,
XmlMessageValidationContext validationContext,
NamespaceContext namespaceContext, TestContext context) {
Assert.isTrue(source instanceof DocumentType, "Missing document type definition in expected xml fragment");
DocumentType receivedDTD = (DocumentType) received;
DocumentType sourceDTD = (DocumentType) source;
if (log.isDebugEnabled()) {
log.debug("Validating document type definition: " +
receivedDTD.getPublicId() + " (" + receivedDTD.getSystemId() + ")");
}
if (!StringUtils.hasText(sourceDTD.getPublicId())) {
Assert.isNull(receivedDTD.getPublicId(),
ValidationUtils.buildValueMismatchErrorMessage("Document type public id not equal",
sourceDTD.getPublicId(), receivedDTD.getPublicId()));
} else if (sourceDTD.getPublicId().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {
if (log.isDebugEnabled()) {
log.debug("Document type public id: '" + receivedDTD.getPublicId() +
"' is ignored by placeholder '" + Citrus.IGNORE_PLACEHOLDER + "'");
}
} else {
Assert.isTrue(StringUtils.hasText(receivedDTD.getPublicId()) &&
receivedDTD.getPublicId().equals(sourceDTD.getPublicId()),
ValidationUtils.buildValueMismatchErrorMessage("Document type public id not equal",
sourceDTD.getPublicId(), receivedDTD.getPublicId()));
}
if (!StringUtils.hasText(sourceDTD.getSystemId())) {
Assert.isNull(receivedDTD.getSystemId(),
ValidationUtils.buildValueMismatchErrorMessage("Document type system id not equal",
sourceDTD.getSystemId(), receivedDTD.getSystemId()));
} else if (sourceDTD.getSystemId().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {
if (log.isDebugEnabled()) {
log.debug("Document type system id: '" + receivedDTD.getSystemId() +
"' is ignored by placeholder '" + Citrus.IGNORE_PLACEHOLDER + "'");
}
} else {
Assert.isTrue(StringUtils.hasText(receivedDTD.getSystemId()) &&
receivedDTD.getSystemId().equals(sourceDTD.getSystemId()),
ValidationUtils.buildValueMismatchErrorMessage("Document type system id not equal",
sourceDTD.getSystemId(), receivedDTD.getSystemId()));
}
validateXmlTree(received.getNextSibling(),
source.getNextSibling(), validationContext, namespaceContext, context);
} } | public class class_name {
private void doDocumentTypeDefinition(Node received, Node source,
XmlMessageValidationContext validationContext,
NamespaceContext namespaceContext, TestContext context) {
Assert.isTrue(source instanceof DocumentType, "Missing document type definition in expected xml fragment");
DocumentType receivedDTD = (DocumentType) received;
DocumentType sourceDTD = (DocumentType) source;
if (log.isDebugEnabled()) {
log.debug("Validating document type definition: " +
receivedDTD.getPublicId() + " (" + receivedDTD.getSystemId() + ")");
}
if (!StringUtils.hasText(sourceDTD.getPublicId())) {
Assert.isNull(receivedDTD.getPublicId(),
ValidationUtils.buildValueMismatchErrorMessage("Document type public id not equal",
sourceDTD.getPublicId(), receivedDTD.getPublicId()));
} else if (sourceDTD.getPublicId().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {
if (log.isDebugEnabled()) {
log.debug("Document type public id: '" + receivedDTD.getPublicId() +
"' is ignored by placeholder '" + Citrus.IGNORE_PLACEHOLDER + "'");
}
} else {
Assert.isTrue(StringUtils.hasText(receivedDTD.getPublicId()) &&
receivedDTD.getPublicId().equals(sourceDTD.getPublicId()),
ValidationUtils.buildValueMismatchErrorMessage("Document type public id not equal",
sourceDTD.getPublicId(), receivedDTD.getPublicId()));
}
if (!StringUtils.hasText(sourceDTD.getSystemId())) {
Assert.isNull(receivedDTD.getSystemId(),
ValidationUtils.buildValueMismatchErrorMessage("Document type system id not equal",
sourceDTD.getSystemId(), receivedDTD.getSystemId()));
} else if (sourceDTD.getSystemId().trim().equals(Citrus.IGNORE_PLACEHOLDER)) {
if (log.isDebugEnabled()) {
log.debug("Document type system id: '" + receivedDTD.getSystemId() +
"' is ignored by placeholder '" + Citrus.IGNORE_PLACEHOLDER + "'");
}
} else {
Assert.isTrue(StringUtils.hasText(receivedDTD.getSystemId()) &&
receivedDTD.getSystemId().equals(sourceDTD.getSystemId()),
ValidationUtils.buildValueMismatchErrorMessage("Document type system id not equal",
sourceDTD.getSystemId(), receivedDTD.getSystemId()));
}
validateXmlTree(received.getNextSibling(),
source.getNextSibling(), validationContext, namespaceContext, context); // depends on control dependency: [if], data = [none]
} } |
public class class_name {
public static void setRotateM(float[] rm, int rmOffset,
float a, float x, float y, float z) {
rm[rmOffset + 3] = 0;
rm[rmOffset + 7] = 0;
rm[rmOffset + 11]= 0;
rm[rmOffset + 12]= 0;
rm[rmOffset + 13]= 0;
rm[rmOffset + 14]= 0;
rm[rmOffset + 15]= 1;
a *= (float) (Math.PI / 180.0f);
float s = (float) Math.sin(a);
float c = (float) Math.cos(a);
if (1.0f == x && 0.0f == y && 0.0f == z) {
rm[rmOffset + 5] = c; rm[rmOffset + 10]= c;
rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s;
rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0;
rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0;
rm[rmOffset + 0] = 1;
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
rm[rmOffset + 0] = c; rm[rmOffset + 10]= c;
rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s;
rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0;
rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0;
rm[rmOffset + 5] = 1;
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
rm[rmOffset + 0] = c; rm[rmOffset + 5] = c;
rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s;
rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0;
rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0;
rm[rmOffset + 10]= 1;
} else {
float len = length(x, y, z);
if (1.0f != len) {
float recipLen = 1.0f / len;
x *= recipLen;
y *= recipLen;
z *= recipLen;
}
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
rm[rmOffset + 0] = x*x*nc + c;
rm[rmOffset + 4] = xy*nc - zs;
rm[rmOffset + 8] = zx*nc + ys;
rm[rmOffset + 1] = xy*nc + zs;
rm[rmOffset + 5] = y*y*nc + c;
rm[rmOffset + 9] = yz*nc - xs;
rm[rmOffset + 2] = zx*nc - ys;
rm[rmOffset + 6] = yz*nc + xs;
rm[rmOffset + 10] = z*z*nc + c;
}
} } | public class class_name {
public static void setRotateM(float[] rm, int rmOffset,
float a, float x, float y, float z) {
rm[rmOffset + 3] = 0;
rm[rmOffset + 7] = 0;
rm[rmOffset + 11]= 0;
rm[rmOffset + 12]= 0;
rm[rmOffset + 13]= 0;
rm[rmOffset + 14]= 0;
rm[rmOffset + 15]= 1;
a *= (float) (Math.PI / 180.0f);
float s = (float) Math.sin(a);
float c = (float) Math.cos(a);
if (1.0f == x && 0.0f == y && 0.0f == z) {
rm[rmOffset + 5] = c; rm[rmOffset + 10]= c;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 6] = s; rm[rmOffset + 9] = -s;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 1] = 0; rm[rmOffset + 2] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 4] = 0; rm[rmOffset + 8] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 0] = 1;
// depends on control dependency: [if], data = [none]
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
rm[rmOffset + 0] = c; rm[rmOffset + 10]= c;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 8] = s; rm[rmOffset + 2] = -s;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 1] = 0; rm[rmOffset + 4] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 6] = 0; rm[rmOffset + 9] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 5] = 1;
// depends on control dependency: [if], data = [none]
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
rm[rmOffset + 0] = c; rm[rmOffset + 5] = c;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 1] = s; rm[rmOffset + 4] = -s;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 2] = 0; rm[rmOffset + 6] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 8] = 0; rm[rmOffset + 9] = 0;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
rm[rmOffset + 10]= 1;
// depends on control dependency: [if], data = [none]
} else {
float len = length(x, y, z);
if (1.0f != len) {
float recipLen = 1.0f / len;
x *= recipLen;
// depends on control dependency: [if], data = [none]
y *= recipLen;
// depends on control dependency: [if], data = [none]
z *= recipLen;
// depends on control dependency: [if], data = [none]
}
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
rm[rmOffset + 0] = x*x*nc + c;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 4] = xy*nc - zs;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 8] = zx*nc + ys;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 1] = xy*nc + zs;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 5] = y*y*nc + c;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 9] = yz*nc - xs;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 2] = zx*nc - ys;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 6] = yz*nc + xs;
// depends on control dependency: [if], data = [none]
rm[rmOffset + 10] = z*z*nc + c;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public TaxonomyTerm createTaxonomyTerm(final String taxonomy, final String name, final String slug,
final String description) throws SQLException {
Term term = createTerm(name, slug);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.createTaxonomyTermTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(insertTaxonomyTermSQL, Statement.RETURN_GENERATED_KEYS);
stmt.setLong(1, term.id);
stmt.setString(2, taxonomy);
stmt.setString(3, Strings.nullToEmpty(description));
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if(rs.next()) {
return new TaxonomyTerm(rs.getLong(1), taxonomy, term, description);
} else {
throw new SQLException("Problem creating taxonomy term (no generated id)");
}
} finally {
ctx.stop();
closeQuietly(conn, stmt, rs);
}
} } | public class class_name {
public TaxonomyTerm createTaxonomyTerm(final String taxonomy, final String name, final String slug,
final String description) throws SQLException {
Term term = createTerm(name, slug);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.createTaxonomyTermTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(insertTaxonomyTermSQL, Statement.RETURN_GENERATED_KEYS);
stmt.setLong(1, term.id);
stmt.setString(2, taxonomy);
stmt.setString(3, Strings.nullToEmpty(description));
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if(rs.next()) {
return new TaxonomyTerm(rs.getLong(1), taxonomy, term, description); // depends on control dependency: [if], data = [none]
} else {
throw new SQLException("Problem creating taxonomy term (no generated id)");
}
} finally {
ctx.stop();
closeQuietly(conn, stmt, rs);
}
} } |
public class class_name {
public static List<MediaType> valueOf(final String... types) throws Err.BadMediaType {
requireNonNull(types, "Types are required.");
List<MediaType> result = new ArrayList<>();
for (String type : types) {
result.add(valueOf(type));
}
return result;
} } | public class class_name {
public static List<MediaType> valueOf(final String... types) throws Err.BadMediaType {
requireNonNull(types, "Types are required.");
List<MediaType> result = new ArrayList<>();
for (String type : types) {
result.add(valueOf(type)); // depends on control dependency: [for], data = [type]
}
return result;
} } |
public class class_name {
public static <K, V> Map<K, V> zip(K[] keys, V[] values, boolean isOrder) {
if (isEmpty(keys) || isEmpty(values)) {
return null;
}
final int size = Math.min(keys.length, values.length);
final Map<K, V> map = CollectionUtil.newHashMap(size, isOrder);
for (int i = 0; i < size; i++) {
map.put(keys[i], values[i]);
}
return map;
} } | public class class_name {
public static <K, V> Map<K, V> zip(K[] keys, V[] values, boolean isOrder) {
if (isEmpty(keys) || isEmpty(values)) {
return null;
// depends on control dependency: [if], data = [none]
}
final int size = Math.min(keys.length, values.length);
final Map<K, V> map = CollectionUtil.newHashMap(size, isOrder);
for (int i = 0; i < size; i++) {
map.put(keys[i], values[i]);
// depends on control dependency: [for], data = [i]
}
return map;
} } |
public class class_name {
public static int findRowIdColumnIndex(String[] columnNames) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
if (columnNames[i].equals("_id")) {
return i;
}
}
return -1;
} } | public class class_name {
public static int findRowIdColumnIndex(String[] columnNames) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
if (columnNames[i].equals("_id")) {
return i; // depends on control dependency: [if], data = [none]
}
}
return -1;
} } |
public class class_name {
public int size() {
int ret = anyMethodRouter.size();
for (MethodlessRouter<T> router : routers.values()) {
ret += router.size();
}
return ret;
} } | public class class_name {
public int size() {
int ret = anyMethodRouter.size();
for (MethodlessRouter<T> router : routers.values()) {
ret += router.size(); // depends on control dependency: [for], data = [router]
}
return ret;
} } |
public class class_name {
@Override
public int compareTo(ChronoZonedDateTime<?> other) {
int cmp = Jdk8Methods.compareLongs(toEpochSecond(), other.toEpochSecond());
if (cmp == 0) {
cmp = toLocalTime().getNano() - other.toLocalTime().getNano();
if (cmp == 0) {
cmp = toLocalDateTime().compareTo(other.toLocalDateTime());
if (cmp == 0) {
cmp = getZone().getId().compareTo(other.getZone().getId());
if (cmp == 0) {
cmp = toLocalDate().getChronology().compareTo(other.toLocalDate().getChronology());
}
}
}
}
return cmp;
} } | public class class_name {
@Override
public int compareTo(ChronoZonedDateTime<?> other) {
int cmp = Jdk8Methods.compareLongs(toEpochSecond(), other.toEpochSecond());
if (cmp == 0) {
cmp = toLocalTime().getNano() - other.toLocalTime().getNano(); // depends on control dependency: [if], data = [none]
if (cmp == 0) {
cmp = toLocalDateTime().compareTo(other.toLocalDateTime()); // depends on control dependency: [if], data = [none]
if (cmp == 0) {
cmp = getZone().getId().compareTo(other.getZone().getId()); // depends on control dependency: [if], data = [none]
if (cmp == 0) {
cmp = toLocalDate().getChronology().compareTo(other.toLocalDate().getChronology()); // depends on control dependency: [if], data = [none]
}
}
}
}
return cmp;
} } |
public class class_name {
public Record makeRecordFromRecordName(String strRecordName, RecordOwner recordOwner)
{
int iOldKeyArea = this.getDefaultOrder();
try {
this.addNew();
this.setKeyArea(ContactType.CODE_KEY);
this.getField(ContactType.CODE).setString(strRecordName);
if (this.seek(DBConstants.EQUALS))
return this.makeContactRecord(recordOwner);
} catch (DBException ex) {
this.setKeyArea(iOldKeyArea);
}
return null;
} } | public class class_name {
public Record makeRecordFromRecordName(String strRecordName, RecordOwner recordOwner)
{
int iOldKeyArea = this.getDefaultOrder();
try {
this.addNew(); // depends on control dependency: [try], data = [none]
this.setKeyArea(ContactType.CODE_KEY); // depends on control dependency: [try], data = [none]
this.getField(ContactType.CODE).setString(strRecordName); // depends on control dependency: [try], data = [none]
if (this.seek(DBConstants.EQUALS))
return this.makeContactRecord(recordOwner);
} catch (DBException ex) {
this.setKeyArea(iOldKeyArea);
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
@Requires("pathName != null")
@Ensures("result != null")
public static String getPackageName(String pathName) {
int lastSep = pathName.lastIndexOf('.');
if (lastSep == -1) {
return "";
} else {
return pathName.substring(0, lastSep);
}
} } | public class class_name {
@Requires("pathName != null")
@Ensures("result != null")
public static String getPackageName(String pathName) {
int lastSep = pathName.lastIndexOf('.');
if (lastSep == -1) {
return ""; // depends on control dependency: [if], data = [none]
} else {
return pathName.substring(0, lastSep); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private <T> void addClass(Set<Class<? extends T>> classes,
String includeRegExp,
String className,
Class<T> ofType,
Class<? extends Annotation> annotationClass) {
if (className.matches(includeRegExp)) {
try {
Class<?> matchingClass = Class.forName(className);
matchingClass.asSubclass(ofType);
classes.add((Class<T>) matchingClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Scannotation found a class that does not exist " + className + " !", cnfe);
} catch (ClassCastException cce) {
throw new IllegalStateException("Class " + className
+ " is annoted with @"+annotationClass+" but does not extend or implement "+ofType);
}
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private <T> void addClass(Set<Class<? extends T>> classes,
String includeRegExp,
String className,
Class<T> ofType,
Class<? extends Annotation> annotationClass) {
if (className.matches(includeRegExp)) {
try {
Class<?> matchingClass = Class.forName(className);
matchingClass.asSubclass(ofType);
classes.add((Class<T>) matchingClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Scannotation found a class that does not exist " + className + " !", cnfe);
} catch (ClassCastException cce) { // depends on control dependency: [catch], data = [none]
throw new IllegalStateException("Class " + className
+ " is annoted with @"+annotationClass+" but does not extend or implement "+ofType);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private double snapToResolution(double scale, ZoomOption option) {
// clip upper bounds
double allowedScale = limitScale(scale);
if (resolutions != null) {
IndexRange indices = getResolutionRange();
if (option == ZoomOption.EXACT || !indices.isValid()) {
// should not or cannot snap to resolutions
return allowedScale;
} else {
// find the new index
int newResolutionIndex = 0;
double screenResolution = 1.0 / allowedScale;
if (screenResolution >= resolutions.get(indices.getMin())) {
newResolutionIndex = indices.getMin();
} else if (screenResolution <= resolutions.get(indices.getMax())) {
newResolutionIndex = indices.getMax();
} else {
for (int i = indices.getMin(); i < indices.getMax(); i++) {
double upper = resolutions.get(i);
double lower = resolutions.get(i + 1);
if (screenResolution <= upper && screenResolution > lower) {
if (option == ZoomOption.LEVEL_FIT) {
newResolutionIndex = i;
break;
} else {
if ((upper / screenResolution) > (screenResolution / lower)) {
newResolutionIndex = i + 1;
break;
} else {
newResolutionIndex = i;
break;
}
}
}
}
}
// check if we need to change level
if (newResolutionIndex == resolutionIndex && option == ZoomOption.LEVEL_CHANGE) {
if (scale > viewState.getScale() && newResolutionIndex < indices.getMax()) {
newResolutionIndex++;
} else if (scale < viewState.getScale() && newResolutionIndex > indices.getMin()) {
newResolutionIndex--;
}
}
resolutionIndex = newResolutionIndex;
return 1.0 / resolutions.get(resolutionIndex);
}
} else {
return scale;
}
} } | public class class_name {
private double snapToResolution(double scale, ZoomOption option) {
// clip upper bounds
double allowedScale = limitScale(scale);
if (resolutions != null) {
IndexRange indices = getResolutionRange();
if (option == ZoomOption.EXACT || !indices.isValid()) {
// should not or cannot snap to resolutions
return allowedScale; // depends on control dependency: [if], data = [none]
} else {
// find the new index
int newResolutionIndex = 0;
double screenResolution = 1.0 / allowedScale;
if (screenResolution >= resolutions.get(indices.getMin())) {
newResolutionIndex = indices.getMin(); // depends on control dependency: [if], data = [none]
} else if (screenResolution <= resolutions.get(indices.getMax())) {
newResolutionIndex = indices.getMax(); // depends on control dependency: [if], data = [none]
} else {
for (int i = indices.getMin(); i < indices.getMax(); i++) {
double upper = resolutions.get(i);
double lower = resolutions.get(i + 1);
if (screenResolution <= upper && screenResolution > lower) {
if (option == ZoomOption.LEVEL_FIT) {
newResolutionIndex = i; // depends on control dependency: [if], data = [none]
break;
} else {
if ((upper / screenResolution) > (screenResolution / lower)) {
newResolutionIndex = i + 1; // depends on control dependency: [if], data = [none]
break;
} else {
newResolutionIndex = i; // depends on control dependency: [if], data = [none]
break;
}
}
}
}
}
// check if we need to change level
if (newResolutionIndex == resolutionIndex && option == ZoomOption.LEVEL_CHANGE) {
if (scale > viewState.getScale() && newResolutionIndex < indices.getMax()) {
newResolutionIndex++; // depends on control dependency: [if], data = [none]
} else if (scale < viewState.getScale() && newResolutionIndex > indices.getMin()) {
newResolutionIndex--; // depends on control dependency: [if], data = [none]
}
}
resolutionIndex = newResolutionIndex; // depends on control dependency: [if], data = [none]
return 1.0 / resolutions.get(resolutionIndex); // depends on control dependency: [if], data = [none]
}
} else {
return scale; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)
{
boolean result = false;
net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);
if (type == null)
{
type = net.sf.mpxj.DayType.DEFAULT;
}
switch (type)
{
case WORKING:
{
result = true;
break;
}
case NON_WORKING:
{
result = false;
break;
}
case DEFAULT:
{
if (mpxjCalendar.getParent() == null)
{
result = false;
}
else
{
result = isWorkingDay(mpxjCalendar.getParent(), day);
}
break;
}
}
return (result);
} } | public class class_name {
private boolean isWorkingDay(ProjectCalendar mpxjCalendar, Day day)
{
boolean result = false;
net.sf.mpxj.DayType type = mpxjCalendar.getWorkingDay(day);
if (type == null)
{
type = net.sf.mpxj.DayType.DEFAULT; // depends on control dependency: [if], data = [none]
}
switch (type)
{
case WORKING:
{
result = true;
break;
}
case NON_WORKING:
{
result = false;
break;
}
case DEFAULT:
{
if (mpxjCalendar.getParent() == null)
{
result = false;
}
else
{
result = isWorkingDay(mpxjCalendar.getParent(), day);
}
break;
}
}
return (result);
} } |
public class class_name {
@Override
public ManagedChannelImpl shutdown() {
channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
if (!shutdown.compareAndSet(false, true)) {
return this;
}
// Put gotoState(SHUTDOWN) as early into the syncContext's queue as possible.
// delayedTransport.shutdown() may also add some tasks into the queue. But some things inside
// delayedTransport.shutdown() like setting delayedTransport.shutdown = true are not run in the
// syncContext's queue and should not be blocked, so we do not drain() immediately here.
final class Shutdown implements Runnable {
@Override
public void run() {
channelLogger.log(ChannelLogLevel.INFO, "Entering SHUTDOWN state");
channelStateManager.gotoState(SHUTDOWN);
}
}
syncContext.executeLater(new Shutdown());
uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
final class CancelIdleTimer implements Runnable {
@Override
public void run() {
cancelIdleTimer(/* permanent= */ true);
}
}
syncContext.execute(new CancelIdleTimer());
return this;
} } | public class class_name {
@Override
public ManagedChannelImpl shutdown() {
channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
if (!shutdown.compareAndSet(false, true)) {
return this; // depends on control dependency: [if], data = [none]
}
// Put gotoState(SHUTDOWN) as early into the syncContext's queue as possible.
// delayedTransport.shutdown() may also add some tasks into the queue. But some things inside
// delayedTransport.shutdown() like setting delayedTransport.shutdown = true are not run in the
// syncContext's queue and should not be blocked, so we do not drain() immediately here.
final class Shutdown implements Runnable {
@Override
public void run() {
channelLogger.log(ChannelLogLevel.INFO, "Entering SHUTDOWN state");
channelStateManager.gotoState(SHUTDOWN);
}
}
syncContext.executeLater(new Shutdown());
uncommittedRetriableStreamsRegistry.onShutdown(SHUTDOWN_STATUS);
final class CancelIdleTimer implements Runnable {
@Override
public void run() {
cancelIdleTimer(/* permanent= */ true);
}
}
syncContext.execute(new CancelIdleTimer());
return this;
} } |
public class class_name {
public Integer delInfoByIdListService(List<String> idList,String tableName){
int status=0;
String tempDbType=calcuDbType();
String tempKeyId=calcuIdKey();
for(String id:idList){
int retStatus=getInnerDao().delObjByBizId(tableName, id, tempKeyId);
status=status+retStatus;
}
return status;
} } | public class class_name {
public Integer delInfoByIdListService(List<String> idList,String tableName){
int status=0;
String tempDbType=calcuDbType();
String tempKeyId=calcuIdKey();
for(String id:idList){
int retStatus=getInnerDao().delObjByBizId(tableName, id, tempKeyId);
status=status+retStatus;
// depends on control dependency: [for], data = [none]
}
return status;
} } |
public class class_name {
protected void updateDeploymentRepository(DeploymentRepository value, String xmlTag, Counter counter,
Element element)
{
boolean shouldExist = value != null;
Element root = updateElement(counter, element, xmlTag, shouldExist);
if (shouldExist)
{
Counter innerCount = new Counter(counter.getDepth() + 1);
findAndReplaceSimpleElement(innerCount, root, "uniqueVersion",
(value.isUniqueVersion() == true) ? null : String.valueOf(value.isUniqueVersion()), "true");
findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null);
findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null);
findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null);
findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default");
}
} } | public class class_name {
protected void updateDeploymentRepository(DeploymentRepository value, String xmlTag, Counter counter,
Element element)
{
boolean shouldExist = value != null;
Element root = updateElement(counter, element, xmlTag, shouldExist);
if (shouldExist)
{
Counter innerCount = new Counter(counter.getDepth() + 1);
findAndReplaceSimpleElement(innerCount, root, "uniqueVersion",
(value.isUniqueVersion() == true) ? null : String.valueOf(value.isUniqueVersion()), "true"); // depends on control dependency: [if], data = [none]
findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); // depends on control dependency: [if], data = [none]
findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); // depends on control dependency: [if], data = [none]
findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); // depends on control dependency: [if], data = [none]
findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ApplicationSummary applicationSummary, ProtocolMarshaller protocolMarshaller) {
if (applicationSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(applicationSummary.getApplicationName(), APPLICATIONNAME_BINDING);
protocolMarshaller.marshall(applicationSummary.getApplicationARN(), APPLICATIONARN_BINDING);
protocolMarshaller.marshall(applicationSummary.getApplicationStatus(), APPLICATIONSTATUS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ApplicationSummary applicationSummary, ProtocolMarshaller protocolMarshaller) {
if (applicationSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(applicationSummary.getApplicationName(), APPLICATIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(applicationSummary.getApplicationARN(), APPLICATIONARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(applicationSummary.getApplicationStatus(), APPLICATIONSTATUS_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 java.util.List<Category> getCategories() {
if (categories == null) {
categories = new com.amazonaws.internal.SdkInternalList<Category>();
}
return categories;
} } | public class class_name {
public java.util.List<Category> getCategories() {
if (categories == null) {
categories = new com.amazonaws.internal.SdkInternalList<Category>(); // depends on control dependency: [if], data = [none]
}
return categories;
} } |
public class class_name {
private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
// Resolve MBean server instance
GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
if (!jmxConfig.enabled())
return;
if (mbeanServer == null) {
mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties());
}
// Resolve jmx domain to use for query MBeans
String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);
// Register query statistics MBean, but only enable it if Infinispan config says so
try {
ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");
InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());
JmxUtil.registerMBean(stats, statsObjName, mbeanServer);
cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class);
} catch (Exception e) {
throw new CacheException("Unable to register query statistics MBean", e);
}
// Register mass indexer MBean, picking metadata from repo
ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
.findComponentMetadata(MassIndexer.class)
.toManageableComponentMetadata();
try {
KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
// TODO: MassIndexer should be some kind of query cache component?
DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
+ queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
} catch (Exception e) {
throw new CacheException("Unable to create MassIndexer MBean", e);
}
} } | public class class_name {
private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
// Resolve MBean server instance
GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
if (!jmxConfig.enabled())
return;
if (mbeanServer == null) {
mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties()); // depends on control dependency: [if], data = [none]
}
// Resolve jmx domain to use for query MBeans
String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);
// Register query statistics MBean, but only enable it if Infinispan config says so
try {
ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");
InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
stats.setStatisticsEnabled(cfg.jmxStatistics().enabled()); // depends on control dependency: [try], data = [none]
JmxUtil.registerMBean(stats, statsObjName, mbeanServer); // depends on control dependency: [try], data = [none]
cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new CacheException("Unable to register query statistics MBean", e);
} // depends on control dependency: [catch], data = [none]
// Register mass indexer MBean, picking metadata from repo
ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
.findComponentMetadata(MassIndexer.class)
.toManageableComponentMetadata();
try {
KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
// TODO: MassIndexer should be some kind of query cache component?
DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
+ queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new CacheException("Unable to create MassIndexer MBean", e);
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.