code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
protected void registerNamespace(
SqlValidatorScope usingScope,
String alias,
SqlValidatorNamespace ns,
boolean forceNullable) {
namespaces.put(ns.getNode(), ns);
if (usingScope != null) {
usingScope.addChild(ns, alias, forceNullable);
}
} } | public class class_name {
protected void registerNamespace(
SqlValidatorScope usingScope,
String alias,
SqlValidatorNamespace ns,
boolean forceNullable) {
namespaces.put(ns.getNode(), ns);
if (usingScope != null) {
usingScope.addChild(ns, alias, forceNullable); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(GetJobRequest getJobRequest, ProtocolMarshaller protocolMarshaller) {
if (getJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getJobRequest.getArn(), ARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetJobRequest getJobRequest, ProtocolMarshaller protocolMarshaller) {
if (getJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getJobRequest.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<Database> getInternalDatabases() {
List<Database> returnList = new ArrayList<>();
for (SortedSet<Database> set : internalDatabases.values()) {
returnList.add(set.iterator().next());
}
return returnList;
} } | public class class_name {
public List<Database> getInternalDatabases() {
List<Database> returnList = new ArrayList<>();
for (SortedSet<Database> set : internalDatabases.values()) {
returnList.add(set.iterator().next()); // depends on control dependency: [for], data = [set]
}
return returnList;
} } |
public class class_name {
public void setHeader(String name, String value) {
if(logger.isDebugEnabled()) {
logger.debug("setHeader - name=" + name + ", value=" + value);
}
if(name == null) {
throw new NullPointerException ("name parameter is null");
}
if(value == null) {
throw new NullPointerException ("value parameter is null");
}
if (isSystemHeader(getModifiableRule(name))) {
throw new IllegalArgumentException(name + " is a system header !");
}
checkCommitted();
try {
// Dealing with Allow:INVITE, ACK, CANCEL, OPTIONS, BYE kind of headers
if(JainSipUtils.LIST_HEADER_NAMES.contains(name)) {
this.message.removeHeader(name);
List<Header> headers = SipFactory.getInstance().createHeaderFactory()
.createHeaders(name + ":" + value);
for (Header header : headers) {
this.message.addHeader(header);
}
} else {
// dealing with non list headers and extension header
Header header = SipFactory.getInstance().createHeaderFactory()
.createHeader(name, value);
this.message.setHeader(header);
}
} catch (Exception e) {
throw new IllegalArgumentException("Error creating header!", e);
}
} } | public class class_name {
public void setHeader(String name, String value) {
if(logger.isDebugEnabled()) {
logger.debug("setHeader - name=" + name + ", value=" + value); // depends on control dependency: [if], data = [none]
}
if(name == null) {
throw new NullPointerException ("name parameter is null");
}
if(value == null) {
throw new NullPointerException ("value parameter is null");
}
if (isSystemHeader(getModifiableRule(name))) {
throw new IllegalArgumentException(name + " is a system header !");
}
checkCommitted();
try {
// Dealing with Allow:INVITE, ACK, CANCEL, OPTIONS, BYE kind of headers
if(JainSipUtils.LIST_HEADER_NAMES.contains(name)) {
this.message.removeHeader(name); // depends on control dependency: [if], data = [none]
List<Header> headers = SipFactory.getInstance().createHeaderFactory()
.createHeaders(name + ":" + value);
for (Header header : headers) {
this.message.addHeader(header); // depends on control dependency: [for], data = [header]
}
} else {
// dealing with non list headers and extension header
Header header = SipFactory.getInstance().createHeaderFactory()
.createHeader(name, value);
this.message.setHeader(header); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
throw new IllegalArgumentException("Error creating header!", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static FloatMatrix gemv(float alpha, FloatMatrix a,
FloatMatrix x, float beta, FloatMatrix y) {
if (false) {
NativeBlas.sgemv('N', a.rows, a.columns, alpha, a.data, 0, a.rows, x.data, 0,
1, beta, y.data, 0, 1);
} else {
if (beta != 0.0f) {
for (int i = 0; i < y.length; i++)
y.data[i] = beta * y.data[i];
} else {
for (int i = 0; i < y.length; i++)
y.data[i] = 0.0f;
}
for (int j = 0; j < a.columns; j++) {
float xj = x.get(j);
if (xj != 0.0f) {
for (int i = 0; i < a.rows; i++)
y.data[i] += alpha * a.get(i, j) * xj;
}
}
}
return y;
} } | public class class_name {
public static FloatMatrix gemv(float alpha, FloatMatrix a,
FloatMatrix x, float beta, FloatMatrix y) {
if (false) {
NativeBlas.sgemv('N', a.rows, a.columns, alpha, a.data, 0, a.rows, x.data, 0,
1, beta, y.data, 0, 1); // depends on control dependency: [if], data = [none]
} else {
if (beta != 0.0f) {
for (int i = 0; i < y.length; i++)
y.data[i] = beta * y.data[i];
} else {
for (int i = 0; i < y.length; i++)
y.data[i] = 0.0f;
}
for (int j = 0; j < a.columns; j++) {
float xj = x.get(j);
if (xj != 0.0f) {
for (int i = 0; i < a.rows; i++)
y.data[i] += alpha * a.get(i, j) * xj;
}
}
}
return y;
} } |
public class class_name {
public EjbLocalRefType<WebFragmentDescriptor> getOrCreateEjbLocalRef()
{
List<Node> nodeList = model.get("ejb-local-ref");
if (nodeList != null && nodeList.size() > 0)
{
return new EjbLocalRefTypeImpl<WebFragmentDescriptor>(this, "ejb-local-ref", model, nodeList.get(0));
}
return createEjbLocalRef();
} } | public class class_name {
public EjbLocalRefType<WebFragmentDescriptor> getOrCreateEjbLocalRef()
{
List<Node> nodeList = model.get("ejb-local-ref");
if (nodeList != null && nodeList.size() > 0)
{
return new EjbLocalRefTypeImpl<WebFragmentDescriptor>(this, "ejb-local-ref", model, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createEjbLocalRef();
} } |
public class class_name {
public static synchronized void update(Map<String, Object> newConfig) {
if (newConfig == null)
throw new NullPointerException("Updated config must not be null");
// Update the logging configuration
LogProviderConfig config = loggingConfig.get();
if (config != null) {
config.update(newConfig);
// Propagate updates to the delegate
getDelegate().update(config);
}
} } | public class class_name {
public static synchronized void update(Map<String, Object> newConfig) {
if (newConfig == null)
throw new NullPointerException("Updated config must not be null");
// Update the logging configuration
LogProviderConfig config = loggingConfig.get();
if (config != null) {
config.update(newConfig); // depends on control dependency: [if], data = [none]
// Propagate updates to the delegate
getDelegate().update(config); // depends on control dependency: [if], data = [(config]
}
} } |
public class class_name {
@Override
public void preparePaint(final Request request) {
if (windowId == null) {
super.preparePaint(request);
} else {
// Get the window component
ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
if (target == null) {
throw new SystemException("No window component for id " + windowId);
}
UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
Environment originalEnvironment = uic.getEnvironment();
uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target));
UIContextHolder.pushContext(target.getContext());
try {
super.preparePaint(request);
} finally {
uic.setEnvironment(originalEnvironment);
UIContextHolder.popContext();
}
}
} } | public class class_name {
@Override
public void preparePaint(final Request request) {
if (windowId == null) {
super.preparePaint(request); // depends on control dependency: [if], data = [none]
} else {
// Get the window component
ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
if (target == null) {
throw new SystemException("No window component for id " + windowId);
}
UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
Environment originalEnvironment = uic.getEnvironment();
uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target)); // depends on control dependency: [if], data = [none]
UIContextHolder.pushContext(target.getContext()); // depends on control dependency: [if], data = [none]
try {
super.preparePaint(request); // depends on control dependency: [try], data = [none]
} finally {
uic.setEnvironment(originalEnvironment);
UIContextHolder.popContext();
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T extends Annotation> T getParameterAnnotation(Class<T> annotationType) {
Annotation[] anns = getParameterAnnotations();
for (Annotation ann : anns) {
if (annotationType.isInstance(ann)) {
return (T) ann;
}
}
return null;
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T extends Annotation> T getParameterAnnotation(Class<T> annotationType) {
Annotation[] anns = getParameterAnnotations();
for (Annotation ann : anns) {
if (annotationType.isInstance(ann)) {
return (T) ann; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public Map<DependencyDescriptor, Set<DependencyDescriptor>> getDependencies() {
if (dependencyMap == null) {
dependencyMap = GradleDependencyResolutionHelper.determineProjectDependencies(project, "runtimeClasspath", true);
}
return dependencyMap;
} } | public class class_name {
@Override
public Map<DependencyDescriptor, Set<DependencyDescriptor>> getDependencies() {
if (dependencyMap == null) {
dependencyMap = GradleDependencyResolutionHelper.determineProjectDependencies(project, "runtimeClasspath", true); // depends on control dependency: [if], data = [none]
}
return dependencyMap;
} } |
public class class_name {
public CallTreeNode getOrAddChild(String name) {
CallTreeNode child = getChild(name);
if (child == null) {
child = addChild(name);
}
return child;
} } | public class class_name {
public CallTreeNode getOrAddChild(String name) {
CallTreeNode child = getChild(name);
if (child == null) {
child = addChild(name);
// depends on control dependency: [if], data = [none]
}
return child;
} } |
public class class_name {
public static SimpleModule createJacksonModule(boolean serializeLinksAsObjects) {
SimpleModule simpleModule = new SimpleModule(JSON_API_JACKSON_MODULE_NAME,
new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(new ErrorDataSerializer());
simpleModule.addDeserializer(ErrorData.class, new ErrorDataDeserializer());
if (serializeLinksAsObjects) {
simpleModule.addSerializer(new LinksInformationSerializer());
}
return simpleModule;
} } | public class class_name {
public static SimpleModule createJacksonModule(boolean serializeLinksAsObjects) {
SimpleModule simpleModule = new SimpleModule(JSON_API_JACKSON_MODULE_NAME,
new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(new ErrorDataSerializer());
simpleModule.addDeserializer(ErrorData.class, new ErrorDataDeserializer());
if (serializeLinksAsObjects) {
simpleModule.addSerializer(new LinksInformationSerializer()); // depends on control dependency: [if], data = [none]
}
return simpleModule;
} } |
public class class_name {
private Glyph createGlyph(Entity e)
{
String id = convertID(e.getUri());
if (glyphMap.containsKey(id))
return glyphMap.get(id);
// Create its glyph and register
Glyph g = createGlyphBasics(e, true);
glyphMap.put(g.getId(), g);
//TODO: export metadata (e.g., from bpe.getAnnotations() map) using the SBGN Extension feature
// SBGNBase.Extension ext = new SBGNBase.Extension();
// g.setExtension(ext);
// Element el = biopaxMetaDoc.createElement(e.getModelInterface().getSimpleName());
// el.setAttribute("uri", e.getUri());
// ext.getAny().add(el);
if (g.getClone() != null)
ubiqueSet.add(g);
if(e instanceof PhysicalEntity) {
PhysicalEntity pe = (PhysicalEntity) e;
assignLocation(pe, g);
if("or".equalsIgnoreCase(g.getClazz())) {
buildGeneric(pe, g, null);
} else if (pe instanceof Complex) {
createComplexContent((Complex) pe, g);
}
}
return g;
} } | public class class_name {
private Glyph createGlyph(Entity e)
{
String id = convertID(e.getUri());
if (glyphMap.containsKey(id))
return glyphMap.get(id);
// Create its glyph and register
Glyph g = createGlyphBasics(e, true);
glyphMap.put(g.getId(), g);
//TODO: export metadata (e.g., from bpe.getAnnotations() map) using the SBGN Extension feature
// SBGNBase.Extension ext = new SBGNBase.Extension();
// g.setExtension(ext);
// Element el = biopaxMetaDoc.createElement(e.getModelInterface().getSimpleName());
// el.setAttribute("uri", e.getUri());
// ext.getAny().add(el);
if (g.getClone() != null)
ubiqueSet.add(g);
if(e instanceof PhysicalEntity) {
PhysicalEntity pe = (PhysicalEntity) e;
assignLocation(pe, g); // depends on control dependency: [if], data = [none]
if("or".equalsIgnoreCase(g.getClazz())) {
buildGeneric(pe, g, null); // depends on control dependency: [if], data = [none]
} else if (pe instanceof Complex) {
createComplexContent((Complex) pe, g); // depends on control dependency: [if], data = [none]
}
}
return g;
} } |
public class class_name {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
otherListeners.addAll(getDefaultOtherListeners());
contextInitialized(servletContextEvent.getServletContext());
for(ServletContextListener listener : otherListeners) {
try {
listener.contextInitialized(servletContextEvent);
}
catch(Exception e){
classLoaderLeakPreventor.error(e);
}
}
} } | public class class_name {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
otherListeners.addAll(getDefaultOtherListeners());
contextInitialized(servletContextEvent.getServletContext());
for(ServletContextListener listener : otherListeners) {
try {
listener.contextInitialized(servletContextEvent); // depends on control dependency: [try], data = [none]
}
catch(Exception e){
classLoaderLeakPreventor.error(e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
if (targets.isEmpty()) {
return null;
}
Symbol descSym = findDescriptorSymbol(targets.head.tsym);
Type descType = findDescriptorType(targets.head);
ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
csym.completer = null;
csym.members_field = new Scope(csym);
MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
csym.members_field.enter(instDescSym);
Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = targets;
csym.type = ctype;
csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
return csym;
} } | public class class_name {
public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
if (targets.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
Symbol descSym = findDescriptorSymbol(targets.head.tsym);
Type descType = findDescriptorType(targets.head);
ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
csym.completer = null;
csym.members_field = new Scope(csym);
MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
csym.members_field.enter(instDescSym);
Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = targets;
csym.type = ctype;
csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
return csym;
} } |
public class class_name {
public void urlEquals(double seconds, String expectedURL) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.urlToBe(expectedURL));
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkUrlEquals(expectedURL, seconds, timeTook);
} catch (TimeoutException e) {
checkUrlEquals(expectedURL, seconds, seconds);
}
} } | public class class_name {
public void urlEquals(double seconds, String expectedURL) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
WebDriverWait wait = new WebDriverWait(app.getDriver(), (long) seconds, DEFAULT_POLLING_INTERVAL);
wait.until(ExpectedConditions.urlToBe(expectedURL)); // depends on control dependency: [try], data = [none]
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkUrlEquals(expectedURL, seconds, timeTook); // depends on control dependency: [try], data = [none]
} catch (TimeoutException e) {
checkUrlEquals(expectedURL, seconds, seconds);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static BasicTagList copyOf(Iterable<String> tags) {
SmallTagMap.Builder builder = SmallTagMap.builder();
for (String tag : tags) {
builder.add(Tags.parseTag(tag));
}
return new BasicTagList(builder.result());
} } | public class class_name {
public static BasicTagList copyOf(Iterable<String> tags) {
SmallTagMap.Builder builder = SmallTagMap.builder();
for (String tag : tags) {
builder.add(Tags.parseTag(tag)); // depends on control dependency: [for], data = [tag]
}
return new BasicTagList(builder.result());
} } |
public class class_name {
public static String encode(byte[] binaryData) {
if (binaryData.length != 16)
return null;
char[] buffer = new char[32];
for (int i = 0; i < 16; i++) {
int low = (int) (binaryData[i] & 0x0f);
int high = (int) ((binaryData[i] & 0xf0) >> 4);
buffer[i * 2] = hexadecimal[high];
buffer[i * 2 + 1] = hexadecimal[low];
}
return new String(buffer);
} } | public class class_name {
public static String encode(byte[] binaryData) {
if (binaryData.length != 16)
return null;
char[] buffer = new char[32];
for (int i = 0; i < 16; i++) {
int low = (int) (binaryData[i] & 0x0f);
int high = (int) ((binaryData[i] & 0xf0) >> 4);
buffer[i * 2] = hexadecimal[high]; // depends on control dependency: [for], data = [i]
buffer[i * 2 + 1] = hexadecimal[low]; // depends on control dependency: [for], data = [i]
}
return new String(buffer);
} } |
public class class_name {
protected void redirectSystemOutAndErr(boolean force) {
if (force || !(System.out instanceof ConsolePrintStream)) {
System.setOut(new ConsolePrintStream(out));
}
if (force || !(System.err instanceof ConsoleErrorPrintStream)) {
System.setErr(new ConsoleErrorPrintStream(err));
}
} } | public class class_name {
protected void redirectSystemOutAndErr(boolean force) {
if (force || !(System.out instanceof ConsolePrintStream)) {
System.setOut(new ConsolePrintStream(out)); // depends on control dependency: [if], data = [none]
}
if (force || !(System.err instanceof ConsoleErrorPrintStream)) {
System.setErr(new ConsoleErrorPrintStream(err)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void process(ProjectFile file, FixedData fixedData, Var2Data varData, Map<Integer, FontBase> fontBases)
{
int groupCount = fixedData.getItemCount();
for (int groupLoop = 0; groupLoop < groupCount; groupLoop++)
{
byte[] groupFixedData = fixedData.getByteArrayValue(groupLoop);
if (groupFixedData == null || groupFixedData.length < 4)
{
continue;
}
Integer groupID = Integer.valueOf(MPPUtility.getInt(groupFixedData, 0));
byte[] groupVarData = varData.getByteArray(groupID, getVarDataType());
if (groupVarData == null)
{
continue;
}
String groupName = MPPUtility.getUnicodeString(groupFixedData, 4);
// 8 byte header, 48 byte blocks for each clause
//System.out.println(ByteArrayHelper.hexdump(groupVarData, true, 16, ""));
// header=4 byte int for unique id
// short 4 = show summary tasks
// short int at byte 6 for number of clauses
//Integer groupUniqueID = Integer.valueOf(MPPUtility.getInt(groupVarData, 0));
boolean showSummaryTasks = (MPPUtility.getShort(groupVarData, 4) != 0);
Group group = new Group(groupID, groupName, showSummaryTasks);
file.getGroups().add(group);
int clauseCount = MPPUtility.getShort(groupVarData, 6);
int offset = 8;
for (int clauseIndex = 0; clauseIndex < clauseCount; clauseIndex++)
{
if (offset + 47 > groupVarData.length)
{
break;
}
GroupClause clause = new GroupClause();
group.addGroupClause(clause);
int fieldID = MPPUtility.getInt(groupVarData, offset);
FieldType type = FieldTypeHelper.getInstance(fieldID);
clause.setField(type);
// from byte 0 2 byte short int - field type
// byte 3 - entity type 0b/0c
// 4th byte in clause is 1=asc 0=desc
// offset+8=font index, from font bases
// offset+12=color, byte
// offset+13=pattern, byte
boolean ascending = (MPPUtility.getByte(groupVarData, offset + 4) != 0);
clause.setAscending(ascending);
int fontIndex = MPPUtility.getByte(groupVarData, offset + 8);
FontBase fontBase = fontBases.get(Integer.valueOf(fontIndex));
int style = MPPUtility.getByte(groupVarData, offset + 9);
boolean bold = ((style & 0x01) != 0);
boolean italic = ((style & 0x02) != 0);
boolean underline = ((style & 0x04) != 0);
int fontColorIndex = MPPUtility.getByte(groupVarData, offset + 10);
ColorType fontColor = ColorType.getInstance(fontColorIndex);
FontStyle fontStyle = new FontStyle(fontBase, italic, bold, underline, false, fontColor.getColor(), null, BackgroundPattern.SOLID);
clause.setFont(fontStyle);
int colorIndex = MPPUtility.getByte(groupVarData, offset + 12);
ColorType color = ColorType.getInstance(colorIndex);
clause.setCellBackgroundColor(color.getColor());
clause.setPattern(BackgroundPattern.getInstance(MPPUtility.getByte(groupVarData, offset + 13) & 0x0F));
// offset+14=group on
int groupOn = MPPUtility.getShort(groupVarData, offset + 14);
clause.setGroupOn(groupOn);
// offset+24=start at
// offset+40=group interval
Object startAt = null;
Object groupInterval = null;
switch (type.getDataType())
{
case DURATION:
case NUMERIC:
case CURRENCY:
{
startAt = Double.valueOf(MPPUtility.getDouble(groupVarData, offset + 24));
groupInterval = Double.valueOf(MPPUtility.getDouble(groupVarData, offset + 40));
break;
}
case PERCENTAGE:
{
startAt = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 24));
groupInterval = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 40));
break;
}
case BOOLEAN:
{
startAt = (MPPUtility.getShort(groupVarData, offset + 24) == 1 ? Boolean.TRUE : Boolean.FALSE);
break;
}
case DATE:
{
startAt = MPPUtility.getTimestamp(groupVarData, offset + 24);
groupInterval = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 40));
break;
}
default:
{
break;
}
}
clause.setStartAt(startAt);
clause.setGroupInterval(groupInterval);
offset += 48;
}
//System.out.println(group);
}
} } | public class class_name {
public void process(ProjectFile file, FixedData fixedData, Var2Data varData, Map<Integer, FontBase> fontBases)
{
int groupCount = fixedData.getItemCount();
for (int groupLoop = 0; groupLoop < groupCount; groupLoop++)
{
byte[] groupFixedData = fixedData.getByteArrayValue(groupLoop);
if (groupFixedData == null || groupFixedData.length < 4)
{
continue;
}
Integer groupID = Integer.valueOf(MPPUtility.getInt(groupFixedData, 0));
byte[] groupVarData = varData.getByteArray(groupID, getVarDataType());
if (groupVarData == null)
{
continue;
}
String groupName = MPPUtility.getUnicodeString(groupFixedData, 4);
// 8 byte header, 48 byte blocks for each clause
//System.out.println(ByteArrayHelper.hexdump(groupVarData, true, 16, ""));
// header=4 byte int for unique id
// short 4 = show summary tasks
// short int at byte 6 for number of clauses
//Integer groupUniqueID = Integer.valueOf(MPPUtility.getInt(groupVarData, 0));
boolean showSummaryTasks = (MPPUtility.getShort(groupVarData, 4) != 0);
Group group = new Group(groupID, groupName, showSummaryTasks);
file.getGroups().add(group); // depends on control dependency: [for], data = [none]
int clauseCount = MPPUtility.getShort(groupVarData, 6);
int offset = 8;
for (int clauseIndex = 0; clauseIndex < clauseCount; clauseIndex++)
{
if (offset + 47 > groupVarData.length)
{
break;
}
GroupClause clause = new GroupClause();
group.addGroupClause(clause); // depends on control dependency: [for], data = [none]
int fieldID = MPPUtility.getInt(groupVarData, offset);
FieldType type = FieldTypeHelper.getInstance(fieldID);
clause.setField(type); // depends on control dependency: [for], data = [none]
// from byte 0 2 byte short int - field type
// byte 3 - entity type 0b/0c
// 4th byte in clause is 1=asc 0=desc
// offset+8=font index, from font bases
// offset+12=color, byte
// offset+13=pattern, byte
boolean ascending = (MPPUtility.getByte(groupVarData, offset + 4) != 0);
clause.setAscending(ascending); // depends on control dependency: [for], data = [none]
int fontIndex = MPPUtility.getByte(groupVarData, offset + 8);
FontBase fontBase = fontBases.get(Integer.valueOf(fontIndex));
int style = MPPUtility.getByte(groupVarData, offset + 9);
boolean bold = ((style & 0x01) != 0);
boolean italic = ((style & 0x02) != 0);
boolean underline = ((style & 0x04) != 0);
int fontColorIndex = MPPUtility.getByte(groupVarData, offset + 10);
ColorType fontColor = ColorType.getInstance(fontColorIndex);
FontStyle fontStyle = new FontStyle(fontBase, italic, bold, underline, false, fontColor.getColor(), null, BackgroundPattern.SOLID);
clause.setFont(fontStyle); // depends on control dependency: [for], data = [none]
int colorIndex = MPPUtility.getByte(groupVarData, offset + 12);
ColorType color = ColorType.getInstance(colorIndex);
clause.setCellBackgroundColor(color.getColor()); // depends on control dependency: [for], data = [none]
clause.setPattern(BackgroundPattern.getInstance(MPPUtility.getByte(groupVarData, offset + 13) & 0x0F)); // depends on control dependency: [for], data = [none]
// offset+14=group on
int groupOn = MPPUtility.getShort(groupVarData, offset + 14);
clause.setGroupOn(groupOn); // depends on control dependency: [for], data = [none]
// offset+24=start at
// offset+40=group interval
Object startAt = null;
Object groupInterval = null;
switch (type.getDataType())
{
case DURATION:
case NUMERIC:
case CURRENCY:
{
startAt = Double.valueOf(MPPUtility.getDouble(groupVarData, offset + 24));
groupInterval = Double.valueOf(MPPUtility.getDouble(groupVarData, offset + 40)); // depends on control dependency: [for], data = [none]
break;
}
case PERCENTAGE:
{
startAt = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 24));
groupInterval = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 40)); // depends on control dependency: [for], data = [none]
break;
}
case BOOLEAN:
{
startAt = (MPPUtility.getShort(groupVarData, offset + 24) == 1 ? Boolean.TRUE : Boolean.FALSE);
break;
}
case DATE:
{
startAt = MPPUtility.getTimestamp(groupVarData, offset + 24);
groupInterval = Integer.valueOf(MPPUtility.getInt(groupVarData, offset + 40));
break;
}
default:
{
break;
}
}
clause.setStartAt(startAt);
clause.setGroupInterval(groupInterval);
offset += 48;
}
//System.out.println(group);
}
} } |
public class class_name {
private List<XColor> getColorListFromDPTWithValueList(
final List<CTDPt> dptList, final List<ParsedCell> cells,
final ThemesTable themeTable, final ChartObject ctObj) {
List<XColor> colors = new ArrayList<>();
if ((dptList != null) && (cells != null)) {
for (int index = 0; index < cells.size(); index++) {
CTDPt dpt = getDPtFromListWithIndex(dptList, index);
CTShapeProperties ctSpPr = null;
if (dpt != null) {
ctSpPr = dpt.getSpPr();
}
colors.add(ColorUtility.geColorFromSpPr(index, ctSpPr,
themeTable, ctObj.isLineColor()));
}
}
return colors;
} } | public class class_name {
private List<XColor> getColorListFromDPTWithValueList(
final List<CTDPt> dptList, final List<ParsedCell> cells,
final ThemesTable themeTable, final ChartObject ctObj) {
List<XColor> colors = new ArrayList<>();
if ((dptList != null) && (cells != null)) {
for (int index = 0; index < cells.size(); index++) {
CTDPt dpt = getDPtFromListWithIndex(dptList, index);
CTShapeProperties ctSpPr = null;
if (dpt != null) {
ctSpPr = dpt.getSpPr();
// depends on control dependency: [if], data = [none]
}
colors.add(ColorUtility.geColorFromSpPr(index, ctSpPr,
themeTable, ctObj.isLineColor()));
// depends on control dependency: [for], data = [none]
}
}
return colors;
} } |
public class class_name {
public SipCall makeCall(String to, String viaNonProxyRoute, String body, String contentType,
String contentSubType, ArrayList<String> additionalHeaders,
ArrayList<String> replaceHeaders) {
try {
return makeCall(to, viaNonProxyRoute,
toHeader(additionalHeaders, contentType, contentSubType), toHeader(replaceHeaders), body);
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(SipSession.EXCEPTION_ENCOUNTERED);
return null;
}
} } | public class class_name {
public SipCall makeCall(String to, String viaNonProxyRoute, String body, String contentType,
String contentSubType, ArrayList<String> additionalHeaders,
ArrayList<String> replaceHeaders) {
try {
return makeCall(to, viaNonProxyRoute,
toHeader(additionalHeaders, contentType, contentSubType), toHeader(replaceHeaders), body); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(SipSession.EXCEPTION_ENCOUNTERED);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected StyledString text(SarlAction element) {
final JvmIdentifiableElement jvmElement = this.jvmModelAssociations.getDirectlyInferredOperation(element);
final String simpleName = element.getName();
if (simpleName != null) {
final QualifiedName qnName = QualifiedName.create(simpleName);
final QualifiedName operator = this.operatorMapping.getOperator(qnName);
if (operator != null) {
final StyledString result = signature(operator.getFirstSegment(), jvmElement);
result.append(" (" + simpleName + ")", StyledString.COUNTER_STYLER); //$NON-NLS-1$//$NON-NLS-2$
return result;
}
}
return signature(element.getName(), jvmElement);
} } | public class class_name {
protected StyledString text(SarlAction element) {
final JvmIdentifiableElement jvmElement = this.jvmModelAssociations.getDirectlyInferredOperation(element);
final String simpleName = element.getName();
if (simpleName != null) {
final QualifiedName qnName = QualifiedName.create(simpleName);
final QualifiedName operator = this.operatorMapping.getOperator(qnName);
if (operator != null) {
final StyledString result = signature(operator.getFirstSegment(), jvmElement);
result.append(" (" + simpleName + ")", StyledString.COUNTER_STYLER); //$NON-NLS-1$//$NON-NLS-2$ // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
}
return signature(element.getName(), jvmElement);
} } |
public class class_name {
public boolean canSendPacket(RTMPMessage message, long pending) {
IRTMPEvent packet = message.getBody();
boolean result = true;
// We currently only drop video packets.
if (packet instanceof VideoData) {
VideoData video = (VideoData) packet;
FrameType type = video.getFrameType();
switch (state) {
case SEND_ALL:
// All packets will be sent
break;
case SEND_INTERFRAMES:
// Only keyframes and interframes will be sent.
if (type == FrameType.KEYFRAME) {
if (pending == 0) {
// Send all frames from now on.
state = SEND_ALL;
}
} else if (type == FrameType.INTERFRAME) {
}
break;
case SEND_KEYFRAMES:
// Only keyframes will be sent.
result = (type == FrameType.KEYFRAME);
if (result && pending == 0) {
// Maybe switch back to SEND_INTERFRAMES after the next keyframe
state = SEND_KEYFRAMES_CHECK;
}
break;
case SEND_KEYFRAMES_CHECK:
// Only keyframes will be sent.
result = (type == FrameType.KEYFRAME);
if (result && pending == 0) {
// Continue with sending interframes as well
state = SEND_INTERFRAMES;
}
break;
default:
}
}
return result;
} } | public class class_name {
public boolean canSendPacket(RTMPMessage message, long pending) {
IRTMPEvent packet = message.getBody();
boolean result = true;
// We currently only drop video packets.
if (packet instanceof VideoData) {
VideoData video = (VideoData) packet;
FrameType type = video.getFrameType();
switch (state) {
case SEND_ALL:
// All packets will be sent
break;
case SEND_INTERFRAMES:
// Only keyframes and interframes will be sent.
if (type == FrameType.KEYFRAME) {
if (pending == 0) {
// Send all frames from now on.
state = SEND_ALL;
// depends on control dependency: [if], data = [none]
}
} else if (type == FrameType.INTERFRAME) {
}
break;
case SEND_KEYFRAMES:
// Only keyframes will be sent.
result = (type == FrameType.KEYFRAME);
if (result && pending == 0) {
// Maybe switch back to SEND_INTERFRAMES after the next keyframe
state = SEND_KEYFRAMES_CHECK;
// depends on control dependency: [if], data = [none]
}
break;
case SEND_KEYFRAMES_CHECK:
// Only keyframes will be sent.
result = (type == FrameType.KEYFRAME);
if (result && pending == 0) {
// Continue with sending interframes as well
state = SEND_INTERFRAMES;
// depends on control dependency: [if], data = [none]
}
break;
default:
}
}
return result;
} } |
public class class_name {
public Property getProperty( Object target,
String propertyName,
String label,
String category,
String description,
Object... allowedValues )
throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
CheckArg.isNotNull(target, "target");
CheckArg.isNotEmpty(propertyName, "propertyName");
Method[] setters = findMethods("set" + propertyName, false);
boolean readOnly = setters.length < 1;
Class<?> type = Object.class;
Method[] getters = findMethods("get" + propertyName, false);
if (getters.length == 0) {
getters = findMethods("is" + propertyName, false);
}
if (getters.length == 0) {
getters = findMethods("are" + propertyName, false);
}
if (getters.length > 0) {
type = getters[0].getReturnType();
}
boolean inferred = true;
Field field = null;
try {
// Find the corresponding field ...
field = getField(targetClass, propertyName);
} catch (NoSuchFieldException e) {
// Nothing to do here
}
if (description == null) {
Description desc = getAnnotation(Description.class, field, getters, setters);
if (desc != null) {
description = localizedString(desc.i18n(), desc.value());
inferred = false;
}
}
if (label == null) {
Label labelAnnotation = getAnnotation(Label.class, field, getters, setters);
if (labelAnnotation != null) {
label = localizedString(labelAnnotation.i18n(), labelAnnotation.value());
inferred = false;
}
}
if (category == null) {
Category cat = getAnnotation(Category.class, field, getters, setters);
if (cat != null) {
category = localizedString(cat.i18n(), cat.value());
inferred = false;
}
}
if (!readOnly) {
ReadOnly readOnlyAnnotation = getAnnotation(ReadOnly.class, field, getters, setters);
if (readOnlyAnnotation != null) {
readOnly = true;
inferred = false;
}
}
Property property = new Property(propertyName, label, description, category, readOnly, type, allowedValues);
property.setInferred(inferred);
return property;
} } | public class class_name {
public Property getProperty( Object target,
String propertyName,
String label,
String category,
String description,
Object... allowedValues )
throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
CheckArg.isNotNull(target, "target");
CheckArg.isNotEmpty(propertyName, "propertyName");
Method[] setters = findMethods("set" + propertyName, false);
boolean readOnly = setters.length < 1;
Class<?> type = Object.class;
Method[] getters = findMethods("get" + propertyName, false);
if (getters.length == 0) {
getters = findMethods("is" + propertyName, false); // depends on control dependency: [if], data = [none]
}
if (getters.length == 0) {
getters = findMethods("are" + propertyName, false); // depends on control dependency: [if], data = [none]
}
if (getters.length > 0) {
type = getters[0].getReturnType(); // depends on control dependency: [if], data = [none]
}
boolean inferred = true;
Field field = null;
try {
// Find the corresponding field ...
field = getField(targetClass, propertyName); // depends on control dependency: [try], data = [none]
} catch (NoSuchFieldException e) {
// Nothing to do here
} // depends on control dependency: [catch], data = [none]
if (description == null) {
Description desc = getAnnotation(Description.class, field, getters, setters);
if (desc != null) {
description = localizedString(desc.i18n(), desc.value()); // depends on control dependency: [if], data = [(desc]
inferred = false; // depends on control dependency: [if], data = [none]
}
}
if (label == null) {
Label labelAnnotation = getAnnotation(Label.class, field, getters, setters);
if (labelAnnotation != null) {
label = localizedString(labelAnnotation.i18n(), labelAnnotation.value()); // depends on control dependency: [if], data = [(labelAnnotation]
inferred = false; // depends on control dependency: [if], data = [none]
}
}
if (category == null) {
Category cat = getAnnotation(Category.class, field, getters, setters);
if (cat != null) {
category = localizedString(cat.i18n(), cat.value()); // depends on control dependency: [if], data = [(cat]
inferred = false; // depends on control dependency: [if], data = [none]
}
}
if (!readOnly) {
ReadOnly readOnlyAnnotation = getAnnotation(ReadOnly.class, field, getters, setters);
if (readOnlyAnnotation != null) {
readOnly = true; // depends on control dependency: [if], data = [none]
inferred = false; // depends on control dependency: [if], data = [none]
}
}
Property property = new Property(propertyName, label, description, category, readOnly, type, allowedValues);
property.setInferred(inferred);
return property;
} } |
public class class_name {
public static final synchronized KnowledgeRuntimeManager getRuntimeManager(QName serviceDomainName, QName serviceName) {
if (serviceDomainName == null) {
serviceDomainName = ROOT_DOMAIN;
}
Map<QName, KnowledgeRuntimeManager> reg = REGISTRY.get(serviceDomainName);
return reg != null ? reg.get(serviceName) : null;
} } | public class class_name {
public static final synchronized KnowledgeRuntimeManager getRuntimeManager(QName serviceDomainName, QName serviceName) {
if (serviceDomainName == null) {
serviceDomainName = ROOT_DOMAIN; // depends on control dependency: [if], data = [none]
}
Map<QName, KnowledgeRuntimeManager> reg = REGISTRY.get(serviceDomainName);
return reg != null ? reg.get(serviceName) : null;
} } |
public class class_name {
public RequestDispatcher getNamedDispatcher(String name)
{
if (name == null || name.length()==0)
name=__DEFAULT_SERVLET;
try { return new Dispatcher(ServletHandler.this,name); }
catch(Exception e) {LogSupport.ignore(log,e);}
return null;
} } | public class class_name {
public RequestDispatcher getNamedDispatcher(String name)
{
if (name == null || name.length()==0)
name=__DEFAULT_SERVLET;
try { return new Dispatcher(ServletHandler.this,name); } // depends on control dependency: [try], data = [none]
catch(Exception e) {LogSupport.ignore(log,e);} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public Yoke listen(int port, @NotNull String address, final Handler<Boolean> handler) {
HttpServer server = vertx.createHttpServer();
listen(server);
if (handler != null) {
server.listen(port, address, new Handler<AsyncResult<HttpServer>>() {
@Override
public void handle(AsyncResult<HttpServer> listen) {
handler.handle(listen.succeeded());
}
});
} else {
server.listen(port, address);
}
return this;
} } | public class class_name {
public Yoke listen(int port, @NotNull String address, final Handler<Boolean> handler) {
HttpServer server = vertx.createHttpServer();
listen(server);
if (handler != null) {
server.listen(port, address, new Handler<AsyncResult<HttpServer>>() {
@Override
public void handle(AsyncResult<HttpServer> listen) {
handler.handle(listen.succeeded());
}
}); // depends on control dependency: [if], data = [none]
} else {
server.listen(port, address); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public final OrderSpecifier<T> asc() {
if (asc == null) {
asc = new OrderSpecifier<T>(Order.ASC, mixin);
}
return asc;
} } | public class class_name {
public final OrderSpecifier<T> asc() {
if (asc == null) {
asc = new OrderSpecifier<T>(Order.ASC, mixin); // depends on control dependency: [if], data = [none]
}
return asc;
} } |
public class class_name {
private ODocument getEdgeWithPossibleId(String start, String end, List<String> ids) {
List<ODocument> edges = getEdgesBetweenModels(start, end);
for (ODocument edge : edges) {
if (ids.contains(OrientModelGraphUtils.getIdFieldValue(edge))) {
return edge;
}
}
return edges.size() != 0 ? edges.get(0) : null;
} } | public class class_name {
private ODocument getEdgeWithPossibleId(String start, String end, List<String> ids) {
List<ODocument> edges = getEdgesBetweenModels(start, end);
for (ODocument edge : edges) {
if (ids.contains(OrientModelGraphUtils.getIdFieldValue(edge))) {
return edge; // depends on control dependency: [if], data = [none]
}
}
return edges.size() != 0 ? edges.get(0) : null;
} } |
public class class_name {
@Override
public T next() {
/* If the item is null and we are complete then calling this is a programming error. */
if (next == null && complete) {
throw new NoSuchElementException("The stream has completed. There are no more items.");
}
/* If the item is an error, throw the error wrapped by a runtime error. */
if (next == ERROR) {
try {
final Object error = blockingQueue.take();
complete = true;
throw new StreamException("Exception from stream", (Throwable) error);
} catch (InterruptedException e) {
Thread.interrupted();
throw new StreamException("Stream sent error but unable to get error from stream", e);
}
} else {
/* Give them the next item but don't store the next item any longer. */
T theNext = next;
next = null;
return theNext;
}
} } | public class class_name {
@Override
public T next() {
/* If the item is null and we are complete then calling this is a programming error. */
if (next == null && complete) {
throw new NoSuchElementException("The stream has completed. There are no more items.");
}
/* If the item is an error, throw the error wrapped by a runtime error. */
if (next == ERROR) {
try {
final Object error = blockingQueue.take();
complete = true; // depends on control dependency: [try], data = [none]
throw new StreamException("Exception from stream", (Throwable) error);
} catch (InterruptedException e) {
Thread.interrupted();
throw new StreamException("Stream sent error but unable to get error from stream", e);
} // depends on control dependency: [catch], data = [none]
} else {
/* Give them the next item but don't store the next item any longer. */
T theNext = next;
next = null; // depends on control dependency: [if], data = [none]
return theNext; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void parseSequenceFlowConditionExpression(Element seqFlowElement, TransitionImpl seqFlow) {
Element conditionExprElement = seqFlowElement.element(CONDITION_EXPRESSION);
if (conditionExprElement != null) {
Condition condition = parseConditionExpression(conditionExprElement);
seqFlow.setProperty(PROPERTYNAME_CONDITION_TEXT, conditionExprElement.getText().trim());
seqFlow.setProperty(PROPERTYNAME_CONDITION, condition);
}
} } | public class class_name {
public void parseSequenceFlowConditionExpression(Element seqFlowElement, TransitionImpl seqFlow) {
Element conditionExprElement = seqFlowElement.element(CONDITION_EXPRESSION);
if (conditionExprElement != null) {
Condition condition = parseConditionExpression(conditionExprElement);
seqFlow.setProperty(PROPERTYNAME_CONDITION_TEXT, conditionExprElement.getText().trim()); // depends on control dependency: [if], data = [none]
seqFlow.setProperty(PROPERTYNAME_CONDITION, condition); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public CompletableFuture<Tuple2<List<String>, ExecutionInfo>> getListJSONAsyncWithStats() {
final RuntimeEngine rte = getRte();
final CassandraOptions options = getOptions();
final StatementWrapper statementWrapper = getInternalBoundStatementWrapper();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(format("Select async with execution info : %s",
statementWrapper.getBoundStatement().preparedStatement().getQueryString()));
}
CompletableFuture<ResultSet> futureRS = rte.execute(statementWrapper);
return futureRS
.thenApply(options::resultSetAsyncListener)
.thenApply(x -> statementWrapper.logReturnResults(x, options.computeMaxDisplayedResults(rte.configContext)))
.thenApply(statementWrapper::logTrace)
.thenApply(resultSet -> Tuple2.of(IntStream
.range(0, resultSet.getAvailableWithoutFetching())
.mapToObj(index -> resultSet.one().getString("[json]"))
.collect(Collectors.toList()), resultSet.getExecutionInfo()));
} } | public class class_name {
@Override
public CompletableFuture<Tuple2<List<String>, ExecutionInfo>> getListJSONAsyncWithStats() {
final RuntimeEngine rte = getRte();
final CassandraOptions options = getOptions();
final StatementWrapper statementWrapper = getInternalBoundStatementWrapper();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(format("Select async with execution info : %s",
statementWrapper.getBoundStatement().preparedStatement().getQueryString())); // depends on control dependency: [if], data = [none]
}
CompletableFuture<ResultSet> futureRS = rte.execute(statementWrapper);
return futureRS
.thenApply(options::resultSetAsyncListener)
.thenApply(x -> statementWrapper.logReturnResults(x, options.computeMaxDisplayedResults(rte.configContext)))
.thenApply(statementWrapper::logTrace)
.thenApply(resultSet -> Tuple2.of(IntStream
.range(0, resultSet.getAvailableWithoutFetching())
.mapToObj(index -> resultSet.one().getString("[json]"))
.collect(Collectors.toList()), resultSet.getExecutionInfo()));
} } |
public class class_name {
private static String toSingleLoopLineMmCifString(Object record, Field[] fields, int[] sizes) {
StringBuilder str = new StringBuilder();
Class<?> c = record.getClass();
if(fields == null)
fields = getFields(c);
if (sizes.length!=fields.length)
throw new IllegalArgumentException("The given sizes of fields differ from the number of declared fields");
int i = -1;
for (Field f : fields) {
i++;
f.setAccessible(true);
try {
Object obj = f.get(record);
String val;
if (obj==null) {
logger.debug("Field {} is null, will write it out as {}",f.getName(),MMCIF_MISSING_VALUE);
val = MMCIF_MISSING_VALUE;
} else {
val = (String) obj;
}
str.append(String.format("%-"+sizes[i]+"s ", addMmCifQuoting(val)));
} catch (IllegalAccessException e) {
logger.warn("Field {} is inaccessible", f.getName());
continue;
} catch (ClassCastException e) {
logger.warn("Could not cast value to String for field {}",f.getName());
continue;
}
}
str.append(newline);
return str.toString();
} } | public class class_name {
private static String toSingleLoopLineMmCifString(Object record, Field[] fields, int[] sizes) {
StringBuilder str = new StringBuilder();
Class<?> c = record.getClass();
if(fields == null)
fields = getFields(c);
if (sizes.length!=fields.length)
throw new IllegalArgumentException("The given sizes of fields differ from the number of declared fields");
int i = -1;
for (Field f : fields) {
i++; // depends on control dependency: [for], data = [none]
f.setAccessible(true); // depends on control dependency: [for], data = [f]
try {
Object obj = f.get(record);
String val;
if (obj==null) {
logger.debug("Field {} is null, will write it out as {}",f.getName(),MMCIF_MISSING_VALUE); // depends on control dependency: [if], data = [none]
val = MMCIF_MISSING_VALUE; // depends on control dependency: [if], data = [none]
} else {
val = (String) obj; // depends on control dependency: [if], data = [none]
}
str.append(String.format("%-"+sizes[i]+"s ", addMmCifQuoting(val))); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
logger.warn("Field {} is inaccessible", f.getName());
continue;
} catch (ClassCastException e) { // depends on control dependency: [catch], data = [none]
logger.warn("Could not cast value to String for field {}",f.getName());
continue;
} // depends on control dependency: [catch], data = [none]
}
str.append(newline);
return str.toString();
} } |
public class class_name {
public static String getMimeTypeForFile(URL url) {
if (url == null) {
//The input url is null so we can't retrieve a mimetype, therefore we return null.
return null;
}
String external = url.toExternalForm();
if (external.indexOf('.') == -1) {
return BINARY;
} else {
String ext = external.substring(external.lastIndexOf('.') + 1);
String mime = KnownMimeTypes.getMimeTypeByExtension(ext);
if (mime == null) {
return BINARY;
} else {
return mime;
}
}
} } | public class class_name {
public static String getMimeTypeForFile(URL url) {
if (url == null) {
//The input url is null so we can't retrieve a mimetype, therefore we return null.
return null; // depends on control dependency: [if], data = [none]
}
String external = url.toExternalForm();
if (external.indexOf('.') == -1) {
return BINARY; // depends on control dependency: [if], data = [none]
} else {
String ext = external.substring(external.lastIndexOf('.') + 1);
String mime = KnownMimeTypes.getMimeTypeByExtension(ext);
if (mime == null) {
return BINARY; // depends on control dependency: [if], data = [none]
} else {
return mime; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static int parseNumericAddress(String ipaddr) {
Matcher m = IP_ADDRESS_PATTERN.matcher(ipaddr);
int ipInt = 0;
if (m.find()) {
for (int i = 1;i < 5;i++)
try {
int ipVal = Integer.valueOf(m.group(i)).intValue();
if ( ipVal < 0 || ipVal > 255) {
return 0;
}
// Add to the integer address
ipInt = (ipInt << 8) + ipVal;
}
catch (NumberFormatException ex) {
return 0;
}
}
// Return the integer address
return ipInt;
} } | public class class_name {
public static int parseNumericAddress(String ipaddr) {
Matcher m = IP_ADDRESS_PATTERN.matcher(ipaddr);
int ipInt = 0;
if (m.find()) {
for (int i = 1;i < 5;i++)
try {
int ipVal = Integer.valueOf(m.group(i)).intValue();
if ( ipVal < 0 || ipVal > 255) {
return 0; // depends on control dependency: [if], data = [none]
}
// Add to the integer address
ipInt = (ipInt << 8) + ipVal; // depends on control dependency: [try], data = [none]
}
catch (NumberFormatException ex) {
return 0;
} // depends on control dependency: [catch], data = [none]
}
// Return the integer address
return ipInt;
} } |
public class class_name {
public final void registerConfiguration(URL nextLocation) {
BindingConfiguration configuration = BindingXmlLoader.load(nextLocation);
for (Provider nextProvider : configuration.getProviders()) {
try {
registerConverterProvider(nextProvider.getProviderClass().newInstance());
} catch (InstantiationException e) {
throw new IllegalStateException("Cannot instantiate binding provider class: " + nextProvider.getProviderClass().getName());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot access binding provider class: " + nextProvider.getProviderClass().getName());
}
}
registerBindingConfigurationEntries(configuration.getBindingEntries());
} } | public class class_name {
public final void registerConfiguration(URL nextLocation) {
BindingConfiguration configuration = BindingXmlLoader.load(nextLocation);
for (Provider nextProvider : configuration.getProviders()) {
try {
registerConverterProvider(nextProvider.getProviderClass().newInstance());
// depends on control dependency: [try], data = [none]
} catch (InstantiationException e) {
throw new IllegalStateException("Cannot instantiate binding provider class: " + nextProvider.getProviderClass().getName());
} catch (IllegalAccessException e) {
// depends on control dependency: [catch], data = [none]
throw new IllegalStateException("Cannot access binding provider class: " + nextProvider.getProviderClass().getName());
}
// depends on control dependency: [catch], data = [none]
}
registerBindingConfigurationEntries(configuration.getBindingEntries());
} } |
public class class_name {
public void marshall(SimpleEmailPart simpleEmailPart, ProtocolMarshaller protocolMarshaller) {
if (simpleEmailPart == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(simpleEmailPart.getCharset(), CHARSET_BINDING);
protocolMarshaller.marshall(simpleEmailPart.getData(), DATA_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SimpleEmailPart simpleEmailPart, ProtocolMarshaller protocolMarshaller) {
if (simpleEmailPart == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(simpleEmailPart.getCharset(), CHARSET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(simpleEmailPart.getData(), DATA_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static long nextThursdayMidnightPlus(long now, long plus) {
long next = (now + timeZoneOffset) / WEEK * WEEK - timeZoneOffset;
next += plus;
if (next < now) {
next += WEEK;
}
return next;
} } | public class class_name {
public static long nextThursdayMidnightPlus(long now, long plus) {
long next = (now + timeZoneOffset) / WEEK * WEEK - timeZoneOffset;
next += plus;
if (next < now) {
next += WEEK;
// depends on control dependency: [if], data = [none]
}
return next;
} } |
public class class_name {
static public String normalize(String path) {
if (path == null || path.length() == 0) return ROOT;
if (path.charAt(0) != PATH_SEPARATOR) {
throw new IllegalArgumentException(
"Network Location path does not start with "
+PATH_SEPARATOR_STR+ ": "+path);
}
int len = path.length();
if (path.charAt(len-1) == PATH_SEPARATOR) {
return path.substring(0, len-1);
}
return path;
} } | public class class_name {
static public String normalize(String path) {
if (path == null || path.length() == 0) return ROOT;
if (path.charAt(0) != PATH_SEPARATOR) {
throw new IllegalArgumentException(
"Network Location path does not start with "
+PATH_SEPARATOR_STR+ ": "+path);
}
int len = path.length();
if (path.charAt(len-1) == PATH_SEPARATOR) {
return path.substring(0, len-1); // depends on control dependency: [if], data = [none]
}
return path;
} } |
public class class_name {
private ConcurrentHashMap<JobVertexID, TaskStateStats> createEmptyTaskStateStatsMap() {
ConcurrentHashMap<JobVertexID, TaskStateStats> taskStatsMap = new ConcurrentHashMap<>(jobVertices.size());
for (ExecutionJobVertex vertex : jobVertices) {
TaskStateStats taskStats = new TaskStateStats(vertex.getJobVertexId(), vertex.getParallelism());
taskStatsMap.put(vertex.getJobVertexId(), taskStats);
}
return taskStatsMap;
} } | public class class_name {
private ConcurrentHashMap<JobVertexID, TaskStateStats> createEmptyTaskStateStatsMap() {
ConcurrentHashMap<JobVertexID, TaskStateStats> taskStatsMap = new ConcurrentHashMap<>(jobVertices.size());
for (ExecutionJobVertex vertex : jobVertices) {
TaskStateStats taskStats = new TaskStateStats(vertex.getJobVertexId(), vertex.getParallelism());
taskStatsMap.put(vertex.getJobVertexId(), taskStats); // depends on control dependency: [for], data = [vertex]
}
return taskStatsMap;
} } |
public class class_name {
void updateGCcounters(){
long gccount = 0;
long gctime = 0;
for(GarbageCollectorMXBean gc :
ManagementFactory.getGarbageCollectorMXBeans()) {
long count = gc.getCollectionCount();
if(count >= 0) {
gccount += count;
}
long time = gc.getCollectionTime();
if(time >= 0) {
gctime += time;
}
}
Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator();
long aftergc = 0;
long maxaftergc = 0;
while (beans.hasNext()){
MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next();
String beanname = bean.getName();
if(!beanname.toUpperCase().contains("OLD GEN")) continue;
MemoryUsage mu = bean.getCollectionUsage();
if(mu == null) continue;
aftergc = mu.getUsed();
if(aftergc > maxaftergc) {
maxaftergc = aftergc;
}
}
counters.findCounter(GC_COUNTER_GROUP,"Total number of GC")
.setValue(gccount);
counters.findCounter(GC_COUNTER_GROUP,"Total time of GC in milliseconds")
.setValue(gctime);
counters.findCounter(GC_COUNTER_GROUP,"Heap size after last GC in bytes")
.setValue(maxaftergc);
long currentMax =
counters.findCounter(GC_COUNTER_GROUP,"Max heap size after GC in bytes")
.getValue();
if(maxaftergc>currentMax){
counters.findCounter(GC_COUNTER_GROUP,"Max heap size after GC in bytes")
.setValue(maxaftergc);
}
} } | public class class_name {
void updateGCcounters(){
long gccount = 0;
long gctime = 0;
for(GarbageCollectorMXBean gc :
ManagementFactory.getGarbageCollectorMXBeans()) {
long count = gc.getCollectionCount();
if(count >= 0) {
gccount += count; // depends on control dependency: [if], data = [none]
}
long time = gc.getCollectionTime();
if(time >= 0) {
gctime += time; // depends on control dependency: [if], data = [none]
}
}
Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator();
long aftergc = 0;
long maxaftergc = 0;
while (beans.hasNext()){
MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next();
String beanname = bean.getName();
if(!beanname.toUpperCase().contains("OLD GEN")) continue;
MemoryUsage mu = bean.getCollectionUsage();
if(mu == null) continue;
aftergc = mu.getUsed(); // depends on control dependency: [while], data = [none]
if(aftergc > maxaftergc) {
maxaftergc = aftergc; // depends on control dependency: [if], data = [none]
}
}
counters.findCounter(GC_COUNTER_GROUP,"Total number of GC")
.setValue(gccount);
counters.findCounter(GC_COUNTER_GROUP,"Total time of GC in milliseconds")
.setValue(gctime);
counters.findCounter(GC_COUNTER_GROUP,"Heap size after last GC in bytes")
.setValue(maxaftergc);
long currentMax =
counters.findCounter(GC_COUNTER_GROUP,"Max heap size after GC in bytes")
.getValue();
if(maxaftergc>currentMax){
counters.findCounter(GC_COUNTER_GROUP,"Max heap size after GC in bytes")
.setValue(maxaftergc); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean hasRelation(Interval interval1, Interval interval2) {
if (interval1 == null || interval2 == null) {
return false;
}
Long minStart1 = interval1.getMinimumStart();
Long maxStart1 = interval1.getMaximumStart();
Long minFinish1 = interval1.getMinimumFinish();
Long maxFinish1 = interval1.getMaximumFinish();
Long minStart2 = interval2.getMinimumStart();
Long maxStart2 = interval2.getMaximumStart();
Long minFinish2 = interval2.getMinimumFinish();
Long maxFinish2 = interval2.getMaximumFinish();
return evenHasRelationCheck(0, minStart1, minStart2)
&& oddHasRelationCheck(1, maxStart1, maxStart2)
&& evenHasRelationCheck(2, minStart1, minFinish2)
&& oddHasRelationCheck(3, maxStart1, maxFinish2)
&& evenHasRelationCheck(4, minFinish1, minStart2)
&& oddHasRelationCheck(5, maxFinish1, maxStart2)
&& evenHasRelationCheck(6, minFinish1, minFinish2)
&& oddHasRelationCheck(7, maxFinish1, maxFinish2);
} } | public class class_name {
public boolean hasRelation(Interval interval1, Interval interval2) {
if (interval1 == null || interval2 == null) {
return false; // depends on control dependency: [if], data = [none]
}
Long minStart1 = interval1.getMinimumStart();
Long maxStart1 = interval1.getMaximumStart();
Long minFinish1 = interval1.getMinimumFinish();
Long maxFinish1 = interval1.getMaximumFinish();
Long minStart2 = interval2.getMinimumStart();
Long maxStart2 = interval2.getMaximumStart();
Long minFinish2 = interval2.getMinimumFinish();
Long maxFinish2 = interval2.getMaximumFinish();
return evenHasRelationCheck(0, minStart1, minStart2)
&& oddHasRelationCheck(1, maxStart1, maxStart2)
&& evenHasRelationCheck(2, minStart1, minFinish2)
&& oddHasRelationCheck(3, maxStart1, maxFinish2)
&& evenHasRelationCheck(4, minFinish1, minStart2)
&& oddHasRelationCheck(5, maxFinish1, maxStart2)
&& evenHasRelationCheck(6, minFinish1, minFinish2)
&& oddHasRelationCheck(7, maxFinish1, maxFinish2);
} } |
public class class_name {
public String getPath() {
String path = getFullPath();
if (m_relativeTo != null) {
path = getResource().getRootPath();
if (path.startsWith(m_relativeTo)) {
path = path.substring(m_relativeTo.length());
if (path.length() == 0) {
path = ".";
}
} else {
String site = getSite();
if (path.startsWith(site + "/") || path.equals(site)) {
path = path.substring(site.length());
}
}
}
if (m_abbrevLength > 0) {
boolean absolute = path.startsWith("/");
path = CmsStringUtil.formatResourceName(path, m_abbrevLength);
if (!absolute && path.startsWith("/")) {
// remove leading '/'
path = path.substring(1);
}
}
return path;
} } | public class class_name {
public String getPath() {
String path = getFullPath();
if (m_relativeTo != null) {
path = getResource().getRootPath(); // depends on control dependency: [if], data = [none]
if (path.startsWith(m_relativeTo)) {
path = path.substring(m_relativeTo.length()); // depends on control dependency: [if], data = [none]
if (path.length() == 0) {
path = "."; // depends on control dependency: [if], data = [none]
}
} else {
String site = getSite();
if (path.startsWith(site + "/") || path.equals(site)) {
path = path.substring(site.length()); // depends on control dependency: [if], data = [none]
}
}
}
if (m_abbrevLength > 0) {
boolean absolute = path.startsWith("/");
path = CmsStringUtil.formatResourceName(path, m_abbrevLength); // depends on control dependency: [if], data = [none]
if (!absolute && path.startsWith("/")) {
// remove leading '/'
path = path.substring(1); // depends on control dependency: [if], data = [none]
}
}
return path;
} } |
public class class_name {
public void marshall(ResetServiceSettingRequest resetServiceSettingRequest, ProtocolMarshaller protocolMarshaller) {
if (resetServiceSettingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resetServiceSettingRequest.getSettingId(), SETTINGID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ResetServiceSettingRequest resetServiceSettingRequest, ProtocolMarshaller protocolMarshaller) {
if (resetServiceSettingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resetServiceSettingRequest.getSettingId(), SETTINGID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean deleteApplication(String appName, String key) {
Utils.require(!m_restClient.isClosed(), "Client has been closed");
Utils.require(appName != null && appName.length() > 0, "appName");
try {
// Send a DELETE request to "/_applications/{application}/{key}".
StringBuilder uri = new StringBuilder(Utils.isEmpty(m_apiPrefix) ? "" : "/" + m_apiPrefix);
uri.append("/_applications/");
uri.append(Utils.urlEncode(appName));
if (!Utils.isEmpty(key)) {
uri.append("/");
uri.append(Utils.urlEncode(key));
}
RESTResponse response = m_restClient.sendRequest(HttpMethod.DELETE, uri.toString());
m_logger.debug("deleteApplication() response: {}", response.toString());
if (response.getCode() != HttpCode.NOT_FOUND) {
// Notfound is acceptable
throwIfErrorResponse(response);
}
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public boolean deleteApplication(String appName, String key) {
Utils.require(!m_restClient.isClosed(), "Client has been closed");
Utils.require(appName != null && appName.length() > 0, "appName");
try {
// Send a DELETE request to "/_applications/{application}/{key}".
StringBuilder uri = new StringBuilder(Utils.isEmpty(m_apiPrefix) ? "" : "/" + m_apiPrefix);
uri.append("/_applications/");
// depends on control dependency: [try], data = [none]
uri.append(Utils.urlEncode(appName));
// depends on control dependency: [try], data = [none]
if (!Utils.isEmpty(key)) {
uri.append("/");
// depends on control dependency: [if], data = [none]
uri.append(Utils.urlEncode(key));
// depends on control dependency: [if], data = [none]
}
RESTResponse response = m_restClient.sendRequest(HttpMethod.DELETE, uri.toString());
m_logger.debug("deleteApplication() response: {}", response.toString());
// depends on control dependency: [try], data = [none]
if (response.getCode() != HttpCode.NOT_FOUND) {
// Notfound is acceptable
throwIfErrorResponse(response);
// depends on control dependency: [if], data = [none]
}
return true;
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException(e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) {
if (suggestions.isEmpty()) {
return Pair.of(Collections.emptyList(), Collections.emptySortedMap());
}
if (topN <= 0) {
topN = suggestions.size();
}
List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN));
//EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4);
EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau);
SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance();
List<Feature> features = new ArrayList<>(topSuggestions.size());
for (String candidate : topSuggestions) {
double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb();
double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
//double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate);
int levenstheinDist = levenstheinDistance.compare(candidate, 3);
double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate);
DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate);
features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate));
}
if (!"noop".equals(score)) {
features.sort(Feature::compareTo);
}
//logger.trace("Features for '%s' in '%s': %n", word, sentence.getText());
//features.stream().map(Feature::toString).forEach(logger::trace);
List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList());
// compute general features, not tied to candidates
SortedMap<String, Float> matchData = new TreeMap<>();
matchData.put("candidateCount", (float) words.size());
List<SuggestedReplacement> suggestionsData = features.stream().map(f -> {
SuggestedReplacement s = new SuggestedReplacement(f.getWord());
s.setFeatures(f.getData());
return s;
}).collect(Collectors.toList());
return Pair.of(suggestionsData, matchData);
} } | public class class_name {
public Pair<List<SuggestedReplacement>, SortedMap<String, Float>> computeFeatures(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) {
if (suggestions.isEmpty()) {
return Pair.of(Collections.emptyList(), Collections.emptySortedMap()); // depends on control dependency: [if], data = [none]
}
if (topN <= 0) {
topN = suggestions.size(); // depends on control dependency: [if], data = [none]
}
List<String> topSuggestions = suggestions.subList(0, Math.min(suggestions.size(), topN));
//EditDistance<Integer> levenshteinDistance = new LevenshteinDistance(4);
EditDistance levenstheinDistance = new EditDistance(word, EditDistance.DistanceAlgorithm.Damerau);
SimilarityScore<Double> jaroWrinklerDistance = new JaroWinklerDistance();
List<Feature> features = new ArrayList<>(topSuggestions.size());
for (String candidate : topSuggestions) {
double prob1 = languageModel.getPseudoProbability(Collections.singletonList(candidate)).getProb();
double prob3 = LanguageModelUtils.get3gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
//double prob4 = LanguageModelUtils.get4gramProbabilityFor(language, languageModel, startPos, sentence, candidate);
long wordCount = ((BaseLanguageModel) languageModel).getCount(candidate);
int levenstheinDist = levenstheinDistance.compare(candidate, 3);
double jaroWrinklerDist = jaroWrinklerDistance.apply(word, candidate);
DetailedDamerauLevenstheinDistance.Distance detailedDistance = DetailedDamerauLevenstheinDistance.compare(word, candidate);
features.add(new Feature(prob1, prob3, wordCount, levenstheinDist, detailedDistance, jaroWrinklerDist, candidate)); // depends on control dependency: [for], data = [candidate]
}
if (!"noop".equals(score)) {
features.sort(Feature::compareTo); // depends on control dependency: [if], data = [none]
}
//logger.trace("Features for '%s' in '%s': %n", word, sentence.getText());
//features.stream().map(Feature::toString).forEach(logger::trace);
List<String> words = features.stream().map(Feature::getWord).collect(Collectors.toList());
// compute general features, not tied to candidates
SortedMap<String, Float> matchData = new TreeMap<>();
matchData.put("candidateCount", (float) words.size());
List<SuggestedReplacement> suggestionsData = features.stream().map(f -> {
SuggestedReplacement s = new SuggestedReplacement(f.getWord());
s.setFeatures(f.getData());
return s;
}).collect(Collectors.toList());
return Pair.of(suggestionsData, matchData);
} } |
public class class_name {
public static Token makeReferenceToken(String bean, String template, String parameter,
String attribute, String property) {
Token token;
if (bean != null) {
token = new Token(TokenType.BEAN, bean);
} else if (template != null) {
token = new Token(TokenType.TEMPLATE, template);
} else if (parameter != null) {
token = new Token(TokenType.PARAMETER, parameter);
} else if (attribute != null) {
token = new Token(TokenType.ATTRIBUTE, attribute);
} else if (property != null) {
token = new Token(TokenType.PROPERTY, property);
} else {
token = null;
}
return token;
} } | public class class_name {
public static Token makeReferenceToken(String bean, String template, String parameter,
String attribute, String property) {
Token token;
if (bean != null) {
token = new Token(TokenType.BEAN, bean); // depends on control dependency: [if], data = [none]
} else if (template != null) {
token = new Token(TokenType.TEMPLATE, template); // depends on control dependency: [if], data = [none]
} else if (parameter != null) {
token = new Token(TokenType.PARAMETER, parameter); // depends on control dependency: [if], data = [none]
} else if (attribute != null) {
token = new Token(TokenType.ATTRIBUTE, attribute); // depends on control dependency: [if], data = [none]
} else if (property != null) {
token = new Token(TokenType.PROPERTY, property); // depends on control dependency: [if], data = [none]
} else {
token = null; // depends on control dependency: [if], data = [none]
}
return token;
} } |
public class class_name {
public static String filterStackTraces(String txt) {
// Check for stack traces, which we may want to trim
StackTraceFlags stackTraceFlags = traceFlags.get();
// We have a little thread-local state machine here with four states controlled by two
// booleans. Our triggers are { "unknown/user code", "just seen IBM code", "second line of IBM code", ">second line of IBM code"}
// "unknown/user code" -> stackTraceFlags.isSuppressingTraces -> false, stackTraceFlags.needsToOutputInternalPackageMarker -> false
// "just seen IBM code" -> stackTraceFlags.needsToOutputInternalPackageMarker->true
// "second line of IBM code" -> stackTraceFlags.needsToOutputInternalPackageMarker->true
// ">second line of IBM code" -> stackTraceFlags.isSuppressingTraces->true
// The final two states are optional
if (txt.startsWith("\tat ")) {
// This is a stack trace, do a more detailed analysis
PackageProcessor packageProcessor = PackageProcessor.getPackageProcessor();
String packageName = PackageProcessor.extractPackageFromStackTraceLine(txt);
// If we don't have a package processor, don't suppress anything
if (packageProcessor != null && packageProcessor.isIBMPackage(packageName)) {
// First internal package, we let through
// Second one, we suppress but say we did
// If we're still suppressing, and this is a stack trace, this is easy - we suppress
if (stackTraceFlags.isSuppressingTraces) {
txt = null;
} else if (stackTraceFlags.needsToOutputInternalPackageMarker) {
// Replace the stack trace with something saying we got rid of it
txt = "\tat " + TruncatableThrowable.INTERNAL_CLASSES_STRING;
// No need to output another marker, we've just output it
stackTraceFlags.needsToOutputInternalPackageMarker = false;
// Suppress any subsequent IBM frames
stackTraceFlags.isSuppressingTraces = true;
} else {
// Let the text through, but make a note not to let anything but an [internal classes] through
stackTraceFlags.needsToOutputInternalPackageMarker = true;
}
} else {
// This is user code, third party API, or Java API, so let it through
// Reset the flags to ensure it gets let through
stackTraceFlags.isSuppressingTraces = false;
stackTraceFlags.needsToOutputInternalPackageMarker = false;
}
} else {
// We're no longer processing a stack, so reset all our state
stackTraceFlags.isSuppressingTraces = false;
stackTraceFlags.needsToOutputInternalPackageMarker = false;
}
return txt;
} } | public class class_name {
public static String filterStackTraces(String txt) {
// Check for stack traces, which we may want to trim
StackTraceFlags stackTraceFlags = traceFlags.get();
// We have a little thread-local state machine here with four states controlled by two
// booleans. Our triggers are { "unknown/user code", "just seen IBM code", "second line of IBM code", ">second line of IBM code"}
// "unknown/user code" -> stackTraceFlags.isSuppressingTraces -> false, stackTraceFlags.needsToOutputInternalPackageMarker -> false
// "just seen IBM code" -> stackTraceFlags.needsToOutputInternalPackageMarker->true
// "second line of IBM code" -> stackTraceFlags.needsToOutputInternalPackageMarker->true
// ">second line of IBM code" -> stackTraceFlags.isSuppressingTraces->true
// The final two states are optional
if (txt.startsWith("\tat ")) {
// This is a stack trace, do a more detailed analysis
PackageProcessor packageProcessor = PackageProcessor.getPackageProcessor();
String packageName = PackageProcessor.extractPackageFromStackTraceLine(txt);
// If we don't have a package processor, don't suppress anything
if (packageProcessor != null && packageProcessor.isIBMPackage(packageName)) {
// First internal package, we let through
// Second one, we suppress but say we did
// If we're still suppressing, and this is a stack trace, this is easy - we suppress
if (stackTraceFlags.isSuppressingTraces) {
txt = null; // depends on control dependency: [if], data = [none]
} else if (stackTraceFlags.needsToOutputInternalPackageMarker) {
// Replace the stack trace with something saying we got rid of it
txt = "\tat " + TruncatableThrowable.INTERNAL_CLASSES_STRING; // depends on control dependency: [if], data = [none]
// No need to output another marker, we've just output it
stackTraceFlags.needsToOutputInternalPackageMarker = false; // depends on control dependency: [if], data = [none]
// Suppress any subsequent IBM frames
stackTraceFlags.isSuppressingTraces = true; // depends on control dependency: [if], data = [none]
} else {
// Let the text through, but make a note not to let anything but an [internal classes] through
stackTraceFlags.needsToOutputInternalPackageMarker = true; // depends on control dependency: [if], data = [none]
}
} else {
// This is user code, third party API, or Java API, so let it through
// Reset the flags to ensure it gets let through
stackTraceFlags.isSuppressingTraces = false; // depends on control dependency: [if], data = [none]
stackTraceFlags.needsToOutputInternalPackageMarker = false; // depends on control dependency: [if], data = [none]
}
} else {
// We're no longer processing a stack, so reset all our state
stackTraceFlags.isSuppressingTraces = false; // depends on control dependency: [if], data = [none]
stackTraceFlags.needsToOutputInternalPackageMarker = false; // depends on control dependency: [if], data = [none]
}
return txt;
} } |
public class class_name {
protected Map<String, List<Object>> buildImmutableAttributeMap(final Map<String, List<Object>> attributes) {
final Map<String, List<Object>> immutableValuesBuilder = this.createImmutableAttributeMap(attributes.size());
final Pattern arrayPattern = Pattern.compile("\\{(.*)\\}");
for (final Map.Entry<String, List<Object>> attrEntry : attributes.entrySet()) {
final String key = attrEntry.getKey();
List<Object> value = attrEntry.getValue();
if (value != null) {
if (!value.isEmpty()) {
final Object result = value.get(0);
if (Array.class.isInstance(result)) {
if (logger.isTraceEnabled()) {
logger.trace("Column {} is classified as a SQL array", key);
}
final String values = result.toString();
if (logger.isTraceEnabled()) {
logger.trace("Converting SQL array values {} using pattern {}", values, arrayPattern.pattern());
}
final Matcher matcher = arrayPattern.matcher(values);
if (matcher.matches()) {
final String[] groups = matcher.group(1).split(",");
value = Arrays.asList(groups);
if (logger.isTraceEnabled()) {
logger.trace("Converted SQL array values {}", values);
}
}
}
}
value = Collections.unmodifiableList(value);
}
if (logger.isTraceEnabled()) {
logger.trace("Collecting attribute {} with value(s) {}", key, value);
}
immutableValuesBuilder.put(key, value);
}
return immutableValuesBuilder;
} } | public class class_name {
protected Map<String, List<Object>> buildImmutableAttributeMap(final Map<String, List<Object>> attributes) {
final Map<String, List<Object>> immutableValuesBuilder = this.createImmutableAttributeMap(attributes.size());
final Pattern arrayPattern = Pattern.compile("\\{(.*)\\}");
for (final Map.Entry<String, List<Object>> attrEntry : attributes.entrySet()) {
final String key = attrEntry.getKey();
List<Object> value = attrEntry.getValue();
if (value != null) {
if (!value.isEmpty()) {
final Object result = value.get(0);
if (Array.class.isInstance(result)) {
if (logger.isTraceEnabled()) {
logger.trace("Column {} is classified as a SQL array", key); // depends on control dependency: [if], data = [none]
}
final String values = result.toString();
if (logger.isTraceEnabled()) {
logger.trace("Converting SQL array values {} using pattern {}", values, arrayPattern.pattern()); // depends on control dependency: [if], data = [none]
}
final Matcher matcher = arrayPattern.matcher(values);
if (matcher.matches()) {
final String[] groups = matcher.group(1).split(",");
value = Arrays.asList(groups); // depends on control dependency: [if], data = [none]
if (logger.isTraceEnabled()) {
logger.trace("Converted SQL array values {}", values); // depends on control dependency: [if], data = [none]
}
}
}
}
value = Collections.unmodifiableList(value); // depends on control dependency: [if], data = [(value]
}
if (logger.isTraceEnabled()) {
logger.trace("Collecting attribute {} with value(s) {}", key, value);
}
immutableValuesBuilder.put(key, value);
}
return immutableValuesBuilder;
} } |
public class class_name {
public java.util.List<String> getUpdateStatus() {
if (updateStatus == null) {
updateStatus = new com.amazonaws.internal.SdkInternalList<String>();
}
return updateStatus;
} } | public class class_name {
public java.util.List<String> getUpdateStatus() {
if (updateStatus == null) {
updateStatus = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return updateStatus;
} } |
public class class_name {
public static boolean checkPositionInside(Element element, int x, int y) {
// ignore x / left-right values for x == -1
if (x != -1) {
// check if the mouse pointer is within the width of the target
int left = CmsDomUtil.getRelativeX(x, element);
int offsetWidth = element.getOffsetWidth();
if ((left <= 0) || (left >= offsetWidth)) {
return false;
}
}
// ignore y / top-bottom values for y == -1
if (y != -1) {
// check if the mouse pointer is within the height of the target
int top = CmsDomUtil.getRelativeY(y, element);
int offsetHeight = element.getOffsetHeight();
if ((top <= 0) || (top >= offsetHeight)) {
return false;
}
}
return true;
} } | public class class_name {
public static boolean checkPositionInside(Element element, int x, int y) {
// ignore x / left-right values for x == -1
if (x != -1) {
// check if the mouse pointer is within the width of the target
int left = CmsDomUtil.getRelativeX(x, element);
int offsetWidth = element.getOffsetWidth();
if ((left <= 0) || (left >= offsetWidth)) {
return false; // depends on control dependency: [if], data = [none]
}
}
// ignore y / top-bottom values for y == -1
if (y != -1) {
// check if the mouse pointer is within the height of the target
int top = CmsDomUtil.getRelativeY(y, element);
int offsetHeight = element.getOffsetHeight();
if ((top <= 0) || (top >= offsetHeight)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
@Override
public void addExtraState(EntityEntryExtraState extraState) {
if ( next == null ) {
next = extraState;
}
else {
next.addExtraState( extraState );
}
} } | public class class_name {
@Override
public void addExtraState(EntityEntryExtraState extraState) {
if ( next == null ) {
next = extraState; // depends on control dependency: [if], data = [none]
}
else {
next.addExtraState( extraState ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void register(ContentViewer handler) {
if (handler.isEditor()) {
String[] types = handler.getTypes();
for (String element : types) {
s_editors.put(element, handler);
}
}
String[] types = handler.getTypes();
for (String element : types) {
s_viewers.put(element, handler);
}
} } | public class class_name {
public static void register(ContentViewer handler) {
if (handler.isEditor()) {
String[] types = handler.getTypes();
for (String element : types) {
s_editors.put(element, handler); // depends on control dependency: [for], data = [element]
}
}
String[] types = handler.getTypes();
for (String element : types) {
s_viewers.put(element, handler); // depends on control dependency: [for], data = [element]
}
} } |
public class class_name {
public static void heapSort(int[] arrays) {
// 将待排序的序列构建成一个大顶堆
for (int i = arrays.length / ValueConsts.TWO_INT; i >= 0; i--) {
heapAdjust(arrays, i, arrays.length);
}
// 逐步将每个最大值的根节点与末尾元素交换,并且再调整二叉树,使其成为大顶堆
for (int i = arrays.length - 1; i > 0; i--) {
// 将堆顶记录和当前未经排序子序列的最后一个记录交换
switchNumber(arrays, 0, i);
// 交换之后,需要重新检查堆是否符合大顶堆,不符合则要调整
heapAdjust(arrays, 0, i);
}
} } | public class class_name {
public static void heapSort(int[] arrays) {
// 将待排序的序列构建成一个大顶堆
for (int i = arrays.length / ValueConsts.TWO_INT; i >= 0; i--) {
heapAdjust(arrays, i, arrays.length); // depends on control dependency: [for], data = [i]
}
// 逐步将每个最大值的根节点与末尾元素交换,并且再调整二叉树,使其成为大顶堆
for (int i = arrays.length - 1; i > 0; i--) {
// 将堆顶记录和当前未经排序子序列的最后一个记录交换
switchNumber(arrays, 0, i); // depends on control dependency: [for], data = [i]
// 交换之后,需要重新检查堆是否符合大顶堆,不符合则要调整
heapAdjust(arrays, 0, i); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
@Override
protected void visitLetContentNode(LetContentNode node) {
String generatedVarName = node.getUniqueVarName();
Expression generatedVar = id(generatedVarName);
// Generate code to define the local var.
jsCodeBuilder.pushOutputVar(generatedVarName);
visitChildren(node);
jsCodeBuilder.popOutputVar();
if (node.getContentKind() != null) {
// If the let node had a content kind specified, it was autoescaped in the corresponding
// context. Hence the result of evaluating the let block is wrapped in a SanitizedContent
// instance of the appropriate kind.
// The expression for the constructor of SanitizedContent of the appropriate kind (e.g.,
// "soydata.VERY_UNSAFE.ordainSanitizedHtml"), or null if the node has no 'kind' attribute.
// Introduce a new variable for this value since it has a different type from the output
// variable (SanitizedContent vs String) and this will enable optimizations in the jscompiler
String wrappedVarName = node.getVarName() + "__wrapped" + node.getId();
jsCodeBuilder.append(
VariableDeclaration.builder(wrappedVarName)
.setRhs(
sanitizedContentOrdainerFunctionForInternalBlocks(node.getContentKind())
.call(generatedVar))
.build());
generatedVar = id(wrappedVarName);
}
// Add a mapping for generating future references to this local var.
templateTranslationContext.soyToJsVariableMappings().put(node.getVarName(), generatedVar);
} } | public class class_name {
@Override
protected void visitLetContentNode(LetContentNode node) {
String generatedVarName = node.getUniqueVarName();
Expression generatedVar = id(generatedVarName);
// Generate code to define the local var.
jsCodeBuilder.pushOutputVar(generatedVarName);
visitChildren(node);
jsCodeBuilder.popOutputVar();
if (node.getContentKind() != null) {
// If the let node had a content kind specified, it was autoescaped in the corresponding
// context. Hence the result of evaluating the let block is wrapped in a SanitizedContent
// instance of the appropriate kind.
// The expression for the constructor of SanitizedContent of the appropriate kind (e.g.,
// "soydata.VERY_UNSAFE.ordainSanitizedHtml"), or null if the node has no 'kind' attribute.
// Introduce a new variable for this value since it has a different type from the output
// variable (SanitizedContent vs String) and this will enable optimizations in the jscompiler
String wrappedVarName = node.getVarName() + "__wrapped" + node.getId();
jsCodeBuilder.append(
VariableDeclaration.builder(wrappedVarName)
.setRhs(
sanitizedContentOrdainerFunctionForInternalBlocks(node.getContentKind())
.call(generatedVar))
.build()); // depends on control dependency: [if], data = [none]
generatedVar = id(wrappedVarName); // depends on control dependency: [if], data = [none]
}
// Add a mapping for generating future references to this local var.
templateTranslationContext.soyToJsVariableMappings().put(node.getVarName(), generatedVar);
} } |
public class class_name {
private String simpleServiceNames(Collection<Service> services) {
StringBuilder buffer = new StringBuilder();
for (Service service : services) {
if (buffer.length() > 0) {
buffer.append(",");
}
buffer.append(service.getClass().getSimpleName());
}
return buffer.toString();
} } | public class class_name {
private String simpleServiceNames(Collection<Service> services) {
StringBuilder buffer = new StringBuilder();
for (Service service : services) {
if (buffer.length() > 0) {
buffer.append(",");
// depends on control dependency: [if], data = [none]
}
buffer.append(service.getClass().getSimpleName());
// depends on control dependency: [for], data = [service]
}
return buffer.toString();
} } |
public class class_name {
public int getSize() {
if (size < 0) {
size = 0;
for (byte[] cache: start) {
size += new RemoteOneFileCache(cache).getSize();
}
for (byte[] cache: end) {
size += new RemoteOneFileCache(cache).getSize();
}
}
return size;
} } | public class class_name {
public int getSize() {
if (size < 0) {
size = 0; // depends on control dependency: [if], data = [none]
for (byte[] cache: start) {
size += new RemoteOneFileCache(cache).getSize(); // depends on control dependency: [for], data = [cache]
}
for (byte[] cache: end) {
size += new RemoteOneFileCache(cache).getSize(); // depends on control dependency: [for], data = [cache]
}
}
return size;
} } |
public class class_name {
private void showToast(@Nullable final String text) {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
toast.show();
} } | public class class_name {
private void showToast(@Nullable final String text) {
if (toast != null) {
toast.cancel(); // depends on control dependency: [if], data = [none]
}
toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
toast.show();
} } |
public class class_name {
public <S> List<S> select(List<EvaluatedCandidate<S>> population,
boolean naturalFitnessScores,
int selectionSize,
Random rng)
{
// Record the cumulative fitness scores. It doesn't matter whether the
// population is sorted or not. We will use these cumulative scores to work out
// an index into the population. The cumulative array itself is implicitly
// sorted since each element must be greater than the previous one. The
// numerical difference between an element and the previous one is directly
// proportional to the probability of the corresponding candidate in the population
// being selected.
double[] cumulativeFitnesses = new double[population.size()];
cumulativeFitnesses[0] = getAdjustedFitness(population.get(0).getFitness(),
naturalFitnessScores);
for (int i = 1; i < population.size(); i++)
{
double fitness = getAdjustedFitness(population.get(i).getFitness(),
naturalFitnessScores);
cumulativeFitnesses[i] = cumulativeFitnesses[i - 1] + fitness;
}
List<S> selection = new ArrayList<S>(selectionSize);
for (int i = 0; i < selectionSize; i++)
{
double randomFitness = rng.nextDouble() * cumulativeFitnesses[cumulativeFitnesses.length - 1];
int index = Arrays.binarySearch(cumulativeFitnesses, randomFitness);
if (index < 0)
{
// Convert negative insertion point to array index.
index = Math.abs(index + 1);
}
selection.add(population.get(index).getCandidate());
}
return selection;
} } | public class class_name {
public <S> List<S> select(List<EvaluatedCandidate<S>> population,
boolean naturalFitnessScores,
int selectionSize,
Random rng)
{
// Record the cumulative fitness scores. It doesn't matter whether the
// population is sorted or not. We will use these cumulative scores to work out
// an index into the population. The cumulative array itself is implicitly
// sorted since each element must be greater than the previous one. The
// numerical difference between an element and the previous one is directly
// proportional to the probability of the corresponding candidate in the population
// being selected.
double[] cumulativeFitnesses = new double[population.size()];
cumulativeFitnesses[0] = getAdjustedFitness(population.get(0).getFitness(),
naturalFitnessScores);
for (int i = 1; i < population.size(); i++)
{
double fitness = getAdjustedFitness(population.get(i).getFitness(),
naturalFitnessScores);
cumulativeFitnesses[i] = cumulativeFitnesses[i - 1] + fitness; // depends on control dependency: [for], data = [i]
}
List<S> selection = new ArrayList<S>(selectionSize);
for (int i = 0; i < selectionSize; i++)
{
double randomFitness = rng.nextDouble() * cumulativeFitnesses[cumulativeFitnesses.length - 1];
int index = Arrays.binarySearch(cumulativeFitnesses, randomFitness);
if (index < 0)
{
// Convert negative insertion point to array index.
index = Math.abs(index + 1); // depends on control dependency: [if], data = [(index]
}
selection.add(population.get(index).getCandidate()); // depends on control dependency: [for], data = [none]
}
return selection;
} } |
public class class_name {
public int updateExpirationTime(Object id, long oldExpirationTime, int size, long newExpirationTime, long newValidatorExpirationTime) {
int returnCode = this.htod.updateExpirationTime(id, oldExpirationTime, size, newExpirationTime, newValidatorExpirationTime);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException);
}
return returnCode;
} } | public class class_name {
public int updateExpirationTime(Object id, long oldExpirationTime, int size, long newExpirationTime, long newValidatorExpirationTime) {
int returnCode = this.htod.updateExpirationTime(id, oldExpirationTime, size, newExpirationTime, newValidatorExpirationTime);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException); // depends on control dependency: [if], data = [none]
}
return returnCode;
} } |
public class class_name {
public static <A> double[] toPrimitiveDoubleArray(A data, NumberArrayAdapter<?, A> adapter) {
if(adapter == DoubleArrayAdapter.STATIC) {
return ((double[]) data).clone();
}
final int len = adapter.size(data);
double[] x = new double[len];
for(int i = 0; i < len; i++) {
x[i] = adapter.getDouble(data, i);
}
return x;
} } | public class class_name {
public static <A> double[] toPrimitiveDoubleArray(A data, NumberArrayAdapter<?, A> adapter) {
if(adapter == DoubleArrayAdapter.STATIC) {
return ((double[]) data).clone(); // depends on control dependency: [if], data = [none]
}
final int len = adapter.size(data);
double[] x = new double[len];
for(int i = 0; i < len; i++) {
x[i] = adapter.getDouble(data, i); // depends on control dependency: [for], data = [i]
}
return x;
} } |
public class class_name {
public void addChildren( Iterable<PlanNode> otherChildren ) {
assert otherChildren != null;
for (PlanNode planNode : otherChildren) {
this.addLastChild(planNode);
}
} } | public class class_name {
public void addChildren( Iterable<PlanNode> otherChildren ) {
assert otherChildren != null;
for (PlanNode planNode : otherChildren) {
this.addLastChild(planNode); // depends on control dependency: [for], data = [planNode]
}
} } |
public class class_name {
private void cacheFieldRefKey(String fieldCacheKey,String idCacheKey,long expired){
if(nullValueCache){
getCacheProvider().set(fieldCacheKey, idCacheKey, expired);
}else{
getCacheProvider().setStr(fieldCacheKey, idCacheKey, expired);
}
} } | public class class_name {
private void cacheFieldRefKey(String fieldCacheKey,String idCacheKey,long expired){
if(nullValueCache){
getCacheProvider().set(fieldCacheKey, idCacheKey, expired);
// depends on control dependency: [if], data = [none]
}else{
getCacheProvider().setStr(fieldCacheKey, idCacheKey, expired);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ServiceReference<Application> getApplicationServiceRef(BundleContext bundleContext, String applicationName) {
ServiceReference<Application> appRef = null;
if (FrameworkState.isValid()) {
Collection<ServiceReference<Application>> appRefs;
try {
appRefs = bundleContext.getServiceReferences(Application.class,
FilterUtils.createPropertyFilter("name", applicationName));
} catch (InvalidSyntaxException e) {
throw new ConfigException(e);
}
if (appRefs != null && appRefs.size() > 0) {
if (appRefs.size() > 1) {
throw new ConfigException(Tr.formatMessage(tc, "duplicate.application.name.CWMCG0202E", applicationName));
}
appRef = appRefs.iterator().next();
}
}
return appRef;
} } | public class class_name {
public static ServiceReference<Application> getApplicationServiceRef(BundleContext bundleContext, String applicationName) {
ServiceReference<Application> appRef = null;
if (FrameworkState.isValid()) {
Collection<ServiceReference<Application>> appRefs;
try {
appRefs = bundleContext.getServiceReferences(Application.class,
FilterUtils.createPropertyFilter("name", applicationName)); // depends on control dependency: [try], data = [none]
} catch (InvalidSyntaxException e) {
throw new ConfigException(e);
} // depends on control dependency: [catch], data = [none]
if (appRefs != null && appRefs.size() > 0) {
if (appRefs.size() > 1) {
throw new ConfigException(Tr.formatMessage(tc, "duplicate.application.name.CWMCG0202E", applicationName));
}
appRef = appRefs.iterator().next(); // depends on control dependency: [if], data = [none]
}
}
return appRef;
} } |
public class class_name {
public void marshall(SqlQueryDatasetAction sqlQueryDatasetAction, ProtocolMarshaller protocolMarshaller) {
if (sqlQueryDatasetAction == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(sqlQueryDatasetAction.getSqlQuery(), SQLQUERY_BINDING);
protocolMarshaller.marshall(sqlQueryDatasetAction.getFilters(), FILTERS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SqlQueryDatasetAction sqlQueryDatasetAction, ProtocolMarshaller protocolMarshaller) {
if (sqlQueryDatasetAction == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(sqlQueryDatasetAction.getSqlQuery(), SQLQUERY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(sqlQueryDatasetAction.getFilters(), FILTERS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Response createApplication( Application app ) {
this.logger.fine( "Request: create application " + app + "." );
Response result;
try {
String tplName = app.getTemplate() == null ? null : app.getTemplate().getName();
String tplQualifier = app.getTemplate() == null ? null : app.getTemplate().getVersion();
String appName = app.getDisplayName() != null ? app.getDisplayName() : app.getName();
ManagedApplication ma = this.manager.applicationMngr().createApplication( appName, app.getDescription(), tplName, tplQualifier );
result = Response.ok().entity( ma.getApplication()).build();
} catch( InvalidApplicationException e ) {
result = handleError(
Status.NOT_FOUND,
new RestError( REST_MNGMT_INVALID_TPL, e, application( app )),
lang( this.manager )).build();
} catch( AlreadyExistingException e ) {
result = handleError(
Status.FORBIDDEN,
new RestError( REST_MNGMT_CONFLICT, e, application( app )),
lang( this.manager )).build();
} catch( IOException e ) {
result = handleError(
Status.UNAUTHORIZED,
new RestError( REST_SAVE_ERROR, e, application( app )),
lang( this.manager )).build();
}
return result;
} } | public class class_name {
@Override
public Response createApplication( Application app ) {
this.logger.fine( "Request: create application " + app + "." );
Response result;
try {
String tplName = app.getTemplate() == null ? null : app.getTemplate().getName();
String tplQualifier = app.getTemplate() == null ? null : app.getTemplate().getVersion();
String appName = app.getDisplayName() != null ? app.getDisplayName() : app.getName();
ManagedApplication ma = this.manager.applicationMngr().createApplication( appName, app.getDescription(), tplName, tplQualifier );
result = Response.ok().entity( ma.getApplication()).build(); // depends on control dependency: [try], data = [none]
} catch( InvalidApplicationException e ) {
result = handleError(
Status.NOT_FOUND,
new RestError( REST_MNGMT_INVALID_TPL, e, application( app )),
lang( this.manager )).build();
} catch( AlreadyExistingException e ) { // depends on control dependency: [catch], data = [none]
result = handleError(
Status.FORBIDDEN,
new RestError( REST_MNGMT_CONFLICT, e, application( app )),
lang( this.manager )).build();
} catch( IOException e ) { // depends on control dependency: [catch], data = [none]
result = handleError(
Status.UNAUTHORIZED,
new RestError( REST_SAVE_ERROR, e, application( app )),
lang( this.manager )).build();
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public static double volumeUnionScaled(SpatialComparable box1, SpatialComparable box2, double scale) {
final int dim = assertSameDimensionality(box1, box2);
double volume = 1.;
for(int i = 0; i < dim; i++) {
final double min = Math.min(box1.getMin(i), box2.getMin(i));
final double max = Math.max(box1.getMax(i), box2.getMax(i));
volume *= (max - min) * scale;
}
return volume;
} } | public class class_name {
public static double volumeUnionScaled(SpatialComparable box1, SpatialComparable box2, double scale) {
final int dim = assertSameDimensionality(box1, box2);
double volume = 1.;
for(int i = 0; i < dim; i++) {
final double min = Math.min(box1.getMin(i), box2.getMin(i));
final double max = Math.max(box1.getMax(i), box2.getMax(i));
volume *= (max - min) * scale; // depends on control dependency: [for], data = [none]
}
return volume;
} } |
public class class_name {
public OverlayIcon withOverlay(ImageIcon ... overlays) {
if(overlays != null) {
for(ImageIcon overlay : overlays) {
this.overlays.add(overlay);
}
}
return this;
} } | public class class_name {
public OverlayIcon withOverlay(ImageIcon ... overlays) {
if(overlays != null) {
for(ImageIcon overlay : overlays) {
this.overlays.add(overlay); // depends on control dependency: [for], data = [overlay]
}
}
return this;
} } |
public class class_name {
public static Partitions parse(String nodes) {
Partitions result = new Partitions();
try {
List<RedisClusterNode> mappedNodes = TOKEN_PATTERN.splitAsStream(nodes).filter(s -> !s.isEmpty())
.map(ClusterPartitionParser::parseNode).collect(Collectors.toList());
result.addAll(mappedNodes);
} catch (Exception e) {
throw new RedisException("Cannot parse " + nodes, e);
}
return result;
} } | public class class_name {
public static Partitions parse(String nodes) {
Partitions result = new Partitions();
try {
List<RedisClusterNode> mappedNodes = TOKEN_PATTERN.splitAsStream(nodes).filter(s -> !s.isEmpty())
.map(ClusterPartitionParser::parseNode).collect(Collectors.toList());
result.addAll(mappedNodes); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RedisException("Cannot parse " + nodes, e);
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
private static ThreadPoolExecutor build(ExecutorBuilder builder) {
final int corePoolSize = builder.corePoolSize;
final int maxPoolSize = builder.maxPoolSize;
final long keepAliveTime = builder.keepAliveTime;
final BlockingQueue<Runnable> workQueue;
if (null != builder.workQueue) {
workQueue = builder.workQueue;
} else {
// corePoolSize为0则要使用SynchronousQueue避免无限阻塞
workQueue = (corePoolSize <= 0) ? new SynchronousQueue<Runnable>() : new LinkedBlockingQueue<Runnable>();
}
final ThreadFactory threadFactory = (null != builder.threadFactory) ? builder.threadFactory : Executors.defaultThreadFactory();
RejectedExecutionHandler handler = ObjectUtil.defaultIfNull(builder.handler, new ThreadPoolExecutor.AbortPolicy());
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(//
corePoolSize, //
maxPoolSize, //
keepAliveTime, TimeUnit.NANOSECONDS, //
workQueue, //
threadFactory, //
handler//
);
if (null != builder.allowCoreThreadTimeOut) {
threadPoolExecutor.allowCoreThreadTimeOut(builder.allowCoreThreadTimeOut);
}
return threadPoolExecutor;
} } | public class class_name {
private static ThreadPoolExecutor build(ExecutorBuilder builder) {
final int corePoolSize = builder.corePoolSize;
final int maxPoolSize = builder.maxPoolSize;
final long keepAliveTime = builder.keepAliveTime;
final BlockingQueue<Runnable> workQueue;
if (null != builder.workQueue) {
workQueue = builder.workQueue;
// depends on control dependency: [if], data = [none]
} else {
// corePoolSize为0则要使用SynchronousQueue避免无限阻塞
workQueue = (corePoolSize <= 0) ? new SynchronousQueue<Runnable>() : new LinkedBlockingQueue<Runnable>();
// depends on control dependency: [if], data = [none]
}
final ThreadFactory threadFactory = (null != builder.threadFactory) ? builder.threadFactory : Executors.defaultThreadFactory();
RejectedExecutionHandler handler = ObjectUtil.defaultIfNull(builder.handler, new ThreadPoolExecutor.AbortPolicy());
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(//
corePoolSize, //
maxPoolSize, //
keepAliveTime, TimeUnit.NANOSECONDS, //
workQueue, //
threadFactory, //
handler//
);
if (null != builder.allowCoreThreadTimeOut) {
threadPoolExecutor.allowCoreThreadTimeOut(builder.allowCoreThreadTimeOut);
// depends on control dependency: [if], data = [builder.allowCoreThreadTimeOut)]
}
return threadPoolExecutor;
} } |
public class class_name {
private Date getRunDate(GitHubRepo repo, boolean firstRun) {
if (firstRun) {
int firstRunDaysHistory = settings.getFirstRunHistoryDays();
if (firstRunDaysHistory > 0) {
return getDate(new Date(), -firstRunDaysHistory, 0);
} else {
return getDate(new Date(), -FIRST_RUN_HISTORY_DEFAULT, 0);
}
} else {
return getDate(new Date(repo.getLastUpdated()), 0, -10);
}
} } | public class class_name {
private Date getRunDate(GitHubRepo repo, boolean firstRun) {
if (firstRun) {
int firstRunDaysHistory = settings.getFirstRunHistoryDays();
if (firstRunDaysHistory > 0) {
return getDate(new Date(), -firstRunDaysHistory, 0); // depends on control dependency: [if], data = [0)]
} else {
return getDate(new Date(), -FIRST_RUN_HISTORY_DEFAULT, 0); // depends on control dependency: [if], data = [0)]
}
} else {
return getDate(new Date(repo.getLastUpdated()), 0, -10); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Set<String> validateJobHealthCheck(final Job job) {
final HealthCheck healthCheck = job.getHealthCheck();
if (healthCheck == null) {
return emptySet();
}
final Set<String> errors = Sets.newHashSet();
if (healthCheck instanceof ExecHealthCheck) {
final List<String> command = ((ExecHealthCheck) healthCheck).getCommand();
if (command == null || command.isEmpty()) {
errors.add("A command must be defined for `docker exec`-based health checks.");
}
} else if (healthCheck instanceof HttpHealthCheck || healthCheck instanceof TcpHealthCheck) {
final String port;
if (healthCheck instanceof HttpHealthCheck) {
port = ((HttpHealthCheck) healthCheck).getPort();
} else {
port = ((TcpHealthCheck) healthCheck).getPort();
}
final Map<String, PortMapping> ports = job.getPorts();
if (isNullOrEmpty(port)) {
errors.add("A port must be defined for HTTP and TCP health checks.");
} else if (!ports.containsKey(port)) {
errors.add(format("Health check port '%s' not defined in the job. Known ports are '%s'",
port, Joiner.on(", ").join(ports.keySet())));
}
}
return errors;
} } | public class class_name {
private Set<String> validateJobHealthCheck(final Job job) {
final HealthCheck healthCheck = job.getHealthCheck();
if (healthCheck == null) {
return emptySet(); // depends on control dependency: [if], data = [none]
}
final Set<String> errors = Sets.newHashSet();
if (healthCheck instanceof ExecHealthCheck) {
final List<String> command = ((ExecHealthCheck) healthCheck).getCommand();
if (command == null || command.isEmpty()) {
errors.add("A command must be defined for `docker exec`-based health checks."); // depends on control dependency: [if], data = [none]
}
} else if (healthCheck instanceof HttpHealthCheck || healthCheck instanceof TcpHealthCheck) {
final String port;
if (healthCheck instanceof HttpHealthCheck) {
port = ((HttpHealthCheck) healthCheck).getPort(); // depends on control dependency: [if], data = [none]
} else {
port = ((TcpHealthCheck) healthCheck).getPort(); // depends on control dependency: [if], data = [none]
}
final Map<String, PortMapping> ports = job.getPorts();
if (isNullOrEmpty(port)) {
errors.add("A port must be defined for HTTP and TCP health checks.");
} else if (!ports.containsKey(port)) {
errors.add(format("Health check port '%s' not defined in the job. Known ports are '%s'",
port, Joiner.on(", ").join(ports.keySet())));
}
}
return errors;
} } |
public class class_name {
private void decodeSubmittedValues(final FacesContext context, final Sheet sheet, final String jsonData) {
if (LangUtils.isValueBlank(jsonData)) {
return;
}
try {
// data comes in as a JSON Object with named properties for the row and columns
// updated this is so that
// multiple updates to the same cell overwrite previous deltas prior to
// submission we don't care about
// the property names, just the values, which we'll process in turn
final JSONObject obj = new JSONObject(jsonData);
final Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
final String key = keys.next();
// data comes in: [row, col, oldValue, newValue, rowKey]
final JSONArray update = obj.getJSONArray(key);
// GitHub #586 pasted more values than rows
if (update.isNull(4)) {
continue;
}
final String rowKey = update.getString(4);
final int col = sheet.getMappedColumn(update.getInt(1));
final String newValue = String.valueOf(update.get(3));
sheet.setSubmittedValue(context, rowKey, col, newValue);
}
}
catch (final JSONException ex) {
throw new FacesException("Failed parsing Ajax JSON message for cell change event:" + ex.getMessage(), ex);
}
} } | public class class_name {
private void decodeSubmittedValues(final FacesContext context, final Sheet sheet, final String jsonData) {
if (LangUtils.isValueBlank(jsonData)) {
return; // depends on control dependency: [if], data = [none]
}
try {
// data comes in as a JSON Object with named properties for the row and columns
// updated this is so that
// multiple updates to the same cell overwrite previous deltas prior to
// submission we don't care about
// the property names, just the values, which we'll process in turn
final JSONObject obj = new JSONObject(jsonData);
final Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
final String key = keys.next();
// data comes in: [row, col, oldValue, newValue, rowKey]
final JSONArray update = obj.getJSONArray(key);
// GitHub #586 pasted more values than rows
if (update.isNull(4)) {
continue;
}
final String rowKey = update.getString(4);
final int col = sheet.getMappedColumn(update.getInt(1));
final String newValue = String.valueOf(update.get(3));
sheet.setSubmittedValue(context, rowKey, col, newValue); // depends on control dependency: [while], data = [none]
}
}
catch (final JSONException ex) {
throw new FacesException("Failed parsing Ajax JSON message for cell change event:" + ex.getMessage(), ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ApplicationGetOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public ApplicationGetOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
@Override
public void deregisterFactory(String name) {
final boolean bTrace = TraceComponent.isAnyTracingEnabled();
if (bTrace && tc.isDebugEnabled()) {
Tr.debug(tc, "Removing factory registration: " + name);
}
Class<?> factory = null;
synchronized (this.factories) {
factory = this.factories.remove(name);
}
if (null != factory) {
final String factoryName = factory.getName();
final List<String> chains = new ArrayList<String>();
synchronized (this) {
for (ChainData chainData : this.chainDataMap.values()) {
// Look at each channel associated with this chain.
for (ChannelData channel : chainData.getChannelList()) {
if (channel.getFactoryType().getName().equals(factoryName)) {
chains.add(chainData.getName());
break; // out of channel loop
}
}
}
}
// create a post-action for cleaning up the chains whose factory has been removed.
Runnable cleanup = new Runnable() {
@Override
public void run() {
for (String chainName : chains) {
cleanupChain(chainName);
}
}
};
// Stop the chain.. the cleanup will happen once the quiesce is complete.
ChannelUtils.stopChains(chains, -1L, cleanup);
}
} } | public class class_name {
@Override
public void deregisterFactory(String name) {
final boolean bTrace = TraceComponent.isAnyTracingEnabled();
if (bTrace && tc.isDebugEnabled()) {
Tr.debug(tc, "Removing factory registration: " + name); // depends on control dependency: [if], data = [none]
}
Class<?> factory = null;
synchronized (this.factories) {
factory = this.factories.remove(name);
}
if (null != factory) {
final String factoryName = factory.getName();
final List<String> chains = new ArrayList<String>();
synchronized (this) { // depends on control dependency: [if], data = [none]
for (ChainData chainData : this.chainDataMap.values()) {
// Look at each channel associated with this chain.
for (ChannelData channel : chainData.getChannelList()) {
if (channel.getFactoryType().getName().equals(factoryName)) {
chains.add(chainData.getName()); // depends on control dependency: [if], data = [none]
break; // out of channel loop
}
}
}
}
// create a post-action for cleaning up the chains whose factory has been removed.
Runnable cleanup = new Runnable() {
@Override
public void run() {
for (String chainName : chains) {
cleanupChain(chainName); // depends on control dependency: [for], data = [chainName]
}
}
};
// Stop the chain.. the cleanup will happen once the quiesce is complete.
ChannelUtils.stopChains(chains, -1L, cleanup); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static String dbgBuffer(ByteBuffer b, int size) {
StringBuilder sb = new StringBuilder();
byte[] bytes = b.array();
for (int i = 0; i < size; i++) {
char ch = (char) bytes[i];
if (Character.isWhitespace(ch) || Character.isLetterOrDigit(ch)) {
sb.append(ch);
} else {
sb.append("\\x");
sb.append(Integer.toHexString(bytes[i] & 0xff));
}
}
return sb.toString();
} } | public class class_name {
static String dbgBuffer(ByteBuffer b, int size) {
StringBuilder sb = new StringBuilder();
byte[] bytes = b.array();
for (int i = 0; i < size; i++) {
char ch = (char) bytes[i];
if (Character.isWhitespace(ch) || Character.isLetterOrDigit(ch)) {
sb.append(ch); // depends on control dependency: [if], data = [none]
} else {
sb.append("\\x"); // depends on control dependency: [if], data = [none]
sb.append(Integer.toHexString(bytes[i] & 0xff)); // depends on control dependency: [if], data = [none]
}
}
return sb.toString();
} } |
public class class_name {
public Observable<ServiceResponse<InputStream>> downloadQueryLogsWithServiceResponseAsync(UUID appId) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
return service.downloadQueryLogs(appId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<InputStream>>>() {
@Override
public Observable<ServiceResponse<InputStream>> call(Response<ResponseBody> response) {
try {
ServiceResponse<InputStream> clientResponse = downloadQueryLogsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<InputStream>> downloadQueryLogsWithServiceResponseAsync(UUID appId) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
return service.downloadQueryLogs(appId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<InputStream>>>() {
@Override
public Observable<ServiceResponse<InputStream>> call(Response<ResponseBody> response) {
try {
ServiceResponse<InputStream> clientResponse = downloadQueryLogsDelegate(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 {
protected void fillRemainingFlowCapacityAndLastDispatchedTime(final ExecutorInfo stats) {
final AzkabanExecutorServer server = AzkabanExecutorServer.getApp();
if (server != null) {
final FlowRunnerManager runnerMgr = AzkabanExecutorServer.getApp().getFlowRunnerManager();
final int assignedFlows = runnerMgr.getNumRunningFlows() + runnerMgr.getNumQueuedFlows();
stats.setRemainingFlowCapacity(runnerMgr.getMaxNumRunningFlows() - assignedFlows);
stats.setNumberOfAssignedFlows(assignedFlows);
stats.setLastDispatchedTime(runnerMgr.getLastFlowSubmittedTime());
} else {
logger.error("failed to get data for remaining flow capacity or LastDispatchedTime"
+ " as the AzkabanExecutorServer has yet been initialized.");
}
} } | public class class_name {
protected void fillRemainingFlowCapacityAndLastDispatchedTime(final ExecutorInfo stats) {
final AzkabanExecutorServer server = AzkabanExecutorServer.getApp();
if (server != null) {
final FlowRunnerManager runnerMgr = AzkabanExecutorServer.getApp().getFlowRunnerManager();
final int assignedFlows = runnerMgr.getNumRunningFlows() + runnerMgr.getNumQueuedFlows();
stats.setRemainingFlowCapacity(runnerMgr.getMaxNumRunningFlows() - assignedFlows); // depends on control dependency: [if], data = [none]
stats.setNumberOfAssignedFlows(assignedFlows); // depends on control dependency: [if], data = [none]
stats.setLastDispatchedTime(runnerMgr.getLastFlowSubmittedTime()); // depends on control dependency: [if], data = [none]
} else {
logger.error("failed to get data for remaining flow capacity or LastDispatchedTime"
+ " as the AzkabanExecutorServer has yet been initialized."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@NonNull
public final synchronized ChronosListener getListener(final int id) {
ChronosListener chronosListener = mListeners.get(id);
if (chronosListener == null) {
chronosListener = new ChronosListener(id);
mListeners.put(id, chronosListener);
}
return chronosListener;
} } | public class class_name {
@NonNull
public final synchronized ChronosListener getListener(final int id) {
ChronosListener chronosListener = mListeners.get(id);
if (chronosListener == null) {
chronosListener = new ChronosListener(id); // depends on control dependency: [if], data = [none]
mListeners.put(id, chronosListener); // depends on control dependency: [if], data = [none]
}
return chronosListener;
} } |
public class class_name {
public void marshall(AttachThingPrincipalRequest attachThingPrincipalRequest, ProtocolMarshaller protocolMarshaller) {
if (attachThingPrincipalRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(attachThingPrincipalRequest.getThingName(), THINGNAME_BINDING);
protocolMarshaller.marshall(attachThingPrincipalRequest.getPrincipal(), PRINCIPAL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AttachThingPrincipalRequest attachThingPrincipalRequest, ProtocolMarshaller protocolMarshaller) {
if (attachThingPrincipalRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(attachThingPrincipalRequest.getThingName(), THINGNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(attachThingPrincipalRequest.getPrincipal(), PRINCIPAL_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<MetricDataQuery> getMetricDataQueries() {
if (metricDataQueries == null) {
metricDataQueries = new com.amazonaws.internal.SdkInternalList<MetricDataQuery>();
}
return metricDataQueries;
} } | public class class_name {
public java.util.List<MetricDataQuery> getMetricDataQueries() {
if (metricDataQueries == null) {
metricDataQueries = new com.amazonaws.internal.SdkInternalList<MetricDataQuery>(); // depends on control dependency: [if], data = [none]
}
return metricDataQueries;
} } |
public class class_name {
@Override
public int compareTo(SAXRecord o) {
int a = this.occurrences.size();
int b = o.getIndexes().size();
if (a == b) {
return 0;
}
else if (a > b) {
return 1;
}
return -1;
} } | public class class_name {
@Override
public int compareTo(SAXRecord o) {
int a = this.occurrences.size();
int b = o.getIndexes().size();
if (a == b) {
return 0; // depends on control dependency: [if], data = [none]
}
else if (a > b) {
return 1; // depends on control dependency: [if], data = [none]
}
return -1;
} } |
public class class_name {
@Override
public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) {
XmlType xmlType = property.xmlInfo.xmlType;
if (property.isNullable() && !property.isInCollection()) {
methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property));
}
if (property.hasTypeAdapter()) {
switch (xmlType) {
case ATTRIBUTE:
methodBuilder.addStatement("$L.write$LAttribute(null, null,$S, " + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")", serializerName, ATTRIBUTE_METHOD, BindProperty.xmlName(property),
TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
case TAG:
methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property));
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
methodBuilder.addStatement("$L.writeEndElement()", serializerName);
break;
case VALUE:
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
case VALUE_CDATA:
methodBuilder.addStatement("$L.writeCData($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
}
} else {
switch (xmlType) {
case ATTRIBUTE:
methodBuilder.addStatement("$L.write$LAttribute(null, null,$S, $L)", serializerName, ATTRIBUTE_METHOD, BindProperty.xmlName(property), getter(beanName, beanClass, property));
break;
case TAG:
methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property));
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
methodBuilder.addStatement("$L.writeEndElement()", serializerName);
break;
case VALUE:
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
break;
case VALUE_CDATA:
methodBuilder.addStatement("$L.writeCData($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
break;
}
}
if (property.isNullable() && !property.isInCollection()) {
methodBuilder.endControlFlow();
}
} } | public class class_name {
@Override
public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) {
XmlType xmlType = property.xmlInfo.xmlType;
if (property.isNullable() && !property.isInCollection()) {
methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); // depends on control dependency: [if], data = [none]
}
if (property.hasTypeAdapter()) {
switch (xmlType) {
case ATTRIBUTE:
methodBuilder.addStatement("$L.write$LAttribute(null, null,$S, " + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")", serializerName, ATTRIBUTE_METHOD, BindProperty.xmlName(property),
TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
case TAG:
methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property));
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
methodBuilder.addStatement("$L.writeEndElement()", serializerName);
break;
case VALUE:
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
case VALUE_CDATA:
methodBuilder.addStatement("$L.writeCData($T.escapeXml10($T.write(" + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER + ")))", serializerName, StringEscapeUtils.class,
NUMBER_UTIL_CLAZZ, TypeAdapterUtils.class, TypeUtility.typeName(property.typeAdapter.adapterClazz), getter(beanName, beanClass, property));
break;
}
} else {
switch (xmlType) {
case ATTRIBUTE:
methodBuilder.addStatement("$L.write$LAttribute(null, null,$S, $L)", serializerName, ATTRIBUTE_METHOD, BindProperty.xmlName(property), getter(beanName, beanClass, property));
break;
case TAG:
methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property));
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
methodBuilder.addStatement("$L.writeEndElement()", serializerName);
break;
case VALUE:
methodBuilder.addStatement("$L.writeCharacters($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
break;
case VALUE_CDATA:
methodBuilder.addStatement("$L.writeCData($T.escapeXml10($T.write($L)))", serializerName, StringEscapeUtils.class, NUMBER_UTIL_CLAZZ, getter(beanName, beanClass, property));
break;
}
}
if (property.isNullable() && !property.isInCollection()) {
methodBuilder.endControlFlow(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean findAndMoveParentWithChildren(
Set<CmsResource> originalSet,
ResourceMap reachability,
ResourceMap result) {
for (CmsResource parent : originalSet) {
Set<CmsResource> reachableResources = reachability.get(parent);
Set<CmsResource> children = Sets.newHashSet();
if (reachableResources.size() > 1) {
for (CmsResource potentialChild : reachableResources) {
if ((potentialChild != parent) && originalSet.contains(potentialChild)) {
children.add(potentialChild);
}
}
if (children.size() > 0) {
result.get(parent).addAll(children);
originalSet.removeAll(children);
originalSet.remove(parent);
return true;
}
}
}
return false;
} } | public class class_name {
private boolean findAndMoveParentWithChildren(
Set<CmsResource> originalSet,
ResourceMap reachability,
ResourceMap result) {
for (CmsResource parent : originalSet) {
Set<CmsResource> reachableResources = reachability.get(parent);
Set<CmsResource> children = Sets.newHashSet();
if (reachableResources.size() > 1) {
for (CmsResource potentialChild : reachableResources) {
if ((potentialChild != parent) && originalSet.contains(potentialChild)) {
children.add(potentialChild); // depends on control dependency: [if], data = [none]
}
}
if (children.size() > 0) {
result.get(parent).addAll(children); // depends on control dependency: [if], data = [none]
originalSet.removeAll(children); // depends on control dependency: [if], data = [none]
originalSet.remove(parent); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
private static String getAnnotationAttributeValueFrom(
final Class<?> annotationType,
final String attributeName,
final List<JavaAnnotation> annotations) {
// QDox uses the fully qualified class name of the annotation for comparison.
// Extract it.
final String fullyQualifiedClassName = annotationType.getName();
JavaAnnotation annotation = null;
String toReturn = null;
if (annotations != null) {
for (JavaAnnotation current : annotations) {
if (current.getType().isA(fullyQualifiedClassName)) {
annotation = current;
break;
}
}
if (annotation != null) {
final Object nameValue = annotation.getNamedParameter(attributeName);
if (nameValue != null && nameValue instanceof String) {
toReturn = ((String) nameValue).trim();
// Remove initial and trailing " chars, if present.
if (toReturn.startsWith("\"") && toReturn.endsWith("\"")) {
toReturn = (((String) nameValue).trim()).substring(1, toReturn.length() - 1);
}
}
}
}
// All Done.
return toReturn;
} } | public class class_name {
private static String getAnnotationAttributeValueFrom(
final Class<?> annotationType,
final String attributeName,
final List<JavaAnnotation> annotations) {
// QDox uses the fully qualified class name of the annotation for comparison.
// Extract it.
final String fullyQualifiedClassName = annotationType.getName();
JavaAnnotation annotation = null;
String toReturn = null;
if (annotations != null) {
for (JavaAnnotation current : annotations) {
if (current.getType().isA(fullyQualifiedClassName)) {
annotation = current; // depends on control dependency: [if], data = [none]
break;
}
}
if (annotation != null) {
final Object nameValue = annotation.getNamedParameter(attributeName);
if (nameValue != null && nameValue instanceof String) {
toReturn = ((String) nameValue).trim(); // depends on control dependency: [if], data = [none]
// Remove initial and trailing " chars, if present.
if (toReturn.startsWith("\"") && toReturn.endsWith("\"")) {
toReturn = (((String) nameValue).trim()).substring(1, toReturn.length() - 1); // depends on control dependency: [if], data = [none]
}
}
}
}
// All Done.
return toReturn;
} } |
public class class_name {
private DSAParametersGenerator getGenerator(String hint)
{
if (hint == null || "SHA-1".equals(hint)) {
return new DSAParametersGenerator();
}
DigestFactory factory;
try {
factory = this.manager.getInstance(DigestFactory.class, hint);
} catch (ComponentLookupException e) {
throw new UnsupportedOperationException("Cryptographic hash (digest) algorithm not found.", e);
}
if (!(factory instanceof AbstractBcDigestFactory)) {
throw new IllegalArgumentException(
"Requested cryptographic hash algorithm is not implemented by a factory compatible with this factory."
+ " Factory found: " + factory.getClass().getName());
}
return new DSAParametersGenerator(((AbstractBcDigestFactory) factory).getDigestInstance());
} } | public class class_name {
private DSAParametersGenerator getGenerator(String hint)
{
if (hint == null || "SHA-1".equals(hint)) {
return new DSAParametersGenerator(); // depends on control dependency: [if], data = [none]
}
DigestFactory factory;
try {
factory = this.manager.getInstance(DigestFactory.class, hint); // depends on control dependency: [try], data = [none]
} catch (ComponentLookupException e) {
throw new UnsupportedOperationException("Cryptographic hash (digest) algorithm not found.", e);
} // depends on control dependency: [catch], data = [none]
if (!(factory instanceof AbstractBcDigestFactory)) {
throw new IllegalArgumentException(
"Requested cryptographic hash algorithm is not implemented by a factory compatible with this factory."
+ " Factory found: " + factory.getClass().getName());
}
return new DSAParametersGenerator(((AbstractBcDigestFactory) factory).getDigestInstance());
} } |
public class class_name {
Map getTrmProperties() {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "getTrmProperties");
}
final Map trmProperties = new HashMap();
final String trmBusName = getBusName();
if ((trmBusName != null) && (!trmBusName.equals(""))) {
trmProperties.put(SibTrmConstants.BUSNAME, trmBusName);
}
final String trmTarget = getTarget();
if ((trmTarget != null) && (!trmTarget.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_GROUP, trmTarget);
}
final String trmTargetType = getTargetType();
if ((trmTargetType != null) && (!trmTargetType.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TYPE, trmTargetType);
}
final String trmTargetSignificance = getTargetSignificance();
if ((trmTargetSignificance != null)
&& (!trmTargetSignificance.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_SIGNIFICANCE,
trmTargetSignificance);
}
final String trmTargetTransportChain = getTargetTransportChain();
if ((trmTargetTransportChain != null)
&& (!trmTargetTransportChain.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TRANSPORT_CHAIN,
trmTargetTransportChain);
}
final String trmProviderEndpoints = getRemoteServerAddress();
if ((trmProviderEndpoints != null)
&& (!trmProviderEndpoints.equals(""))) {
trmProperties.put(SibTrmConstants.PROVIDER_ENDPOINTS,
trmProviderEndpoints);
}
final String trmTargetTransport = getTargetTransport();
if ((trmTargetTransport != null)
&& (!trmTargetTransport.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TRANSPORT_TYPE,
trmTargetTransport);
}
final String trmConnectionProximity = getConnectionProximity();
if ((trmConnectionProximity != null)
&& (!trmConnectionProximity.equals(""))) {
trmProperties.put(SibTrmConstants.CONNECTION_PROXIMITY,
trmConnectionProximity);
}
final String trmSubscriptionProtocol = getSubscriptionProtocol();
if ((trmSubscriptionProtocol != null)
&& (!trmSubscriptionProtocol.equals(""))) {
trmProperties.put(SibTrmConstants.SUBSCRIPTION_PROTOCOL,
trmSubscriptionProtocol);
}
final String trmMulticastInterface = getMulticastInterface();
if ((trmMulticastInterface != null)
&& (!trmMulticastInterface.equals(""))) {
trmProperties.put(SibTrmConstants.MULTICAST_INTERFACE,
trmMulticastInterface);
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "getTrmProperties", trmProperties);
}
return trmProperties;
} } | public class class_name {
Map getTrmProperties() {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "getTrmProperties"); // depends on control dependency: [if], data = [none]
}
final Map trmProperties = new HashMap();
final String trmBusName = getBusName();
if ((trmBusName != null) && (!trmBusName.equals(""))) {
trmProperties.put(SibTrmConstants.BUSNAME, trmBusName); // depends on control dependency: [if], data = [none]
}
final String trmTarget = getTarget();
if ((trmTarget != null) && (!trmTarget.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_GROUP, trmTarget); // depends on control dependency: [if], data = [none]
}
final String trmTargetType = getTargetType();
if ((trmTargetType != null) && (!trmTargetType.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TYPE, trmTargetType); // depends on control dependency: [if], data = [none]
}
final String trmTargetSignificance = getTargetSignificance();
if ((trmTargetSignificance != null)
&& (!trmTargetSignificance.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_SIGNIFICANCE,
trmTargetSignificance); // depends on control dependency: [if], data = [none]
}
final String trmTargetTransportChain = getTargetTransportChain();
if ((trmTargetTransportChain != null)
&& (!trmTargetTransportChain.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TRANSPORT_CHAIN,
trmTargetTransportChain); // depends on control dependency: [if], data = [none]
}
final String trmProviderEndpoints = getRemoteServerAddress();
if ((trmProviderEndpoints != null)
&& (!trmProviderEndpoints.equals(""))) {
trmProperties.put(SibTrmConstants.PROVIDER_ENDPOINTS,
trmProviderEndpoints); // depends on control dependency: [if], data = [none]
}
final String trmTargetTransport = getTargetTransport();
if ((trmTargetTransport != null)
&& (!trmTargetTransport.equals(""))) {
trmProperties.put(SibTrmConstants.TARGET_TRANSPORT_TYPE,
trmTargetTransport); // depends on control dependency: [if], data = [none]
}
final String trmConnectionProximity = getConnectionProximity();
if ((trmConnectionProximity != null)
&& (!trmConnectionProximity.equals(""))) {
trmProperties.put(SibTrmConstants.CONNECTION_PROXIMITY,
trmConnectionProximity); // depends on control dependency: [if], data = [none]
}
final String trmSubscriptionProtocol = getSubscriptionProtocol();
if ((trmSubscriptionProtocol != null)
&& (!trmSubscriptionProtocol.equals(""))) {
trmProperties.put(SibTrmConstants.SUBSCRIPTION_PROTOCOL,
trmSubscriptionProtocol); // depends on control dependency: [if], data = [none]
}
final String trmMulticastInterface = getMulticastInterface();
if ((trmMulticastInterface != null)
&& (!trmMulticastInterface.equals(""))) {
trmProperties.put(SibTrmConstants.MULTICAST_INTERFACE,
trmMulticastInterface); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "getTrmProperties", trmProperties); // depends on control dependency: [if], data = [none]
}
return trmProperties;
} } |
public class class_name {
public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
if (itemsSeen_ == 0) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null);
} else {
return toByteArray(serDe, data_.get(0).getClass());
}
} } | public class class_name {
public byte[] toByteArray(final ArrayOfItemsSerDe<? super T> serDe) {
if (itemsSeen_ == 0) {
// null class is ok since empty -- no need to call serDe
return toByteArray(serDe, null); // depends on control dependency: [if], data = [none]
} else {
return toByteArray(serDe, data_.get(0).getClass()); // depends on control dependency: [if], data = [0)]
}
} } |
public class class_name {
public void clientInboundTrailers(Metadata trailers) {
for (StreamTracer tracer : tracers) {
((ClientStreamTracer) tracer).inboundTrailers(trailers);
}
} } | public class class_name {
public void clientInboundTrailers(Metadata trailers) {
for (StreamTracer tracer : tracers) {
((ClientStreamTracer) tracer).inboundTrailers(trailers); // depends on control dependency: [for], data = [tracer]
}
} } |
public class class_name {
@GwtIncompatible("Unnecessary")
private static void maybeCreateDirsForPath(String pathPrefix) {
if (!Strings.isNullOrEmpty(pathPrefix)) {
String dirName =
pathPrefix.charAt(pathPrefix.length() - 1) == File.separatorChar
? pathPrefix.substring(0, pathPrefix.length() - 1)
: new File(pathPrefix).getParent();
if (dirName != null) {
new File(dirName).mkdirs();
}
}
} } | public class class_name {
@GwtIncompatible("Unnecessary")
private static void maybeCreateDirsForPath(String pathPrefix) {
if (!Strings.isNullOrEmpty(pathPrefix)) {
String dirName =
pathPrefix.charAt(pathPrefix.length() - 1) == File.separatorChar
? pathPrefix.substring(0, pathPrefix.length() - 1)
: new File(pathPrefix).getParent();
if (dirName != null) {
new File(dirName).mkdirs(); // depends on control dependency: [if], data = [(dirName]
}
}
} } |
public class class_name {
public XidImpl getXidImpl(boolean createIfAbsent) {
if (tc.isEntryEnabled())
Tr.entry(tc, "getXidImpl", new Object[] { this, createIfAbsent });
if (createIfAbsent && (_xid == null)) {
// Create an XID as this transaction identifier.
_xid = new XidImpl(new TxPrimaryKey(_localTID, Configuration.getCurrentEpoch()));
}
if (tc.isEntryEnabled())
Tr.exit(tc, "getXidImpl", _xid);
return (XidImpl) _xid;
} } | public class class_name {
public XidImpl getXidImpl(boolean createIfAbsent) {
if (tc.isEntryEnabled())
Tr.entry(tc, "getXidImpl", new Object[] { this, createIfAbsent });
if (createIfAbsent && (_xid == null)) {
// Create an XID as this transaction identifier.
_xid = new XidImpl(new TxPrimaryKey(_localTID, Configuration.getCurrentEpoch())); // depends on control dependency: [if], data = [none]
}
if (tc.isEntryEnabled())
Tr.exit(tc, "getXidImpl", _xid);
return (XidImpl) _xid;
} } |
public class class_name {
private static <T> void batchReject(T[] array, int start, int end, FastListRejectProcedure<T> castProcedure)
{
for (int i = start; i < end; i++)
{
castProcedure.value(array[i]);
}
} } | public class class_name {
private static <T> void batchReject(T[] array, int start, int end, FastListRejectProcedure<T> castProcedure)
{
for (int i = start; i < end; i++)
{
castProcedure.value(array[i]); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
private void splitDays(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
{
LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
for (TimephasedWork assignment : list)
{
while (assignment != null)
{
Date startDay = DateHelper.getDayStartDate(assignment.getStart());
Date finishDay = DateHelper.getDayStartDate(assignment.getFinish());
// special case - when the finishday time is midnight, it's really the previous day...
if (assignment.getFinish().getTime() == finishDay.getTime())
{
finishDay = DateHelper.addDays(finishDay, -1);
}
if (startDay.getTime() == finishDay.getTime())
{
result.add(assignment);
break;
}
TimephasedWork[] split = splitFirstDay(calendar, assignment);
if (split[0] != null)
{
result.add(split[0]);
}
assignment = split[1];
}
}
list.clear();
list.addAll(result);
} } | public class class_name {
private void splitDays(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
{
LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
for (TimephasedWork assignment : list)
{
while (assignment != null)
{
Date startDay = DateHelper.getDayStartDate(assignment.getStart());
Date finishDay = DateHelper.getDayStartDate(assignment.getFinish());
// special case - when the finishday time is midnight, it's really the previous day...
if (assignment.getFinish().getTime() == finishDay.getTime())
{
finishDay = DateHelper.addDays(finishDay, -1); // depends on control dependency: [if], data = [none]
}
if (startDay.getTime() == finishDay.getTime())
{
result.add(assignment); // depends on control dependency: [if], data = [none]
break;
}
TimephasedWork[] split = splitFirstDay(calendar, assignment);
if (split[0] != null)
{
result.add(split[0]); // depends on control dependency: [if], data = [(split[0]]
}
assignment = split[1]; // depends on control dependency: [while], data = [none]
}
}
list.clear();
list.addAll(result);
} } |
public class class_name {
synchronized void addInterestedByClass(Class<?> clazz, Collection<ProbeListener> newListeners) {
Set<ProbeListener> currentListeners = listenersByClass.get(clazz);
if (currentListeners == null) {
currentListeners = new HashSet<ProbeListener>();
listenersByClass.put(clazz, currentListeners);
}
currentListeners.addAll(newListeners);
} } | public class class_name {
synchronized void addInterestedByClass(Class<?> clazz, Collection<ProbeListener> newListeners) {
Set<ProbeListener> currentListeners = listenersByClass.get(clazz);
if (currentListeners == null) {
currentListeners = new HashSet<ProbeListener>(); // depends on control dependency: [if], data = [none]
listenersByClass.put(clazz, currentListeners); // depends on control dependency: [if], data = [none]
}
currentListeners.addAll(newListeners);
} } |
public class class_name {
@Override
public boolean collide(final Collidable collidable, final Collidable collidable2) {
// check if bounding boxes intersect
if (!RECTANGLE_COLLISION_CHECKER.collide(collidable, collidable2)) {
return false;
}
final Point position = collidable.getPosition();
final Point position2 = collidable2.getPosition();
final CollisionRaster collisionRaster = collidable.getCollisionRaster();
final CollisionRaster collisionRaster2 = collidable2.getCollisionRaster();
// get the overlapping box
final int startX = Math.max(position.x, position2.x);
final int endX = Math.min(position.x + collidable.getDimension().width,
position2.x + collidable2.getDimension().width);
final int startY = Math.max(position.y, position2.y);
final int endY = Math.min(position.y + collidable.getDimension().height,
position2.y + collidable2.getDimension().height);
final int endX1 = endX - position.x;
final int endX2 = endX - position2.x;
final int stop1 = position.x + -1;
final int stop2 = position2.x + -1;
// this is the fast path of finding collisions: we expect the none transparent
// pixel to be around the center, using padding will increase this effect.
final int stepSize = ((endY - startY) / 3) + 1;
for (int i = stepSize - 1; i >= 0; i--) {
for (int y = startY + i; y < endY; y += stepSize) {
final int yOfPosition = y - position.y;
int absolute1 = position.x + collisionRaster.nextNotTransparentPixel(
startX - position.x, endX1, yOfPosition
);
if (absolute1 == stop1) {
continue;
}
final int yOfPosition2 = y - position2.y;
int absolute2 = position2.x + collisionRaster2.nextNotTransparentPixel(
startX - position2.x, endX2, yOfPosition2
);
if (absolute2 == stop2) {
continue;
}
while (true) {
if (absolute1 > absolute2) {
absolute2 = position2.x + collisionRaster2.nextNotTransparentPixel(
absolute1 - position2.x, endX2, yOfPosition2
);
if (absolute2 == stop2) {
break;
}
} else if (absolute1 < absolute2) {
absolute1 = position.x + collisionRaster.nextNotTransparentPixel(
absolute2 - position.x, endX1, yOfPosition
);
if (absolute1 == stop1) {
break;
}
} else {
return true;
}
}
}
}
return false;
} } | public class class_name {
@Override
public boolean collide(final Collidable collidable, final Collidable collidable2) {
// check if bounding boxes intersect
if (!RECTANGLE_COLLISION_CHECKER.collide(collidable, collidable2)) {
return false; // depends on control dependency: [if], data = [none]
}
final Point position = collidable.getPosition();
final Point position2 = collidable2.getPosition();
final CollisionRaster collisionRaster = collidable.getCollisionRaster();
final CollisionRaster collisionRaster2 = collidable2.getCollisionRaster();
// get the overlapping box
final int startX = Math.max(position.x, position2.x);
final int endX = Math.min(position.x + collidable.getDimension().width,
position2.x + collidable2.getDimension().width);
final int startY = Math.max(position.y, position2.y);
final int endY = Math.min(position.y + collidable.getDimension().height,
position2.y + collidable2.getDimension().height);
final int endX1 = endX - position.x;
final int endX2 = endX - position2.x;
final int stop1 = position.x + -1;
final int stop2 = position2.x + -1;
// this is the fast path of finding collisions: we expect the none transparent
// pixel to be around the center, using padding will increase this effect.
final int stepSize = ((endY - startY) / 3) + 1;
for (int i = stepSize - 1; i >= 0; i--) {
for (int y = startY + i; y < endY; y += stepSize) {
final int yOfPosition = y - position.y;
int absolute1 = position.x + collisionRaster.nextNotTransparentPixel(
startX - position.x, endX1, yOfPosition
);
if (absolute1 == stop1) {
continue;
}
final int yOfPosition2 = y - position2.y;
int absolute2 = position2.x + collisionRaster2.nextNotTransparentPixel(
startX - position2.x, endX2, yOfPosition2
);
if (absolute2 == stop2) {
continue;
}
while (true) {
if (absolute1 > absolute2) {
absolute2 = position2.x + collisionRaster2.nextNotTransparentPixel(
absolute1 - position2.x, endX2, yOfPosition2
); // depends on control dependency: [if], data = [none]
if (absolute2 == stop2) {
break;
}
} else if (absolute1 < absolute2) {
absolute1 = position.x + collisionRaster.nextNotTransparentPixel(
absolute2 - position.x, endX1, yOfPosition
); // depends on control dependency: [if], data = [none]
if (absolute1 == stop1) {
break;
}
} else {
return true; // depends on control dependency: [if], data = [none]
}
}
}
}
return false;
} } |
public class class_name {
@Override
public void queueDeployed(LocalQueue queue)
{
try
{
if (jmxAgent != null)
jmxAgent.register(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=queues,name="+queue.getName()), queue);
}
catch (Exception e)
{
log.error("Cannot register local queue on JMX agent",e);
}
} } | public class class_name {
@Override
public void queueDeployed(LocalQueue queue)
{
try
{
if (jmxAgent != null)
jmxAgent.register(new ObjectName(JMXAgent.JMX_DOMAIN+":type=Engines,engine="+engine.getName()+",children=queues,name="+queue.getName()), queue);
}
catch (Exception e)
{
log.error("Cannot register local queue on JMX agent",e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
void checkComplete() {
if ((groupId != null && artifactId != null && version != null) || releaseId != null) {
return;
} else if (releaseId == null) {
if (groupId == null) {
throw new IllegalStateException("No groupId has been set yet.");
} else if (artifactId == null) {
throw new IllegalStateException("No artifactId has been set yet.");
} else if (version == null) {
throw new IllegalStateException("No version has been set yet.");
} else if (groupId.equals(artifactId) && artifactId.equals(version) && version == null) {
throw new IllegalStateException("None of groupId, artifactId, version or releaseId have been set.");
}
}
} } | public class class_name {
void checkComplete() {
if ((groupId != null && artifactId != null && version != null) || releaseId != null) {
return; // depends on control dependency: [if], data = [none]
} else if (releaseId == null) {
if (groupId == null) {
throw new IllegalStateException("No groupId has been set yet.");
} else if (artifactId == null) {
throw new IllegalStateException("No artifactId has been set yet.");
} else if (version == null) {
throw new IllegalStateException("No version has been set yet.");
} else if (groupId.equals(artifactId) && artifactId.equals(version) && version == null) {
throw new IllegalStateException("None of groupId, artifactId, version or releaseId have been set.");
}
}
} } |
public class class_name {
private void drawPoint(BufferedImage image) {
if (this.pointPower == -1) {
return;
}
Random r = new Random();
Graphics2D g2 = (Graphics2D) image.getGraphics();
int max = this.w * this.h / this.pointPower;
for (int i = 0; i < max; i++) {
int x = r.nextInt(w);
int y = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(this.randomColor());
g2.drawOval(x, y, 1, 1);
}
g2.dispose();
} } | public class class_name {
private void drawPoint(BufferedImage image) {
if (this.pointPower == -1) {
return; // depends on control dependency: [if], data = [none]
}
Random r = new Random();
Graphics2D g2 = (Graphics2D) image.getGraphics();
int max = this.w * this.h / this.pointPower;
for (int i = 0; i < max; i++) {
int x = r.nextInt(w);
int y = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F)); // depends on control dependency: [for], data = [none]
g2.setColor(this.randomColor()); // depends on control dependency: [for], data = [none]
g2.drawOval(x, y, 1, 1); // depends on control dependency: [for], data = [none]
}
g2.dispose();
} } |
public class class_name {
public List<GroupedDiagnositcs> getGroupedErrors() {
List<GroupedDiagnositcs> grouped = new ArrayList<>();
Diagnostic previousError = null;
GroupedDiagnositcs group = null;
for (Diagnostic theError : getErrors()) {
boolean isNewField = ((previousError == null) || (previousError.getContext() != theError.
getContext())
|| (previousError.getComponent() != theError.getComponent()));
if (group == null || isNewField) {
group = new GroupedDiagnositcs();
grouped.add(group);
}
group.addDiagnostic(theError);
previousError = theError;
}
return Collections.unmodifiableList(grouped);
} } | public class class_name {
public List<GroupedDiagnositcs> getGroupedErrors() {
List<GroupedDiagnositcs> grouped = new ArrayList<>();
Diagnostic previousError = null;
GroupedDiagnositcs group = null;
for (Diagnostic theError : getErrors()) {
boolean isNewField = ((previousError == null) || (previousError.getContext() != theError.
getContext())
|| (previousError.getComponent() != theError.getComponent()));
if (group == null || isNewField) {
group = new GroupedDiagnositcs(); // depends on control dependency: [if], data = [none]
grouped.add(group); // depends on control dependency: [if], data = [(group]
}
group.addDiagnostic(theError); // depends on control dependency: [for], data = [theError]
previousError = theError; // depends on control dependency: [for], data = [theError]
}
return Collections.unmodifiableList(grouped);
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.