code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public Observable<ServiceResponse<List<Image>>> getUntaggedImagesWithServiceResponseAsync(UUID projectId, UUID iterationId, String orderBy, Integer take, Integer skip) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
return service.getUntaggedImages(projectId, iterationId, orderBy, take, skip, this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Image>>>>() {
@Override
public Observable<ServiceResponse<List<Image>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<Image>> clientResponse = getUntaggedImagesDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<List<Image>>> getUntaggedImagesWithServiceResponseAsync(UUID projectId, UUID iterationId, String orderBy, Integer take, Integer skip) {
if (projectId == null) {
throw new IllegalArgumentException("Parameter projectId is required and cannot be null.");
}
if (this.client.apiKey() == null) {
throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null.");
}
return service.getUntaggedImages(projectId, iterationId, orderBy, take, skip, this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Image>>>>() {
@Override
public Observable<ServiceResponse<List<Image>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<Image>> clientResponse = getUntaggedImagesDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public FacesConfigFacetType<FacesConfigRendererType<T>> getOrCreateFacet()
{
List<Node> nodeList = childNode.get("facet");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigFacetTypeImpl<FacesConfigRendererType<T>>(this, "facet", childNode, nodeList.get(0));
}
return createFacet();
} } | public class class_name {
public FacesConfigFacetType<FacesConfigRendererType<T>> getOrCreateFacet()
{
List<Node> nodeList = childNode.get("facet");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigFacetTypeImpl<FacesConfigRendererType<T>>(this, "facet", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createFacet();
} } |
public class class_name {
private static AxesWalker createDefaultWalker(Compiler compiler, int opPos,
WalkingIterator lpi, int analysis)
{
AxesWalker ai = null;
int stepType = compiler.getOp(opPos);
/*
System.out.println("0: "+compiler.getOp(opPos));
System.out.println("1: "+compiler.getOp(opPos+1));
System.out.println("2: "+compiler.getOp(opPos+2));
System.out.println("3: "+compiler.getOp(opPos+3));
System.out.println("4: "+compiler.getOp(opPos+4));
System.out.println("5: "+compiler.getOp(opPos+5));
*/
boolean simpleInit = false;
int totalNumberWalkers = (analysis & BITS_COUNT);
boolean prevIsOneStepDown = true;
switch (stepType)
{
case OpCodes.OP_VARIABLE :
case OpCodes.OP_EXTFUNCTION :
case OpCodes.OP_FUNCTION :
case OpCodes.OP_GROUP :
prevIsOneStepDown = false;
if (DEBUG_WALKER_CREATION)
System.out.println("new walker: FilterExprWalker: " + analysis
+ ", " + compiler.toString());
ai = new FilterExprWalker(lpi);
simpleInit = true;
break;
case OpCodes.FROM_ROOT :
ai = new AxesWalker(lpi, Axis.ROOT);
break;
case OpCodes.FROM_ANCESTORS :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.ANCESTOR);
break;
case OpCodes.FROM_ANCESTORS_OR_SELF :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.ANCESTORORSELF);
break;
case OpCodes.FROM_ATTRIBUTES :
ai = new AxesWalker(lpi, Axis.ATTRIBUTE);
break;
case OpCodes.FROM_NAMESPACE :
ai = new AxesWalker(lpi, Axis.NAMESPACE);
break;
case OpCodes.FROM_CHILDREN :
ai = new AxesWalker(lpi, Axis.CHILD);
break;
case OpCodes.FROM_DESCENDANTS :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.DESCENDANT);
break;
case OpCodes.FROM_DESCENDANTS_OR_SELF :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.DESCENDANTORSELF);
break;
case OpCodes.FROM_FOLLOWING :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.FOLLOWING);
break;
case OpCodes.FROM_FOLLOWING_SIBLINGS :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.FOLLOWINGSIBLING);
break;
case OpCodes.FROM_PRECEDING :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PRECEDING);
break;
case OpCodes.FROM_PRECEDING_SIBLINGS :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PRECEDINGSIBLING);
break;
case OpCodes.FROM_PARENT :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PARENT);
break;
case OpCodes.FROM_SELF :
ai = new AxesWalker(lpi, Axis.SELF);
break;
default :
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NULL_ERROR_HANDLER, new Object[]{Integer.toString(stepType)})); //"Programmer's assertion: unknown opcode: "
//+ stepType);
}
if (simpleInit)
{
ai.initNodeTest(DTMFilter.SHOW_ALL);
}
else
{
int whatToShow = compiler.getWhatToShow(opPos);
/*
System.out.print("construct: ");
NodeTest.debugWhatToShow(whatToShow);
System.out.println("or stuff: "+(whatToShow & (DTMFilter.SHOW_ATTRIBUTE
| DTMFilter.SHOW_ELEMENT
| DTMFilter.SHOW_PROCESSING_INSTRUCTION)));
*/
if ((0 == (whatToShow
& (DTMFilter.SHOW_ATTRIBUTE | DTMFilter.SHOW_NAMESPACE | DTMFilter.SHOW_ELEMENT
| DTMFilter.SHOW_PROCESSING_INSTRUCTION))) || (whatToShow == DTMFilter.SHOW_ALL))
ai.initNodeTest(whatToShow);
else
{
ai.initNodeTest(whatToShow, compiler.getStepNS(opPos),
compiler.getStepLocalName(opPos));
}
}
return ai;
} } | public class class_name {
private static AxesWalker createDefaultWalker(Compiler compiler, int opPos,
WalkingIterator lpi, int analysis)
{
AxesWalker ai = null;
int stepType = compiler.getOp(opPos);
/*
System.out.println("0: "+compiler.getOp(opPos));
System.out.println("1: "+compiler.getOp(opPos+1));
System.out.println("2: "+compiler.getOp(opPos+2));
System.out.println("3: "+compiler.getOp(opPos+3));
System.out.println("4: "+compiler.getOp(opPos+4));
System.out.println("5: "+compiler.getOp(opPos+5));
*/
boolean simpleInit = false;
int totalNumberWalkers = (analysis & BITS_COUNT);
boolean prevIsOneStepDown = true;
switch (stepType)
{
case OpCodes.OP_VARIABLE :
case OpCodes.OP_EXTFUNCTION :
case OpCodes.OP_FUNCTION :
case OpCodes.OP_GROUP :
prevIsOneStepDown = false;
if (DEBUG_WALKER_CREATION)
System.out.println("new walker: FilterExprWalker: " + analysis
+ ", " + compiler.toString());
ai = new FilterExprWalker(lpi);
simpleInit = true;
break;
case OpCodes.FROM_ROOT :
ai = new AxesWalker(lpi, Axis.ROOT);
break;
case OpCodes.FROM_ANCESTORS :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.ANCESTOR);
break;
case OpCodes.FROM_ANCESTORS_OR_SELF :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.ANCESTORORSELF);
break;
case OpCodes.FROM_ATTRIBUTES :
ai = new AxesWalker(lpi, Axis.ATTRIBUTE);
break;
case OpCodes.FROM_NAMESPACE :
ai = new AxesWalker(lpi, Axis.NAMESPACE);
break;
case OpCodes.FROM_CHILDREN :
ai = new AxesWalker(lpi, Axis.CHILD);
break;
case OpCodes.FROM_DESCENDANTS :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.DESCENDANT);
break;
case OpCodes.FROM_DESCENDANTS_OR_SELF :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.DESCENDANTORSELF);
break;
case OpCodes.FROM_FOLLOWING :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.FOLLOWING);
break;
case OpCodes.FROM_FOLLOWING_SIBLINGS :
prevIsOneStepDown = false;
ai = new AxesWalker(lpi, Axis.FOLLOWINGSIBLING);
break;
case OpCodes.FROM_PRECEDING :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PRECEDING);
break;
case OpCodes.FROM_PRECEDING_SIBLINGS :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PRECEDINGSIBLING);
break;
case OpCodes.FROM_PARENT :
prevIsOneStepDown = false;
ai = new ReverseAxesWalker(lpi, Axis.PARENT);
break;
case OpCodes.FROM_SELF :
ai = new AxesWalker(lpi, Axis.SELF);
break;
default :
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NULL_ERROR_HANDLER, new Object[]{Integer.toString(stepType)})); //"Programmer's assertion: unknown opcode: "
//+ stepType);
}
if (simpleInit)
{
ai.initNodeTest(DTMFilter.SHOW_ALL); // depends on control dependency: [if], data = [none]
}
else
{
int whatToShow = compiler.getWhatToShow(opPos);
/*
System.out.print("construct: ");
NodeTest.debugWhatToShow(whatToShow);
System.out.println("or stuff: "+(whatToShow & (DTMFilter.SHOW_ATTRIBUTE
| DTMFilter.SHOW_ELEMENT
| DTMFilter.SHOW_PROCESSING_INSTRUCTION)));
*/
if ((0 == (whatToShow
& (DTMFilter.SHOW_ATTRIBUTE | DTMFilter.SHOW_NAMESPACE | DTMFilter.SHOW_ELEMENT
| DTMFilter.SHOW_PROCESSING_INSTRUCTION))) || (whatToShow == DTMFilter.SHOW_ALL))
ai.initNodeTest(whatToShow);
else
{
ai.initNodeTest(whatToShow, compiler.getStepNS(opPos),
compiler.getStepLocalName(opPos)); // depends on control dependency: [if], data = [(whatToShow]
}
}
return ai;
} } |
public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void remove() {
super.remove();
for (VariableInstanceEntity variableInstance : variableStore.getVariables()) {
invokeVariableLifecycleListenersDelete(variableInstance, this,
Arrays.<VariableInstanceLifecycleListener<CoreVariableInstance>>asList((VariableInstanceLifecycleListener) VariableInstanceEntityPersistenceListener.INSTANCE));
variableStore.removeVariable(variableInstance.getName());
}
CommandContext commandContext = Context.getCommandContext();
for (CaseSentryPartEntity sentryPart : getCaseSentryParts()) {
commandContext
.getCaseSentryPartManager()
.deleteSentryPart(sentryPart);
}
// finally delete this execution
commandContext
.getCaseExecutionManager()
.deleteCaseExecution(this);
} } | public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void remove() {
super.remove();
for (VariableInstanceEntity variableInstance : variableStore.getVariables()) {
invokeVariableLifecycleListenersDelete(variableInstance, this,
Arrays.<VariableInstanceLifecycleListener<CoreVariableInstance>>asList((VariableInstanceLifecycleListener) VariableInstanceEntityPersistenceListener.INSTANCE)); // depends on control dependency: [for], data = [variableInstance]
variableStore.removeVariable(variableInstance.getName()); // depends on control dependency: [for], data = [variableInstance]
}
CommandContext commandContext = Context.getCommandContext();
for (CaseSentryPartEntity sentryPart : getCaseSentryParts()) {
commandContext
.getCaseSentryPartManager()
.deleteSentryPart(sentryPart); // depends on control dependency: [for], data = [none]
}
// finally delete this execution
commandContext
.getCaseExecutionManager()
.deleteCaseExecution(this);
} } |
public class class_name {
public static Link parse(String origin, String link, boolean allowModuleName) {
String originMod = origin;
int index = link.indexOf('#');
if (index == -1) {
if (allowModuleName) {
index = link.lastIndexOf('/');
if (index == -1) {
return new Link(null, null, link);
}
return new Link(null, link.substring(0, index), link.substring(index + 1));
}
return new Link(null, null, link);
}
String name = link.substring(index + 1);
String uri = link.substring(0, index);
if (originMod == null) {
originMod = "";
} else {
index = originMod.lastIndexOf('/');
originMod = index == -1 ? "" : originMod.substring(0, index);
}
if (uri.startsWith("../")) {
uri = uri.substring(3);
}
while (uri.startsWith("../")) {
index = originMod.lastIndexOf('/');
if (index == -1) {
originMod = "";
} else {
originMod = originMod.substring(0, index);
}
uri = uri.substring(3);
}
return new Link(originMod.isEmpty() ? uri : originMod + '/' + uri, null, name);
} } | public class class_name {
public static Link parse(String origin, String link, boolean allowModuleName) {
String originMod = origin;
int index = link.indexOf('#');
if (index == -1) {
if (allowModuleName) {
index = link.lastIndexOf('/'); // depends on control dependency: [if], data = [none]
if (index == -1) {
return new Link(null, null, link); // depends on control dependency: [if], data = [none]
}
return new Link(null, link.substring(0, index), link.substring(index + 1)); // depends on control dependency: [if], data = [none]
}
return new Link(null, null, link); // depends on control dependency: [if], data = [none]
}
String name = link.substring(index + 1);
String uri = link.substring(0, index);
if (originMod == null) {
originMod = ""; // depends on control dependency: [if], data = [none]
} else {
index = originMod.lastIndexOf('/'); // depends on control dependency: [if], data = [none]
originMod = index == -1 ? "" : originMod.substring(0, index); // depends on control dependency: [if], data = [none]
}
if (uri.startsWith("../")) {
uri = uri.substring(3); // depends on control dependency: [if], data = [none]
}
while (uri.startsWith("../")) {
index = originMod.lastIndexOf('/'); // depends on control dependency: [while], data = [none]
if (index == -1) {
originMod = ""; // depends on control dependency: [if], data = [none]
} else {
originMod = originMod.substring(0, index); // depends on control dependency: [if], data = [none]
}
uri = uri.substring(3); // depends on control dependency: [while], data = [none]
}
return new Link(originMod.isEmpty() ? uri : originMod + '/' + uri, null, name);
} } |
public class class_name {
public Set<String> getParameterNames(Set<String> allParameterNames)
{
Set<String> names = new HashSet<String>();
for (String propertyName : allParameterNames)
{
int index = propertyNameMatchIndex(propertyName);
if (index > 0)
{
names.add(propertyName.substring(index));
}
}
return names;
} } | public class class_name {
public Set<String> getParameterNames(Set<String> allParameterNames)
{
Set<String> names = new HashSet<String>();
for (String propertyName : allParameterNames)
{
int index = propertyNameMatchIndex(propertyName);
if (index > 0)
{
names.add(propertyName.substring(index)); // depends on control dependency: [if], data = [(index]
}
}
return names;
} } |
public class class_name {
public void newSaturate(IAtomContainer atomContainer) throws CDKException {
logger.info("Saturating atomContainer by adjusting bond orders...");
boolean allSaturated = allSaturated(atomContainer);
if (!allSaturated) {
IBond[] bonds = new IBond[atomContainer.getBondCount()];
for (int i = 0; i < bonds.length; i++)
bonds[i] = atomContainer.getBond(i);
boolean succeeded = newSaturate(bonds, atomContainer);
for (int i = 0; i < bonds.length; i++) {
if (bonds[i].getOrder() == IBond.Order.DOUBLE && bonds[i].getFlag(CDKConstants.ISAROMATIC)
&& (bonds[i].getBegin().getSymbol().equals("N") && bonds[i].getEnd().getSymbol().equals("N"))) {
int atomtohandle = 0;
if (bonds[i].getBegin().getSymbol().equals("N")) atomtohandle = 1;
List<IBond> bondstohandle = atomContainer.getConnectedBondsList(bonds[i].getAtom(atomtohandle));
for (int k = 0; k < bondstohandle.size(); k++) {
IBond bond = bondstohandle.get(k);
if (bond.getOrder() == IBond.Order.SINGLE && bond.getFlag(CDKConstants.ISAROMATIC)) {
bond.setOrder(IBond.Order.DOUBLE);
bonds[i].setOrder(IBond.Order.SINGLE);
break;
}
}
}
}
if (!succeeded) {
throw new CDKException("Could not saturate this atomContainer!");
}
}
} } | public class class_name {
public void newSaturate(IAtomContainer atomContainer) throws CDKException {
logger.info("Saturating atomContainer by adjusting bond orders...");
boolean allSaturated = allSaturated(atomContainer);
if (!allSaturated) {
IBond[] bonds = new IBond[atomContainer.getBondCount()];
for (int i = 0; i < bonds.length; i++)
bonds[i] = atomContainer.getBond(i);
boolean succeeded = newSaturate(bonds, atomContainer);
for (int i = 0; i < bonds.length; i++) {
if (bonds[i].getOrder() == IBond.Order.DOUBLE && bonds[i].getFlag(CDKConstants.ISAROMATIC)
&& (bonds[i].getBegin().getSymbol().equals("N") && bonds[i].getEnd().getSymbol().equals("N"))) {
int atomtohandle = 0;
if (bonds[i].getBegin().getSymbol().equals("N")) atomtohandle = 1;
List<IBond> bondstohandle = atomContainer.getConnectedBondsList(bonds[i].getAtom(atomtohandle));
for (int k = 0; k < bondstohandle.size(); k++) {
IBond bond = bondstohandle.get(k);
if (bond.getOrder() == IBond.Order.SINGLE && bond.getFlag(CDKConstants.ISAROMATIC)) {
bond.setOrder(IBond.Order.DOUBLE); // depends on control dependency: [if], data = [none]
bonds[i].setOrder(IBond.Order.SINGLE); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
if (!succeeded) {
throw new CDKException("Could not saturate this atomContainer!");
}
}
} } |
public class class_name {
public void marshall(GetAggregateComplianceDetailsByConfigRuleRequest getAggregateComplianceDetailsByConfigRuleRequest,
ProtocolMarshaller protocolMarshaller) {
if (getAggregateComplianceDetailsByConfigRuleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getConfigurationAggregatorName(), CONFIGURATIONAGGREGATORNAME_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getConfigRuleName(), CONFIGRULENAME_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getAccountId(), ACCOUNTID_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getAwsRegion(), AWSREGION_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getComplianceType(), COMPLIANCETYPE_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetAggregateComplianceDetailsByConfigRuleRequest getAggregateComplianceDetailsByConfigRuleRequest,
ProtocolMarshaller protocolMarshaller) {
if (getAggregateComplianceDetailsByConfigRuleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getConfigurationAggregatorName(), CONFIGURATIONAGGREGATORNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getConfigRuleName(), CONFIGRULENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getAccountId(), ACCOUNTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getAwsRegion(), AWSREGION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getComplianceType(), COMPLIANCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getAggregateComplianceDetailsByConfigRuleRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void append2slow( ) {
// PUBDEV-2639 - don't die for many rows, few columns -> can be long chunks
// if( _sparseLen > FileVec.DFLT_CHUNK_SIZE )
// throw new ArrayIndexOutOfBoundsException(_sparseLen);
assert _ds==null;
if(_ms != null && _sparseLen > 0){
if(_id == null) { // check for sparseness
int nzs = _ms._nzs + (_missing != null?_missing.cardinality():0);
int nonnas = _sparseLen - ((_missing != null)?_missing.cardinality():0);
if((nonnas+1)*_sparseRatio < _len) {
set_sparse(nonnas,Compress.NA);
assert _id.length == _ms.len():"id.len = " + _id.length + ", ms.len = " + _ms.len();
assert _sparseLen <= _len;
return;
} else if((nzs+1)*_sparseRatio < _len) { // note order important here
set_sparse(nzs,Compress.ZERO);
assert _sparseLen <= _len;
assert _sparseLen == nzs;
return;
}
} else {
// verify we're still sufficiently sparse
if(2*_sparseLen > _len) cancel_sparse();
else _id = MemoryManager.arrayCopyOf(_id, _id.length*2);
}
_ms.resize(_sparseLen*2);
_xs.resize(_sparseLen*2);
} else {
_ms = new Mantissas(16);
_xs = new Exponents(16);
if (_id != null) _id = new int[16];
}
assert _sparseLen <= _len;
} } | public class class_name {
private void append2slow( ) {
// PUBDEV-2639 - don't die for many rows, few columns -> can be long chunks
// if( _sparseLen > FileVec.DFLT_CHUNK_SIZE )
// throw new ArrayIndexOutOfBoundsException(_sparseLen);
assert _ds==null;
if(_ms != null && _sparseLen > 0){
if(_id == null) { // check for sparseness
int nzs = _ms._nzs + (_missing != null?_missing.cardinality():0);
int nonnas = _sparseLen - ((_missing != null)?_missing.cardinality():0);
if((nonnas+1)*_sparseRatio < _len) {
set_sparse(nonnas,Compress.NA); // depends on control dependency: [if], data = [none]
assert _id.length == _ms.len():"id.len = " + _id.length + ", ms.len = " + _ms.len();
assert _sparseLen <= _len;
return; // depends on control dependency: [if], data = [none]
} else if((nzs+1)*_sparseRatio < _len) { // note order important here
set_sparse(nzs,Compress.ZERO); // depends on control dependency: [if], data = [none]
assert _sparseLen <= _len;
assert _sparseLen == nzs;
return; // depends on control dependency: [if], data = [none]
}
} else {
// verify we're still sufficiently sparse
if(2*_sparseLen > _len) cancel_sparse();
else _id = MemoryManager.arrayCopyOf(_id, _id.length*2);
}
_ms.resize(_sparseLen*2); // depends on control dependency: [if], data = [none]
_xs.resize(_sparseLen*2); // depends on control dependency: [if], data = [none]
} else {
_ms = new Mantissas(16); // depends on control dependency: [if], data = [none]
_xs = new Exponents(16); // depends on control dependency: [if], data = [none]
if (_id != null) _id = new int[16];
}
assert _sparseLen <= _len;
} } |
public class class_name {
@Override
public void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws ServletException, IOException {
CallFuture<NaviRpcResponse> callFuture = new CallFuture<NaviRpcResponse>();
try {
NaviRpcExporter serviceExporter = getRpcExporter(httpRequest);
String protocol = getProtocolByHttpContentType(httpRequest);
LocalContext.getContext().setStartTime().setProtocol(protocol)
.setFromIp(IPUtils.getIpAddr(httpRequest))
.setServiceName(serviceExporter.getName());
byte[] byteArray = ByteUtil.readStream(httpRequest.getInputStream(),
httpRequest.getContentLength());
LocalContext.getContext().setReqByteSize(byteArray.length);
NaviRpcRequest request = new NaviRpcRequest(serviceExporter, byteArray);
processor.service(request, callFuture);
} catch (InvalidRequestException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
} catch (InvalidProtocolException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_ACCEPTABLE);
} catch (ServiceNotFoundException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
} catch (CodecException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
callFuture.cancel(true);
} catch (DeserilizeNullException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
} catch (MethodNotFoundException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
} catch (ServerErrorException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} catch (Exception e) {
callFuture.cancel(true);
LOG.error(e.getMessage(), e);
httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} finally {
try {
buildHttpResponse(httpResponse, callFuture.get(), httpRequest.getContentType(),
httpRequest.getCharacterEncoding());
} catch (InterruptedException e2) {
LOG.error(e2.getMessage(), e2);
}
LocalContext.removeContext();
}
} } | public class class_name {
@Override
public void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
throws ServletException, IOException {
CallFuture<NaviRpcResponse> callFuture = new CallFuture<NaviRpcResponse>();
try {
NaviRpcExporter serviceExporter = getRpcExporter(httpRequest);
String protocol = getProtocolByHttpContentType(httpRequest);
LocalContext.getContext().setStartTime().setProtocol(protocol)
.setFromIp(IPUtils.getIpAddr(httpRequest))
.setServiceName(serviceExporter.getName());
byte[] byteArray = ByteUtil.readStream(httpRequest.getInputStream(),
httpRequest.getContentLength());
LocalContext.getContext().setReqByteSize(byteArray.length);
NaviRpcRequest request = new NaviRpcRequest(serviceExporter, byteArray);
processor.service(request, callFuture);
} catch (InvalidRequestException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
} catch (InvalidProtocolException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_ACCEPTABLE);
} catch (ServiceNotFoundException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
} catch (CodecException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
callFuture.cancel(true);
} catch (DeserilizeNullException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_BAD_REQUEST);
} catch (MethodNotFoundException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_NOT_FOUND);
} catch (ServerErrorException e) {
callFuture.cancel(true);
LOG.warn(e.getMessage());
httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} catch (Exception e) {
callFuture.cancel(true);
LOG.error(e.getMessage(), e);
httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
} finally {
try {
buildHttpResponse(httpResponse, callFuture.get(), httpRequest.getContentType(),
httpRequest.getCharacterEncoding()); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e2) {
LOG.error(e2.getMessage(), e2);
} // depends on control dependency: [catch], data = [none]
LocalContext.removeContext();
}
} } |
public class class_name {
@Override
public PathImpl getParent()
{
if (_pathname.length() <= 1)
return lookup("/");
int length = _pathname.length();
int lastSlash = _pathname.lastIndexOf('/');
if (lastSlash < 1)
return lookup("/");
if (lastSlash == length - 1) {
lastSlash = _pathname.lastIndexOf('/', length - 2);
if (lastSlash < 1)
return lookup("/");
}
return lookup(_pathname.substring(0, lastSlash));
} } | public class class_name {
@Override
public PathImpl getParent()
{
if (_pathname.length() <= 1)
return lookup("/");
int length = _pathname.length();
int lastSlash = _pathname.lastIndexOf('/');
if (lastSlash < 1)
return lookup("/");
if (lastSlash == length - 1) {
lastSlash = _pathname.lastIndexOf('/', length - 2); // depends on control dependency: [if], data = [none]
if (lastSlash < 1)
return lookup("/");
}
return lookup(_pathname.substring(0, lastSlash));
} } |
public class class_name {
private void read_problem(File learningFile) throws IOException {
BufferedReader fp = new BufferedReader(new FileReader(learningFile));
Vector vy = new Vector();
Vector vx = new Vector();
int max_index = 0;
while (true) {
String line = fp.readLine();
if (line == null)
break;
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
vy.addElement(st.nextToken());
int m = st.countTokens() / 2;
svm_node[] x = new svm_node[m];
for (int j = 0; j < m; j++) {
x[j] = new svm_node();
x[j].index = Integer.parseInt(st.nextToken());
x[j].value = Double.parseDouble(st.nextToken());
}
if (m > 0)
max_index = Math.max(max_index, x[m - 1].index);
vx.addElement(x);
}
prob = new svm_problem();
prob.l=vy.size();
prob.y = new double[prob.l];
prob.x = new svm_node[prob.l][];
for (int i = 0; i < prob.l; i++)
prob.x[i]= (svm_node[]) vx.elementAt(i);
for (int i = 0; i < prob.l; i++) {
double labell = Double.parseDouble((String) vy.elementAt(i));
prob.y[i]= labell;
}
if (param.gamma == 0)
param.gamma = 1.0 / max_index;
fp.close();
} } | public class class_name {
private void read_problem(File learningFile) throws IOException {
BufferedReader fp = new BufferedReader(new FileReader(learningFile));
Vector vy = new Vector();
Vector vx = new Vector();
int max_index = 0;
while (true) {
String line = fp.readLine();
if (line == null)
break;
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
vy.addElement(st.nextToken());
int m = st.countTokens() / 2;
svm_node[] x = new svm_node[m];
for (int j = 0; j < m; j++) {
x[j] = new svm_node();
// depends on control dependency: [for], data = [j]
x[j].index = Integer.parseInt(st.nextToken());
// depends on control dependency: [for], data = [j]
x[j].value = Double.parseDouble(st.nextToken());
// depends on control dependency: [for], data = [j]
}
if (m > 0)
max_index = Math.max(max_index, x[m - 1].index);
vx.addElement(x);
}
prob = new svm_problem();
prob.l=vy.size();
prob.y = new double[prob.l];
prob.x = new svm_node[prob.l][];
for (int i = 0; i < prob.l; i++)
prob.x[i]= (svm_node[]) vx.elementAt(i);
for (int i = 0; i < prob.l; i++) {
double labell = Double.parseDouble((String) vy.elementAt(i));
prob.y[i]= labell;
}
if (param.gamma == 0)
param.gamma = 1.0 / max_index;
fp.close();
} } |
public class class_name {
public void addDouble(double value) {
data[endOffset] = value;
endOffset++;
// Grow the buffer if needed
if (endOffset == data.length && !reachedMax)
resize();
// Loop over and advance the start point if needed
if (endOffset == data.length) {
endOffset = 0;
}
if (endOffset == startOffset)
startOffset++;
if (startOffset == data.length)
startOffset = 0;
} } | public class class_name {
public void addDouble(double value) {
data[endOffset] = value;
endOffset++;
// Grow the buffer if needed
if (endOffset == data.length && !reachedMax)
resize();
// Loop over and advance the start point if needed
if (endOffset == data.length) {
endOffset = 0;
// depends on control dependency: [if], data = [none]
}
if (endOffset == startOffset)
startOffset++;
if (startOffset == data.length)
startOffset = 0;
} } |
public class class_name {
public static byte[] getVariableByteSigned(int value) {
long absValue = Math.abs((long) value);
if (absValue < 64) { // 2^6
// encode the number in a single byte
if (value < 0) {
return new byte[]{(byte) (absValue | 0x40)};
}
return new byte[]{(byte) absValue};
} else if (absValue < 8192) { // 2^13
// encode the number in two bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x40)};
}
return new byte[]{(byte) (absValue | 0x80), (byte) (absValue >> 7)};
} else if (absValue < 1048576) { // 2^20
// encode the number in three bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x40)};
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80), (byte) (absValue >> 14)};
} else if (absValue < 134217728) { // 2^27
// encode the number in four bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x40)};
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) (absValue >> 21)};
} else {
// encode the number in five bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x80),
(byte) ((absValue >> 28) | 0x40)};
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x80), (byte) (absValue >> 28)};
}
} } | public class class_name {
public static byte[] getVariableByteSigned(int value) {
long absValue = Math.abs((long) value);
if (absValue < 64) { // 2^6
// encode the number in a single byte
if (value < 0) {
return new byte[]{(byte) (absValue | 0x40)}; // depends on control dependency: [if], data = [0)]
}
return new byte[]{(byte) absValue}; // depends on control dependency: [if], data = [none]
} else if (absValue < 8192) { // 2^13
// encode the number in two bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x40)}; // depends on control dependency: [if], data = [0)]
}
return new byte[]{(byte) (absValue | 0x80), (byte) (absValue >> 7)}; // depends on control dependency: [if], data = [(absValue]
} else if (absValue < 1048576) { // 2^20
// encode the number in three bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x40)}; // depends on control dependency: [if], data = [0)]
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80), (byte) (absValue >> 14)}; // depends on control dependency: [if], data = [(absValue]
} else if (absValue < 134217728) { // 2^27
// encode the number in four bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x40)}; // depends on control dependency: [if], data = [0)]
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) (absValue >> 21)}; // depends on control dependency: [if], data = [(absValue]
} else {
// encode the number in five bytes
if (value < 0) {
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x80),
(byte) ((absValue >> 28) | 0x40)}; // depends on control dependency: [if], data = [0)]
}
return new byte[]{(byte) (absValue | 0x80), (byte) ((absValue >> 7) | 0x80),
(byte) ((absValue >> 14) | 0x80), (byte) ((absValue >> 21) | 0x80), (byte) (absValue >> 28)}; // depends on control dependency: [if], data = [(absValue]
}
} } |
public class class_name {
public ModifyReplicationGroupShardConfigurationRequest withReshardingConfiguration(ReshardingConfiguration... reshardingConfiguration) {
if (this.reshardingConfiguration == null) {
setReshardingConfiguration(new com.amazonaws.internal.SdkInternalList<ReshardingConfiguration>(reshardingConfiguration.length));
}
for (ReshardingConfiguration ele : reshardingConfiguration) {
this.reshardingConfiguration.add(ele);
}
return this;
} } | public class class_name {
public ModifyReplicationGroupShardConfigurationRequest withReshardingConfiguration(ReshardingConfiguration... reshardingConfiguration) {
if (this.reshardingConfiguration == null) {
setReshardingConfiguration(new com.amazonaws.internal.SdkInternalList<ReshardingConfiguration>(reshardingConfiguration.length)); // depends on control dependency: [if], data = [none]
}
for (ReshardingConfiguration ele : reshardingConfiguration) {
this.reshardingConfiguration.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public Double getProcessorMetric(String processorNumber, ID metricToCollect) {
CentralProcessor processor = getProcessor();
if (processor == null) {
return null;
}
int processorIndex;
try {
processorIndex = Integer.parseInt(processorNumber);
if (processorIndex < 0 || processorIndex >= processor.getLogicalProcessorCount()) {
return null;
}
} catch (Exception e) {
return null;
}
if (PlatformMetricType.PROCESSOR_CPU_USAGE.getMetricTypeId().equals(metricToCollect)) {
return processor.getProcessorCpuLoadBetweenTicks()[processorIndex];
} else {
throw new UnsupportedOperationException("Invalid processor metric to collect: " + metricToCollect);
}
} } | public class class_name {
public Double getProcessorMetric(String processorNumber, ID metricToCollect) {
CentralProcessor processor = getProcessor();
if (processor == null) {
return null; // depends on control dependency: [if], data = [none]
}
int processorIndex;
try {
processorIndex = Integer.parseInt(processorNumber); // depends on control dependency: [try], data = [none]
if (processorIndex < 0 || processorIndex >= processor.getLogicalProcessorCount()) {
return null; // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
return null;
} // depends on control dependency: [catch], data = [none]
if (PlatformMetricType.PROCESSOR_CPU_USAGE.getMetricTypeId().equals(metricToCollect)) {
return processor.getProcessorCpuLoadBetweenTicks()[processorIndex]; // depends on control dependency: [if], data = [none]
} else {
throw new UnsupportedOperationException("Invalid processor metric to collect: " + metricToCollect);
}
} } |
public class class_name {
List<JCExpression> typeList() {
ListBuffer<JCExpression> ts = new ListBuffer<JCExpression>();
ts.append(parseType());
while (token.kind == COMMA) {
nextToken();
ts.append(parseType());
}
return ts.toList();
} } | public class class_name {
List<JCExpression> typeList() {
ListBuffer<JCExpression> ts = new ListBuffer<JCExpression>();
ts.append(parseType());
while (token.kind == COMMA) {
nextToken(); // depends on control dependency: [while], data = [none]
ts.append(parseType()); // depends on control dependency: [while], data = [none]
}
return ts.toList();
} } |
public class class_name {
protected void updateController(Dictionary<String, ?> dictionary,
ServerControllerFactory controllerFactory) {
// We want to make sure the configuration is known before starting the
// service tracker, else the configuration could be set after the
// service is found which would cause a restart of the service
if (!initialConfigSet) {
initialConfigSet = true;
this.config = dictionary;
this.factory = controllerFactory;
dynamicsServiceTracker = new ServiceTracker<>(
bundleContext, ServerControllerFactory.class,
new DynamicsServiceTrackerCustomizer());
dynamicsServiceTracker.open();
return;
}
if (same(dictionary, this.config) && same(controllerFactory, this.factory)) {
return;
}
if (httpServiceFactoryReg != null) {
httpServiceFactoryReg.unregister();
httpServiceFactoryReg = null;
}
if (managedServiceFactoryReg != null) {
managedServiceFactoryReg.unregister();
managedServiceFactoryReg = null;
}
if (serverController != null) {
serverController.stop();
serverController = null;
}
if (controllerFactory != null) {
try {
final PropertyResolver tmpResolver = new BundleContextPropertyResolver(
bundleContext, new DefaultPropertyResolver());
final PropertyResolver resolver = dictionary != null
? new DictionaryPropertyResolver(dictionary, tmpResolver)
: tmpResolver;
final ConfigurationImpl configuration = new ConfigurationImpl(resolver);
if (dictionary != null) {
// PAXWEB-1169: dictionary comes directly from configadmin.
// however, org.ops4j.util.property.PropertyStore.m_properties gets also filled after
// calling org.ops4j.util.property.PropertyStore.set() in every getXXX() method of
// ConfigurationImpl...
// For now, the dictionary is set from configadmin only and not from unpredictable state of
// PropertyStore.m_properties (which over time may contain default values for properties
// which are not found in PropertyResolver passed to the configurationImpl object)
configuration.setDictionary(dictionary);
}
final ServerModel serverModel = new ServerModel();
serverController = controllerFactory.createServerController(serverModel);
serverController.configure(configuration);
Dictionary<String, Object> props = determineServiceProperties(
dictionary, configuration,
serverController.getHttpPort(),
serverController.getHttpSecurePort());
// register a SCOPE_BUNDLE ServiceFactory - every bundle will have their
// own HttpService/WebContainer
httpServiceFactoryReg = bundleContext.registerService(
new String[] { HttpService.class.getName(), WebContainer.class.getName() },
new HttpServiceFactoryImpl() {
@Override
HttpService createService(final Bundle bundle) {
return new HttpServiceProxy(new HttpServiceStarted(
bundle, serverController, serverModel,
servletEventDispatcher));
}
}, props);
if (!serverController.isStarted()) {
while (!serverController.isConfigured()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOG.warn("caught interruptexception while waiting for configuration", e);
Thread.currentThread().interrupt();
return;
}
}
LOG.info("Starting server controller {}", serverController.getClass().getName());
serverController.start();
}
// ManagedServiceFactory for org.ops4j.pax.web.context factory PID
// we need registered WebContainer for this MSF to work
createManagedServiceFactory(bundleContext);
//CHECKSTYLE:OFF
} catch (Throwable t) {
// TODO: ignore those exceptions if the bundle is being stopped
LOG.error("Unable to start pax web server: " + t.getMessage(), t);
}
//CHECKSTYLE:ON
} else {
LOG.info("ServerControllerFactory is gone, HTTP Service is not available now.");
}
this.factory = controllerFactory;
this.config = dictionary;
} } | public class class_name {
protected void updateController(Dictionary<String, ?> dictionary,
ServerControllerFactory controllerFactory) {
// We want to make sure the configuration is known before starting the
// service tracker, else the configuration could be set after the
// service is found which would cause a restart of the service
if (!initialConfigSet) {
initialConfigSet = true; // depends on control dependency: [if], data = [none]
this.config = dictionary; // depends on control dependency: [if], data = [none]
this.factory = controllerFactory; // depends on control dependency: [if], data = [none]
dynamicsServiceTracker = new ServiceTracker<>(
bundleContext, ServerControllerFactory.class,
new DynamicsServiceTrackerCustomizer()); // depends on control dependency: [if], data = [none]
dynamicsServiceTracker.open(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (same(dictionary, this.config) && same(controllerFactory, this.factory)) {
return; // depends on control dependency: [if], data = [none]
}
if (httpServiceFactoryReg != null) {
httpServiceFactoryReg.unregister(); // depends on control dependency: [if], data = [none]
httpServiceFactoryReg = null; // depends on control dependency: [if], data = [none]
}
if (managedServiceFactoryReg != null) {
managedServiceFactoryReg.unregister(); // depends on control dependency: [if], data = [none]
managedServiceFactoryReg = null; // depends on control dependency: [if], data = [none]
}
if (serverController != null) {
serverController.stop(); // depends on control dependency: [if], data = [none]
serverController = null; // depends on control dependency: [if], data = [none]
}
if (controllerFactory != null) {
try {
final PropertyResolver tmpResolver = new BundleContextPropertyResolver(
bundleContext, new DefaultPropertyResolver());
final PropertyResolver resolver = dictionary != null
? new DictionaryPropertyResolver(dictionary, tmpResolver)
: tmpResolver;
final ConfigurationImpl configuration = new ConfigurationImpl(resolver);
if (dictionary != null) {
// PAXWEB-1169: dictionary comes directly from configadmin.
// however, org.ops4j.util.property.PropertyStore.m_properties gets also filled after
// calling org.ops4j.util.property.PropertyStore.set() in every getXXX() method of
// ConfigurationImpl...
// For now, the dictionary is set from configadmin only and not from unpredictable state of
// PropertyStore.m_properties (which over time may contain default values for properties
// which are not found in PropertyResolver passed to the configurationImpl object)
configuration.setDictionary(dictionary); // depends on control dependency: [if], data = [(dictionary]
}
final ServerModel serverModel = new ServerModel();
serverController = controllerFactory.createServerController(serverModel); // depends on control dependency: [try], data = [none]
serverController.configure(configuration); // depends on control dependency: [try], data = [none]
Dictionary<String, Object> props = determineServiceProperties(
dictionary, configuration,
serverController.getHttpPort(),
serverController.getHttpSecurePort());
// register a SCOPE_BUNDLE ServiceFactory - every bundle will have their
// own HttpService/WebContainer
httpServiceFactoryReg = bundleContext.registerService(
new String[] { HttpService.class.getName(), WebContainer.class.getName() },
new HttpServiceFactoryImpl() {
@Override
HttpService createService(final Bundle bundle) {
return new HttpServiceProxy(new HttpServiceStarted(
bundle, serverController, serverModel,
servletEventDispatcher));
}
}, props); // depends on control dependency: [try], data = [none]
if (!serverController.isStarted()) {
while (!serverController.isConfigured()) {
try {
Thread.sleep(100); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
LOG.warn("caught interruptexception while waiting for configuration", e);
Thread.currentThread().interrupt();
return;
} // depends on control dependency: [catch], data = [none]
}
LOG.info("Starting server controller {}", serverController.getClass().getName()); // depends on control dependency: [if], data = [none]
serverController.start(); // depends on control dependency: [if], data = [none]
}
// ManagedServiceFactory for org.ops4j.pax.web.context factory PID
// we need registered WebContainer for this MSF to work
createManagedServiceFactory(bundleContext); // depends on control dependency: [try], data = [none]
//CHECKSTYLE:OFF
} catch (Throwable t) {
// TODO: ignore those exceptions if the bundle is being stopped
LOG.error("Unable to start pax web server: " + t.getMessage(), t);
} // depends on control dependency: [catch], data = [none]
//CHECKSTYLE:ON
} else {
LOG.info("ServerControllerFactory is gone, HTTP Service is not available now."); // depends on control dependency: [if], data = [none]
}
this.factory = controllerFactory;
this.config = dictionary;
} } |
public class class_name {
private void updateBlocks() {
for (Block<S, L> block : splitBlocks) {
// Ignore blocks that have no elements in their sub blocks.
int inSubBlocks = block.getElementsInSubBlocks();
if (inSubBlocks == 0) {
continue;
}
boolean blockRemains = (inSubBlocks < block.size());
boolean reuseBlock = !blockRemains;
List<UnorderedCollection<State<S, L>>> subBlocks = block.getSubBlocks();
// If there is only one sub block which contains all elements of
// the block, then no split needs to be performed.
if (!blockRemains && subBlocks.size() == 1) {
block.clearSubBlocks();
continue;
}
Iterator<UnorderedCollection<State<S, L>>> subBlockIt = subBlocks.iterator();
if (reuseBlock) {
UnorderedCollection<State<S, L>> first = subBlockIt.next();
block.getStates().swap(first);
updateBlockReferences(block);
}
while (subBlockIt.hasNext()) {
UnorderedCollection<State<S, L>> subBlockStates = subBlockIt.next();
if (blockRemains) {
for (State<S, L> state : subBlockStates) {
block.removeState(state.getBlockReference());
}
}
Block<S, L> subBlock = new Block<>(numBlocks++, subBlockStates);
updateBlockReferences(subBlock);
newBlocks.add(subBlock);
addToPartition(subBlock);
}
newBlocks.add(block);
block.clearSubBlocks();
// If the split block previously was in the queue, add all newly
// created blocks to the queue. Otherwise, it's enough to add
// all but the largest
if (removeFromSplitterQueue(block)) {
addAllToSplitterQueue(newBlocks);
} else {
addAllButLargest(newBlocks);
}
newBlocks.clear();
}
splitBlocks.clear();
} } | public class class_name {
private void updateBlocks() {
for (Block<S, L> block : splitBlocks) {
// Ignore blocks that have no elements in their sub blocks.
int inSubBlocks = block.getElementsInSubBlocks();
if (inSubBlocks == 0) {
continue;
}
boolean blockRemains = (inSubBlocks < block.size());
boolean reuseBlock = !blockRemains;
List<UnorderedCollection<State<S, L>>> subBlocks = block.getSubBlocks();
// If there is only one sub block which contains all elements of
// the block, then no split needs to be performed.
if (!blockRemains && subBlocks.size() == 1) {
block.clearSubBlocks(); // depends on control dependency: [if], data = [none]
continue;
}
Iterator<UnorderedCollection<State<S, L>>> subBlockIt = subBlocks.iterator();
if (reuseBlock) {
UnorderedCollection<State<S, L>> first = subBlockIt.next();
block.getStates().swap(first); // depends on control dependency: [if], data = [none]
updateBlockReferences(block); // depends on control dependency: [if], data = [none]
}
while (subBlockIt.hasNext()) {
UnorderedCollection<State<S, L>> subBlockStates = subBlockIt.next();
if (blockRemains) {
for (State<S, L> state : subBlockStates) {
block.removeState(state.getBlockReference()); // depends on control dependency: [for], data = [state]
}
}
Block<S, L> subBlock = new Block<>(numBlocks++, subBlockStates);
updateBlockReferences(subBlock); // depends on control dependency: [while], data = [none]
newBlocks.add(subBlock); // depends on control dependency: [while], data = [none]
addToPartition(subBlock); // depends on control dependency: [while], data = [none]
}
newBlocks.add(block); // depends on control dependency: [for], data = [block]
block.clearSubBlocks(); // depends on control dependency: [for], data = [block]
// If the split block previously was in the queue, add all newly
// created blocks to the queue. Otherwise, it's enough to add
// all but the largest
if (removeFromSplitterQueue(block)) {
addAllToSplitterQueue(newBlocks); // depends on control dependency: [if], data = [none]
} else {
addAllButLargest(newBlocks); // depends on control dependency: [if], data = [none]
}
newBlocks.clear(); // depends on control dependency: [for], data = [none]
}
splitBlocks.clear();
} } |
public class class_name {
public Object last()
{
if (tc.isEntryEnabled()) Tr.entry(tc, "last",this);
Object lastObject = null;
while (hasNext())
{
lastObject = next();
}
if (tc.isEntryEnabled()) Tr.exit(tc, "last",lastObject);
return preprocessResult(lastObject);
} } | public class class_name {
public Object last()
{
if (tc.isEntryEnabled()) Tr.entry(tc, "last",this);
Object lastObject = null;
while (hasNext())
{
lastObject = next(); // depends on control dependency: [while], data = [none]
}
if (tc.isEntryEnabled()) Tr.exit(tc, "last",lastObject);
return preprocessResult(lastObject);
} } |
public class class_name {
public ApiFuture<?> mutate(final Mutation mutation) {
closedReadLock.lock();
try {
if (closed) {
throw new IllegalStateException("Cannot mutate when the BufferedMutator is closed.");
}
return offer(mutation);
} finally {
closedReadLock.unlock();
}
} } | public class class_name {
public ApiFuture<?> mutate(final Mutation mutation) {
closedReadLock.lock();
try {
if (closed) {
throw new IllegalStateException("Cannot mutate when the BufferedMutator is closed.");
}
return offer(mutation); // depends on control dependency: [try], data = [none]
} finally {
closedReadLock.unlock();
}
} } |
public class class_name {
public static long[] longArrayWrappedOrCopy(CollectionNumber coll) {
long[] array = wrappedLongArray(coll);
if (array != null) {
return array;
}
return longArrayCopyOf(coll);
} } | public class class_name {
public static long[] longArrayWrappedOrCopy(CollectionNumber coll) {
long[] array = wrappedLongArray(coll);
if (array != null) {
return array;
// depends on control dependency: [if], data = [none]
}
return longArrayCopyOf(coll);
} } |
public class class_name {
public static final Collator getInstance(ULocale locale) {
// fetching from service cache is faster than instantiation
if (locale == null) {
locale = ULocale.getDefault();
}
Collator coll = getShim().getInstance(locale);
if (!locale.getName().equals(locale.getBaseName())) { // any keywords?
setAttributesFromKeywords(locale, coll,
(coll instanceof RuleBasedCollator) ? (RuleBasedCollator)coll : null);
}
return coll;
} } | public class class_name {
public static final Collator getInstance(ULocale locale) {
// fetching from service cache is faster than instantiation
if (locale == null) {
locale = ULocale.getDefault(); // depends on control dependency: [if], data = [none]
}
Collator coll = getShim().getInstance(locale);
if (!locale.getName().equals(locale.getBaseName())) { // any keywords?
setAttributesFromKeywords(locale, coll,
(coll instanceof RuleBasedCollator) ? (RuleBasedCollator)coll : null); // depends on control dependency: [if], data = [none]
}
return coll;
} } |
public class class_name {
private boolean hasConstantField(PackageDoc pkg) {
ClassDoc[] classes
= (pkg.name().length() > 0)
? pkg.allClasses()
: configuration.classDocCatalog.allClasses(DocletConstants.DEFAULT_PACKAGE_NAME);
boolean found = false;
for (ClassDoc doc : classes) {
if (doc.isIncluded() && hasConstantField(doc)) {
found = true;
}
}
return found;
} } | public class class_name {
private boolean hasConstantField(PackageDoc pkg) {
ClassDoc[] classes
= (pkg.name().length() > 0)
? pkg.allClasses()
: configuration.classDocCatalog.allClasses(DocletConstants.DEFAULT_PACKAGE_NAME);
boolean found = false;
for (ClassDoc doc : classes) {
if (doc.isIncluded() && hasConstantField(doc)) {
found = true; // depends on control dependency: [if], data = [none]
}
}
return found;
} } |
public class class_name {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
SuggestedFix.Builder fix = null;
if (isInjectedConstructor(methodTree, state)) {
for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) {
if (OPTIONAL_INJECTION_MATCHER.matches(annotationTree, state)) {
// Replace the annotation with "@Inject"
if (fix == null) {
fix = SuggestedFix.builder();
}
fix = fix.replace(annotationTree, "@Inject");
} else if (BINDING_ANNOTATION_MATCHER.matches(annotationTree, state)) {
// Remove the binding annotation
if (fix == null) {
fix = SuggestedFix.builder();
}
fix = fix.delete(annotationTree);
}
}
}
if (fix == null) {
return Description.NO_MATCH;
} else {
return describeMatch(methodTree, fix.build());
}
} } | public class class_name {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
SuggestedFix.Builder fix = null;
if (isInjectedConstructor(methodTree, state)) {
for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) {
if (OPTIONAL_INJECTION_MATCHER.matches(annotationTree, state)) {
// Replace the annotation with "@Inject"
if (fix == null) {
fix = SuggestedFix.builder(); // depends on control dependency: [if], data = [none]
}
fix = fix.replace(annotationTree, "@Inject"); // depends on control dependency: [if], data = [none]
} else if (BINDING_ANNOTATION_MATCHER.matches(annotationTree, state)) {
// Remove the binding annotation
if (fix == null) {
fix = SuggestedFix.builder(); // depends on control dependency: [if], data = [none]
}
fix = fix.delete(annotationTree); // depends on control dependency: [if], data = [none]
}
}
}
if (fix == null) {
return Description.NO_MATCH; // depends on control dependency: [if], data = [none]
} else {
return describeMatch(methodTree, fix.build()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final hqlParser.bitwiseOrExpression_return bitwiseOrExpression() throws RecognitionException {
hqlParser.bitwiseOrExpression_return retval = new hqlParser.bitwiseOrExpression_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token BOR191=null;
ParserRuleReturnScope bitwiseXOrExpression190 =null;
ParserRuleReturnScope bitwiseXOrExpression192 =null;
CommonTree BOR191_tree=null;
try {
// hql.g:527:2: ( bitwiseXOrExpression ( BOR ^ bitwiseXOrExpression )* )
// hql.g:527:4: bitwiseXOrExpression ( BOR ^ bitwiseXOrExpression )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_bitwiseXOrExpression_in_bitwiseOrExpression2361);
bitwiseXOrExpression190=bitwiseXOrExpression();
state._fsp--;
adaptor.addChild(root_0, bitwiseXOrExpression190.getTree());
// hql.g:527:25: ( BOR ^ bitwiseXOrExpression )*
loop67:
while (true) {
int alt67=2;
int LA67_0 = input.LA(1);
if ( (LA67_0==BOR) ) {
alt67=1;
}
switch (alt67) {
case 1 :
// hql.g:527:26: BOR ^ bitwiseXOrExpression
{
BOR191=(Token)match(input,BOR,FOLLOW_BOR_in_bitwiseOrExpression2364);
BOR191_tree = (CommonTree)adaptor.create(BOR191);
root_0 = (CommonTree)adaptor.becomeRoot(BOR191_tree, root_0);
pushFollow(FOLLOW_bitwiseXOrExpression_in_bitwiseOrExpression2367);
bitwiseXOrExpression192=bitwiseXOrExpression();
state._fsp--;
adaptor.addChild(root_0, bitwiseXOrExpression192.getTree());
}
break;
default :
break loop67;
}
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} } | public class class_name {
public final hqlParser.bitwiseOrExpression_return bitwiseOrExpression() throws RecognitionException {
hqlParser.bitwiseOrExpression_return retval = new hqlParser.bitwiseOrExpression_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token BOR191=null;
ParserRuleReturnScope bitwiseXOrExpression190 =null;
ParserRuleReturnScope bitwiseXOrExpression192 =null;
CommonTree BOR191_tree=null;
try {
// hql.g:527:2: ( bitwiseXOrExpression ( BOR ^ bitwiseXOrExpression )* )
// hql.g:527:4: bitwiseXOrExpression ( BOR ^ bitwiseXOrExpression )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_bitwiseXOrExpression_in_bitwiseOrExpression2361);
bitwiseXOrExpression190=bitwiseXOrExpression();
state._fsp--;
adaptor.addChild(root_0, bitwiseXOrExpression190.getTree());
// hql.g:527:25: ( BOR ^ bitwiseXOrExpression )*
loop67:
while (true) {
int alt67=2;
int LA67_0 = input.LA(1);
if ( (LA67_0==BOR) ) {
alt67=1; // depends on control dependency: [if], data = [none]
}
switch (alt67) {
case 1 :
// hql.g:527:26: BOR ^ bitwiseXOrExpression
{
BOR191=(Token)match(input,BOR,FOLLOW_BOR_in_bitwiseOrExpression2364);
BOR191_tree = (CommonTree)adaptor.create(BOR191);
root_0 = (CommonTree)adaptor.becomeRoot(BOR191_tree, root_0);
pushFollow(FOLLOW_bitwiseXOrExpression_in_bitwiseOrExpression2367);
bitwiseXOrExpression192=bitwiseXOrExpression();
state._fsp--;
adaptor.addChild(root_0, bitwiseXOrExpression192.getTree());
}
break;
default :
break loop67;
}
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} } |
public class class_name {
@Override
public CPAttachmentFileEntry fetchByC_C_T_ST_Last(long classNameId,
long classPK, int type, int status,
OrderByComparator<CPAttachmentFileEntry> orderByComparator) {
int count = countByC_C_T_ST(classNameId, classPK, type, status);
if (count == 0) {
return null;
}
List<CPAttachmentFileEntry> list = findByC_C_T_ST(classNameId, classPK,
type, status, count - 1, count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} } | public class class_name {
@Override
public CPAttachmentFileEntry fetchByC_C_T_ST_Last(long classNameId,
long classPK, int type, int status,
OrderByComparator<CPAttachmentFileEntry> orderByComparator) {
int count = countByC_C_T_ST(classNameId, classPK, type, status);
if (count == 0) {
return null; // depends on control dependency: [if], data = [none]
}
List<CPAttachmentFileEntry> list = findByC_C_T_ST(classNameId, classPK,
type, status, count - 1, count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public final <V> boolean match(final MatcherContext<V> context)
{
/*
* TODO! Check logic
*
* At this point, if we have enough cycles, we can't determined whether
* our joining rule would match empty... Which is illegal.
*/
int cycles = 0;
if (!joined.getSubContext(context).runMatcher())
return enoughCycles(cycles);
cycles++;
Object snapshot = context.getValueStack().takeSnapshot();
int beforeCycle = context.getCurrentIndex();
while (runAgain(cycles) && matchCycle(context, beforeCycle)) {
beforeCycle = context.getCurrentIndex();
snapshot = context.getValueStack().takeSnapshot();
cycles++;
}
context.getValueStack().restoreSnapshot(snapshot);
context.setCurrentIndex(beforeCycle);
return enoughCycles(cycles);
} } | public class class_name {
@Override
public final <V> boolean match(final MatcherContext<V> context)
{
/*
* TODO! Check logic
*
* At this point, if we have enough cycles, we can't determined whether
* our joining rule would match empty... Which is illegal.
*/
int cycles = 0;
if (!joined.getSubContext(context).runMatcher())
return enoughCycles(cycles);
cycles++;
Object snapshot = context.getValueStack().takeSnapshot();
int beforeCycle = context.getCurrentIndex();
while (runAgain(cycles) && matchCycle(context, beforeCycle)) {
beforeCycle = context.getCurrentIndex(); // depends on control dependency: [while], data = [none]
snapshot = context.getValueStack().takeSnapshot(); // depends on control dependency: [while], data = [none]
cycles++; // depends on control dependency: [while], data = [none]
}
context.getValueStack().restoreSnapshot(snapshot);
context.setCurrentIndex(beforeCycle);
return enoughCycles(cycles);
} } |
public class class_name {
public final float toPoint() {
if (unit == FontSizeUnit.PIXEL) {
return (size / 4 * 3);
}
if (unit == FontSizeUnit.EM) {
return (size * 12);
}
if (unit == FontSizeUnit.PERCENT) {
return (size / 100 * 12);
}
if (unit == FontSizeUnit.POINT) {
return size;
}
throw new IllegalStateException("Unknown unit: " + unit);
} } | public class class_name {
public final float toPoint() {
if (unit == FontSizeUnit.PIXEL) {
return (size / 4 * 3);
// depends on control dependency: [if], data = [none]
}
if (unit == FontSizeUnit.EM) {
return (size * 12);
// depends on control dependency: [if], data = [none]
}
if (unit == FontSizeUnit.PERCENT) {
return (size / 100 * 12);
// depends on control dependency: [if], data = [none]
}
if (unit == FontSizeUnit.POINT) {
return size;
// depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Unknown unit: " + unit);
} } |
public class class_name {
protected Credential getServiceCredentialsFromRequest(final WebApplicationService service, final HttpServletRequest request) {
val pgtUrl = request.getParameter(CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL);
if (StringUtils.isNotBlank(pgtUrl)) {
try {
val registeredService = serviceValidateConfigurationContext.getServicesManager().findServiceBy(service);
verifyRegisteredServiceProperties(registeredService, service);
return new HttpBasedServiceCredential(new URL(pgtUrl), registeredService);
} catch (final Exception e) {
LOGGER.error("Error constructing [{}]", CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL, e);
}
}
return null;
} } | public class class_name {
protected Credential getServiceCredentialsFromRequest(final WebApplicationService service, final HttpServletRequest request) {
val pgtUrl = request.getParameter(CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL);
if (StringUtils.isNotBlank(pgtUrl)) {
try {
val registeredService = serviceValidateConfigurationContext.getServicesManager().findServiceBy(service);
verifyRegisteredServiceProperties(registeredService, service); // depends on control dependency: [try], data = [none]
return new HttpBasedServiceCredential(new URL(pgtUrl), registeredService); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
LOGGER.error("Error constructing [{}]", CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL, e);
} // depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
public Long getLong(final String key) {
Number number = (Number) map.get(key);
if (number == null) {
return null;
}
if (number instanceof Long) {
return (Long) number;
}
return number.longValue();
} } | public class class_name {
public Long getLong(final String key) {
Number number = (Number) map.get(key);
if (number == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (number instanceof Long) {
return (Long) number; // depends on control dependency: [if], data = [none]
}
return number.longValue();
} } |
public class class_name {
public static int extract(int bs, int low, int high) {
bs = bs >> low;
int mask = 0;
for (int i = 0; i < (high - low); i++) {
mask += 1 << i;
}
return bs & mask;
} } | public class class_name {
public static int extract(int bs, int low, int high) {
bs = bs >> low;
int mask = 0;
for (int i = 0; i < (high - low); i++) {
mask += 1 << i;
// depends on control dependency: [for], data = [i]
}
return bs & mask;
} } |
public class class_name {
public static String getString(IMolecularFormula formula, String[] orderElements,
boolean setOne, boolean setMassNumber) {
StringBuilder stringMF = new StringBuilder();
List<IIsotope> isotopesList = putInOrder(orderElements, formula);
Integer q = formula.getCharge();
if (q != null && q != 0)
stringMF.append('[');
if (!setMassNumber) {
int count = 0;
int prev = -1;
for (IIsotope isotope : isotopesList) {
if (!Objects.equals(isotope.getAtomicNumber(), prev)) {
if (count != 0)
appendElement(stringMF,
null, prev,
setOne || count != 1 ? count : 0);
prev = isotope.getAtomicNumber();
count = formula.getIsotopeCount(isotope);
} else
count += formula.getIsotopeCount(isotope);
}
if (count != 0)
appendElement(stringMF,
null, prev,
setOne || count != 1 ? count : 0);
} else {
for (IIsotope isotope : isotopesList) {
int count = formula.getIsotopeCount(isotope);
appendElement(stringMF,
isotope.getMassNumber(), isotope.getAtomicNumber(),
setOne || count != 1 ? count : 0);
}
}
if (q != null && q != 0) {
stringMF.append(']');
if (q > 0) {
if (q > 1)
stringMF.append(q);
stringMF.append('+');
} else {
if (q < -1)
stringMF.append(-q);
stringMF.append('-');
}
}
return stringMF.toString();
} } | public class class_name {
public static String getString(IMolecularFormula formula, String[] orderElements,
boolean setOne, boolean setMassNumber) {
StringBuilder stringMF = new StringBuilder();
List<IIsotope> isotopesList = putInOrder(orderElements, formula);
Integer q = formula.getCharge();
if (q != null && q != 0)
stringMF.append('[');
if (!setMassNumber) {
int count = 0;
int prev = -1;
for (IIsotope isotope : isotopesList) {
if (!Objects.equals(isotope.getAtomicNumber(), prev)) {
if (count != 0)
appendElement(stringMF,
null, prev,
setOne || count != 1 ? count : 0);
prev = isotope.getAtomicNumber(); // depends on control dependency: [if], data = [none]
count = formula.getIsotopeCount(isotope); // depends on control dependency: [if], data = [none]
} else
count += formula.getIsotopeCount(isotope);
}
if (count != 0)
appendElement(stringMF,
null, prev,
setOne || count != 1 ? count : 0);
} else {
for (IIsotope isotope : isotopesList) {
int count = formula.getIsotopeCount(isotope);
appendElement(stringMF,
isotope.getMassNumber(), isotope.getAtomicNumber(),
setOne || count != 1 ? count : 0); // depends on control dependency: [for], data = [none]
}
}
if (q != null && q != 0) {
stringMF.append(']'); // depends on control dependency: [if], data = [none]
if (q > 0) {
if (q > 1)
stringMF.append(q);
stringMF.append('+'); // depends on control dependency: [if], data = [none]
} else {
if (q < -1)
stringMF.append(-q);
stringMF.append('-'); // depends on control dependency: [if], data = [none]
}
}
return stringMF.toString();
} } |
public class class_name {
public static Object box(Object property, Class<?> to) {
if (property instanceof Exception) {
throw new RuntimeException((Exception) property);
}
if (property == null) {
return property;
}
if (property.getClass().equals(to)) {
return property;
}
if (property instanceof String && String.class.isAssignableFrom(to)) {
return property;
}
if ((property instanceof String || property instanceof Boolean) && Boolean.class.isAssignableFrom(to)) {
if (((String) property).equalsIgnoreCase("true") || property.equals("1")) {
return true;
}
if (((String) property).equalsIgnoreCase("false") || property.equals("0")) {
return false;
}
}
if ((property instanceof String || property instanceof Integer) && Integer.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0;
}
return new Integer(property.toString());
}
if ((property instanceof String || property instanceof Integer || property instanceof Long) && Long.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0L;
}
return new Long(property.toString());
}
if ((property instanceof String || property instanceof Double) && Double.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0D;
}
return new Double(property.toString());
}
return to.cast(property);
} } | public class class_name {
public static Object box(Object property, Class<?> to) {
if (property instanceof Exception) {
throw new RuntimeException((Exception) property);
}
if (property == null) {
return property; // depends on control dependency: [if], data = [none]
}
if (property.getClass().equals(to)) {
return property; // depends on control dependency: [if], data = [none]
}
if (property instanceof String && String.class.isAssignableFrom(to)) {
return property; // depends on control dependency: [if], data = [none]
}
if ((property instanceof String || property instanceof Boolean) && Boolean.class.isAssignableFrom(to)) {
if (((String) property).equalsIgnoreCase("true") || property.equals("1")) {
return true; // depends on control dependency: [if], data = [none]
}
if (((String) property).equalsIgnoreCase("false") || property.equals("0")) {
return false; // depends on control dependency: [if], data = [none]
}
}
if ((property instanceof String || property instanceof Integer) && Integer.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0; // depends on control dependency: [if], data = [none]
}
return new Integer(property.toString()); // depends on control dependency: [if], data = [none]
}
if ((property instanceof String || property instanceof Integer || property instanceof Long) && Long.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0L; // depends on control dependency: [if], data = [none]
}
return new Long(property.toString()); // depends on control dependency: [if], data = [none]
}
if ((property instanceof String || property instanceof Double) && Double.class.isAssignableFrom(to)) {
if (((String) property).isEmpty()) {
return 0D; // depends on control dependency: [if], data = [none]
}
return new Double(property.toString()); // depends on control dependency: [if], data = [none]
}
return to.cast(property);
} } |
public class class_name {
private void handleConsensusAnnotation(String featureName, String value) {
if (featureName.equals(GC_SECONDARY_STRUCTURE)) {
stockholmStructure.getConsAnnotation().setSecondaryStructure(value);
} else if (featureName.equals(GC_SEQUENSE_CONSENSUS)) {
stockholmStructure.getConsAnnotation().setSequenceConsensus(value);
} else if (featureName.equals(GC_SURFACE_ACCESSIBILITY)) {
stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value);
} else if (featureName.equals(GC_TRANS_MEMBRANE)) {
stockholmStructure.getConsAnnotation().setTransMembrane(value);
} else if (featureName.equals(GC_POSTERIOR_PROBABILITY)) {
stockholmStructure.getConsAnnotation().setPosteriorProbability(value);
} else if (featureName.equals(GC_LIGAND_BINDING)) {
stockholmStructure.getConsAnnotation().setLigandBinding(value);
} else if (featureName.equals(GC_ACTIVE_SITE)) {
stockholmStructure.getConsAnnotation().setActiveSite(value);
} else if (featureName.equals(GC_AS_PFAM_PREDICTED)) {
stockholmStructure.getConsAnnotation().setAsPFamPredicted(value);
} else if (featureName.equals(GC_AS_SWISSPROT)) {
stockholmStructure.getConsAnnotation().setAsSwissProt(value);
} else if (featureName.equals(GC_INTRON)) {
stockholmStructure.getConsAnnotation().setIntron(value);
} else if (featureName.equals(GC_REFERENCE_ANNOTATION)) {
stockholmStructure.getConsAnnotation().setReferenceAnnotation(value);
} else if (featureName.equals(GC_MODEL_MASK)) {
stockholmStructure.getConsAnnotation().setModelMask(value);
} else {
// unknown feature
logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName);
}
} } | public class class_name {
private void handleConsensusAnnotation(String featureName, String value) {
if (featureName.equals(GC_SECONDARY_STRUCTURE)) {
stockholmStructure.getConsAnnotation().setSecondaryStructure(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_SEQUENSE_CONSENSUS)) {
stockholmStructure.getConsAnnotation().setSequenceConsensus(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_SURFACE_ACCESSIBILITY)) {
stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_TRANS_MEMBRANE)) {
stockholmStructure.getConsAnnotation().setTransMembrane(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_POSTERIOR_PROBABILITY)) {
stockholmStructure.getConsAnnotation().setPosteriorProbability(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_LIGAND_BINDING)) {
stockholmStructure.getConsAnnotation().setLigandBinding(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_ACTIVE_SITE)) {
stockholmStructure.getConsAnnotation().setActiveSite(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_AS_PFAM_PREDICTED)) {
stockholmStructure.getConsAnnotation().setAsPFamPredicted(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_AS_SWISSPROT)) {
stockholmStructure.getConsAnnotation().setAsSwissProt(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_INTRON)) {
stockholmStructure.getConsAnnotation().setIntron(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_REFERENCE_ANNOTATION)) {
stockholmStructure.getConsAnnotation().setReferenceAnnotation(value); // depends on control dependency: [if], data = [none]
} else if (featureName.equals(GC_MODEL_MASK)) {
stockholmStructure.getConsAnnotation().setModelMask(value); // depends on control dependency: [if], data = [none]
} else {
// unknown feature
logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public EClass getIfcExternalReference() {
if (ifcExternalReferenceEClass == null) {
ifcExternalReferenceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(244);
}
return ifcExternalReferenceEClass;
} } | public class class_name {
@Override
public EClass getIfcExternalReference() {
if (ifcExternalReferenceEClass == null) {
ifcExternalReferenceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(244);
// depends on control dependency: [if], data = [none]
}
return ifcExternalReferenceEClass;
} } |
public class class_name {
private List<GovernmentBodyAnnualOutcomeSummary> getGovernmentBodyList() {
final List<GovernmentBodyAnnualOutcomeSummary> result = new ArrayList<>();
try {
result.addAll(esvGovernmentBodyOperationOutcomeReader.readIncomeCsv());
result.addAll(esvGovernmentBodyOperationOutcomeReader.readOutgoingCsv());
} catch (final IOException e) {
LOGGER.error(GET_GOVERNMENT_BODY_REPORT,e);
return result;
}
return result;
} } | public class class_name {
private List<GovernmentBodyAnnualOutcomeSummary> getGovernmentBodyList() {
final List<GovernmentBodyAnnualOutcomeSummary> result = new ArrayList<>();
try {
result.addAll(esvGovernmentBodyOperationOutcomeReader.readIncomeCsv()); // depends on control dependency: [try], data = [none]
result.addAll(esvGovernmentBodyOperationOutcomeReader.readOutgoingCsv()); // depends on control dependency: [try], data = [none]
} catch (final IOException e) {
LOGGER.error(GET_GOVERNMENT_BODY_REPORT,e);
return result;
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public EClass getIfcSweptDiskSolid() {
if (ifcSweptDiskSolidEClass == null) {
ifcSweptDiskSolidEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(586);
}
return ifcSweptDiskSolidEClass;
} } | public class class_name {
public EClass getIfcSweptDiskSolid() {
if (ifcSweptDiskSolidEClass == null) {
ifcSweptDiskSolidEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(586);
// depends on control dependency: [if], data = [none]
}
return ifcSweptDiskSolidEClass;
} } |
public class class_name {
public void removeKey(int key) {
if (key == first.value) {
removeMin();
return;
}
if (key == last.value) {
removeMax();
return;
}
// if both children of root are black, set root to red
if ((root.left == null || !root.left.red) && (root.right == null || !root.right.red))
root.red = true;
root = removeKey(root, key);
if (root != null) root.red = false;
} } | public class class_name {
public void removeKey(int key) {
if (key == first.value) {
removeMin();
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
if (key == last.value) {
removeMax();
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
// if both children of root are black, set root to red
if ((root.left == null || !root.left.red) && (root.right == null || !root.right.red))
root.red = true;
root = removeKey(root, key);
if (root != null) root.red = false;
} } |
public class class_name {
public DocServiceBuilder exampleRequestForMethod(String serviceName, String methodName,
Iterable<?> exampleRequests) {
requireNonNull(serviceName, "serviceName");
requireNonNull(methodName, "methodName");
requireNonNull(exampleRequests, "exampleRequests");
for (Object e : exampleRequests) {
requireNonNull(e, "exampleRequests contains null.");
exampleRequest0(serviceName, methodName,
serializeExampleRequest(serviceName, methodName, e));
}
return this;
} } | public class class_name {
public DocServiceBuilder exampleRequestForMethod(String serviceName, String methodName,
Iterable<?> exampleRequests) {
requireNonNull(serviceName, "serviceName");
requireNonNull(methodName, "methodName");
requireNonNull(exampleRequests, "exampleRequests");
for (Object e : exampleRequests) {
requireNonNull(e, "exampleRequests contains null."); // depends on control dependency: [for], data = [e]
exampleRequest0(serviceName, methodName,
serializeExampleRequest(serviceName, methodName, e)); // depends on control dependency: [for], data = [e]
}
return this;
} } |
public class class_name {
private static SQLException addHostInformationToException(SQLException exception,
Protocol protocol) {
if (protocol != null) {
return new SQLException(exception.getMessage()
+ "\non " + protocol.getHostAddress().toString() + ",master="
+ protocol.isMasterConnection(), exception.getSQLState(), exception.getErrorCode(),
exception.getCause());
}
return exception;
} } | public class class_name {
private static SQLException addHostInformationToException(SQLException exception,
Protocol protocol) {
if (protocol != null) {
return new SQLException(exception.getMessage()
+ "\non " + protocol.getHostAddress().toString() + ",master="
+ protocol.isMasterConnection(), exception.getSQLState(), exception.getErrorCode(),
exception.getCause()); // depends on control dependency: [if], data = [none]
}
return exception;
} } |
public class class_name {
public String getHeaders()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
Enumeration names = req.getHeaderNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Enumeration values = req.getHeaders(name);
StringBuffer sb = new StringBuffer();
boolean first = true;
while (values.hasMoreElements())
{
if (!first)
{
sb.append(" | ");
}
first = false;
sb.append(values.nextElement());
}
info.put(name, sb.toString());
}
return toHTMLTable("headers", info);
} } | public class class_name {
public String getHeaders()
{
Map info = new TreeMap();
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
Enumeration names = req.getHeaderNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
Enumeration values = req.getHeaders(name);
StringBuffer sb = new StringBuffer();
boolean first = true;
while (values.hasMoreElements())
{
if (!first)
{
sb.append(" | "); // depends on control dependency: [if], data = [none]
}
first = false; // depends on control dependency: [while], data = [none]
sb.append(values.nextElement()); // depends on control dependency: [while], data = [none]
}
info.put(name, sb.toString()); // depends on control dependency: [while], data = [none]
}
return toHTMLTable("headers", info);
} } |
public class class_name {
public int[] findLongest(CharSequence query, int start)
{
if ((query == null) || (start >= query.length()))
{
return new int[]{0, -1};
}
int state = 1;
int maxLength = 0;
int lastVal = -1;
for (int i = start; i < query.length(); i++)
{
int[] res = transferValues(state, query.charAt(i));
if (res[0] == -1)
{
break;
}
state = res[0];
if (res[1] != -1)
{
maxLength = i - start + 1;
lastVal = res[1];
}
}
return new int[]{maxLength, lastVal};
} } | public class class_name {
public int[] findLongest(CharSequence query, int start)
{
if ((query == null) || (start >= query.length()))
{
return new int[]{0, -1}; // depends on control dependency: [if], data = [none]
}
int state = 1;
int maxLength = 0;
int lastVal = -1;
for (int i = start; i < query.length(); i++)
{
int[] res = transferValues(state, query.charAt(i));
if (res[0] == -1)
{
break;
}
state = res[0]; // depends on control dependency: [for], data = [none]
if (res[1] != -1)
{
maxLength = i - start + 1; // depends on control dependency: [if], data = [none]
lastVal = res[1]; // depends on control dependency: [if], data = [none]
}
}
return new int[]{maxLength, lastVal};
} } |
public class class_name {
@Override
public void start(final Logger logger) {
try {
logger.logInfo("Starting OpenDJ server");
final MemoryBackend backend;
if (getLdifFile() == null) {
backend = new MemoryBackend();
} else {
final InputStream inputStream = new FileInputStream(getLdifFile());
final LDIFEntryReader reader = new LDIFEntryReader(inputStream);
backend = new MemoryBackend(reader);
}
final ServerConnectionFactory<LDAPClientContext, Integer> connectionHandler = Connections.newServerConnectionFactory(backend);
final LDAPListenerOptions options = new LDAPListenerOptions().setBacklog(4096);
listener = new LDAPListener("localhost", getServerPort(), connectionHandler, options);
logger.logInfo("Started OpenDJ server");
} catch (final IOException e) {
logger.logError("Error starting OpenDJ server", e);
}
} } | public class class_name {
@Override
public void start(final Logger logger) {
try {
logger.logInfo("Starting OpenDJ server");
final MemoryBackend backend;
if (getLdifFile() == null) {
backend = new MemoryBackend(); // depends on control dependency: [if], data = [none]
} else {
final InputStream inputStream = new FileInputStream(getLdifFile());
final LDIFEntryReader reader = new LDIFEntryReader(inputStream);
backend = new MemoryBackend(reader); // depends on control dependency: [if], data = [none]
}
final ServerConnectionFactory<LDAPClientContext, Integer> connectionHandler = Connections.newServerConnectionFactory(backend);
final LDAPListenerOptions options = new LDAPListenerOptions().setBacklog(4096);
listener = new LDAPListener("localhost", getServerPort(), connectionHandler, options);
logger.logInfo("Started OpenDJ server");
} catch (final IOException e) {
logger.logError("Error starting OpenDJ server", e);
}
} } |
public class class_name {
public String getQuery() {
StringBuilder query = new StringBuilder();
if (queryTail.length() > 0) {
if (queryHead.length() == 0) {
query.append("{?")
.append(queryTail)
.append("}");
} else if (queryHead.length() > 0) {
query.append(queryHead)
.append("{&")
.append(queryTail)
.append("}");
}
} else {
query.append(queryHead);
}
return query.toString();
} } | public class class_name {
public String getQuery() {
StringBuilder query = new StringBuilder();
if (queryTail.length() > 0) {
if (queryHead.length() == 0) {
query.append("{?")
.append(queryTail)
.append("}"); // depends on control dependency: [if], data = [none]
} else if (queryHead.length() > 0) {
query.append(queryHead)
.append("{&")
.append(queryTail)
.append("}"); // depends on control dependency: [if], data = [none]
}
} else {
query.append(queryHead); // depends on control dependency: [if], data = [none]
}
return query.toString();
} } |
public class class_name {
protected void update(List<TableInfo> tableInfos)
{
for (TableInfo tableInfo : tableInfos)
{
DBObject options = setCollectionProperties(tableInfo);
DB db = mongo.getDB(databaseName);
DBCollection collection = null;
if (tableInfo.getLobColumnInfo().isEmpty())
{
if (!db.collectionExists(tableInfo.getTableName()))
{
collection = db.createCollection(tableInfo.getTableName(), options);
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName(), showQuery);
}
collection = collection != null ? collection : db.getCollection(tableInfo.getTableName());
boolean isCappedCollection = isCappedCollection(tableInfo);
if (!isCappedCollection)
{
createIndexes(tableInfo, collection);
}
}
else
{
checkMultipleLobs(tableInfo);
if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.FILES))
{
coll = db.createCollection(tableInfo.getTableName() + MongoDBUtils.FILES, options);
createUniqueIndexGFS(coll, tableInfo.getIdColumnName());
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName() + MongoDBUtils.FILES,
showQuery);
}
if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.CHUNKS))
{
db.createCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS, options);
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName() + MongoDBUtils.CHUNKS,
showQuery);
}
}
}
} } | public class class_name {
protected void update(List<TableInfo> tableInfos)
{
for (TableInfo tableInfo : tableInfos)
{
DBObject options = setCollectionProperties(tableInfo);
DB db = mongo.getDB(databaseName);
DBCollection collection = null;
if (tableInfo.getLobColumnInfo().isEmpty())
{
if (!db.collectionExists(tableInfo.getTableName()))
{
collection = db.createCollection(tableInfo.getTableName(), options); // depends on control dependency: [if], data = [none]
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName(), showQuery); // depends on control dependency: [if], data = [none]
}
collection = collection != null ? collection : db.getCollection(tableInfo.getTableName()); // depends on control dependency: [if], data = [none]
boolean isCappedCollection = isCappedCollection(tableInfo);
if (!isCappedCollection)
{
createIndexes(tableInfo, collection); // depends on control dependency: [if], data = [none]
}
}
else
{
checkMultipleLobs(tableInfo); // depends on control dependency: [if], data = [none]
if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.FILES))
{
coll = db.createCollection(tableInfo.getTableName() + MongoDBUtils.FILES, options); // depends on control dependency: [if], data = [none]
createUniqueIndexGFS(coll, tableInfo.getIdColumnName()); // depends on control dependency: [if], data = [none]
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName() + MongoDBUtils.FILES,
showQuery); // depends on control dependency: [if], data = [none]
}
if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.CHUNKS))
{
db.createCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS, options); // depends on control dependency: [if], data = [none]
KunderaCoreUtils.printQuery("Create collection: " + tableInfo.getTableName() + MongoDBUtils.CHUNKS,
showQuery); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@Override
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
Object columnValue, Class entityClazz)
{
List<Object> rowKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);
}
else
{
Selector selector = clientFactory.getSelector(pool);
SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
IndexClause ix = Selector.newIndexClause(Bytes.EMPTY, 10000, Selector.newIndexExpression(columnName
+ Constants.JOIN_COLUMN_NAME_SEPARATOR + columnValue, IndexOperator.EQ,
Bytes.fromByteArray(PropertyAccessorHelper.getBytes(columnValue))));
Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(tableName, ix, slicePredicate,
getConsistencyLevel());
// iterate through complete map and
Iterator<Bytes> rowIter = qResults.keySet().iterator();
while (rowIter.hasNext())
{
Bytes rowKey = rowIter.next();
PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata
.getIdAttribute().getJavaMember());
Object value = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), rowKey.toByteArray());
rowKeys.add(value);
}
}
if (rowKeys != null && !rowKeys.isEmpty())
{
return rowKeys.toArray(new Object[0]);
}
if (log.isInfoEnabled())
{
log.info("No row keys found, returning null.");
}
return null;
} } | public class class_name {
@Override
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
Object columnValue, Class entityClazz)
{
List<Object> rowKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz); // depends on control dependency: [if], data = [none]
}
else
{
Selector selector = clientFactory.getSelector(pool);
SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
IndexClause ix = Selector.newIndexClause(Bytes.EMPTY, 10000, Selector.newIndexExpression(columnName
+ Constants.JOIN_COLUMN_NAME_SEPARATOR + columnValue, IndexOperator.EQ,
Bytes.fromByteArray(PropertyAccessorHelper.getBytes(columnValue))));
Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(tableName, ix, slicePredicate,
getConsistencyLevel());
// iterate through complete map and
Iterator<Bytes> rowIter = qResults.keySet().iterator();
while (rowIter.hasNext())
{
Bytes rowKey = rowIter.next();
PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata
.getIdAttribute().getJavaMember());
Object value = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), rowKey.toByteArray());
rowKeys.add(value); // depends on control dependency: [while], data = [none]
}
}
if (rowKeys != null && !rowKeys.isEmpty())
{
return rowKeys.toArray(new Object[0]); // depends on control dependency: [if], data = [none]
}
if (log.isInfoEnabled())
{
log.info("No row keys found, returning null."); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public void sawOpcode(int seen) {
boolean reset = true;
switch (state) { // TODO: Refactor this to use state pattern, not nested
// switches
case SEEN_NOTHING:
reset = sawOpcodeAfterNothing(seen);
break;
case SEEN_ALOAD:
reset = sawOpcodeAfterLoad(seen);
break;
case SEEN_GETFIELD:
reset = sawOpcodeAfterGetField(seen);
break;
case SEEN_DUAL_LOADS:
reset = sawOpcodeAfterDualLoads(seen);
break;
case SEEN_INVOKEVIRTUAL:
if (seen == Const.INVOKEVIRTUAL) {
checkForSGSU();
}
break;
}
if (reset) {
beanReference1 = null;
beanReference2 = null;
propType = null;
propName = null;
sawField = false;
state = State.SEEN_NOTHING;
}
} } | public class class_name {
@Override
public void sawOpcode(int seen) {
boolean reset = true;
switch (state) { // TODO: Refactor this to use state pattern, not nested
// switches
case SEEN_NOTHING:
reset = sawOpcodeAfterNothing(seen);
break;
case SEEN_ALOAD:
reset = sawOpcodeAfterLoad(seen);
break;
case SEEN_GETFIELD:
reset = sawOpcodeAfterGetField(seen);
break;
case SEEN_DUAL_LOADS:
reset = sawOpcodeAfterDualLoads(seen);
break;
case SEEN_INVOKEVIRTUAL:
if (seen == Const.INVOKEVIRTUAL) {
checkForSGSU(); // depends on control dependency: [if], data = [none]
}
break;
}
if (reset) {
beanReference1 = null; // depends on control dependency: [if], data = [none]
beanReference2 = null; // depends on control dependency: [if], data = [none]
propType = null; // depends on control dependency: [if], data = [none]
propName = null; // depends on control dependency: [if], data = [none]
sawField = false; // depends on control dependency: [if], data = [none]
state = State.SEEN_NOTHING; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DoubleDBIDList getRKNN(DBIDRef id) {
TreeSet<DoubleDBIDPair> rKNN = materialized_RkNN.get(id);
if(rKNN == null) {
return null;
}
ModifiableDoubleDBIDList ret = DBIDUtil.newDistanceDBIDList(rKNN.size());
for(DoubleDBIDPair pair : rKNN) {
ret.add(pair);
}
ret.sort();
return ret;
} } | public class class_name {
public DoubleDBIDList getRKNN(DBIDRef id) {
TreeSet<DoubleDBIDPair> rKNN = materialized_RkNN.get(id);
if(rKNN == null) {
return null; // depends on control dependency: [if], data = [none]
}
ModifiableDoubleDBIDList ret = DBIDUtil.newDistanceDBIDList(rKNN.size());
for(DoubleDBIDPair pair : rKNN) {
ret.add(pair); // depends on control dependency: [for], data = [pair]
}
ret.sort();
return ret;
} } |
public class class_name {
protected void configureDatabaseIdent (String dbident)
{
_dbident = dbident;
// give the repository a chance to do any schema migration before things get further
// underway
try {
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
migrateSchema(conn, liaison);
return null;
}
});
} catch (PersistenceException pe) {
log.warning("Failure migrating schema", "dbident", _dbident, pe);
}
} } | public class class_name {
protected void configureDatabaseIdent (String dbident)
{
_dbident = dbident;
// give the repository a chance to do any schema migration before things get further
// underway
try {
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
migrateSchema(conn, liaison);
return null;
}
}); // depends on control dependency: [try], data = [none]
} catch (PersistenceException pe) {
log.warning("Failure migrating schema", "dbident", _dbident, pe);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String underscoreToCamelCase(final String undescoredString) {
// Split the string for each underscore
final String[] parts = undescoredString.split(CASE_SEPARATOR);
final StringBuilder camelCaseString = new StringBuilder(undescoredString.length());
camelCaseString.append(parts[0].toLowerCase(Locale.getDefault()));
// Skip the first part already added
for (int i = 1; i < parts.length; i++) {
// First letter to upper case
camelCaseString.append(parts[i].substring(0, 1).toUpperCase(Locale.getDefault()));
// Others to lower case
camelCaseString.append(parts[i].substring(1).toLowerCase(Locale.getDefault()));
}
return camelCaseString.toString();
} } | public class class_name {
public static String underscoreToCamelCase(final String undescoredString) {
// Split the string for each underscore
final String[] parts = undescoredString.split(CASE_SEPARATOR);
final StringBuilder camelCaseString = new StringBuilder(undescoredString.length());
camelCaseString.append(parts[0].toLowerCase(Locale.getDefault()));
// Skip the first part already added
for (int i = 1; i < parts.length; i++) {
// First letter to upper case
camelCaseString.append(parts[i].substring(0, 1).toUpperCase(Locale.getDefault())); // depends on control dependency: [for], data = [i]
// Others to lower case
camelCaseString.append(parts[i].substring(1).toLowerCase(Locale.getDefault())); // depends on control dependency: [for], data = [i]
}
return camelCaseString.toString();
} } |
public class class_name {
@Override
public double similarity(@NonNull String label1, @NonNull String label2) {
if (label1 == null || label2 == null) {
log.debug("LABELS: " + label1 + ": " + (label1 == null ? "null" : EXISTS) + ";" + label2 + " vec2:"
+ (label2 == null ? "null" : EXISTS));
return Double.NaN;
}
if (!vocabCache.hasToken(label1)) {
log.debug("Unknown token 1 requested: [{}]", label1);
return Double.NaN;
}
if (!vocabCache.hasToken(label2)) {
log.debug("Unknown token 2 requested: [{}]", label2);
return Double.NaN;
}
INDArray vec1 = lookupTable.vector(label1).dup();
INDArray vec2 = lookupTable.vector(label2).dup();
if (vec1 == null || vec2 == null) {
log.debug(label1 + ": " + (vec1 == null ? "null" : EXISTS) + ";" + label2 + " vec2:"
+ (vec2 == null ? "null" : EXISTS));
return Double.NaN;
}
if (label1.equals(label2))
return 1.0;
return Transforms.cosineSim(vec1, vec2);
} } | public class class_name {
@Override
public double similarity(@NonNull String label1, @NonNull String label2) {
if (label1 == null || label2 == null) {
log.debug("LABELS: " + label1 + ": " + (label1 == null ? "null" : EXISTS) + ";" + label2 + " vec2:"
+ (label2 == null ? "null" : EXISTS)); // depends on control dependency: [if], data = [(label1]
return Double.NaN; // depends on control dependency: [if], data = [none]
}
if (!vocabCache.hasToken(label1)) {
log.debug("Unknown token 1 requested: [{}]", label1); // depends on control dependency: [if], data = [none]
return Double.NaN; // depends on control dependency: [if], data = [none]
}
if (!vocabCache.hasToken(label2)) {
log.debug("Unknown token 2 requested: [{}]", label2); // depends on control dependency: [if], data = [none]
return Double.NaN; // depends on control dependency: [if], data = [none]
}
INDArray vec1 = lookupTable.vector(label1).dup();
INDArray vec2 = lookupTable.vector(label2).dup();
if (vec1 == null || vec2 == null) {
log.debug(label1 + ": " + (vec1 == null ? "null" : EXISTS) + ";" + label2 + " vec2:"
+ (vec2 == null ? "null" : EXISTS)); // depends on control dependency: [if], data = [(vec1]
return Double.NaN; // depends on control dependency: [if], data = [none]
}
if (label1.equals(label2))
return 1.0;
return Transforms.cosineSim(vec1, vec2);
} } |
public class class_name {
public DescribeInternetGatewaysResult withInternetGateways(InternetGateway... internetGateways) {
if (this.internetGateways == null) {
setInternetGateways(new com.amazonaws.internal.SdkInternalList<InternetGateway>(internetGateways.length));
}
for (InternetGateway ele : internetGateways) {
this.internetGateways.add(ele);
}
return this;
} } | public class class_name {
public DescribeInternetGatewaysResult withInternetGateways(InternetGateway... internetGateways) {
if (this.internetGateways == null) {
setInternetGateways(new com.amazonaws.internal.SdkInternalList<InternetGateway>(internetGateways.length)); // depends on control dependency: [if], data = [none]
}
for (InternetGateway ele : internetGateways) {
this.internetGateways.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public final void mROLLUP() throws RecognitionException {
try {
int _type = ROLLUP;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:592:17: ( ( 'ROLLUP' | 'rollup' ) )
// druidG.g:592:18: ( 'ROLLUP' | 'rollup' )
{
// druidG.g:592:18: ( 'ROLLUP' | 'rollup' )
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='R') ) {
alt9=1;
}
else if ( (LA9_0=='r') ) {
alt9=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1 :
// druidG.g:592:19: 'ROLLUP'
{
match("ROLLUP");
}
break;
case 2 :
// druidG.g:592:31: 'rollup'
{
match("rollup");
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mROLLUP() throws RecognitionException {
try {
int _type = ROLLUP;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:592:17: ( ( 'ROLLUP' | 'rollup' ) )
// druidG.g:592:18: ( 'ROLLUP' | 'rollup' )
{
// druidG.g:592:18: ( 'ROLLUP' | 'rollup' )
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='R') ) {
alt9=1; // depends on control dependency: [if], data = [none]
}
else if ( (LA9_0=='r') ) {
alt9=2; // depends on control dependency: [if], data = [none]
}
else {
NoViableAltException nvae =
new NoViableAltException("", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1 :
// druidG.g:592:19: 'ROLLUP'
{
match("ROLLUP");
}
break;
case 2 :
// druidG.g:592:31: 'rollup'
{
match("rollup");
}
break;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
private final boolean sniff(byte[] content) {
byte[] beginning = content;
if (content.length > maxOffsetGuess && maxOffsetGuess > 0) {
beginning = Arrays.copyOfRange(content, 0, maxOffsetGuess);
}
int position = Bytes.indexOf(beginning, clue);
if (position != -1) {
return true;
}
return false;
} } | public class class_name {
private final boolean sniff(byte[] content) {
byte[] beginning = content;
if (content.length > maxOffsetGuess && maxOffsetGuess > 0) {
beginning = Arrays.copyOfRange(content, 0, maxOffsetGuess); // depends on control dependency: [if], data = [none]
}
int position = Bytes.indexOf(beginning, clue);
if (position != -1) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static Object find(Object self, Closure closure) {
BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object value = iter.next();
if (bcw.call(value)) {
return value;
}
}
return null;
} } | public class class_name {
public static Object find(Object self, Closure closure) {
BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
Object value = iter.next();
if (bcw.call(value)) {
return value; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private void maximize()
{
if (timer != null)
{
timer.stop();
timer = null;
}
final int targetHeight = getSuperPreferredHeight();
double steps = (double)durationMS / delayMS;
double delta = targetHeight - currentHeight;
final int stepSize = (int)Math.ceil(delta / steps);
currentHeight = getHeight();
//System.out.println("steps " + steps);
//System.out.println("currentHeight " + currentHeight);
//System.out.println("delta " + delta);
//System.out.println("stepSize " + stepSize);
timer = new Timer(delayMS, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
minimized = false;
currentHeight += stepSize;
currentHeight = Math.min(currentHeight, targetHeight);
if (currentHeight >= targetHeight)
{
currentHeight = Integer.MAX_VALUE;
timer.stop();
timer = null;
}
revalidate();
}
});
timer.setInitialDelay(0);
timer.start();
} } | public class class_name {
private void maximize()
{
if (timer != null)
{
timer.stop();
// depends on control dependency: [if], data = [none]
timer = null;
// depends on control dependency: [if], data = [none]
}
final int targetHeight = getSuperPreferredHeight();
double steps = (double)durationMS / delayMS;
double delta = targetHeight - currentHeight;
final int stepSize = (int)Math.ceil(delta / steps);
currentHeight = getHeight();
//System.out.println("steps " + steps);
//System.out.println("currentHeight " + currentHeight);
//System.out.println("delta " + delta);
//System.out.println("stepSize " + stepSize);
timer = new Timer(delayMS, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
minimized = false;
currentHeight += stepSize;
currentHeight = Math.min(currentHeight, targetHeight);
if (currentHeight >= targetHeight)
{
currentHeight = Integer.MAX_VALUE;
// depends on control dependency: [if], data = [none]
timer.stop();
// depends on control dependency: [if], data = [none]
timer = null;
// depends on control dependency: [if], data = [none]
}
revalidate();
}
});
timer.setInitialDelay(0);
timer.start();
} } |
public class class_name {
public static DifferenceEvaluator
chain(final DifferenceEvaluator... evaluators) {
return new DifferenceEvaluator() {
@Override
public ComparisonResult evaluate(Comparison comparison, ComparisonResult orig) {
ComparisonResult finalResult = orig;
for (DifferenceEvaluator ev : evaluators) {
ComparisonResult evaluated = ev.evaluate(comparison, finalResult);
finalResult = evaluated;
}
return finalResult;
}
};
} } | public class class_name {
public static DifferenceEvaluator
chain(final DifferenceEvaluator... evaluators) {
return new DifferenceEvaluator() {
@Override
public ComparisonResult evaluate(Comparison comparison, ComparisonResult orig) {
ComparisonResult finalResult = orig;
for (DifferenceEvaluator ev : evaluators) {
ComparisonResult evaluated = ev.evaluate(comparison, finalResult);
finalResult = evaluated; // depends on control dependency: [for], data = [ev]
}
return finalResult;
}
};
} } |
public class class_name {
@Override
public void subscribe(String channel, ISubscriber<ID, DATA> subscriber) {
try {
Set<ISubscriber<ID, DATA>> subs = subscriptions.get(channel);
synchronized (subs) {
subs.add(subscriber);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
@Override
public void subscribe(String channel, ISubscriber<ID, DATA> subscriber) {
try {
Set<ISubscriber<ID, DATA>> subs = subscriptions.get(channel);
synchronized (subs) { // depends on control dependency: [try], data = [none]
subs.add(subscriber);
}
} catch (ExecutionException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void adjustHue(ColorMatrix cm, float value)
{
value = cleanValue(value, 180f) / 180f * (float) Math.PI;
if (value == 0)
{
return;
}
float cosVal = (float) Math.cos(value);
float sinVal = (float) Math.sin(value);
float lumR = 0.213f;
float lumG = 0.715f;
float lumB = 0.072f;
float[] mat = new float[]
{
lumR + cosVal * (1 - lumR) + sinVal * (-lumR), lumG + cosVal * (-lumG) + sinVal * (-lumG), lumB + cosVal * (-lumB) + sinVal * (1 - lumB), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (0.143f), lumG + cosVal * (1 - lumG) + sinVal * (0.140f), lumB + cosVal * (-lumB) + sinVal * (-0.283f), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (-(1 - lumR)), lumG + cosVal * (-lumG) + sinVal * (lumG), lumB + cosVal * (1 - lumB) + sinVal * (lumB), 0, 0,
0f, 0f, 0f, 1f, 0f
};
cm.postConcat(new ColorMatrix(mat));
} } | public class class_name {
public static void adjustHue(ColorMatrix cm, float value)
{
value = cleanValue(value, 180f) / 180f * (float) Math.PI;
if (value == 0)
{
return; // depends on control dependency: [if], data = [none]
}
float cosVal = (float) Math.cos(value);
float sinVal = (float) Math.sin(value);
float lumR = 0.213f;
float lumG = 0.715f;
float lumB = 0.072f;
float[] mat = new float[]
{
lumR + cosVal * (1 - lumR) + sinVal * (-lumR), lumG + cosVal * (-lumG) + sinVal * (-lumG), lumB + cosVal * (-lumB) + sinVal * (1 - lumB), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (0.143f), lumG + cosVal * (1 - lumG) + sinVal * (0.140f), lumB + cosVal * (-lumB) + sinVal * (-0.283f), 0, 0,
lumR + cosVal * (-lumR) + sinVal * (-(1 - lumR)), lumG + cosVal * (-lumG) + sinVal * (lumG), lumB + cosVal * (1 - lumB) + sinVal * (lumB), 0, 0,
0f, 0f, 0f, 1f, 0f
};
cm.postConcat(new ColorMatrix(mat));
} } |
public class class_name {
private void parseSchemasElement(Element element,
BeanDefinitionBuilder builder,
ParserContext parserContext) {
Element schemasElement = DomUtils.getChildElementByTagName(element, SCHEMAS);
if (schemasElement != null) {
List<Element> schemaElements = DomUtils.getChildElements(schemasElement);
ManagedList<RuntimeBeanReference> beanReferences = constructRuntimeBeanReferences(parserContext, schemaElements);
if (!beanReferences.isEmpty()) {
builder.addPropertyValue(SCHEMAS, beanReferences);
}
}
} } | public class class_name {
private void parseSchemasElement(Element element,
BeanDefinitionBuilder builder,
ParserContext parserContext) {
Element schemasElement = DomUtils.getChildElementByTagName(element, SCHEMAS);
if (schemasElement != null) {
List<Element> schemaElements = DomUtils.getChildElements(schemasElement);
ManagedList<RuntimeBeanReference> beanReferences = constructRuntimeBeanReferences(parserContext, schemaElements);
if (!beanReferences.isEmpty()) {
builder.addPropertyValue(SCHEMAS, beanReferences); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public Collection<Approval> getApprovals(String userId, String clientId) {
Collection<Approval> result = new HashSet<Approval>();
Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId);
for (OAuth2AccessToken token : tokens) {
OAuth2Authentication authentication = store.readAuthentication(token);
if (authentication != null) {
Date expiresAt = token.getExpiration();
for (String scope : token.getScope()) {
result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED));
}
}
}
return result;
} } | public class class_name {
@Override
public Collection<Approval> getApprovals(String userId, String clientId) {
Collection<Approval> result = new HashSet<Approval>();
Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId);
for (OAuth2AccessToken token : tokens) {
OAuth2Authentication authentication = store.readAuthentication(token);
if (authentication != null) {
Date expiresAt = token.getExpiration();
for (String scope : token.getScope()) {
result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED)); // depends on control dependency: [for], data = [scope]
}
}
}
return result;
} } |
public class class_name {
public static String getCallSimpleName(XAbstractFeatureCall featureCall,
ILogicalContainerProvider logicalContainerProvider,
IdentifiableSimpleNameProvider featureNameProvider,
Function0<? extends String> nullKeyword,
Function0<? extends String> thisKeyword,
Function0<? extends String> superKeyword,
Function1<? super JvmIdentifiableElement, ? extends String> referenceNameLambda) {
String name = null;
final JvmIdentifiableElement calledFeature = featureCall.getFeature();
if (calledFeature instanceof JvmConstructor) {
final JvmDeclaredType constructorContainer = ((JvmConstructor) calledFeature).getDeclaringType();
final JvmIdentifiableElement logicalContainer = logicalContainerProvider.getNearestLogicalContainer(featureCall);
final JvmDeclaredType contextType = ((JvmMember) logicalContainer).getDeclaringType();
if (contextType == constructorContainer) {
name = thisKeyword.apply();
} else {
name = superKeyword.apply();
}
} else if (calledFeature != null) {
final String referenceName = referenceNameLambda.apply(calledFeature);
if (referenceName != null) {
name = referenceName;
} else if (calledFeature instanceof JvmOperation) {
name = featureNameProvider.getSimpleName(calledFeature);
} else {
name = featureCall.getConcreteSyntaxFeatureName();
}
}
if (name == null) {
return nullKeyword.apply();
}
return name;
} } | public class class_name {
public static String getCallSimpleName(XAbstractFeatureCall featureCall,
ILogicalContainerProvider logicalContainerProvider,
IdentifiableSimpleNameProvider featureNameProvider,
Function0<? extends String> nullKeyword,
Function0<? extends String> thisKeyword,
Function0<? extends String> superKeyword,
Function1<? super JvmIdentifiableElement, ? extends String> referenceNameLambda) {
String name = null;
final JvmIdentifiableElement calledFeature = featureCall.getFeature();
if (calledFeature instanceof JvmConstructor) {
final JvmDeclaredType constructorContainer = ((JvmConstructor) calledFeature).getDeclaringType();
final JvmIdentifiableElement logicalContainer = logicalContainerProvider.getNearestLogicalContainer(featureCall);
final JvmDeclaredType contextType = ((JvmMember) logicalContainer).getDeclaringType();
if (contextType == constructorContainer) {
name = thisKeyword.apply(); // depends on control dependency: [if], data = [none]
} else {
name = superKeyword.apply(); // depends on control dependency: [if], data = [none]
}
} else if (calledFeature != null) {
final String referenceName = referenceNameLambda.apply(calledFeature);
if (referenceName != null) {
name = referenceName; // depends on control dependency: [if], data = [none]
} else if (calledFeature instanceof JvmOperation) {
name = featureNameProvider.getSimpleName(calledFeature); // depends on control dependency: [if], data = [none]
} else {
name = featureCall.getConcreteSyntaxFeatureName(); // depends on control dependency: [if], data = [none]
}
}
if (name == null) {
return nullKeyword.apply(); // depends on control dependency: [if], data = [none]
}
return name;
} } |
public class class_name {
private void publishEvent(WSJobExecution objectToPublish, String eventToPublishTo, String correlationId) {
if (eventsPublisher != null) {
eventsPublisher.publishJobExecutionEvent(objectToPublish, eventToPublishTo, correlationId);
}
} } | public class class_name {
private void publishEvent(WSJobExecution objectToPublish, String eventToPublishTo, String correlationId) {
if (eventsPublisher != null) {
eventsPublisher.publishJobExecutionEvent(objectToPublish, eventToPublishTo, correlationId); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public ModifyVpcEndpointRequest withAddSecurityGroupIds(String... addSecurityGroupIds) {
if (this.addSecurityGroupIds == null) {
setAddSecurityGroupIds(new com.amazonaws.internal.SdkInternalList<String>(addSecurityGroupIds.length));
}
for (String ele : addSecurityGroupIds) {
this.addSecurityGroupIds.add(ele);
}
return this;
} } | public class class_name {
public ModifyVpcEndpointRequest withAddSecurityGroupIds(String... addSecurityGroupIds) {
if (this.addSecurityGroupIds == null) {
setAddSecurityGroupIds(new com.amazonaws.internal.SdkInternalList<String>(addSecurityGroupIds.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : addSecurityGroupIds) {
this.addSecurityGroupIds.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private String buildUrlName(final String host, final String port) {
try {
return "tango://" + TangoUrl.getCanonicalName(host) + ":" + port;
}
catch (DevFailed e) {
return "tango://" + host + ":" + port;
}
} } | public class class_name {
private String buildUrlName(final String host, final String port) {
try {
return "tango://" + TangoUrl.getCanonicalName(host) + ":" + port;
}
catch (DevFailed e) {
return "tango://" + host + ":" + port;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public PeriodFormatter withParseType(PeriodType type) {
if (type == iParseType) {
return this;
}
return new PeriodFormatter(iPrinter, iParser, iLocale, type);
} } | public class class_name {
public PeriodFormatter withParseType(PeriodType type) {
if (type == iParseType) {
return this; // depends on control dependency: [if], data = [none]
}
return new PeriodFormatter(iPrinter, iParser, iLocale, type);
} } |
public class class_name {
private String sanitize(String path) {
String sanitized = path.replaceAll( "\\\\", "/" );
if ( sanitized.matches( "^[a-z]:.*" ) ) {
sanitized = sanitized.substring(0,1).toUpperCase() + sanitized.substring(1);
}
return sanitized;
} } | public class class_name {
private String sanitize(String path) {
String sanitized = path.replaceAll( "\\\\", "/" );
if ( sanitized.matches( "^[a-z]:.*" ) ) {
sanitized = sanitized.substring(0,1).toUpperCase() + sanitized.substring(1); // depends on control dependency: [if], data = [none]
}
return sanitized;
} } |
public class class_name {
private URI getRelativePath(final URI href) {
final URI keyValue;
final URI inputMap = job.getFileInfo(fi -> fi.isInput).stream()
.map(fi -> fi.uri)
.findFirst()
.orElse(null);
if (inputMap != null) {
final URI tmpMap = job.tempDirURI.resolve(inputMap);
keyValue = tmpMap.resolve(stripFragment(href));
} else {
keyValue = job.tempDirURI.resolve(stripFragment(href));
}
return URLUtils.getRelativePath(currentFile, keyValue);
} } | public class class_name {
private URI getRelativePath(final URI href) {
final URI keyValue;
final URI inputMap = job.getFileInfo(fi -> fi.isInput).stream()
.map(fi -> fi.uri)
.findFirst()
.orElse(null);
if (inputMap != null) {
final URI tmpMap = job.tempDirURI.resolve(inputMap);
keyValue = tmpMap.resolve(stripFragment(href)); // depends on control dependency: [if], data = [none]
} else {
keyValue = job.tempDirURI.resolve(stripFragment(href)); // depends on control dependency: [if], data = [none]
}
return URLUtils.getRelativePath(currentFile, keyValue);
} } |
public class class_name {
protected void setConnectionType(VirtualConnection vc) {
if (this.myType == 0 || vc == null) {
ConnectionType newType = ConnectionType.getVCConnectionType(vc);
this.myType = (newType == null) ? 0 : newType.export();
}
} } | public class class_name {
protected void setConnectionType(VirtualConnection vc) {
if (this.myType == 0 || vc == null) {
ConnectionType newType = ConnectionType.getVCConnectionType(vc);
this.myType = (newType == null) ? 0 : newType.export(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getString(String key) {
if (key == null || key.isEmpty()) {
return null;
}
String property = null;
for (ConfigurationSource configurationSource : configurationSources) {
property = configurationSource.getValue(key);
if (property != null) {
break;
}
}
return property;
} } | public class class_name {
public String getString(String key) {
if (key == null || key.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
String property = null;
for (ConfigurationSource configurationSource : configurationSources) {
property = configurationSource.getValue(key); // depends on control dependency: [for], data = [configurationSource]
if (property != null) {
break;
}
}
return property;
} } |
public class class_name {
private void sendInputStream(InputStream inputStream) {
byte[] buffer = new byte[ONE_KB];
int read;
try {
// This method uses a blocking while loop to receive all contents of the underlying input stream.
// AudioInputStreams, typically used for streaming microphone inputs return 0 only when the stream has been
// closed. Elsewise AudioInputStream.read() blocks until enough audio frames are read.
while (((read = inputStream.read(buffer)) > 0) && socketOpen) {
// If OkHttp's WebSocket queue gets overwhelmed, it'll abruptly close the connection
// (see: https://github.com/square/okhttp/issues/3317). This will ensure we wait until the coast is clear.
while (socket.queueSize() > QUEUE_SIZE_LIMIT) {
Thread.sleep(QUEUE_WAIT_MILLIS);
}
if (read == ONE_KB) {
socket.send(ByteString.of(buffer));
} else {
socket.send(ByteString.of(Arrays.copyOfRange(buffer, 0, read)));
}
}
} catch (IOException | InterruptedException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// do nothing - the InputStream may have already been closed externally.
}
}
} } | public class class_name {
private void sendInputStream(InputStream inputStream) {
byte[] buffer = new byte[ONE_KB];
int read;
try {
// This method uses a blocking while loop to receive all contents of the underlying input stream.
// AudioInputStreams, typically used for streaming microphone inputs return 0 only when the stream has been
// closed. Elsewise AudioInputStream.read() blocks until enough audio frames are read.
while (((read = inputStream.read(buffer)) > 0) && socketOpen) {
// If OkHttp's WebSocket queue gets overwhelmed, it'll abruptly close the connection
// (see: https://github.com/square/okhttp/issues/3317). This will ensure we wait until the coast is clear.
while (socket.queueSize() > QUEUE_SIZE_LIMIT) {
Thread.sleep(QUEUE_WAIT_MILLIS); // depends on control dependency: [while], data = [none]
}
if (read == ONE_KB) {
socket.send(ByteString.of(buffer)); // depends on control dependency: [if], data = [none]
} else {
socket.send(ByteString.of(Arrays.copyOfRange(buffer, 0, read))); // depends on control dependency: [if], data = [none]
}
}
} catch (IOException | InterruptedException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
} finally { // depends on control dependency: [catch], data = [none]
try {
inputStream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// do nothing - the InputStream may have already been closed externally.
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override
public void setProperties(Configuration<?> config) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "setProperties", config);
}
if (properties != null) {
for (Property ptype : properties) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Name is " + ptype.getName() + "Value is " + ptype.getValue());
}
config.addProperty(ptype.getName(), ptype.getValue());
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "setProperties");
}
} } | public class class_name {
@Override
public void setProperties(Configuration<?> config) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "setProperties", config); // depends on control dependency: [if], data = [none]
}
if (properties != null) {
for (Property ptype : properties) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Name is " + ptype.getName() + "Value is " + ptype.getValue()); // depends on control dependency: [if], data = [none]
}
config.addProperty(ptype.getName(), ptype.getValue()); // depends on control dependency: [for], data = [ptype]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "setProperties"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static boolean isCentralRepositoryFromSuperPom( Repository repo )
{
if ( repo != null )
{
if ( "central".equals( repo.getId() ) )
{
RepositoryPolicy snapshots = repo.getSnapshots();
if ( snapshots != null && !snapshots.isEnabled() )
{
return true;
}
}
}
return false;
} } | public class class_name {
private static boolean isCentralRepositoryFromSuperPom( Repository repo )
{
if ( repo != null )
{
if ( "central".equals( repo.getId() ) )
{
RepositoryPolicy snapshots = repo.getSnapshots();
if ( snapshots != null && !snapshots.isEnabled() )
{
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
private void tokenizeChinese(JCas jcas) {
try {
// read tokenized text to add tokens to the jcas
Process proc = ttprops.getChineseTokenizationProcess();
Logger.printDetail(component, "Chinese tokenization: " + ttprops.chineseTokenizerPath);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream(), "UTF-8"));
Integer tokenOffset = 0;
// loop through all the lines in the stdout output
String[] inSplits = jcas.getDocumentText().split("[\\r\\n]+");
for(String inSplit : inSplits) {
out.write(inSplit);
out.newLine();
out.flush();
// do one initial read
String s = in.readLine();
do {
// break out of the loop if we've read a null
if(s == null)
break;
String[] outSplits = s.split("\\s+");
for(String tok : outSplits) {
if(jcas.getDocumentText().indexOf(tok, tokenOffset) < 0)
throw new RuntimeException("Could not find token " + tok +
" in JCas after tokenizing with Chinese tokenization script.");
// create tokens and add them to the jcas's indexes.
Token newToken = new Token(jcas);
newToken.setBegin(jcas.getDocumentText().indexOf(tok, tokenOffset));
newToken.setEnd(newToken.getBegin() + tok.length());
newToken.addToIndexes();
tokenOffset = newToken.getEnd();
}
// break out of the loop if the next read will block
if(!in.ready())
break;
s = in.readLine();
} while(true);
}
// clean up
in.close();
proc.destroy();
} catch (Exception e) {
e.printStackTrace();
}
} } | public class class_name {
private void tokenizeChinese(JCas jcas) {
try {
// read tokenized text to add tokens to the jcas
Process proc = ttprops.getChineseTokenizationProcess();
Logger.printDetail(component, "Chinese tokenization: " + ttprops.chineseTokenizerPath); // depends on control dependency: [try], data = [none]
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream(), "UTF-8"));
Integer tokenOffset = 0;
// loop through all the lines in the stdout output
String[] inSplits = jcas.getDocumentText().split("[\\r\\n]+");
for(String inSplit : inSplits) {
out.write(inSplit); // depends on control dependency: [for], data = [inSplit]
out.newLine(); // depends on control dependency: [for], data = [none]
out.flush(); // depends on control dependency: [for], data = [none]
// do one initial read
String s = in.readLine();
do {
// break out of the loop if we've read a null
if(s == null)
break;
String[] outSplits = s.split("\\s+");
for(String tok : outSplits) {
if(jcas.getDocumentText().indexOf(tok, tokenOffset) < 0)
throw new RuntimeException("Could not find token " + tok +
" in JCas after tokenizing with Chinese tokenization script.");
// create tokens and add them to the jcas's indexes.
Token newToken = new Token(jcas);
newToken.setBegin(jcas.getDocumentText().indexOf(tok, tokenOffset)); // depends on control dependency: [for], data = [tok]
newToken.setEnd(newToken.getBegin() + tok.length()); // depends on control dependency: [for], data = [tok]
newToken.addToIndexes(); // depends on control dependency: [for], data = [none]
tokenOffset = newToken.getEnd(); // depends on control dependency: [for], data = [tok]
}
// break out of the loop if the next read will block
if(!in.ready())
break;
s = in.readLine();
} while(true);
}
// clean up
in.close(); // depends on control dependency: [try], data = [none]
proc.destroy(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void addLevelsToDatabase(final BuildDatabase buildDatabase, final Level level) {
// Add the level to the database
buildDatabase.add(level);
// Add the child levels to the database
for (final Level childLevel : level.getChildLevels()) {
addLevelsToDatabase(buildDatabase, childLevel);
}
} } | public class class_name {
public static void addLevelsToDatabase(final BuildDatabase buildDatabase, final Level level) {
// Add the level to the database
buildDatabase.add(level);
// Add the child levels to the database
for (final Level childLevel : level.getChildLevels()) {
addLevelsToDatabase(buildDatabase, childLevel); // depends on control dependency: [for], data = [childLevel]
}
} } |
public class class_name {
public List<Map<String, Object>> getNstd() {
if (nstd == null) {
nstd = new ArrayList<>();
}
return nstd;
} } | public class class_name {
public List<Map<String, Object>> getNstd() {
if (nstd == null) {
nstd = new ArrayList<>(); // depends on control dependency: [if], data = [none]
}
return nstd;
} } |
public class class_name {
public String getTextOrDefault(String defaultValueIfEmpty) {
String text = getText();
if(text.isEmpty()) {
return defaultValueIfEmpty;
}
return text;
} } | public class class_name {
public String getTextOrDefault(String defaultValueIfEmpty) {
String text = getText();
if(text.isEmpty()) {
return defaultValueIfEmpty; // depends on control dependency: [if], data = [none]
}
return text;
} } |
public class class_name {
@Override
public boolean isScreenOn() {
CommandLine command = adbCommand("shell", "dumpsys power");
try {
String powerState = ShellCommand.exec(command).toLowerCase();
if (powerState.indexOf("mscreenon=true") > -1
|| powerState.indexOf("mpowerstate=0") == -1) {
return true;
}
} catch (ShellCommandException e) {
log.info("Could not get property init.svc.bootanim", e);
}
return false;
} } | public class class_name {
@Override
public boolean isScreenOn() {
CommandLine command = adbCommand("shell", "dumpsys power");
try {
String powerState = ShellCommand.exec(command).toLowerCase();
if (powerState.indexOf("mscreenon=true") > -1
|| powerState.indexOf("mpowerstate=0") == -1) {
return true; // depends on control dependency: [if], data = [none]
}
} catch (ShellCommandException e) {
log.info("Could not get property init.svc.bootanim", e);
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
public ModelAdapter<?, Item> clear() {
if (mOriginalItems != null) {
mOriginalItems.clear();
publishResults(mConstraint, performFiltering(mConstraint));
return mItemAdapter;
} else {
return mItemAdapter.clear();
}
} } | public class class_name {
public ModelAdapter<?, Item> clear() {
if (mOriginalItems != null) {
mOriginalItems.clear(); // depends on control dependency: [if], data = [none]
publishResults(mConstraint, performFiltering(mConstraint)); // depends on control dependency: [if], data = [none]
return mItemAdapter; // depends on control dependency: [if], data = [none]
} else {
return mItemAdapter.clear(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void main(String[] args) {
try(FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("classpath:applicationContext-generator-bash.xml");){
logger.info("Context loaded");
ProjectMetaData projectMetaData = buildProjectMetaData(args);
Project project;
CodeGenerator codeGenerator = appContext.getBean(CodeGenerator.class);
try {
logger.info("start loading project");
ProjectLoader projectLoader = appContext.getBean(ProjectLoader.class);
project = projectLoader.loadProject(projectMetaData);
logger.info("loading project " + project.projectName + " completed");
} catch (Exception e) {
logger.error("failed", e);
return;
}
try {
logger.info("start persisting project");
ProjectMetaDataService projectMetaDataService = appContext.getBean(ProjectMetaDataService.class);
projectMetaDataService.initProjectMetaData(projectMetaData);
logger.info("persisting project completed");
} catch (Exception e) {
logger.error("failed", e);
return;
}
try {
logger.info("start copying resources");
codeGenerator.initResources(project);
logger.info("copying resources completed");
} catch (Exception e) {
logger.error("failed", e);
return;
}
try {
logger.info("start writing configuration");
codeGenerator.initConfiguration(project);
logger.info("writing configuration completed");
} catch (Exception e) {
logger.error("failed", e);
return;
}
}
} } | public class class_name {
public static void main(String[] args) {
try(FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("classpath:applicationContext-generator-bash.xml");){
logger.info("Context loaded");
ProjectMetaData projectMetaData = buildProjectMetaData(args);
Project project;
CodeGenerator codeGenerator = appContext.getBean(CodeGenerator.class);
try {
logger.info("start loading project");
// depends on control dependency: [try], data = [none]
ProjectLoader projectLoader = appContext.getBean(ProjectLoader.class);
project = projectLoader.loadProject(projectMetaData);
// depends on control dependency: [try], data = [none]
logger.info("loading project " + project.projectName + " completed");
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("failed", e);
return;
}
// depends on control dependency: [catch], data = [none]
try {
logger.info("start persisting project");
// depends on control dependency: [try], data = [none]
ProjectMetaDataService projectMetaDataService = appContext.getBean(ProjectMetaDataService.class);
projectMetaDataService.initProjectMetaData(projectMetaData);
// depends on control dependency: [try], data = [none]
logger.info("persisting project completed");
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("failed", e);
return;
}
// depends on control dependency: [catch], data = [none]
try {
logger.info("start copying resources");
// depends on control dependency: [try], data = [none]
codeGenerator.initResources(project);
// depends on control dependency: [try], data = [none]
logger.info("copying resources completed");
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("failed", e);
return;
}
// depends on control dependency: [catch], data = [none]
try {
logger.info("start writing configuration");
// depends on control dependency: [try], data = [none]
codeGenerator.initConfiguration(project);
// depends on control dependency: [try], data = [none]
logger.info("writing configuration completed");
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("failed", e);
return;
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static HttpResponse executeGet(final String url,
final Map<String, Object> parameters) {
try {
return executeGet(url, null, null, parameters);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
} } | public class class_name {
public static HttpResponse executeGet(final String url,
final Map<String, Object> parameters) {
try {
return executeGet(url, null, null, parameters); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
@SuppressWarnings({"unchecked", "rawtypes"})
public void setField(final FieldDescriptorType descriptor,
Object value) {
if (descriptor.isRepeated()) {
if (!(value instanceof List)) {
throw new IllegalArgumentException(
"Wrong object type used with protocol message reflection.");
}
// Wrap the contents in a new list so that the caller cannot change
// the list's contents after setting it.
final List newList = new ArrayList();
newList.addAll((List) value);
for (final Object element : newList) {
verifyType(descriptor.getLiteType(), element);
}
value = newList;
} else {
verifyType(descriptor.getLiteType(), value);
}
if (value instanceof LazyField) {
hasLazyField = true;
}
fields.put(descriptor, value);
} } | public class class_name {
@SuppressWarnings({"unchecked", "rawtypes"})
public void setField(final FieldDescriptorType descriptor,
Object value) {
if (descriptor.isRepeated()) {
if (!(value instanceof List)) {
throw new IllegalArgumentException(
"Wrong object type used with protocol message reflection.");
}
// Wrap the contents in a new list so that the caller cannot change
// the list's contents after setting it.
final List newList = new ArrayList();
newList.addAll((List) value); // depends on control dependency: [if], data = [none]
for (final Object element : newList) {
verifyType(descriptor.getLiteType(), element); // depends on control dependency: [for], data = [element]
}
value = newList; // depends on control dependency: [if], data = [none]
} else {
verifyType(descriptor.getLiteType(), value); // depends on control dependency: [if], data = [none]
}
if (value instanceof LazyField) {
hasLazyField = true; // depends on control dependency: [if], data = [none]
}
fields.put(descriptor, value);
} } |
public class class_name {
public static boolean isCompositeComponent(UIComponent component) {
if (component == null) {
throw new NullPointerException();
}
boolean result = false;
if (null != component.isCompositeComponent) {
result = component.isCompositeComponent.booleanValue();
} else {
result = component.isCompositeComponent =
(component.getAttributes().containsKey(
Resource.COMPONENT_RESOURCE_KEY));
}
return result;
} } | public class class_name {
public static boolean isCompositeComponent(UIComponent component) {
if (component == null) {
throw new NullPointerException();
}
boolean result = false;
if (null != component.isCompositeComponent) {
result = component.isCompositeComponent.booleanValue(); // depends on control dependency: [if], data = [none]
} else {
result = component.isCompositeComponent =
(component.getAttributes().containsKey(
Resource.COMPONENT_RESOURCE_KEY)); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
String generateHtmlForElement(boolean firstRun, MessageSource messageSource, FormCheckerElement elem, boolean html5Validation) {
InputElementStructure inputStruct = new InputElementStructure();
// errors
ValidationResult vr = getErrors(elem, firstRun);
if (!vr.isValid()) {
inputStruct.setErrors(formatError(messageSource.getMessage(vr)));
}
// label
boolean displayLabel = !StringUtils.isEmpty(elem.getDescription());
if (displayLabel) {
inputStruct.setLabel(getLabelForElement(elem, getLabelAttributes(elem), firstRun));
}
// input tag
Map<String, String> attribs = new LinkedHashMap<>();
addAttributesToInputFields(attribs, elem);
inputStruct.setInput(elem.getInputTag(attribs, messageSource, html5Validation));
// help tag
if (!StringUtils.isEmpty(elem.getHelpText())) {
inputStruct.setHelp(getHelpTag(elem.getHelpText(), elem));
}
return getCompleteRenderedInput(inputStruct, elem, firstRun);
} } | public class class_name {
String generateHtmlForElement(boolean firstRun, MessageSource messageSource, FormCheckerElement elem, boolean html5Validation) {
InputElementStructure inputStruct = new InputElementStructure();
// errors
ValidationResult vr = getErrors(elem, firstRun);
if (!vr.isValid()) {
inputStruct.setErrors(formatError(messageSource.getMessage(vr))); // depends on control dependency: [if], data = [none]
}
// label
boolean displayLabel = !StringUtils.isEmpty(elem.getDescription());
if (displayLabel) {
inputStruct.setLabel(getLabelForElement(elem, getLabelAttributes(elem), firstRun)); // depends on control dependency: [if], data = [none]
}
// input tag
Map<String, String> attribs = new LinkedHashMap<>();
addAttributesToInputFields(attribs, elem);
inputStruct.setInput(elem.getInputTag(attribs, messageSource, html5Validation));
// help tag
if (!StringUtils.isEmpty(elem.getHelpText())) {
inputStruct.setHelp(getHelpTag(elem.getHelpText(), elem)); // depends on control dependency: [if], data = [none]
}
return getCompleteRenderedInput(inputStruct, elem, firstRun);
} } |
public class class_name {
@GET
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(I18nPermissions.LOCALE_READ)
public Response getSupportedLocales() {
List<LocaleRepresentation> locales = supportedLocaleFinder.findSupportedLocales();
if (!locales.isEmpty()) {
return Response.ok(locales).build();
}
return Response.noContent().build();
} } | public class class_name {
@GET
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(I18nPermissions.LOCALE_READ)
public Response getSupportedLocales() {
List<LocaleRepresentation> locales = supportedLocaleFinder.findSupportedLocales();
if (!locales.isEmpty()) {
return Response.ok(locales).build(); // depends on control dependency: [if], data = [none]
}
return Response.noContent().build();
} } |
public class class_name {
public String resolveStaticField(ValueExpression exprVE) {
if (exprVE != null) {
String exprStr = exprVE.getExpressionString();
Matcher matcher = STATIC_FIELD_PATTERN.matcher(exprStr);
if (matcher.find()) {
return matcher.group(1);
}
}
return null;
} } | public class class_name {
public String resolveStaticField(ValueExpression exprVE) {
if (exprVE != null) {
String exprStr = exprVE.getExpressionString();
Matcher matcher = STATIC_FIELD_PATTERN.matcher(exprStr);
if (matcher.find()) {
return matcher.group(1); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void setTransitGateways(java.util.Collection<TransitGateway> transitGateways) {
if (transitGateways == null) {
this.transitGateways = null;
return;
}
this.transitGateways = new com.amazonaws.internal.SdkInternalList<TransitGateway>(transitGateways);
} } | public class class_name {
public void setTransitGateways(java.util.Collection<TransitGateway> transitGateways) {
if (transitGateways == null) {
this.transitGateways = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.transitGateways = new com.amazonaws.internal.SdkInternalList<TransitGateway>(transitGateways);
} } |
public class class_name {
protected final String parseSystemId(char quoteChar, boolean convertLFs,
String errorMsg)
throws XMLStreamException
{
char[] buf = getNameBuffer(-1);
int ptr = 0;
while (true) {
char c = (mInputPtr < mInputEnd) ?
mInputBuffer[mInputPtr++] : getNextChar(errorMsg);
if (c == quoteChar) {
break;
}
/* ??? 14-Jun-2004, TSa: Should we normalize linefeeds or not?
* It seems like we should, for all input... so that's the way it
* works.
*/
if (c == '\n') {
markLF();
} else if (c == '\r') {
if (peekNext() == '\n') {
++mInputPtr;
if (!convertLFs) {
/* The only tricky thing; need to preserve 2-char LF; need to
* output one char from here, then can fall back to default:
*/
if (ptr >= buf.length) {
buf = expandBy50Pct(buf);
}
buf[ptr++] = '\r';
}
c = '\n';
} else if (convertLFs) {
c = '\n';
}
}
// Other than that, let's just append it:
if (ptr >= buf.length) {
buf = expandBy50Pct(buf);
}
buf[ptr++] = c;
}
return (ptr == 0) ? "" : new String(buf, 0, ptr);
} } | public class class_name {
protected final String parseSystemId(char quoteChar, boolean convertLFs,
String errorMsg)
throws XMLStreamException
{
char[] buf = getNameBuffer(-1);
int ptr = 0;
while (true) {
char c = (mInputPtr < mInputEnd) ?
mInputBuffer[mInputPtr++] : getNextChar(errorMsg);
if (c == quoteChar) {
break;
}
/* ??? 14-Jun-2004, TSa: Should we normalize linefeeds or not?
* It seems like we should, for all input... so that's the way it
* works.
*/
if (c == '\n') {
markLF(); // depends on control dependency: [if], data = [none]
} else if (c == '\r') {
if (peekNext() == '\n') {
++mInputPtr; // depends on control dependency: [if], data = [none]
if (!convertLFs) {
/* The only tricky thing; need to preserve 2-char LF; need to
* output one char from here, then can fall back to default:
*/
if (ptr >= buf.length) {
buf = expandBy50Pct(buf); // depends on control dependency: [if], data = [none]
}
buf[ptr++] = '\r'; // depends on control dependency: [if], data = [none]
}
c = '\n'; // depends on control dependency: [if], data = [none]
} else if (convertLFs) {
c = '\n'; // depends on control dependency: [if], data = [none]
}
}
// Other than that, let's just append it:
if (ptr >= buf.length) {
buf = expandBy50Pct(buf); // depends on control dependency: [if], data = [none]
}
buf[ptr++] = c;
}
return (ptr == 0) ? "" : new String(buf, 0, ptr);
} } |
public class class_name {
private String generateParsedSql(ProcessedInput processedInput) {
String originalSql = processedInput.getOriginalSql();
StringBuilder actualSql = new StringBuilder();
List paramNames = processedInput.getSqlParameterNames();
int lastIndex = 0;
for (int i = 0; i < paramNames.size(); i++) {
int[] indexes = processedInput.getSqlParameterBoundaries().get(i);
int startIndex = indexes[0];
int endIndex = indexes[1];
actualSql.append(originalSql.substring(lastIndex, startIndex));
actualSql.append("?");
lastIndex = endIndex;
}
actualSql.append(originalSql.substring(lastIndex, originalSql.length()));
return actualSql.toString();
} } | public class class_name {
private String generateParsedSql(ProcessedInput processedInput) {
String originalSql = processedInput.getOriginalSql();
StringBuilder actualSql = new StringBuilder();
List paramNames = processedInput.getSqlParameterNames();
int lastIndex = 0;
for (int i = 0; i < paramNames.size(); i++) {
int[] indexes = processedInput.getSqlParameterBoundaries().get(i);
int startIndex = indexes[0];
int endIndex = indexes[1];
actualSql.append(originalSql.substring(lastIndex, startIndex));
// depends on control dependency: [for], data = [none]
actualSql.append("?");
// depends on control dependency: [for], data = [none]
lastIndex = endIndex;
// depends on control dependency: [for], data = [none]
}
actualSql.append(originalSql.substring(lastIndex, originalSql.length()));
return actualSql.toString();
} } |
public class class_name {
public static int[] colRowFromCoordinate( Coordinate coordinate, GridGeometry2D gridGeometry, Point point ) {
try {
DirectPosition pos = new DirectPosition2D(coordinate.x, coordinate.y);
GridCoordinates2D worldToGrid = gridGeometry.worldToGrid(pos);
if (point != null) {
point.x = worldToGrid.x;
point.y = worldToGrid.y;
}
return new int[]{worldToGrid.x, worldToGrid.y};
} catch (InvalidGridGeometryException e) {
e.printStackTrace();
} catch (TransformException e) {
e.printStackTrace();
}
point.x = Integer.MAX_VALUE;
point.y = Integer.MAX_VALUE;
return null;
} } | public class class_name {
public static int[] colRowFromCoordinate( Coordinate coordinate, GridGeometry2D gridGeometry, Point point ) {
try {
DirectPosition pos = new DirectPosition2D(coordinate.x, coordinate.y);
GridCoordinates2D worldToGrid = gridGeometry.worldToGrid(pos);
if (point != null) {
point.x = worldToGrid.x; // depends on control dependency: [if], data = [none]
point.y = worldToGrid.y; // depends on control dependency: [if], data = [none]
}
return new int[]{worldToGrid.x, worldToGrid.y}; // depends on control dependency: [try], data = [none]
} catch (InvalidGridGeometryException e) {
e.printStackTrace();
} catch (TransformException e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
point.x = Integer.MAX_VALUE;
point.y = Integer.MAX_VALUE;
return null;
} } |
public class class_name {
public Fleet withFleetErrors(FleetError... fleetErrors) {
if (this.fleetErrors == null) {
setFleetErrors(new java.util.ArrayList<FleetError>(fleetErrors.length));
}
for (FleetError ele : fleetErrors) {
this.fleetErrors.add(ele);
}
return this;
} } | public class class_name {
public Fleet withFleetErrors(FleetError... fleetErrors) {
if (this.fleetErrors == null) {
setFleetErrors(new java.util.ArrayList<FleetError>(fleetErrors.length)); // depends on control dependency: [if], data = [none]
}
for (FleetError ele : fleetErrors) {
this.fleetErrors.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = IDEWorkbenchPlugin.getDefault().getDialogSettings();
IDialogSettings section = settings.getSection(DIALOG_SETTINGS_SECTION);
if (section == null) {
section = settings.addNewSection(DIALOG_SETTINGS_SECTION);
}
return section;
} } | public class class_name {
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = IDEWorkbenchPlugin.getDefault().getDialogSettings();
IDialogSettings section = settings.getSection(DIALOG_SETTINGS_SECTION);
if (section == null) {
section = settings.addNewSection(DIALOG_SETTINGS_SECTION); // depends on control dependency: [if], data = [none]
}
return section;
} } |
public class class_name {
static TypeVariableSignature parse(final Parser parser, final String definingClassName) throws ParseException {
final char peek = parser.peek();
if (peek == 'T') {
parser.next();
if (!TypeUtils.getIdentifierToken(parser)) {
throw new ParseException(parser, "Could not parse type variable signature");
}
parser.expect(';');
final TypeVariableSignature typeVariableSignature = new TypeVariableSignature(parser.currToken(),
definingClassName);
// Save type variable signatures in the parser state, so method and class type signatures can link
// to type signatures
@SuppressWarnings("unchecked")
List<TypeVariableSignature> typeVariableSignatures = (List<TypeVariableSignature>) parser.getState();
if (typeVariableSignatures == null) {
parser.setState(typeVariableSignatures = new ArrayList<>());
}
typeVariableSignatures.add(typeVariableSignature);
return typeVariableSignature;
} else {
return null;
}
} } | public class class_name {
static TypeVariableSignature parse(final Parser parser, final String definingClassName) throws ParseException {
final char peek = parser.peek();
if (peek == 'T') {
parser.next();
if (!TypeUtils.getIdentifierToken(parser)) {
throw new ParseException(parser, "Could not parse type variable signature");
}
parser.expect(';');
final TypeVariableSignature typeVariableSignature = new TypeVariableSignature(parser.currToken(),
definingClassName);
// Save type variable signatures in the parser state, so method and class type signatures can link
// to type signatures
@SuppressWarnings("unchecked")
List<TypeVariableSignature> typeVariableSignatures = (List<TypeVariableSignature>) parser.getState();
if (typeVariableSignatures == null) {
parser.setState(typeVariableSignatures = new ArrayList<>()); // depends on control dependency: [if], data = [(typeVariableSignatures]
}
typeVariableSignatures.add(typeVariableSignature);
return typeVariableSignature;
} else {
return null;
}
} } |
public class class_name {
public List<JAXBElement<? extends AuthenticationConfigurationType>> getAuthenticationConfiguration() {
if (authenticationConfiguration == null) {
authenticationConfiguration = new ArrayList<JAXBElement<? extends AuthenticationConfigurationType>>();
}
return this.authenticationConfiguration;
} } | public class class_name {
public List<JAXBElement<? extends AuthenticationConfigurationType>> getAuthenticationConfiguration() {
if (authenticationConfiguration == null) {
authenticationConfiguration = new ArrayList<JAXBElement<? extends AuthenticationConfigurationType>>(); // depends on control dependency: [if], data = [none]
}
return this.authenticationConfiguration;
} } |
public class class_name {
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType();
}
return com.sun.tools.javac.code.Type.noType;
} } | public class class_name {
@Override @DefinedBy(Api.COMPILER_TREE)
public TypeMirror getOriginalType(javax.lang.model.type.ErrorType errorType) {
if (errorType instanceof com.sun.tools.javac.code.Type.ErrorType) {
return ((com.sun.tools.javac.code.Type.ErrorType)errorType).getOriginalType(); // depends on control dependency: [if], data = [none]
}
return com.sun.tools.javac.code.Type.noType;
} } |
public class class_name {
public static CmsVfsEntryBean generateVfsPreloadData(
final CmsObject cms,
final CmsTreeOpenState vfsState,
final Set<String> folders) {
CmsVfsEntryBean vfsPreloadData = null;
A_CmsTreeTabDataPreloader<CmsVfsEntryBean> vfsloader = new A_CmsTreeTabDataPreloader<CmsVfsEntryBean>() {
@SuppressWarnings("synthetic-access")
@Override
protected CmsVfsEntryBean createEntry(CmsObject innerCms, CmsResource resource) throws CmsException {
String title = innerCms.readPropertyObject(
resource,
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
boolean isEditable = false;
try {
isEditable = innerCms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.ALL);
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
}
return internalCreateVfsEntryBean(innerCms, resource, title, true, isEditable, null, false);
}
};
Set<CmsResource> treeOpenResources = Sets.newHashSet();
if (vfsState != null) {
for (CmsUUID structureId : vfsState.getOpenItems()) {
try {
treeOpenResources.add(cms.readResource(structureId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED));
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
CmsObject rootCms = null;
Set<CmsResource> folderSetResources = Sets.newHashSet();
try {
rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
if (!((folders == null) || folders.isEmpty())) {
for (String folder : folders) {
try {
folderSetResources.add(rootCms.readResource(folder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED));
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
} catch (CmsException e1) {
LOG.error(e1.getLocalizedMessage(), e1);
}
try {
vfsPreloadData = vfsloader.preloadData(cms, treeOpenResources, folderSetResources);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
return vfsPreloadData;
} } | public class class_name {
public static CmsVfsEntryBean generateVfsPreloadData(
final CmsObject cms,
final CmsTreeOpenState vfsState,
final Set<String> folders) {
CmsVfsEntryBean vfsPreloadData = null;
A_CmsTreeTabDataPreloader<CmsVfsEntryBean> vfsloader = new A_CmsTreeTabDataPreloader<CmsVfsEntryBean>() {
@SuppressWarnings("synthetic-access")
@Override
protected CmsVfsEntryBean createEntry(CmsObject innerCms, CmsResource resource) throws CmsException {
String title = innerCms.readPropertyObject(
resource,
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue();
boolean isEditable = false;
try {
isEditable = innerCms.hasPermissions(
resource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.ALL);
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
}
return internalCreateVfsEntryBean(innerCms, resource, title, true, isEditable, null, false);
}
};
Set<CmsResource> treeOpenResources = Sets.newHashSet();
if (vfsState != null) {
for (CmsUUID structureId : vfsState.getOpenItems()) {
try {
treeOpenResources.add(cms.readResource(structureId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
CmsObject rootCms = null;
Set<CmsResource> folderSetResources = Sets.newHashSet();
try {
rootCms = OpenCms.initCmsObject(cms); // depends on control dependency: [try], data = [none]
rootCms.getRequestContext().setSiteRoot(""); // depends on control dependency: [try], data = [none]
if (!((folders == null) || folders.isEmpty())) {
for (String folder : folders) {
try {
folderSetResources.add(rootCms.readResource(folder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
} catch (CmsException e1) {
LOG.error(e1.getLocalizedMessage(), e1);
} // depends on control dependency: [catch], data = [none]
try {
vfsPreloadData = vfsloader.preloadData(cms, treeOpenResources, folderSetResources); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
return vfsPreloadData;
} } |
public class class_name {
public GuidedDecisionTable52 upgrade(GuidedDecisionTable52 source) {
final GuidedDecisionTable52 destination = source;
for (BaseColumn column : source.getExpandedColumns()) {
DTColumnConfig52 dtColumn = null;
if (column instanceof MetadataCol52) {
dtColumn = (DTColumnConfig52) column;
} else if (column instanceof AttributeCol52) {
dtColumn = (DTColumnConfig52) column;
} else if (column instanceof ConditionCol52) {
dtColumn = (DTColumnConfig52) column;
} else if (column instanceof ActionCol52) {
dtColumn = (DTColumnConfig52) column;
}
if (dtColumn instanceof LimitedEntryCol) {
dtColumn = null;
}
if (dtColumn instanceof BRLVariableColumn) {
dtColumn = null;
}
if (dtColumn != null) {
final String legacyDefaultValue = dtColumn.defaultValue;
if (legacyDefaultValue != null) {
dtColumn.setDefaultValue(new DTCellValue52(legacyDefaultValue));
dtColumn.defaultValue = null;
}
}
}
return destination;
} } | public class class_name {
public GuidedDecisionTable52 upgrade(GuidedDecisionTable52 source) {
final GuidedDecisionTable52 destination = source;
for (BaseColumn column : source.getExpandedColumns()) {
DTColumnConfig52 dtColumn = null;
if (column instanceof MetadataCol52) {
dtColumn = (DTColumnConfig52) column; // depends on control dependency: [if], data = [none]
} else if (column instanceof AttributeCol52) {
dtColumn = (DTColumnConfig52) column; // depends on control dependency: [if], data = [none]
} else if (column instanceof ConditionCol52) {
dtColumn = (DTColumnConfig52) column; // depends on control dependency: [if], data = [none]
} else if (column instanceof ActionCol52) {
dtColumn = (DTColumnConfig52) column; // depends on control dependency: [if], data = [none]
}
if (dtColumn instanceof LimitedEntryCol) {
dtColumn = null; // depends on control dependency: [if], data = [none]
}
if (dtColumn instanceof BRLVariableColumn) {
dtColumn = null; // depends on control dependency: [if], data = [none]
}
if (dtColumn != null) {
final String legacyDefaultValue = dtColumn.defaultValue;
if (legacyDefaultValue != null) {
dtColumn.setDefaultValue(new DTCellValue52(legacyDefaultValue)); // depends on control dependency: [if], data = [(legacyDefaultValue]
dtColumn.defaultValue = null; // depends on control dependency: [if], data = [none]
}
}
}
return destination;
} } |
public class class_name {
@Override
public void run (long timeToRun) {
// Increment the frame number
frame++;
// Clear the list of tasks to run
runList.size = 0;
// Go through each task
for (int i = 0; i < schedulableRecords.size; i++) {
SchedulableRecord record = schedulableRecords.get(i);
// If it is due, schedule it
if ((frame + record.phase) % record.frequency == 0) runList.add(record);
}
// Keep track of the current time
long lastTime = TimeUtils.nanoTime();
// Find the number of tasks we need to run
int numToRun = runList.size;
// Go through the tasks to run
for (int i = 0; i < numToRun; i++) {
// Find the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime;
long availableTime = timeToRun / (numToRun - i);
// Run the schedulable object
runList.get(i).schedulable.run(availableTime);
// Store the current time
lastTime = currentTime;
}
} } | public class class_name {
@Override
public void run (long timeToRun) {
// Increment the frame number
frame++;
// Clear the list of tasks to run
runList.size = 0;
// Go through each task
for (int i = 0; i < schedulableRecords.size; i++) {
SchedulableRecord record = schedulableRecords.get(i);
// If it is due, schedule it
if ((frame + record.phase) % record.frequency == 0) runList.add(record);
}
// Keep track of the current time
long lastTime = TimeUtils.nanoTime();
// Find the number of tasks we need to run
int numToRun = runList.size;
// Go through the tasks to run
for (int i = 0; i < numToRun; i++) {
// Find the available time
long currentTime = TimeUtils.nanoTime();
timeToRun -= currentTime - lastTime; // depends on control dependency: [for], data = [none]
long availableTime = timeToRun / (numToRun - i);
// Run the schedulable object
runList.get(i).schedulable.run(availableTime); // depends on control dependency: [for], data = [i]
// Store the current time
lastTime = currentTime; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private SparseTensor reduceDimensions(Set<Integer> dimensionsToEliminate,
boolean useSum, Backpointers backpointers) {
// TODO(jayantk): This method can be generalized to support a
// generic reduce
// operation (as a function), but it's unclear what the effect on
// performance will be.
// Rotate all of the dimensions which are being eliminated to the
// end of the keyNums array.
int[] newLabels = new int[numDimensions()];
int[] inversionPermutation = new int[numDimensions()];
int[] newDimensions = new int[numDimensions()];
int[] newDimensionSizes = new int[numDimensions()];
int numEliminated = 0;
int[] dimensionNums = getDimensionNumbers();
int[] dimensionSizes = getDimensionSizes();
for (int i = 0; i < dimensionNums.length; i++) {
if (dimensionsToEliminate.contains(dimensionNums[i])) {
// Dimension labels must be unique, hence numEliminated.
newLabels[i] = Integer.MAX_VALUE - numEliminated;
inversionPermutation[dimensionNums.length - (numEliminated + 1)] = i;
numEliminated++;
} else {
newLabels[i] = dimensionNums[i];
inversionPermutation[i - numEliminated] = i;
newDimensions[i - numEliminated] = dimensionNums[i];
newDimensionSizes[i - numEliminated] = dimensionSizes[i];
}
}
if (numEliminated == 0) {
// If none of the dimensions being eliminated are actually part of
// this tensor, then there's no need to do any more work.
if (backpointers != null) {
backpointers.setBackpointers(keyNums, keyNums, keyNums.length, this);
}
return this;
} else if (numEliminated == dimensionNums.length && backpointers == null && useSum) {
// Faster implementation for summing up all values in the tensor,
// a common operation.
return sumOutAllDimensions();
}
SparseTensor relabeled = relabelDimensions(newLabels);
int resultNumDimensions = dimensionNums.length - numEliminated;
// Get a number which we can divide each key by to map it to a key
// in the reduced dimensional tensor.
long keyNumDenominator = (resultNumDimensions > 0) ? relabeled.indexOffsets[resultNumDimensions - 1] :
relabeled.indexOffsets[0] * relabeled.getDimensionSizes()[0];
long[] resultKeyInts = new long[relabeled.values.length];
long[] backpointerKeyInts = new long[relabeled.values.length];
double[] resultValues = new double[relabeled.values.length];
int resultInd = 0;
long[] relabeledKeyNums = relabeled.keyNums;
double[] relabeledValues = relabeled.values;
int relabeledValuesLength = relabeled.values.length;
for (int i = 0; i < relabeledValuesLength; i++) {
long relabeledKeyNumI = relabeledKeyNums[i];
if (i != 0 && resultInd > 0 &&
(relabeledKeyNumI / keyNumDenominator) == resultKeyInts[resultInd - 1]) {
// This key maps to the same entry as the previous key.
if (useSum) {
resultValues[resultInd - 1] += relabeledValues[i];
} else {
double resultVal = resultValues[resultInd - 1];
double relabeledVal = relabeledValues[i];
if (relabeledVal > resultVal) {
resultValues[resultInd - 1] = relabeledVal;
backpointerKeyInts[resultInd - 1] = relabeledKeyNumI;
}
}
} else {
if (resultInd > 0 && resultValues[resultInd - 1] == 0.0) {
// Make sure the result tensor contains no zero-valued
// entries.
resultInd--;
}
resultKeyInts[resultInd] = relabeledKeyNumI / keyNumDenominator;
backpointerKeyInts[resultInd] = relabeledKeyNumI;
resultValues[resultInd] = relabeledValues[i];
resultInd++;
}
int prevIndex = resultInd - 1;
if (!useSum && resultValues[prevIndex] < 0.0) {
// Ensure that, if values is negative, we include missing keys
// in the maximization.
long prevKeyNum = relabeledKeyNumI - 1;
long nextKeyNum = relabeledKeyNumI + 1;
if (i > 0 && relabeledKeyNums[i - 1] != prevKeyNum
&& prevKeyNum / keyNumDenominator == resultKeyInts[prevIndex]) {
// prevKeyNum is not in relabeled, but has a higher value
// than the current key.
resultValues[prevIndex] = 0.0;
backpointerKeyInts[prevIndex] = prevKeyNum;
} else if (i + 1 < relabeledValuesLength && relabeledKeyNums[i + 1] != nextKeyNum
&& nextKeyNum / keyNumDenominator == resultKeyInts[prevIndex]) {
// nextKeyNum is not in relabeled, but has a higher value
// than the current key. Delete the current key from the tensor.
resultValues[prevIndex] = 0.0;
backpointerKeyInts[prevIndex] = nextKeyNum;
}
}
}
if (backpointers != null) {
// backpointerKeyInts needs to have the inverse dimension
// relabeling applied to it.
long[] transformedBackpointers = transformKeyNums(backpointerKeyInts, relabeled.indexOffsets,
this.indexOffsets, inversionPermutation);
backpointers.setBackpointers(resultKeyInts, transformedBackpointers, resultInd, this);
}
return resizeIntoTable(ArrayUtils.copyOf(newDimensions, resultNumDimensions),
ArrayUtils.copyOf(newDimensionSizes, resultNumDimensions),
resultKeyInts, resultValues, resultInd);
} } | public class class_name {
private SparseTensor reduceDimensions(Set<Integer> dimensionsToEliminate,
boolean useSum, Backpointers backpointers) {
// TODO(jayantk): This method can be generalized to support a
// generic reduce
// operation (as a function), but it's unclear what the effect on
// performance will be.
// Rotate all of the dimensions which are being eliminated to the
// end of the keyNums array.
int[] newLabels = new int[numDimensions()];
int[] inversionPermutation = new int[numDimensions()];
int[] newDimensions = new int[numDimensions()];
int[] newDimensionSizes = new int[numDimensions()];
int numEliminated = 0;
int[] dimensionNums = getDimensionNumbers();
int[] dimensionSizes = getDimensionSizes();
for (int i = 0; i < dimensionNums.length; i++) {
if (dimensionsToEliminate.contains(dimensionNums[i])) {
// Dimension labels must be unique, hence numEliminated.
newLabels[i] = Integer.MAX_VALUE - numEliminated; // depends on control dependency: [if], data = [none]
inversionPermutation[dimensionNums.length - (numEliminated + 1)] = i; // depends on control dependency: [if], data = [none]
numEliminated++; // depends on control dependency: [if], data = [none]
} else {
newLabels[i] = dimensionNums[i]; // depends on control dependency: [if], data = [none]
inversionPermutation[i - numEliminated] = i; // depends on control dependency: [if], data = [none]
newDimensions[i - numEliminated] = dimensionNums[i]; // depends on control dependency: [if], data = [none]
newDimensionSizes[i - numEliminated] = dimensionSizes[i]; // depends on control dependency: [if], data = [none]
}
}
if (numEliminated == 0) {
// If none of the dimensions being eliminated are actually part of
// this tensor, then there's no need to do any more work.
if (backpointers != null) {
backpointers.setBackpointers(keyNums, keyNums, keyNums.length, this); // depends on control dependency: [if], data = [none]
}
return this; // depends on control dependency: [if], data = [none]
} else if (numEliminated == dimensionNums.length && backpointers == null && useSum) {
// Faster implementation for summing up all values in the tensor,
// a common operation.
return sumOutAllDimensions(); // depends on control dependency: [if], data = [none]
}
SparseTensor relabeled = relabelDimensions(newLabels);
int resultNumDimensions = dimensionNums.length - numEliminated;
// Get a number which we can divide each key by to map it to a key
// in the reduced dimensional tensor.
long keyNumDenominator = (resultNumDimensions > 0) ? relabeled.indexOffsets[resultNumDimensions - 1] :
relabeled.indexOffsets[0] * relabeled.getDimensionSizes()[0];
long[] resultKeyInts = new long[relabeled.values.length];
long[] backpointerKeyInts = new long[relabeled.values.length];
double[] resultValues = new double[relabeled.values.length];
int resultInd = 0;
long[] relabeledKeyNums = relabeled.keyNums;
double[] relabeledValues = relabeled.values;
int relabeledValuesLength = relabeled.values.length;
for (int i = 0; i < relabeledValuesLength; i++) {
long relabeledKeyNumI = relabeledKeyNums[i];
if (i != 0 && resultInd > 0 &&
(relabeledKeyNumI / keyNumDenominator) == resultKeyInts[resultInd - 1]) {
// This key maps to the same entry as the previous key.
if (useSum) {
resultValues[resultInd - 1] += relabeledValues[i]; // depends on control dependency: [if], data = [none]
} else {
double resultVal = resultValues[resultInd - 1];
double relabeledVal = relabeledValues[i];
if (relabeledVal > resultVal) {
resultValues[resultInd - 1] = relabeledVal; // depends on control dependency: [if], data = [none]
backpointerKeyInts[resultInd - 1] = relabeledKeyNumI; // depends on control dependency: [if], data = [none]
}
}
} else {
if (resultInd > 0 && resultValues[resultInd - 1] == 0.0) {
// Make sure the result tensor contains no zero-valued
// entries.
resultInd--; // depends on control dependency: [if], data = [none]
}
resultKeyInts[resultInd] = relabeledKeyNumI / keyNumDenominator; // depends on control dependency: [if], data = [none]
backpointerKeyInts[resultInd] = relabeledKeyNumI; // depends on control dependency: [if], data = [none]
resultValues[resultInd] = relabeledValues[i]; // depends on control dependency: [if], data = [none]
resultInd++; // depends on control dependency: [if], data = [none]
}
int prevIndex = resultInd - 1;
if (!useSum && resultValues[prevIndex] < 0.0) {
// Ensure that, if values is negative, we include missing keys
// in the maximization.
long prevKeyNum = relabeledKeyNumI - 1;
long nextKeyNum = relabeledKeyNumI + 1;
if (i > 0 && relabeledKeyNums[i - 1] != prevKeyNum
&& prevKeyNum / keyNumDenominator == resultKeyInts[prevIndex]) {
// prevKeyNum is not in relabeled, but has a higher value
// than the current key.
resultValues[prevIndex] = 0.0; // depends on control dependency: [if], data = [none]
backpointerKeyInts[prevIndex] = prevKeyNum; // depends on control dependency: [if], data = [prevKeyNum]
} else if (i + 1 < relabeledValuesLength && relabeledKeyNums[i + 1] != nextKeyNum
&& nextKeyNum / keyNumDenominator == resultKeyInts[prevIndex]) {
// nextKeyNum is not in relabeled, but has a higher value
// than the current key. Delete the current key from the tensor.
resultValues[prevIndex] = 0.0; // depends on control dependency: [if], data = [none]
backpointerKeyInts[prevIndex] = nextKeyNum; // depends on control dependency: [if], data = [none]
}
}
}
if (backpointers != null) {
// backpointerKeyInts needs to have the inverse dimension
// relabeling applied to it.
long[] transformedBackpointers = transformKeyNums(backpointerKeyInts, relabeled.indexOffsets,
this.indexOffsets, inversionPermutation);
backpointers.setBackpointers(resultKeyInts, transformedBackpointers, resultInd, this); // depends on control dependency: [if], data = [none]
}
return resizeIntoTable(ArrayUtils.copyOf(newDimensions, resultNumDimensions),
ArrayUtils.copyOf(newDimensionSizes, resultNumDimensions),
resultKeyInts, resultValues, resultInd);
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.