code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private File getFileFromConfigDirectory(String file, File def) {
File f = new File(configDirectory, file);
if (configDirectory != null && f.exists()) {
return f;
}
if (def != null && def.exists()) {
return def;
}
return null;
} } | public class class_name {
private File getFileFromConfigDirectory(String file, File def) {
File f = new File(configDirectory, file);
if (configDirectory != null && f.exists()) {
return f; // depends on control dependency: [if], data = [none]
}
if (def != null && def.exists()) {
return def; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static String chomp(final String str) {
if (N.isNullOrEmpty(str)) {
return str;
}
if (str.length() == 1) {
final char ch = str.charAt(0);
if (ch == N.CHAR_CR || ch == N.CHAR_LF) {
return N.EMPTY_STRING;
}
return str;
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == N.CHAR_LF) {
if (str.charAt(lastIdx - 1) == N.CHAR_CR) {
lastIdx--;
}
} else if (last != N.CHAR_CR) {
lastIdx++;
}
return lastIdx == str.length() ? str : str.substring(0, lastIdx);
} } | public class class_name {
public static String chomp(final String str) {
if (N.isNullOrEmpty(str)) {
return str;
// depends on control dependency: [if], data = [none]
}
if (str.length() == 1) {
final char ch = str.charAt(0);
if (ch == N.CHAR_CR || ch == N.CHAR_LF) {
return N.EMPTY_STRING;
// depends on control dependency: [if], data = [none]
}
return str;
// depends on control dependency: [if], data = [none]
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == N.CHAR_LF) {
if (str.charAt(lastIdx - 1) == N.CHAR_CR) {
lastIdx--;
// depends on control dependency: [if], data = [none]
}
} else if (last != N.CHAR_CR) {
lastIdx++;
// depends on control dependency: [if], data = [none]
}
return lastIdx == str.length() ? str : str.substring(0, lastIdx);
} } |
public class class_name {
public String getMarshaledName() {
String serializedName = getSerializedName();
if (!serializedName.isEmpty()) {
return serializedName;
}
return names.raw;
} } | public class class_name {
public String getMarshaledName() {
String serializedName = getSerializedName();
if (!serializedName.isEmpty()) {
return serializedName; // depends on control dependency: [if], data = [none]
}
return names.raw;
} } |
public class class_name {
public void applyTo(final PeekViewActivity activity, final View base) {
final GestureDetectorCompat detector =
new GestureDetectorCompat(activity, new GestureListener(activity, base, this));
base.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, final MotionEvent motionEvent) {
// we use the detector for the long and short click motion events
detector.onTouchEvent(motionEvent);
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
forceRippleAnimation(base, motionEvent);
}
return true;
}
});
} } | public class class_name {
public void applyTo(final PeekViewActivity activity, final View base) {
final GestureDetectorCompat detector =
new GestureDetectorCompat(activity, new GestureListener(activity, base, this));
base.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, final MotionEvent motionEvent) {
// we use the detector for the long and short click motion events
detector.onTouchEvent(motionEvent);
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
forceRippleAnimation(base, motionEvent); // depends on control dependency: [if], data = [none]
}
return true;
}
});
} } |
public class class_name {
public static String getElasticSearchAddDocument(Map<String, String> values) {
StringBuilder builder = new StringBuilder();
builder.append("{");
boolean first = true;
for (Map.Entry<String, String> pair : values.entrySet()) {
if (!first) {
builder.append(",");
}
JSONUtils.addElasticSearchField(builder, pair);
first = false;
}
builder.append("}");
return builder.toString();
} } | public class class_name {
public static String getElasticSearchAddDocument(Map<String, String> values) {
StringBuilder builder = new StringBuilder();
builder.append("{");
boolean first = true;
for (Map.Entry<String, String> pair : values.entrySet()) {
if (!first) {
builder.append(","); // depends on control dependency: [if], data = [none]
}
JSONUtils.addElasticSearchField(builder, pair); // depends on control dependency: [for], data = [pair]
first = false; // depends on control dependency: [for], data = [none]
}
builder.append("}");
return builder.toString();
} } |
public class class_name {
public final void synpred172_Java_fragment() throws RecognitionException {
Token y=null;
ParserRuleReturnScope z =null;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: (y= 'else' ( 'if' parExpression )? z= statement )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: y= 'else' ( 'if' parExpression )? z= statement
{
y=(Token)match(input,78,FOLLOW_78_in_synpred172_Java3290); if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:16: ( 'if' parExpression )?
int alt215=2;
int LA215_0 = input.LA(1);
if ( (LA215_0==87) ) {
int LA215_1 = input.LA(2);
if ( (LA215_1==36) ) {
int LA215_43 = input.LA(3);
if ( (synpred171_Java()) ) {
alt215=1;
}
}
}
switch (alt215) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:17: 'if' parExpression
{
match(input,87,FOLLOW_87_in_synpred172_Java3294); if (state.failed) return;
pushFollow(FOLLOW_parExpression_in_synpred172_Java3296);
parExpression();
state._fsp--;
if (state.failed) return;
}
break;
}
pushFollow(FOLLOW_statement_in_synpred172_Java3327);
z=statement();
state._fsp--;
if (state.failed) return;
}
} } | public class class_name {
public final void synpred172_Java_fragment() throws RecognitionException {
Token y=null;
ParserRuleReturnScope z =null;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: (y= 'else' ( 'if' parExpression )? z= statement )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:6: y= 'else' ( 'if' parExpression )? z= statement
{
y=(Token)match(input,78,FOLLOW_78_in_synpred172_Java3290); if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:16: ( 'if' parExpression )?
int alt215=2;
int LA215_0 = input.LA(1);
if ( (LA215_0==87) ) {
int LA215_1 = input.LA(2);
if ( (LA215_1==36) ) {
int LA215_43 = input.LA(3);
if ( (synpred171_Java()) ) {
alt215=1; // depends on control dependency: [if], data = [none]
}
}
}
switch (alt215) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:787:17: 'if' parExpression
{
match(input,87,FOLLOW_87_in_synpred172_Java3294); if (state.failed) return;
pushFollow(FOLLOW_parExpression_in_synpred172_Java3296);
parExpression();
state._fsp--;
if (state.failed) return;
}
break;
}
pushFollow(FOLLOW_statement_in_synpred172_Java3327);
z=statement();
state._fsp--;
if (state.failed) return;
}
} } |
public class class_name {
private HashMap<String, String> getMapFromJson(String customJson) {
HashMap<String, String> command = new HashMap<>();
if (customJson != null) {
try {
JSONObject jsonObject = new JSONObject(customJson);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
command.put(key, value);
}
return command;
} catch (JSONException exception) {
return null;
}
} else
return null;
} } | public class class_name {
private HashMap<String, String> getMapFromJson(String customJson) {
HashMap<String, String> command = new HashMap<>();
if (customJson != null) {
try {
JSONObject jsonObject = new JSONObject(customJson);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
command.put(key, value); // depends on control dependency: [while], data = [none]
}
return command; // depends on control dependency: [try], data = [none]
} catch (JSONException exception) {
return null;
} // depends on control dependency: [catch], data = [none]
} else
return null;
} } |
public class class_name {
protected void checkDOMVersion(Hashtable h)
{
if (null == h)
h = new Hashtable();
final String DOM_LEVEL2_CLASS = "org.w3c.dom.Document";
final String DOM_LEVEL2_METHOD = "createElementNS"; // String, String
final String DOM_LEVEL2WD_CLASS = "org.w3c.dom.Node";
final String DOM_LEVEL2WD_METHOD = "supported"; // String, String
final String DOM_LEVEL2FD_CLASS = "org.w3c.dom.Node";
final String DOM_LEVEL2FD_METHOD = "isSupported"; // String, String
final Class twoStringArgs[] = { java.lang.String.class,
java.lang.String.class };
try
{
Class clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2_CLASS, ObjectFactory.findClassLoader(), true);
Method method = clazz.getMethod(DOM_LEVEL2_METHOD, twoStringArgs);
// If we succeeded, we have loaded interfaces from a
// level 2 DOM somewhere
h.put(VERSION + "DOM", "2.0");
try
{
// Check for the working draft version, which is
// commonly found, but won't work anymore
clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2WD_CLASS, ObjectFactory.findClassLoader(), true);
method = clazz.getMethod(DOM_LEVEL2WD_METHOD, twoStringArgs);
h.put(ERROR + VERSION + "DOM.draftlevel", "2.0wd");
h.put(ERROR, ERROR_FOUND);
}
catch (Exception e2)
{
try
{
// Check for the final draft version as well
clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2FD_CLASS, ObjectFactory.findClassLoader(), true);
method = clazz.getMethod(DOM_LEVEL2FD_METHOD, twoStringArgs);
h.put(VERSION + "DOM.draftlevel", "2.0fd");
}
catch (Exception e3)
{
h.put(ERROR + VERSION + "DOM.draftlevel", "2.0unknown");
h.put(ERROR, ERROR_FOUND);
}
}
}
catch (Exception e)
{
h.put(ERROR + VERSION + "DOM",
"ERROR attempting to load DOM level 2 class: " + e.toString());
h.put(ERROR, ERROR_FOUND);
}
//@todo load an actual DOM implmementation and query it as well
//@todo load an actual DOM implmementation and check if
// isNamespaceAware() == true, which is needed to parse
// xsl stylesheet files into a DOM
} } | public class class_name {
protected void checkDOMVersion(Hashtable h)
{
if (null == h)
h = new Hashtable();
final String DOM_LEVEL2_CLASS = "org.w3c.dom.Document";
final String DOM_LEVEL2_METHOD = "createElementNS"; // String, String
final String DOM_LEVEL2WD_CLASS = "org.w3c.dom.Node";
final String DOM_LEVEL2WD_METHOD = "supported"; // String, String
final String DOM_LEVEL2FD_CLASS = "org.w3c.dom.Node";
final String DOM_LEVEL2FD_METHOD = "isSupported"; // String, String
final Class twoStringArgs[] = { java.lang.String.class,
java.lang.String.class };
try
{
Class clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2_CLASS, ObjectFactory.findClassLoader(), true);
Method method = clazz.getMethod(DOM_LEVEL2_METHOD, twoStringArgs);
// If we succeeded, we have loaded interfaces from a
// level 2 DOM somewhere
h.put(VERSION + "DOM", "2.0");
try
{
// Check for the working draft version, which is
// commonly found, but won't work anymore
clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2WD_CLASS, ObjectFactory.findClassLoader(), true);
method = clazz.getMethod(DOM_LEVEL2WD_METHOD, twoStringArgs);
h.put(ERROR + VERSION + "DOM.draftlevel", "2.0wd");
h.put(ERROR, ERROR_FOUND);
}
catch (Exception e2)
{
try
{
// Check for the final draft version as well
clazz = ObjectFactory.findProviderClass(
DOM_LEVEL2FD_CLASS, ObjectFactory.findClassLoader(), true); // depends on control dependency: [try], data = [none]
method = clazz.getMethod(DOM_LEVEL2FD_METHOD, twoStringArgs); // depends on control dependency: [try], data = [none]
h.put(VERSION + "DOM.draftlevel", "2.0fd"); // depends on control dependency: [try], data = [none]
}
catch (Exception e3)
{
h.put(ERROR + VERSION + "DOM.draftlevel", "2.0unknown");
h.put(ERROR, ERROR_FOUND);
} // depends on control dependency: [catch], data = [none]
}
}
catch (Exception e)
{
h.put(ERROR + VERSION + "DOM",
"ERROR attempting to load DOM level 2 class: " + e.toString());
h.put(ERROR, ERROR_FOUND);
}
//@todo load an actual DOM implmementation and query it as well
//@todo load an actual DOM implmementation and check if
// isNamespaceAware() == true, which is needed to parse
// xsl stylesheet files into a DOM
} } |
public class class_name {
public void setupSubMenus(String strMenu)
{
Record recMenu = this.getMainRecord();
try {
String strCommandNoCommas = Utility.replace(strMenu, ",", null); // Get any commas out
boolean bIsNumeric = Utility.isNumeric(strCommandNoCommas);
if (bIsNumeric)
{
recMenu.setKeyArea(Menus.ID_KEY);
recMenu.getField(Menus.ID).setString(strCommandNoCommas);
bIsNumeric = recMenu.seek("=");
}
if (!bIsNumeric)
{
recMenu.setKeyArea(Menus.CODE_KEY);
recMenu.getField(Menus.CODE).setString(strMenu);
if (!recMenu.seek("="))
{ // Not found, try the default main menu
recMenu.getField(Menus.CODE).setString(HtmlConstants.MAIN_MENU_KEY);
recMenu.seek("=");
}
}
} catch (DBException ex) {
ex.printStackTrace(); // Never
}
String strParentID = recMenu.getField(Menus.ID).toString();
BaseListener listener = recMenu.getListener(StringSubFileFilter.class.getName());
if (listener != null)
{ // Should just change the string
recMenu.removeListener(listener, true);
}
recMenu.setKeyArea(Menus.PARENT_FOLDER_ID_KEY);
recMenu.addListener(new StringSubFileFilter(strParentID, recMenu.getField(Menus.PARENT_FOLDER_ID), null, null, null, null));
} } | public class class_name {
public void setupSubMenus(String strMenu)
{
Record recMenu = this.getMainRecord();
try {
String strCommandNoCommas = Utility.replace(strMenu, ",", null); // Get any commas out
boolean bIsNumeric = Utility.isNumeric(strCommandNoCommas);
if (bIsNumeric)
{
recMenu.setKeyArea(Menus.ID_KEY); // depends on control dependency: [if], data = [none]
recMenu.getField(Menus.ID).setString(strCommandNoCommas); // depends on control dependency: [if], data = [none]
bIsNumeric = recMenu.seek("="); // depends on control dependency: [if], data = [none]
}
if (!bIsNumeric)
{
recMenu.setKeyArea(Menus.CODE_KEY); // depends on control dependency: [if], data = [none]
recMenu.getField(Menus.CODE).setString(strMenu); // depends on control dependency: [if], data = [none]
if (!recMenu.seek("="))
{ // Not found, try the default main menu
recMenu.getField(Menus.CODE).setString(HtmlConstants.MAIN_MENU_KEY); // depends on control dependency: [if], data = [none]
recMenu.seek("="); // depends on control dependency: [if], data = [none]
}
}
} catch (DBException ex) {
ex.printStackTrace(); // Never
} // depends on control dependency: [catch], data = [none]
String strParentID = recMenu.getField(Menus.ID).toString();
BaseListener listener = recMenu.getListener(StringSubFileFilter.class.getName());
if (listener != null)
{ // Should just change the string
recMenu.removeListener(listener, true); // depends on control dependency: [if], data = [(listener]
}
recMenu.setKeyArea(Menus.PARENT_FOLDER_ID_KEY);
recMenu.addListener(new StringSubFileFilter(strParentID, recMenu.getField(Menus.PARENT_FOLDER_ID), null, null, null, null));
} } |
public class class_name {
private void readTableBlock(int startIndex, int blockLength)
{
for (int index = startIndex; index < (startIndex + blockLength - 11); index++)
{
if (matchPattern(TABLE_BLOCK_PATTERNS, index))
{
int offset = index + 7;
int nameLength = FastTrackUtility.getInt(m_buffer, offset);
offset += 4;
String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();
FastTrackTableType type = REQUIRED_TABLES.get(name);
if (type != null)
{
m_currentTable = new FastTrackTable(type, this);
m_tables.put(type, m_currentTable);
}
else
{
m_currentTable = null;
}
m_currentFields.clear();
break;
}
}
} } | public class class_name {
private void readTableBlock(int startIndex, int blockLength)
{
for (int index = startIndex; index < (startIndex + blockLength - 11); index++)
{
if (matchPattern(TABLE_BLOCK_PATTERNS, index))
{
int offset = index + 7;
int nameLength = FastTrackUtility.getInt(m_buffer, offset);
offset += 4; // depends on control dependency: [if], data = [none]
String name = new String(m_buffer, offset, nameLength, CharsetHelper.UTF16LE).toUpperCase();
FastTrackTableType type = REQUIRED_TABLES.get(name);
if (type != null)
{
m_currentTable = new FastTrackTable(type, this); // depends on control dependency: [if], data = [(type]
m_tables.put(type, m_currentTable); // depends on control dependency: [if], data = [(type]
}
else
{
m_currentTable = null; // depends on control dependency: [if], data = [none]
}
m_currentFields.clear(); // depends on control dependency: [if], data = [none]
break;
}
}
} } |
public class class_name {
@Override
public RandomVariable[] getFactorLoading(double time, int component, RandomVariable[] realizationAtTimeIndex) {
int timeIndex = timeDiscretization.getTimeIndex(time);
if(timeIndex < 0) {
timeIndex = -timeIndex - 2;
}
return getFactorLoading(timeIndex, component, realizationAtTimeIndex);
} } | public class class_name {
@Override
public RandomVariable[] getFactorLoading(double time, int component, RandomVariable[] realizationAtTimeIndex) {
int timeIndex = timeDiscretization.getTimeIndex(time);
if(timeIndex < 0) {
timeIndex = -timeIndex - 2; // depends on control dependency: [if], data = [none]
}
return getFactorLoading(timeIndex, component, realizationAtTimeIndex);
} } |
public class class_name {
@Override
public HttpResponse execute(InvocationContext context, HttpRequestBase request) {
HttpResponse response = null;
try {
response = fetchResponse(context, request);
}
catch(RequestExecutionException ree) {
executionHandler.onError(context, ree);
}
if(response != null) {
if(successful(response)) {
executionHandler.onSuccess(context, response);
}
else {
executionHandler.onFailure(context, response);
}
}
return response;
} } | public class class_name {
@Override
public HttpResponse execute(InvocationContext context, HttpRequestBase request) {
HttpResponse response = null;
try {
response = fetchResponse(context, request); // depends on control dependency: [try], data = [none]
}
catch(RequestExecutionException ree) {
executionHandler.onError(context, ree);
} // depends on control dependency: [catch], data = [none]
if(response != null) {
if(successful(response)) {
executionHandler.onSuccess(context, response); // depends on control dependency: [if], data = [none]
}
else {
executionHandler.onFailure(context, response); // depends on control dependency: [if], data = [none]
}
}
return response;
} } |
public class class_name {
public Set<String> getDetailPageTypes() {
if (m_detailPageTypes != null) {
return m_detailPageTypes;
}
Set<String> result = new HashSet<String>();
for (CmsADEConfigDataInternal configData : m_siteConfigurationsByPath.values()) {
List<CmsDetailPageInfo> detailPageInfos = configData.getOwnDetailPages();
for (CmsDetailPageInfo info : detailPageInfos) {
result.add(info.getType());
}
}
m_detailPageTypes = result;
return result;
} } | public class class_name {
public Set<String> getDetailPageTypes() {
if (m_detailPageTypes != null) {
return m_detailPageTypes; // depends on control dependency: [if], data = [none]
}
Set<String> result = new HashSet<String>();
for (CmsADEConfigDataInternal configData : m_siteConfigurationsByPath.values()) {
List<CmsDetailPageInfo> detailPageInfos = configData.getOwnDetailPages();
for (CmsDetailPageInfo info : detailPageInfos) {
result.add(info.getType()); // depends on control dependency: [for], data = [info]
}
}
m_detailPageTypes = result;
return result;
} } |
public class class_name {
final public void BracketSuffix() throws ParseException {
/*@bgen(jjtree) BracketSuffix */
AstBracketSuffix jjtn000 = new AstBracketSuffix(JJTBRACKETSUFFIX);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
jj_consume_token(LBRACK);
Expression();
jj_consume_token(RBRACK);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
} } | public class class_name {
final public void BracketSuffix() throws ParseException {
/*@bgen(jjtree) BracketSuffix */
AstBracketSuffix jjtn000 = new AstBracketSuffix(JJTBRACKETSUFFIX);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
jj_consume_token(LBRACK);
Expression();
jj_consume_token(RBRACK);
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000); // depends on control dependency: [if], data = [none]
jjtc000 = false; // depends on control dependency: [if], data = [none]
} else {
jjtree.popNode(); // depends on control dependency: [if], data = [none]
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(ContainerDefinition containerDefinition, ProtocolMarshaller protocolMarshaller) {
if (containerDefinition == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerDefinition.getContainerHostname(), CONTAINERHOSTNAME_BINDING);
protocolMarshaller.marshall(containerDefinition.getImage(), IMAGE_BINDING);
protocolMarshaller.marshall(containerDefinition.getModelDataUrl(), MODELDATAURL_BINDING);
protocolMarshaller.marshall(containerDefinition.getEnvironment(), ENVIRONMENT_BINDING);
protocolMarshaller.marshall(containerDefinition.getModelPackageName(), MODELPACKAGENAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ContainerDefinition containerDefinition, ProtocolMarshaller protocolMarshaller) {
if (containerDefinition == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerDefinition.getContainerHostname(), CONTAINERHOSTNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerDefinition.getImage(), IMAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerDefinition.getModelDataUrl(), MODELDATAURL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerDefinition.getEnvironment(), ENVIRONMENT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(containerDefinition.getModelPackageName(), MODELPACKAGENAME_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 float rNonsep(float[] y, int A) {
float tmp, denominator, numerator;
tmp = (float) Math.ceil(A / (float) 2.0);
denominator = y.length * tmp * ((float) 1.0 + (float) 2.0 * A - (float) 2.0 * tmp) / A;
numerator = (float) 0.0;
for (int j = 0; j < y.length; j++) {
numerator += y[j];
for (int k = 0; k <= A - 2; k++) {
numerator += Math.abs(y[j] - y[(j + k + 1) % y.length]);
}
}
return correctTo01(numerator / denominator);
} } | public class class_name {
public float rNonsep(float[] y, int A) {
float tmp, denominator, numerator;
tmp = (float) Math.ceil(A / (float) 2.0);
denominator = y.length * tmp * ((float) 1.0 + (float) 2.0 * A - (float) 2.0 * tmp) / A;
numerator = (float) 0.0;
for (int j = 0; j < y.length; j++) {
numerator += y[j];
// depends on control dependency: [for], data = [j]
for (int k = 0; k <= A - 2; k++) {
numerator += Math.abs(y[j] - y[(j + k + 1) % y.length]);
// depends on control dependency: [for], data = [k]
}
}
return correctTo01(numerator / denominator);
} } |
public class class_name {
public static void addPropertyBoolean(
CmsCmisTypeManager typeManager,
PropertiesImpl props,
String typeId,
Set<String> filter,
String id,
boolean value) {
if (!checkAddProperty(typeManager, props, typeId, filter, id)) {
return;
}
props.addProperty(new PropertyBooleanImpl(id, Boolean.valueOf(value)));
} } | public class class_name {
public static void addPropertyBoolean(
CmsCmisTypeManager typeManager,
PropertiesImpl props,
String typeId,
Set<String> filter,
String id,
boolean value) {
if (!checkAddProperty(typeManager, props, typeId, filter, id)) {
return;
// depends on control dependency: [if], data = [none]
}
props.addProperty(new PropertyBooleanImpl(id, Boolean.valueOf(value)));
} } |
public class class_name {
public final void tryMakeWhereEnum(final StringBuffer pSbWhere,
final IRequestData pRequestData, final Class<?> pEntityClass,
final String pFldNm,
final Map<String, Object> pFilterMap,
final Set<String> pFilterAppearance) throws Exception {
String nmRnd = pRequestData.getParameter("nmRnd");
String fltOrdPrefix;
if (nmRnd.contains("pickerDub")) {
fltOrdPrefix = "fltordPD";
} else if (nmRnd.contains("picker")) {
fltOrdPrefix = "fltordP";
} else {
fltOrdPrefix = "fltordM";
}
String fltforcedName = fltOrdPrefix + "forcedFor";
String fltforced = pRequestData.getParameter(fltforcedName);
if (fltforced != null) {
pFilterMap.put(fltforcedName, fltforced);
}
String nmFldVal = fltOrdPrefix + pFldNm + "Val";
String fltVal = pRequestData.getParameter(nmFldVal);
String nmFldOpr = fltOrdPrefix + pFldNm + "Opr";
String valFldOpr = pRequestData.getParameter(nmFldOpr);
if (fltVal != null && fltVal.length() > 0 && valFldOpr != null
&& !valFldOpr.equals("disabled") && !valFldOpr.equals("")) {
String val;
String valAppear;
Field fldEnum = this.fieldsRapiHolder.getFor(pEntityClass, pFldNm);
Class classEnum = fldEnum.getType();
if (valFldOpr.equals("in")) {
StringBuffer sbVal = new StringBuffer("(");
StringBuffer sbValAppear = new StringBuffer("(");
boolean isFirst = true;
for (String vl : fltVal.split(",")) {
if (isFirst) {
isFirst = false;
} else {
sbVal.append(", ");
sbValAppear.append(", ");
}
Enum enVal = Enum.valueOf(classEnum, vl);
sbVal.append(String.valueOf(enVal.ordinal()));
sbValAppear.append(getSrvI18n().getMsg(vl));
}
val = sbVal.toString() + ")";
valAppear = sbValAppear.toString() + ")";
} else {
Enum enVal = Enum.valueOf(classEnum, fltVal);
val = String.valueOf(enVal.ordinal());
valAppear = getSrvI18n().getMsg(fltVal);
}
pFilterMap.put(fltOrdPrefix + pFldNm + "ValAppearance", valAppear);
pFilterMap.put(nmFldVal, fltVal);
pFilterMap.put(nmFldOpr, valFldOpr);
String cond = pEntityClass.getSimpleName().toUpperCase()
+ "." + pFldNm.toUpperCase() + " "
+ toSqlOperator(valFldOpr)
+ " " + val;
if (pSbWhere.toString().length() == 0) {
pSbWhere.append(cond);
} else {
pSbWhere.append(" and " + cond);
}
if (pFilterAppearance != null) {
pFilterAppearance.add(getSrvI18n().getMsg(pFldNm) + " "
+ getSrvI18n().getMsg(valFldOpr) + " " + valAppear);
}
}
} } | public class class_name {
public final void tryMakeWhereEnum(final StringBuffer pSbWhere,
final IRequestData pRequestData, final Class<?> pEntityClass,
final String pFldNm,
final Map<String, Object> pFilterMap,
final Set<String> pFilterAppearance) throws Exception {
String nmRnd = pRequestData.getParameter("nmRnd");
String fltOrdPrefix;
if (nmRnd.contains("pickerDub")) {
fltOrdPrefix = "fltordPD";
} else if (nmRnd.contains("picker")) {
fltOrdPrefix = "fltordP";
} else {
fltOrdPrefix = "fltordM";
}
String fltforcedName = fltOrdPrefix + "forcedFor";
String fltforced = pRequestData.getParameter(fltforcedName);
if (fltforced != null) {
pFilterMap.put(fltforcedName, fltforced);
}
String nmFldVal = fltOrdPrefix + pFldNm + "Val";
String fltVal = pRequestData.getParameter(nmFldVal);
String nmFldOpr = fltOrdPrefix + pFldNm + "Opr";
String valFldOpr = pRequestData.getParameter(nmFldOpr);
if (fltVal != null && fltVal.length() > 0 && valFldOpr != null
&& !valFldOpr.equals("disabled") && !valFldOpr.equals("")) {
String val;
String valAppear;
Field fldEnum = this.fieldsRapiHolder.getFor(pEntityClass, pFldNm);
Class classEnum = fldEnum.getType();
if (valFldOpr.equals("in")) {
StringBuffer sbVal = new StringBuffer("(");
StringBuffer sbValAppear = new StringBuffer("(");
boolean isFirst = true;
for (String vl : fltVal.split(",")) {
if (isFirst) {
isFirst = false; // depends on control dependency: [if], data = [none]
} else {
sbVal.append(", "); // depends on control dependency: [if], data = [none]
sbValAppear.append(", "); // depends on control dependency: [if], data = [none]
}
Enum enVal = Enum.valueOf(classEnum, vl);
sbVal.append(String.valueOf(enVal.ordinal()));
sbValAppear.append(getSrvI18n().getMsg(vl));
}
val = sbVal.toString() + ")";
valAppear = sbValAppear.toString() + ")";
} else {
Enum enVal = Enum.valueOf(classEnum, fltVal);
val = String.valueOf(enVal.ordinal());
valAppear = getSrvI18n().getMsg(fltVal);
}
pFilterMap.put(fltOrdPrefix + pFldNm + "ValAppearance", valAppear);
pFilterMap.put(nmFldVal, fltVal);
pFilterMap.put(nmFldOpr, valFldOpr);
String cond = pEntityClass.getSimpleName().toUpperCase()
+ "." + pFldNm.toUpperCase() + " "
+ toSqlOperator(valFldOpr)
+ " " + val;
if (pSbWhere.toString().length() == 0) {
pSbWhere.append(cond);
} else {
pSbWhere.append(" and " + cond);
}
if (pFilterAppearance != null) {
pFilterAppearance.add(getSrvI18n().getMsg(pFldNm) + " "
+ getSrvI18n().getMsg(valFldOpr) + " " + valAppear);
}
}
} } |
public class class_name {
private void auditEventSafAuthDetails(Object[] methodParams) {
// Getting object array which have audit fields
Object[] varargs = (Object[]) methodParams[1];
// Get audit fields and convert them to respective type
int safReturnCode = (Integer) varargs[0];
int racfReturnCode = (Integer) varargs[1];
int racfReasonCode = (Integer) varargs[2];
String userSecurityName = (String) varargs[3];
String safProfile = (String) varargs[4];
String safClass = (String) varargs[5];
Boolean authDecision = (Boolean) varargs[6];
String principalName = (String) varargs[7];
String applid = (String) varargs[8];
if (auditServiceRef.getService() != null
&& auditServiceRef.getService().isAuditRequired(AuditConstants.SECURITY_SAF_AUTHZ_DETAILS,
AuditConstants.SUCCESS)) {
// Create audit event
SAFAuthorizationDetailsEvent safAuthDetails = new SAFAuthorizationDetailsEvent(safReturnCode,
racfReturnCode, racfReasonCode, userSecurityName, applid, safProfile, safClass, authDecision,
principalName);
auditServiceRef.getService().sendEvent(safAuthDetails);
}
} } | public class class_name {
private void auditEventSafAuthDetails(Object[] methodParams) {
// Getting object array which have audit fields
Object[] varargs = (Object[]) methodParams[1];
// Get audit fields and convert them to respective type
int safReturnCode = (Integer) varargs[0];
int racfReturnCode = (Integer) varargs[1];
int racfReasonCode = (Integer) varargs[2];
String userSecurityName = (String) varargs[3];
String safProfile = (String) varargs[4];
String safClass = (String) varargs[5];
Boolean authDecision = (Boolean) varargs[6];
String principalName = (String) varargs[7];
String applid = (String) varargs[8];
if (auditServiceRef.getService() != null
&& auditServiceRef.getService().isAuditRequired(AuditConstants.SECURITY_SAF_AUTHZ_DETAILS,
AuditConstants.SUCCESS)) {
// Create audit event
SAFAuthorizationDetailsEvent safAuthDetails = new SAFAuthorizationDetailsEvent(safReturnCode,
racfReturnCode, racfReasonCode, userSecurityName, applid, safProfile, safClass, authDecision,
principalName);
auditServiceRef.getService().sendEvent(safAuthDetails); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setMargin(@Nullable String marginString) {
if (!TextUtils.isEmpty(marginString)) {
// remove leading and ending '[' ']'
try {
marginString = marginString.trim().substring(1, marginString.length() - 1);
String marginStringArray[] = marginString.split(",");
int size = marginStringArray.length > 4 ? 4 : marginStringArray.length;
for (int i = 0; i < size; i++) {
String marginStr = marginStringArray[i];
if (!TextUtils.isEmpty(marginStr)) {
margin[i] = parseSize(marginStr.trim().replace("\"", ""), 0);
} else {
margin[i] = 0;
}
}
Arrays.fill(margin, size, margin.length, margin[size - 1]);
} catch (Exception e) {
Arrays.fill(margin, 0);
}
}
} } | public class class_name {
public void setMargin(@Nullable String marginString) {
if (!TextUtils.isEmpty(marginString)) {
// remove leading and ending '[' ']'
try {
marginString = marginString.trim().substring(1, marginString.length() - 1); // depends on control dependency: [try], data = [none]
String marginStringArray[] = marginString.split(",");
int size = marginStringArray.length > 4 ? 4 : marginStringArray.length;
for (int i = 0; i < size; i++) {
String marginStr = marginStringArray[i];
if (!TextUtils.isEmpty(marginStr)) {
margin[i] = parseSize(marginStr.trim().replace("\"", ""), 0); // depends on control dependency: [if], data = [none]
} else {
margin[i] = 0; // depends on control dependency: [if], data = [none]
}
}
Arrays.fill(margin, size, margin.length, margin[size - 1]); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
Arrays.fill(margin, 0);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void setBackgroundPaint(final Paint PAINT) {
if (null == backgroundPaint) {
_backgroundPaint = PAINT;
fireUpdateEvent(REDRAW_EVENT);
} else {
backgroundPaint.set(PAINT);
}
} } | public class class_name {
public void setBackgroundPaint(final Paint PAINT) {
if (null == backgroundPaint) {
_backgroundPaint = PAINT; // depends on control dependency: [if], data = [none]
fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
backgroundPaint.set(PAINT); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void registerColumnFamily(String columnFamilyName, ColumnFamilyHandle handle) {
MetricGroup group = metricGroup.addGroup(columnFamilyName);
for (String property : options.getProperties()) {
RocksDBNativeMetricView gauge = new RocksDBNativeMetricView(handle, property);
group.gauge(property, gauge);
}
} } | public class class_name {
void registerColumnFamily(String columnFamilyName, ColumnFamilyHandle handle) {
MetricGroup group = metricGroup.addGroup(columnFamilyName);
for (String property : options.getProperties()) {
RocksDBNativeMetricView gauge = new RocksDBNativeMetricView(handle, property);
group.gauge(property, gauge); // depends on control dependency: [for], data = [property]
}
} } |
public class class_name {
public <T> T asOrElse(Class<T> clazz, @NonNull Supplier<T> supplier) {
if (isNull()) {
return supplier.get();
}
T value = as(clazz);
if (value == null) {
return supplier.get();
}
return value;
} } | public class class_name {
public <T> T asOrElse(Class<T> clazz, @NonNull Supplier<T> supplier) {
if (isNull()) {
return supplier.get(); // depends on control dependency: [if], data = [none]
}
T value = as(clazz);
if (value == null) {
return supplier.get(); // depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels, boolean enableSch) {
if(context.skipUpdatingDpmProperties) {
return;
}
try {
FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
.configure(new Parameters().properties()
.setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties")
.setThrowExceptionOnMissing(true)
.setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
.setIncludesAllowed(false));
PropertiesConfiguration config = null;
config = builder.getConfiguration();
config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch));
config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL);
config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL);
if (labels != null && labels.size() > 0) {
config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ','));
} else {
config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, "");
}
builder.save();
} catch (ConfigurationException e) {
throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e);
}
} } | public class class_name {
private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels, boolean enableSch) {
if(context.skipUpdatingDpmProperties) {
return; // depends on control dependency: [if], data = [none]
}
try {
FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
.configure(new Parameters().properties()
.setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties")
.setThrowExceptionOnMissing(true)
.setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
.setIncludesAllowed(false));
PropertiesConfiguration config = null;
config = builder.getConfiguration(); // depends on control dependency: [try], data = [none]
config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch)); // depends on control dependency: [try], data = [none]
config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL); // depends on control dependency: [try], data = [none]
config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL); // depends on control dependency: [try], data = [none]
if (labels != null && labels.size() > 0) {
config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ',')); // depends on control dependency: [if], data = [(labels]
} else {
config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, ""); // depends on control dependency: [if], data = [none]
}
builder.save(); // depends on control dependency: [try], data = [none]
} catch (ConfigurationException e) {
throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Set getMembers() throws DAVException {
// Query the DAV:resource-type property to depth one.
Collection querySet = new Vector();
querySet.add(DAV_RESOURCE_TYPE);
URLTable resourceTable = getProperties(querySet, IContext.DEPTH_ONE);
// Create a collection for the reply, and remove
// ourselves from the answer.
Set reply = new HashSet();
try {
resourceTable.remove(locator.getResourceURL());
} catch (MalformedURLException exception) {
throw new DAVException(Policy.bind("exception.malformedLocator")); //$NON-NLS-1$
}
// The keys of the result correspond to the receiver's internal members.
Enumeration resourceNameEnum = resourceTable.keys();
while (resourceNameEnum.hasMoreElements()) {
URL url = (URL) resourceNameEnum.nextElement();
// Get the props for that resource
Hashtable propertyTable = (Hashtable) resourceTable.get(url);
Assert.isNotNull(propertyTable);
PropertyStatus propertyStatus = (PropertyStatus) propertyTable.get(DAV_RESOURCE_TYPE);
Assert.isNotNull(propertyStatus);
// If we have a DAV:collection element, then create a collection handle,
// all other resource types are created as regular resource handles.
ILocator newLocator = davClient.getDAVFactory().newLocator(url.toString());
Element property = propertyStatus.getProperty();
try {
if (ElementEditor.hasChild(property, DAV_COLLECTION_RESOURCE_TYPE))
reply.add(new CollectionHandle(davClient, newLocator));
else
reply.add(new ResourceHandle(davClient, newLocator));
} catch (MalformedElementException exception) {
throw new SystemException(exception);
}
} // end-while
return reply;
} } | public class class_name {
public Set getMembers() throws DAVException {
// Query the DAV:resource-type property to depth one.
Collection querySet = new Vector();
querySet.add(DAV_RESOURCE_TYPE);
URLTable resourceTable = getProperties(querySet, IContext.DEPTH_ONE);
// Create a collection for the reply, and remove
// ourselves from the answer.
Set reply = new HashSet();
try {
resourceTable.remove(locator.getResourceURL());
} catch (MalformedURLException exception) {
throw new DAVException(Policy.bind("exception.malformedLocator")); //$NON-NLS-1$
}
// The keys of the result correspond to the receiver's internal members.
Enumeration resourceNameEnum = resourceTable.keys();
while (resourceNameEnum.hasMoreElements()) {
URL url = (URL) resourceNameEnum.nextElement();
// Get the props for that resource
Hashtable propertyTable = (Hashtable) resourceTable.get(url);
Assert.isNotNull(propertyTable); // depends on control dependency: [while], data = [none]
PropertyStatus propertyStatus = (PropertyStatus) propertyTable.get(DAV_RESOURCE_TYPE);
Assert.isNotNull(propertyStatus); // depends on control dependency: [while], data = [none]
// If we have a DAV:collection element, then create a collection handle,
// all other resource types are created as regular resource handles.
ILocator newLocator = davClient.getDAVFactory().newLocator(url.toString());
Element property = propertyStatus.getProperty();
try {
if (ElementEditor.hasChild(property, DAV_COLLECTION_RESOURCE_TYPE))
reply.add(new CollectionHandle(davClient, newLocator));
else
reply.add(new ResourceHandle(davClient, newLocator));
} catch (MalformedElementException exception) {
throw new SystemException(exception);
} // depends on control dependency: [catch], data = [none]
} // end-while
return reply;
} } |
public class class_name {
public void marshall(PhaseContext phaseContext, ProtocolMarshaller protocolMarshaller) {
if (phaseContext == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(phaseContext.getStatusCode(), STATUSCODE_BINDING);
protocolMarshaller.marshall(phaseContext.getMessage(), MESSAGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(PhaseContext phaseContext, ProtocolMarshaller protocolMarshaller) {
if (phaseContext == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(phaseContext.getStatusCode(), STATUSCODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(phaseContext.getMessage(), MESSAGE_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 void showCache(Formatter format) {
ArrayList<CacheElement.CacheFile> allFiles = new ArrayList<>(files.size());
for (CacheElement elem : cache.values()) {
synchronized (elem) {
allFiles.addAll(elem.list);
}
}
Collections.sort(allFiles); // sort so oldest are on top
format.format("%nFileCache %s (min=%d softLimit=%d hardLimit=%d scour=%d secs):%n", name, minElements, softLimit, hardLimit, period/1000);
format.format(" isLocked accesses lastAccess location %n");
for (CacheElement.CacheFile file : allFiles) {
String loc = file.ncfile != null ? file.ncfile.getLocation() : "null";
format.format("%8s %9d %s == %s %n", file.isLocked, file.countAccessed, CalendarDateFormatter.toDateTimeStringISO(file.lastAccessed), loc);
}
showStats(format);
} } | public class class_name {
@Override
public void showCache(Formatter format) {
ArrayList<CacheElement.CacheFile> allFiles = new ArrayList<>(files.size());
for (CacheElement elem : cache.values()) {
synchronized (elem) {
// depends on control dependency: [for], data = [elem]
allFiles.addAll(elem.list);
}
}
Collections.sort(allFiles); // sort so oldest are on top
format.format("%nFileCache %s (min=%d softLimit=%d hardLimit=%d scour=%d secs):%n", name, minElements, softLimit, hardLimit, period/1000);
format.format(" isLocked accesses lastAccess location %n");
for (CacheElement.CacheFile file : allFiles) {
String loc = file.ncfile != null ? file.ncfile.getLocation() : "null";
format.format("%8s %9d %s == %s %n", file.isLocked, file.countAccessed, CalendarDateFormatter.toDateTimeStringISO(file.lastAccessed), loc);
// depends on control dependency: [for], data = [file]
}
showStats(format);
} } |
public class class_name {
public Set<E> getSubSet(int k) {
int from = -1;
//TODO: very bad. Bounds should be memorized
for (int x = 0; x < values.size(); x++) {
int cIdx = index.get(values.get(x).id());
if (cIdx == k && from == -1) {
from = x;
}
if (from >= 0 && cIdx > k) {
return new ElementSubSet<>(this, k, from, x);
}
}
if (from >= 0) {
return new ElementSubSet<>(this, k, from, values.size());
}
return Collections.emptySet();
} } | public class class_name {
public Set<E> getSubSet(int k) {
int from = -1;
//TODO: very bad. Bounds should be memorized
for (int x = 0; x < values.size(); x++) {
int cIdx = index.get(values.get(x).id());
if (cIdx == k && from == -1) {
from = x; // depends on control dependency: [if], data = [none]
}
if (from >= 0 && cIdx > k) {
return new ElementSubSet<>(this, k, from, x); // depends on control dependency: [if], data = [none]
}
}
if (from >= 0) {
return new ElementSubSet<>(this, k, from, values.size()); // depends on control dependency: [if], data = [none]
}
return Collections.emptySet();
} } |
public class class_name {
protected StyleSheet parseAndImport(Object source, NetworkProcessor network, String encoding, SourceType type,
StyleSheet sheet, Preparator preparator, URL base, List<MediaQuery> media)
throws CSSException, IOException {
CSSParser parser = createParser(source, network, encoding, type, base);
CSSParserExtractor extractor = parse(parser, type, preparator, media);
for (int i = 0; i < extractor.getImportPaths().size(); i++) {
String path = extractor.getImportPaths().get(i);
List<MediaQuery> imedia = extractor.getImportMedia().get(i);
if (((imedia == null || imedia.isEmpty()) && CSSFactory.getAutoImportMedia().matchesEmpty()) //no media query specified
|| CSSFactory.getAutoImportMedia().matchesOneOf(imedia)) //or some media query matches to the autoload media spec
{
URL url = DataURLHandler.createURL(base, path);
try {
parseAndImport(url, network, encoding, SourceType.URL, sheet, preparator, url, imedia);
} catch (IOException e) {
log.warn("Couldn't read imported style sheet: {}", e.getMessage());
}
} else
log.trace("Skipping import {} (media not matching)", path);
}
return addRulesToStyleSheet(extractor.getRules(), sheet);
} } | public class class_name {
protected StyleSheet parseAndImport(Object source, NetworkProcessor network, String encoding, SourceType type,
StyleSheet sheet, Preparator preparator, URL base, List<MediaQuery> media)
throws CSSException, IOException {
CSSParser parser = createParser(source, network, encoding, type, base);
CSSParserExtractor extractor = parse(parser, type, preparator, media);
for (int i = 0; i < extractor.getImportPaths().size(); i++) {
String path = extractor.getImportPaths().get(i);
List<MediaQuery> imedia = extractor.getImportMedia().get(i);
if (((imedia == null || imedia.isEmpty()) && CSSFactory.getAutoImportMedia().matchesEmpty()) //no media query specified
|| CSSFactory.getAutoImportMedia().matchesOneOf(imedia)) //or some media query matches to the autoload media spec
{
URL url = DataURLHandler.createURL(base, path);
try {
parseAndImport(url, network, encoding, SourceType.URL, sheet, preparator, url, imedia); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
log.warn("Couldn't read imported style sheet: {}", e.getMessage());
} // depends on control dependency: [catch], data = [none]
} else
log.trace("Skipping import {} (media not matching)", path);
}
return addRulesToStyleSheet(extractor.getRules(), sheet);
} } |
public class class_name {
@Override
public void merge(MinMaxHolder another){
BigInteger anotherMin = toBigInteger(another.getMin());
if (anotherMin != null){
evaluate(anotherMin);
}
BigInteger anotherMax = toBigInteger(another.getMax());
if (anotherMax != null){
evaluate(anotherMax);
}
} } | public class class_name {
@Override
public void merge(MinMaxHolder another){
BigInteger anotherMin = toBigInteger(another.getMin());
if (anotherMin != null){
evaluate(anotherMin); // depends on control dependency: [if], data = [(anotherMin]
}
BigInteger anotherMax = toBigInteger(another.getMax());
if (anotherMax != null){
evaluate(anotherMax); // depends on control dependency: [if], data = [(anotherMax]
}
} } |
public class class_name {
public void hookScannerHook(Scanner scan) {
Iterator<ExtensionHook> iter = extensionHooks.values().iterator();
while (iter.hasNext()) {
ExtensionHook hook = iter.next();
List<ScannerHook> scannerHookList = hook.getScannerHookList();
for (ScannerHook scannerHook : scannerHookList) {
try {
if (hook != null) {
scan.addScannerHook(scannerHook);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
} } | public class class_name {
public void hookScannerHook(Scanner scan) {
Iterator<ExtensionHook> iter = extensionHooks.values().iterator();
while (iter.hasNext()) {
ExtensionHook hook = iter.next();
List<ScannerHook> scannerHookList = hook.getScannerHookList();
for (ScannerHook scannerHook : scannerHookList) {
try {
if (hook != null) {
scan.addScannerHook(scannerHook);
// depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
// depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public Set sunion(Object... keys) {
Jedis jedis = getJedis();
try {
Set<byte[]> data = jedis.sunion(keysToBytesArray(keys));
Set<Object> result = new HashSet<Object>();
valueSetFromBytesSet(data, result);
return result;
}
finally {close(jedis);}
} } | public class class_name {
@SuppressWarnings("rawtypes")
public Set sunion(Object... keys) {
Jedis jedis = getJedis();
try {
Set<byte[]> data = jedis.sunion(keysToBytesArray(keys));
Set<Object> result = new HashSet<Object>();
valueSetFromBytesSet(data, result);
// depends on control dependency: [try], data = [none]
return result;
// depends on control dependency: [try], data = [none]
}
finally {close(jedis);}
} } |
public class class_name {
private boolean baseUsedInClass(Node n){
for (Node curr = n; curr != null; curr = curr.getParent()){
if (curr.isClassMembers()) {
return true;
}
}
return false;
} } | public class class_name {
private boolean baseUsedInClass(Node n){
for (Node curr = n; curr != null; curr = curr.getParent()){
if (curr.isClassMembers()) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public TCPPort createEndPoint() throws ChannelException {
TCPPort tcpPort = super.createEndPoint();
try {
this.asyncChannelGroup = findOrCreateACG();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "AioTCPChannel created completion port for inbound connections on host " + getConfig().getHostname() + ", port " + getConfig().getPort()
+ ", completionPort = " + this.asyncChannelGroup.getCompletionPort());
}
} catch (AsyncException ae) {
ChannelException ce = new ChannelException("Error creating async channel group ");
ce.initCause(ae);
throw ce;
}
return tcpPort;
} } | public class class_name {
public TCPPort createEndPoint() throws ChannelException {
TCPPort tcpPort = super.createEndPoint();
try {
this.asyncChannelGroup = findOrCreateACG();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "AioTCPChannel created completion port for inbound connections on host " + getConfig().getHostname() + ", port " + getConfig().getPort()
+ ", completionPort = " + this.asyncChannelGroup.getCompletionPort()); // depends on control dependency: [if], data = [none]
}
} catch (AsyncException ae) {
ChannelException ce = new ChannelException("Error creating async channel group ");
ce.initCause(ae);
throw ce;
}
return tcpPort;
} } |
public class class_name {
public EClass getIfcComplexNumber() {
if (ifcComplexNumberEClass == null) {
ifcComplexNumberEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(934);
}
return ifcComplexNumberEClass;
} } | public class class_name {
public EClass getIfcComplexNumber() {
if (ifcComplexNumberEClass == null) {
ifcComplexNumberEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(934);
// depends on control dependency: [if], data = [none]
}
return ifcComplexNumberEClass;
} } |
public class class_name {
private void removeSpoolFile() throws IOException
{
if (spoolFile != null)
{
if (spoolFile instanceof SpoolFile)
{
(spoolFile).release(this);
}
if (PrivilegedFileHelper.exists(spoolFile))
{
if (!PrivilegedFileHelper.delete(spoolFile))
{
spoolConfig.fileCleaner.addFile(spoolFile);
if (LOG.isDebugEnabled())
{
LOG.debug("Could not remove file. Add to fileCleaner "
+ PrivilegedFileHelper.getAbsolutePath(spoolFile));
}
}
}
}
} } | public class class_name {
private void removeSpoolFile() throws IOException
{
if (spoolFile != null)
{
if (spoolFile instanceof SpoolFile)
{
(spoolFile).release(this);
}
if (PrivilegedFileHelper.exists(spoolFile))
{
if (!PrivilegedFileHelper.delete(spoolFile))
{
spoolConfig.fileCleaner.addFile(spoolFile); // depends on control dependency: [if], data = [none]
if (LOG.isDebugEnabled())
{
LOG.debug("Could not remove file. Add to fileCleaner "
+ PrivilegedFileHelper.getAbsolutePath(spoolFile)); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public IconType<FacesConfigManagedPropertyType<T>> getOrCreateIcon()
{
List<Node> nodeList = childNode.get("icon");
if (nodeList != null && nodeList.size() > 0)
{
return new IconTypeImpl<FacesConfigManagedPropertyType<T>>(this, "icon", childNode, nodeList.get(0));
}
return createIcon();
} } | public class class_name {
public IconType<FacesConfigManagedPropertyType<T>> getOrCreateIcon()
{
List<Node> nodeList = childNode.get("icon");
if (nodeList != null && nodeList.size() > 0)
{
return new IconTypeImpl<FacesConfigManagedPropertyType<T>>(this, "icon", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createIcon();
} } |
public class class_name {
public static List<Map<String, Object>> handleWorkBookToMapList(File file) throws ReadExcelException {
List<Map<String, Object>> listMap = null;
try {
Workbook workbook = WorkbookFactory.create(file);
listMap = ReadExcelUtils.handleWorkBookToMapList(workbook);
if (workbook != null) {
workbook.close();
}
} catch (Exception e) {
throw new ReadExcelException(e.getMessage());
}
return listMap;
} } | public class class_name {
public static List<Map<String, Object>> handleWorkBookToMapList(File file) throws ReadExcelException {
List<Map<String, Object>> listMap = null;
try {
Workbook workbook = WorkbookFactory.create(file);
listMap = ReadExcelUtils.handleWorkBookToMapList(workbook);
if (workbook != null) {
workbook.close(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
throw new ReadExcelException(e.getMessage());
}
return listMap;
} } |
public class class_name {
public static boolean isLiteralValue(Node n, boolean includeFunctions) {
switch (n.getToken()) {
case CAST:
return isLiteralValue(n.getFirstChild(), includeFunctions);
case ARRAYLIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if ((!child.isEmpty()) && !isLiteralValue(child, includeFunctions)) {
return false;
}
}
return true;
case REGEXP:
// Return true only if all descendants are const.
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if (!isLiteralValue(child, includeFunctions)) {
return false;
}
}
return true;
case OBJECTLIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
switch (child.getToken()) {
case MEMBER_FUNCTION_DEF:
case GETTER_DEF:
case SETTER_DEF:
// { methodName() {...} }
// { get propertyName() {...} }
// { set propertyName(value) {...} }
if (!includeFunctions) {
return false;
}
break;
case COMPUTED_PROP:
// { [key_expression]: value, ... }
// { [key_expression](args) {...}, ... }
// { get [key_expression]() {...}, ... }
// { set [key_expression](args) {...}, ... }
if (!isLiteralValue(child.getFirstChild(), includeFunctions)
|| !isLiteralValue(child.getLastChild(), includeFunctions)) {
return false;
}
break;
case SPREAD:
if (!isLiteralValue(child.getOnlyChild(), includeFunctions)) {
return false;
}
break;
case STRING_KEY:
// { key: value, ... }
// { "quoted_key": value, ... }
if (!isLiteralValue(child.getOnlyChild(), includeFunctions)) {
return false;
}
break;
default:
throw new IllegalArgumentException(
"Unexpected child of OBJECTLIT: " + child.toStringTree());
}
}
return true;
case FUNCTION:
return includeFunctions && !NodeUtil.isFunctionDeclaration(n);
case TEMPLATELIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if (child.isTemplateLitSub()) {
if (!isLiteralValue(child.getFirstChild(), includeFunctions)) {
return false;
}
}
}
return true;
default:
return isImmutableValue(n);
}
} } | public class class_name {
public static boolean isLiteralValue(Node n, boolean includeFunctions) {
switch (n.getToken()) {
case CAST:
return isLiteralValue(n.getFirstChild(), includeFunctions);
case ARRAYLIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if ((!child.isEmpty()) && !isLiteralValue(child, includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
case REGEXP:
// Return true only if all descendants are const.
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if (!isLiteralValue(child, includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
case OBJECTLIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
switch (child.getToken()) {
case MEMBER_FUNCTION_DEF:
case GETTER_DEF:
case SETTER_DEF:
// { methodName() {...} }
// { get propertyName() {...} }
// { set propertyName(value) {...} }
if (!includeFunctions) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case COMPUTED_PROP:
// { [key_expression]: value, ... }
// { [key_expression](args) {...}, ... }
// { get [key_expression]() {...}, ... }
// { set [key_expression](args) {...}, ... }
if (!isLiteralValue(child.getFirstChild(), includeFunctions)
|| !isLiteralValue(child.getLastChild(), includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case SPREAD:
if (!isLiteralValue(child.getOnlyChild(), includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case STRING_KEY:
// { key: value, ... }
// { "quoted_key": value, ... }
if (!isLiteralValue(child.getOnlyChild(), includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
break;
default:
throw new IllegalArgumentException(
"Unexpected child of OBJECTLIT: " + child.toStringTree());
}
}
return true;
case FUNCTION:
return includeFunctions && !NodeUtil.isFunctionDeclaration(n);
case TEMPLATELIT:
for (Node child = n.getFirstChild(); child != null; child = child.getNext()) {
if (child.isTemplateLitSub()) {
if (!isLiteralValue(child.getFirstChild(), includeFunctions)) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
return true;
default:
return isImmutableValue(n);
}
} } |
public class class_name {
@SuppressWarnings({"unused", "WeakerAccess"})
public ArrayList<CTInboxMessage> getUnreadInboxMessages(){
ArrayList<CTInboxMessage> inboxMessageArrayList = new ArrayList<>();
synchronized (inboxControllerLock) {
if(ctInboxController != null){
ArrayList<CTMessageDAO> messageDAOArrayList = ctInboxController.getUnreadMessages();
for (CTMessageDAO messageDAO : messageDAOArrayList) {
inboxMessageArrayList.add(new CTInboxMessage(messageDAO.toJSON()));
}
return inboxMessageArrayList;
} else {
getConfigLogger().debug(getAccountId(),"Notification Inbox not initialized");
return null;
}
}
} } | public class class_name {
@SuppressWarnings({"unused", "WeakerAccess"})
public ArrayList<CTInboxMessage> getUnreadInboxMessages(){
ArrayList<CTInboxMessage> inboxMessageArrayList = new ArrayList<>();
synchronized (inboxControllerLock) {
if(ctInboxController != null){
ArrayList<CTMessageDAO> messageDAOArrayList = ctInboxController.getUnreadMessages();
for (CTMessageDAO messageDAO : messageDAOArrayList) {
inboxMessageArrayList.add(new CTInboxMessage(messageDAO.toJSON())); // depends on control dependency: [for], data = [messageDAO]
}
return inboxMessageArrayList; // depends on control dependency: [if], data = [none]
} else {
getConfigLogger().debug(getAccountId(),"Notification Inbox not initialized"); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void repairSurvivors()
{
// cancel() and repair() must be synchronized by the caller (the deliver lock,
// currently). If cancelled and the last repair message arrives, don't send
// out corrections!
if (this.m_promotionResult.isCancelled()) {
repairLogger.debug(m_whoami + "skipping repair message creation for cancelled Term.");
return;
}
if (repairLogger.isDebugEnabled()) {
repairLogger.debug(m_whoami + "received all repair logs and is repairing surviving replicas.");
}
for (Iv2RepairLogResponseMessage li : m_repairLogUnion) {
// send the repair log union to all the survivors. SPIs will ignore
// CompleteTransactionMessages for transactions which have already
// completed, so this has the effect of making sure that any holes
// in the repair log are filled without explicitly having to
// discover and track them.
VoltMessage repairMsg = createRepairMessage(li);
if (repairLogger.isDebugEnabled()) {
repairLogger.debug(m_whoami + "repairing: " + CoreUtils.hsIdCollectionToString(m_survivors) + " with: " + TxnEgo.txnIdToString(li.getTxnId()) +
" " + repairMsg);
}
if (repairMsg != null) {
m_mailbox.repairReplicasWith(m_survivors, repairMsg);
}
}
m_promotionResult.set(new RepairResult(m_maxSeenTxnId));
} } | public class class_name {
public void repairSurvivors()
{
// cancel() and repair() must be synchronized by the caller (the deliver lock,
// currently). If cancelled and the last repair message arrives, don't send
// out corrections!
if (this.m_promotionResult.isCancelled()) {
repairLogger.debug(m_whoami + "skipping repair message creation for cancelled Term."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (repairLogger.isDebugEnabled()) {
repairLogger.debug(m_whoami + "received all repair logs and is repairing surviving replicas."); // depends on control dependency: [if], data = [none]
}
for (Iv2RepairLogResponseMessage li : m_repairLogUnion) {
// send the repair log union to all the survivors. SPIs will ignore
// CompleteTransactionMessages for transactions which have already
// completed, so this has the effect of making sure that any holes
// in the repair log are filled without explicitly having to
// discover and track them.
VoltMessage repairMsg = createRepairMessage(li);
if (repairLogger.isDebugEnabled()) {
repairLogger.debug(m_whoami + "repairing: " + CoreUtils.hsIdCollectionToString(m_survivors) + " with: " + TxnEgo.txnIdToString(li.getTxnId()) +
" " + repairMsg); // depends on control dependency: [if], data = [none]
}
if (repairMsg != null) {
m_mailbox.repairReplicasWith(m_survivors, repairMsg); // depends on control dependency: [if], data = [none]
}
}
m_promotionResult.set(new RepairResult(m_maxSeenTxnId));
} } |
public class class_name {
public void loadFunctions(CatalogContext catalogContext) {
final CatalogMap<Function> catalogFunctions = catalogContext.database.getFunctions();
// Remove obsolete tokens
for (UserDefinedFunctionRunner runner : m_udfs.values()) {
// The function that the current UserDefinedFunctionRunner is referring to
// does not exist in the catalog anymore, we need to remove its token.
if (catalogFunctions.get(runner.m_functionName) == null) {
FunctionForVoltDB.deregisterUserDefinedFunction(runner.m_functionName);
}
}
// Build new UDF runners
ImmutableMap.Builder<Integer, UserDefinedFunctionRunner> builder =
ImmutableMap.<Integer, UserDefinedFunctionRunner>builder();
for (final Function catalogFunction : catalogFunctions) {
final String className = catalogFunction.getClassname();
Class<?> funcClass = null;
try {
funcClass = catalogContext.classForProcedureOrUDF(className);
}
catch (final ClassNotFoundException e) {
if (className.startsWith("org.voltdb.")) {
String msg = String.format(ORGVOLTDB_FUNCCNAME_ERROR_FMT, className);
VoltDB.crashLocalVoltDB(msg, false, null);
}
else {
String msg = String.format(UNABLETOLOAD_ERROR_FMT, className);
VoltDB.crashLocalVoltDB(msg, false, null);
}
}
Object funcInstance = null;
try {
funcInstance = funcClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(String.format("Error instantiating function \"%s\"", className), e);
}
assert(funcInstance != null);
builder.put(catalogFunction.getFunctionid(), new UserDefinedFunctionRunner(catalogFunction, funcInstance));
}
loadBuiltInJavaFunctions(builder);
m_udfs = builder.build();
} } | public class class_name {
public void loadFunctions(CatalogContext catalogContext) {
final CatalogMap<Function> catalogFunctions = catalogContext.database.getFunctions();
// Remove obsolete tokens
for (UserDefinedFunctionRunner runner : m_udfs.values()) {
// The function that the current UserDefinedFunctionRunner is referring to
// does not exist in the catalog anymore, we need to remove its token.
if (catalogFunctions.get(runner.m_functionName) == null) {
FunctionForVoltDB.deregisterUserDefinedFunction(runner.m_functionName); // depends on control dependency: [if], data = [none]
}
}
// Build new UDF runners
ImmutableMap.Builder<Integer, UserDefinedFunctionRunner> builder =
ImmutableMap.<Integer, UserDefinedFunctionRunner>builder();
for (final Function catalogFunction : catalogFunctions) {
final String className = catalogFunction.getClassname();
Class<?> funcClass = null;
try {
funcClass = catalogContext.classForProcedureOrUDF(className);
}
catch (final ClassNotFoundException e) {
if (className.startsWith("org.voltdb.")) {
String msg = String.format(ORGVOLTDB_FUNCCNAME_ERROR_FMT, className);
VoltDB.crashLocalVoltDB(msg, false, null);
}
else {
String msg = String.format(UNABLETOLOAD_ERROR_FMT, className);
VoltDB.crashLocalVoltDB(msg, false, null);
}
}
Object funcInstance = null;
try {
funcInstance = funcClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(String.format("Error instantiating function \"%s\"", className), e);
}
assert(funcInstance != null);
builder.put(catalogFunction.getFunctionid(), new UserDefinedFunctionRunner(catalogFunction, funcInstance));
}
loadBuiltInJavaFunctions(builder);
m_udfs = builder.build();
} } |
public class class_name {
public int getNumberOfFiles() throws IOException {
DistributedFileSystem dfs = (DistributedFileSystem)fs;
RemoteIterator<LocatedFileStatus> iter = dfs.listLocatedStatus(outputPath);
int fn = 0;
while (iter.hasNext()) {
LocatedFileStatus lfs = iter.next();
if (lfs.isDir())
continue;
if (lfs.getBlockLocations().length != 1)
continue;
String curHost = rtc.cur_datanode;
for (String host: lfs.getBlockLocations()[0].getHosts()) {
if (curHost.equals(host)){
fn++;
break;
}
}
}
LOG.info(" Found " + fn + " files in " + dfs.getUri());
return fn;
} } | public class class_name {
public int getNumberOfFiles() throws IOException {
DistributedFileSystem dfs = (DistributedFileSystem)fs;
RemoteIterator<LocatedFileStatus> iter = dfs.listLocatedStatus(outputPath);
int fn = 0;
while (iter.hasNext()) {
LocatedFileStatus lfs = iter.next();
if (lfs.isDir())
continue;
if (lfs.getBlockLocations().length != 1)
continue;
String curHost = rtc.cur_datanode;
for (String host: lfs.getBlockLocations()[0].getHosts()) {
if (curHost.equals(host)){
fn++; // depends on control dependency: [if], data = [none]
break;
}
}
}
LOG.info(" Found " + fn + " files in " + dfs.getUri());
return fn;
} } |
public class class_name {
private static void doStormTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS)) {
heronConfig.put(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS,
heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).toString());
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_WORKERS)) {
Integer nWorkers = Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_WORKERS));
org.apache.heron.api.Config.setNumStmgrs(heronConfig, nWorkers);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)) {
Integer nSecs =
Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS));
org.apache.heron.api.Config.setMessageTimeoutSecs(heronConfig, nSecs);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING)) {
Integer nPending =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING).toString());
org.apache.heron.api.Config.setMaxSpoutPending(heronConfig, nPending);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS)) {
Integer tSecs =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS).toString());
org.apache.heron.api.Config.setTickTupleFrequency(heronConfig, tSecs);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_DEBUG)) {
Boolean dBg =
Boolean.parseBoolean(heronConfig.get(org.apache.storm.Config.TOPOLOGY_DEBUG).toString());
org.apache.heron.api.Config.setDebug(heronConfig, dBg);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT)) {
org.apache.heron.api.Config.setEnvironment(heronConfig,
(Map) heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT));
}
} } | public class class_name {
private static void doStormTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS)) {
heronConfig.put(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS,
heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).toString()); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_WORKERS)) {
Integer nWorkers = Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_WORKERS));
org.apache.heron.api.Config.setNumStmgrs(heronConfig, nWorkers); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)) {
Integer nSecs =
Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS));
org.apache.heron.api.Config.setMessageTimeoutSecs(heronConfig, nSecs); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING)) {
Integer nPending =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING).toString());
org.apache.heron.api.Config.setMaxSpoutPending(heronConfig, nPending); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS)) {
Integer tSecs =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS).toString());
org.apache.heron.api.Config.setTickTupleFrequency(heronConfig, tSecs); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_DEBUG)) {
Boolean dBg =
Boolean.parseBoolean(heronConfig.get(org.apache.storm.Config.TOPOLOGY_DEBUG).toString());
org.apache.heron.api.Config.setDebug(heronConfig, dBg); // depends on control dependency: [if], data = [none]
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT)) {
org.apache.heron.api.Config.setEnvironment(heronConfig,
(Map) heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ApprovalResult approvalResult, ProtocolMarshaller protocolMarshaller) {
if (approvalResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(approvalResult.getSummary(), SUMMARY_BINDING);
protocolMarshaller.marshall(approvalResult.getStatus(), STATUS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ApprovalResult approvalResult, ProtocolMarshaller protocolMarshaller) {
if (approvalResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(approvalResult.getSummary(), SUMMARY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(approvalResult.getStatus(), STATUS_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 <T> byte[] serialize(T object) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static <T> byte[] serialize(T object) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object); // depends on control dependency: [try], data = [none]
return byteArrayOutputStream.toByteArray(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Consumer<Subscription> subscriberLoop(final FragmentHandler fragmentHandler, final int limit,
final AtomicBoolean running, final IdleStrategy idleStrategy, final AtomicBoolean launched) {
return (subscription) -> {
try {
while (running.get()) {
idleStrategy.idle(subscription.poll(fragmentHandler, limit));
launched.set(true);
}
} catch (final Exception ex) {
LangUtil.rethrowUnchecked(ex);
}
};
} } | public class class_name {
public static Consumer<Subscription> subscriberLoop(final FragmentHandler fragmentHandler, final int limit,
final AtomicBoolean running, final IdleStrategy idleStrategy, final AtomicBoolean launched) {
return (subscription) -> {
try {
while (running.get()) {
idleStrategy.idle(subscription.poll(fragmentHandler, limit)); // depends on control dependency: [while], data = [none]
launched.set(true); // depends on control dependency: [while], data = [none]
}
} catch (final Exception ex) {
LangUtil.rethrowUnchecked(ex);
} // depends on control dependency: [catch], data = [none]
};
} } |
public class class_name {
private MQLinkHandler createMQLinkHandler(
MQLinkDefinition mqld,
VirtualLinkDefinition virtualLinkDefinition,
LocalTransaction transaction) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"createMQLinkHandler",
new Object[] { mqld, virtualLinkDefinition, transaction });
MQLinkHandler mqLinkHandler = null;
// Create a new LinkHandler, which is created locked
try
{
mqLinkHandler =
new MQLinkHandler(
mqld,
virtualLinkDefinition,
messageProcessor,
this,
transaction,
durableSubscriptions);
} catch (OutOfCacheSpace e)
{
// No FFDC code needed
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", "SIResourceException");
throw new SIResourceException(e);
} catch (MessageStoreException e)
{
// MessageStoreException shouldn't occur so FFDC.
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.DestinationManager.createMQLinkHandler",
"1:6948:1.508.1.7",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", "SIResourceException");
throw new SIResourceException(e);
}
mqLinkHandler.setLocal();
LinkIndex.Type type = new LinkIndex.Type();
type.local = Boolean.TRUE; //new Boolean(mqLinkHandler.hasLocal());
type.mqLink = Boolean.TRUE;
type.remote = Boolean.FALSE;
type.state = State.ACTIVE;
linkIndex.put(mqLinkHandler, type);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", mqLinkHandler);
return mqLinkHandler;
} } | public class class_name {
private MQLinkHandler createMQLinkHandler(
MQLinkDefinition mqld,
VirtualLinkDefinition virtualLinkDefinition,
LocalTransaction transaction) throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"createMQLinkHandler",
new Object[] { mqld, virtualLinkDefinition, transaction });
MQLinkHandler mqLinkHandler = null;
// Create a new LinkHandler, which is created locked
try
{
mqLinkHandler =
new MQLinkHandler(
mqld,
virtualLinkDefinition,
messageProcessor,
this,
transaction,
durableSubscriptions); // depends on control dependency: [try], data = [none]
} catch (OutOfCacheSpace e)
{
// No FFDC code needed
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", "SIResourceException");
throw new SIResourceException(e);
} catch (MessageStoreException e) // depends on control dependency: [catch], data = [none]
{
// MessageStoreException shouldn't occur so FFDC.
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.DestinationManager.createMQLinkHandler",
"1:6948:1.508.1.7",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", "SIResourceException");
throw new SIResourceException(e);
} // depends on control dependency: [catch], data = [none]
mqLinkHandler.setLocal();
LinkIndex.Type type = new LinkIndex.Type();
type.local = Boolean.TRUE; //new Boolean(mqLinkHandler.hasLocal());
type.mqLink = Boolean.TRUE;
type.remote = Boolean.FALSE;
type.state = State.ACTIVE;
linkIndex.put(mqLinkHandler, type);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createMQLinkHandler", mqLinkHandler);
return mqLinkHandler;
} } |
public class class_name {
public static Atom[] getRepresentativeAtoms(Structure structure) {
if (structure.isNmr())
return StructureTools.getRepresentativeAtomArray(structure);
else {
// Get Atoms of all models
List<Atom> atomList = new ArrayList<Atom>();
for (int m = 0; m < structure.nrModels(); m++) {
for (Chain c : structure.getModel(m))
atomList.addAll(Arrays.asList(StructureTools
.getRepresentativeAtomArray(c)));
}
return atomList.toArray(new Atom[0]);
}
} } | public class class_name {
public static Atom[] getRepresentativeAtoms(Structure structure) {
if (structure.isNmr())
return StructureTools.getRepresentativeAtomArray(structure);
else {
// Get Atoms of all models
List<Atom> atomList = new ArrayList<Atom>();
for (int m = 0; m < structure.nrModels(); m++) {
for (Chain c : structure.getModel(m))
atomList.addAll(Arrays.asList(StructureTools
.getRepresentativeAtomArray(c)));
}
return atomList.toArray(new Atom[0]); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static JBossWebMetaData getJBossWebMetaData(final DeploymentUnit unit) {
final WarMetaData warMetaData = getOptionalAttachment(unit, WarMetaData.ATTACHMENT_KEY);
JBossWebMetaData result = null;
if (warMetaData != null) {
result = warMetaData.getMergedJBossWebMetaData();
if (result == null) {
result = warMetaData.getJBossWebMetaData();
}
} else {
result = getOptionalAttachment(unit, WSAttachmentKeys.JBOSSWEB_METADATA_KEY);
}
return result;
} } | public class class_name {
public static JBossWebMetaData getJBossWebMetaData(final DeploymentUnit unit) {
final WarMetaData warMetaData = getOptionalAttachment(unit, WarMetaData.ATTACHMENT_KEY);
JBossWebMetaData result = null;
if (warMetaData != null) {
result = warMetaData.getMergedJBossWebMetaData(); // depends on control dependency: [if], data = [none]
if (result == null) {
result = warMetaData.getJBossWebMetaData(); // depends on control dependency: [if], data = [none]
}
} else {
result = getOptionalAttachment(unit, WSAttachmentKeys.JBOSSWEB_METADATA_KEY); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public List<Map<String, String>> pipelinePossibleStates(RangeTag action,
List<Map<String, String>> possibleStateList) {
String variable = action.getName();
BigDecimal from = new BigDecimal(action.getFrom());
BigDecimal to = new BigDecimal(action.getTo());
BigDecimal step;
if (action.getStep() != null) {
step = new BigDecimal(action.getStep());
} else {
step = BigDecimal.ONE;
}
List<BigDecimal> rangeValues = new ArrayList<>();
if (step.signum() == 1) {
for (BigDecimal current = from; current.compareTo(to) <= 0; current = current.add(step)) {
rangeValues.add(current);
}
} else if (step.signum() == -1) {
for (BigDecimal current = from; current.compareTo(to) >= 0; current = current.add(step)) {
rangeValues.add(current);
}
} else {
rangeValues.add(from);
}
//take the product
List<Map<String, String>> productTemp = new LinkedList<>();
for (Map<String, String> p : possibleStateList) {
for (BigDecimal value : rangeValues) {
HashMap<String, String> n = new HashMap<>(p);
n.put(variable, value.toString());
productTemp.add(n);
}
}
return productTemp;
} } | public class class_name {
public List<Map<String, String>> pipelinePossibleStates(RangeTag action,
List<Map<String, String>> possibleStateList) {
String variable = action.getName();
BigDecimal from = new BigDecimal(action.getFrom());
BigDecimal to = new BigDecimal(action.getTo());
BigDecimal step;
if (action.getStep() != null) {
step = new BigDecimal(action.getStep());
// depends on control dependency: [if], data = [(action.getStep()]
} else {
step = BigDecimal.ONE;
// depends on control dependency: [if], data = [none]
}
List<BigDecimal> rangeValues = new ArrayList<>();
if (step.signum() == 1) {
for (BigDecimal current = from; current.compareTo(to) <= 0; current = current.add(step)) {
rangeValues.add(current);
// depends on control dependency: [for], data = [current]
}
} else if (step.signum() == -1) {
for (BigDecimal current = from; current.compareTo(to) >= 0; current = current.add(step)) {
rangeValues.add(current);
// depends on control dependency: [for], data = [current]
}
} else {
rangeValues.add(from);
// depends on control dependency: [if], data = [none]
}
//take the product
List<Map<String, String>> productTemp = new LinkedList<>();
for (Map<String, String> p : possibleStateList) {
for (BigDecimal value : rangeValues) {
HashMap<String, String> n = new HashMap<>(p);
n.put(variable, value.toString());
// depends on control dependency: [for], data = [value]
productTemp.add(n);
// depends on control dependency: [for], data = [none]
}
}
return productTemp;
} } |
public class class_name {
private void loadImplementationsInJar(final Test test, final String parent, final String path,
final JarInputStream stream) {
try {
JarEntry entry;
while ((entry = stream.getNextJarEntry()) != null) {
final String name = entry.getName();
if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
addIfMatching(test, name);
}
}
} catch (final IOException ioe) {
LOGGER.error("Could not search jar file '" + path + "' for classes matching criteria: " + test
+ " due to an IOException", ioe);
}
} } | public class class_name {
private void loadImplementationsInJar(final Test test, final String parent, final String path,
final JarInputStream stream) {
try {
JarEntry entry;
while ((entry = stream.getNextJarEntry()) != null) {
final String name = entry.getName();
if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
addIfMatching(test, name); // depends on control dependency: [if], data = [none]
}
}
} catch (final IOException ioe) {
LOGGER.error("Could not search jar file '" + path + "' for classes matching criteria: " + test
+ " due to an IOException", ioe);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String getEntityId(I_CmsXmlContentValue contentValue) {
String result = CmsContentDefinition.uuidToEntityId(
contentValue.getDocument().getFile().getStructureId(),
contentValue.getLocale().toString());
String valuePath = contentValue.getPath();
if (valuePath.contains("/")) {
result += "/" + valuePath.substring(0, valuePath.lastIndexOf("/"));
}
if (contentValue.isChoiceOption()) {
result += "/"
+ CmsType.CHOICE_ATTRIBUTE_NAME
+ "_"
+ contentValue.getName()
+ "["
+ contentValue.getXmlIndex()
+ "]";
}
return result;
} } | public class class_name {
public static String getEntityId(I_CmsXmlContentValue contentValue) {
String result = CmsContentDefinition.uuidToEntityId(
contentValue.getDocument().getFile().getStructureId(),
contentValue.getLocale().toString());
String valuePath = contentValue.getPath();
if (valuePath.contains("/")) {
result += "/" + valuePath.substring(0, valuePath.lastIndexOf("/")); // depends on control dependency: [if], data = [none]
}
if (contentValue.isChoiceOption()) {
result += "/"
+ CmsType.CHOICE_ATTRIBUTE_NAME
+ "_"
+ contentValue.getName()
+ "["
+ contentValue.getXmlIndex()
+ "]"; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public static boolean isBinaryExpressionType(Expression expression, List<String> tokens) {
if (expression instanceof BinaryExpression) {
if (tokens.contains(((BinaryExpression) expression).getOperation().getText())) {
return true;
}
}
return false;
} } | public class class_name {
public static boolean isBinaryExpressionType(Expression expression, List<String> tokens) {
if (expression instanceof BinaryExpression) {
if (tokens.contains(((BinaryExpression) expression).getOperation().getText())) {
return true;
// depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private static void startIfNotStarted(String serviceName) {
synchronized (queueNames) {
if (!queueNames.contains(serviceName)) {
//以下是新建一个rabbitmq客户端
try {
IMqConsumerClient.singleton.consumeStaticQueue(TransferQueueUtil.getTransferQueue(serviceName), callback);
queueNames.add(serviceName);
} catch (Throwable e) {
LOG.warn("订阅静态队列失败:" + serviceName, e);
}
}
}
} } | public class class_name {
private static void startIfNotStarted(String serviceName) {
synchronized (queueNames) {
if (!queueNames.contains(serviceName)) {
//以下是新建一个rabbitmq客户端
try {
IMqConsumerClient.singleton.consumeStaticQueue(TransferQueueUtil.getTransferQueue(serviceName), callback); // depends on control dependency: [try], data = [none]
queueNames.add(serviceName); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
LOG.warn("订阅静态队列失败:" + serviceName, e);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public static FailoverStrategy.Factory loadFailoverStrategy(Configuration config, @Nullable Logger logger) {
final String strategyParam = config.getString(JobManagerOptions.EXECUTION_FAILOVER_STRATEGY);
if (StringUtils.isNullOrWhitespaceOnly(strategyParam)) {
if (logger != null) {
logger.warn("Null config value for {} ; using default failover strategy (full restarts).",
JobManagerOptions.EXECUTION_FAILOVER_STRATEGY.key());
}
return new RestartAllStrategy.Factory();
}
else {
switch (strategyParam.toLowerCase()) {
case FULL_RESTART_STRATEGY_NAME:
return new RestartAllStrategy.Factory();
case PIPELINED_REGION_RESTART_STRATEGY_NAME:
return new RestartPipelinedRegionStrategy.Factory();
case INDIVIDUAL_RESTART_STRATEGY_NAME:
return new RestartIndividualStrategy.Factory();
default:
// we could interpret the parameter as a factory class name and instantiate that
// for now we simply do not support this
throw new IllegalConfigurationException("Unknown failover strategy: " + strategyParam);
}
}
} } | public class class_name {
public static FailoverStrategy.Factory loadFailoverStrategy(Configuration config, @Nullable Logger logger) {
final String strategyParam = config.getString(JobManagerOptions.EXECUTION_FAILOVER_STRATEGY);
if (StringUtils.isNullOrWhitespaceOnly(strategyParam)) {
if (logger != null) {
logger.warn("Null config value for {} ; using default failover strategy (full restarts).", // depends on control dependency: [if], data = [none]
JobManagerOptions.EXECUTION_FAILOVER_STRATEGY.key()); // depends on control dependency: [if], data = [none]
}
return new RestartAllStrategy.Factory(); // depends on control dependency: [if], data = [none]
}
else {
switch (strategyParam.toLowerCase()) {
case FULL_RESTART_STRATEGY_NAME:
return new RestartAllStrategy.Factory();
case PIPELINED_REGION_RESTART_STRATEGY_NAME:
return new RestartPipelinedRegionStrategy.Factory();
case INDIVIDUAL_RESTART_STRATEGY_NAME:
return new RestartIndividualStrategy.Factory();
default:
// we could interpret the parameter as a factory class name and instantiate that
// for now we simply do not support this
throw new IllegalConfigurationException("Unknown failover strategy: " + strategyParam);
}
}
} } |
public class class_name {
protected boolean internalEquals(ValueData another)
{
if (another instanceof ReferenceValueData)
{
return ((ReferenceValueData)another).value.equals(value);
}
return false;
} } | public class class_name {
protected boolean internalEquals(ValueData another)
{
if (another instanceof ReferenceValueData)
{
return ((ReferenceValueData)another).value.equals(value); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
protected boolean restartPossible() {
boolean restart = false;
if (!syncConfig.isCleanStart()) {
// Determines if the configuration has been changed since the
// previous run. If it has, a restart cannot occur.
SyncToolConfigParser syncConfigParser = new SyncToolConfigParser();
SyncToolConfig prevConfig =
syncConfigParser.retrievePrevConfig(syncConfig.getWorkDir());
if (prevConfig != null) {
restart = configEquals(syncConfig, prevConfig);
}
}
return restart;
} } | public class class_name {
protected boolean restartPossible() {
boolean restart = false;
if (!syncConfig.isCleanStart()) {
// Determines if the configuration has been changed since the
// previous run. If it has, a restart cannot occur.
SyncToolConfigParser syncConfigParser = new SyncToolConfigParser();
SyncToolConfig prevConfig =
syncConfigParser.retrievePrevConfig(syncConfig.getWorkDir());
if (prevConfig != null) {
restart = configEquals(syncConfig, prevConfig); // depends on control dependency: [if], data = [none]
}
}
return restart;
} } |
public class class_name {
@Override
public String getPathInfo() {
if (!this.pathInfoComputed) {
final String uri = getRequestURI();
final int servletPathLength = getServletPath().length();
if (uri.length() == servletPathLength) {
this.pathInfo = null;
} else {
this.pathInfo = uri.replaceAll("[/]{2,}", "/").substring(servletPathLength);
if ("".equals(this.pathInfo) && servletPathLength != 0) {
this.pathInfo = null;
}
}
this.pathInfoComputed = true;
}
return this.pathInfo;
} } | public class class_name {
@Override
public String getPathInfo() {
if (!this.pathInfoComputed) {
final String uri = getRequestURI();
final int servletPathLength = getServletPath().length();
if (uri.length() == servletPathLength) {
this.pathInfo = null; // depends on control dependency: [if], data = [none]
} else {
this.pathInfo = uri.replaceAll("[/]{2,}", "/").substring(servletPathLength); // depends on control dependency: [if], data = [servletPathLength)]
if ("".equals(this.pathInfo) && servletPathLength != 0) {
this.pathInfo = null; // depends on control dependency: [if], data = [none]
}
}
this.pathInfoComputed = true; // depends on control dependency: [if], data = [none]
}
return this.pathInfo;
} } |
public class class_name {
public QueryBuilder withShadowScope(ShadowScope shadowScope){
Validate.argumentIsNotNull(shadowScope);
this.shadowScope = shadowScope;
if (shadowScope == DEEP_PLUS && maxGapsToFill == 0) {
this.maxGapsToFill = DEFAULT_GAPS_TO_FILL_LIMIT;
}
return this;
} } | public class class_name {
public QueryBuilder withShadowScope(ShadowScope shadowScope){
Validate.argumentIsNotNull(shadowScope);
this.shadowScope = shadowScope;
if (shadowScope == DEEP_PLUS && maxGapsToFill == 0) {
this.maxGapsToFill = DEFAULT_GAPS_TO_FILL_LIMIT; // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public void auditUpdateNotificationEvent(RFC3881EventOutcomeCodes eventOutcome,
String pixMgrIpAddress, String sendingFacility, String sendingApp,
String consumerEndpointUri, String receivingFacility, String receivingApp,
String hl7MessageControlId,
String[] patientIds)
{
if (!isAuditorEnabled()) {
return;
}
auditPatientRecordEvent(
true,
new IHETransactionEventTypeCodes.PIXUpdateNotification(), eventOutcome, RFC3881EventCodes.RFC3881EventActionCodes.READ,
sendingFacility, sendingApp, getSystemAltUserId(), pixMgrIpAddress,
receivingFacility, receivingApp, null, EventUtils.getAddressForUrl(consumerEndpointUri, false),
null,
hl7MessageControlId,
patientIds, null, null);
} } | public class class_name {
public void auditUpdateNotificationEvent(RFC3881EventOutcomeCodes eventOutcome,
String pixMgrIpAddress, String sendingFacility, String sendingApp,
String consumerEndpointUri, String receivingFacility, String receivingApp,
String hl7MessageControlId,
String[] patientIds)
{
if (!isAuditorEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
auditPatientRecordEvent(
true,
new IHETransactionEventTypeCodes.PIXUpdateNotification(), eventOutcome, RFC3881EventCodes.RFC3881EventActionCodes.READ,
sendingFacility, sendingApp, getSystemAltUserId(), pixMgrIpAddress,
receivingFacility, receivingApp, null, EventUtils.getAddressForUrl(consumerEndpointUri, false),
null,
hl7MessageControlId,
patientIds, null, null);
} } |
public class class_name {
protected Parser parser(Key jobKey) {
ParserProvider pp = ParserService.INSTANCE.getByInfo(_parse_type);
if (pp != null) {
return pp.createParser(this, jobKey);
}
throw new H2OIllegalArgumentException("Unknown file type. Parse cannot be completed.",
"Attempted to invoke a parser for ParseType:" + _parse_type + ", which doesn't exist.");
} } | public class class_name {
protected Parser parser(Key jobKey) {
ParserProvider pp = ParserService.INSTANCE.getByInfo(_parse_type);
if (pp != null) {
return pp.createParser(this, jobKey); // depends on control dependency: [if], data = [none]
}
throw new H2OIllegalArgumentException("Unknown file type. Parse cannot be completed.",
"Attempted to invoke a parser for ParseType:" + _parse_type + ", which doesn't exist.");
} } |
public class class_name {
public synchronized static void entering(String classname, long fnr)
{
// int fnr = (int) fnr2; //Here the long value is casted into in to be used as index to the arrays.
requesting(classname, (int) fnr);// the #req counter is changed to add one to it.
try
{
if (!evalPP(classname, fnr)) // the first evaluation of the permition predicate.
{
waiting(classname, (int) fnr, +1);// if the permission predicate is false. It add one to the #waiting
// counter.
while (!evalPP(classname, fnr))// reevaluation of the permission predicate.
{
Sentinel.class.wait(); // actual thread wait method. This freeze the thread waiting for the
// execution of its method.
}
waiting(classname, (int) fnr, -1); // if predicate changes to true, #waiting is changed to remove one.
}
} catch (InterruptedException e)
{
}
activating(classname, (int) fnr);// the #act and the #active counters are change to add one to them
} } | public class class_name {
public synchronized static void entering(String classname, long fnr)
{
// int fnr = (int) fnr2; //Here the long value is casted into in to be used as index to the arrays.
requesting(classname, (int) fnr);// the #req counter is changed to add one to it.
try
{
if (!evalPP(classname, fnr)) // the first evaluation of the permition predicate.
{
waiting(classname, (int) fnr, +1);// if the permission predicate is false. It add one to the #waiting // depends on control dependency: [if], data = [none]
// counter.
while (!evalPP(classname, fnr))// reevaluation of the permission predicate.
{
Sentinel.class.wait(); // actual thread wait method. This freeze the thread waiting for the // depends on control dependency: [while], data = [none]
// execution of its method.
}
waiting(classname, (int) fnr, -1); // if predicate changes to true, #waiting is changed to remove one. // depends on control dependency: [if], data = [none]
}
} catch (InterruptedException e)
{
} // depends on control dependency: [catch], data = [none]
activating(classname, (int) fnr);// the #act and the #active counters are change to add one to them
} } |
public class class_name {
public void setCloudWatchDashboards(java.util.Collection<CloudWatchDashboard> cloudWatchDashboards) {
if (cloudWatchDashboards == null) {
this.cloudWatchDashboards = null;
return;
}
this.cloudWatchDashboards = new java.util.ArrayList<CloudWatchDashboard>(cloudWatchDashboards);
} } | public class class_name {
public void setCloudWatchDashboards(java.util.Collection<CloudWatchDashboard> cloudWatchDashboards) {
if (cloudWatchDashboards == null) {
this.cloudWatchDashboards = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.cloudWatchDashboards = new java.util.ArrayList<CloudWatchDashboard>(cloudWatchDashboards);
} } |
public class class_name {
public static boolean tangentLines(Point2D_F64 pt , EllipseRotated_F64 ellipse ,
Point2D_F64 tangentA , Point2D_F64 tangentB )
{
// Derivation:
// Compute the tangent at only point along the ellipse by computing dy/dx
// x*b^2/(y*a^2) or - x*b^2/(y*a^2) are the possible solutions for the tangent
// The slope of the line and the gradient are the same, so this is true:
// y - y' -x*b^2
// ------- = -------
// x - x' y*a^2
//
// (x,y) is point on ellipse, (x',y') is pt that lines pass through
//
// that becomes
// y^2*a^2 + x^2*b^2 = x'*x*b^2 + y'*y*a^2
// use the equation for the ellipse (centered and aligned at origin)
// a^2*b^2 = x'*x*b^2 + y'*y*a^2
//
// solve for y
// plug into ellipse equation
// solve for x, which is a quadratic equation
// translate and rotate into ellipse reference frame
double cphi = Math.cos(ellipse.phi);
double sphi = Math.sin(ellipse.phi);
double tmpx = pt.x - ellipse.center.x;
double tmpy = pt.y - ellipse.center.y;
double xt = tmpx*cphi + tmpy*sphi;
double yt = -tmpx*sphi + tmpy*cphi;
// solve
double a2 = ellipse.a*ellipse.a;
double b2 = ellipse.b*ellipse.b;
// quadratic equation for the two variants.
// solving for x
double aa0 = yt*yt/b2 + xt*xt/a2;
double bb0 = -2.0*xt;
double cc0 = a2*(1.0-yt*yt/b2);
double descriminant0 = bb0*bb0 - 4.0*aa0*cc0;
// solving for y
double aa1 = xt*xt/a2 + yt*yt/b2;
double bb1 = -2.0*yt;
double cc1 = b2*(1.0-xt*xt/a2);
double descriminant1 = bb1*bb1 - 4.0*aa1*cc1;
double x0,y0, x1,y1;
if( descriminant0 < 0 && descriminant1 < 0 ) {
return false;
} else if( descriminant0 > descriminant1 ) {
if( yt == 0 )
return false;
double right = Math.sqrt(descriminant0);
x0 = (-bb0 + right)/(2.0*aa0);
x1 = (-bb0 - right)/(2.0*aa0);
y0 = b2/yt - xt*x0*b2/(yt*a2);
y1 = b2/yt - xt*x1*b2/(yt*a2);
} else {
if( xt == 0 )
return false;
double right = Math.sqrt(descriminant1);
y0 = (-bb1 + right)/(2.0*aa1);
y1 = (-bb1 - right)/(2.0*aa1);
x0 = a2/xt - yt*y0*a2/(xt*b2);
x1 = a2/xt - yt*y1*a2/(xt*b2);
}
// convert the lines back into world space
tangentA.x = x0*cphi - y0*sphi + ellipse.center.x;
tangentA.y = x0*sphi + y0*cphi + ellipse.center.y;
tangentB.x = x1*cphi - y1*sphi + ellipse.center.x;
tangentB.y = x1*sphi + y1*cphi + ellipse.center.y;
return true;
} } | public class class_name {
public static boolean tangentLines(Point2D_F64 pt , EllipseRotated_F64 ellipse ,
Point2D_F64 tangentA , Point2D_F64 tangentB )
{
// Derivation:
// Compute the tangent at only point along the ellipse by computing dy/dx
// x*b^2/(y*a^2) or - x*b^2/(y*a^2) are the possible solutions for the tangent
// The slope of the line and the gradient are the same, so this is true:
// y - y' -x*b^2
// ------- = -------
// x - x' y*a^2
//
// (x,y) is point on ellipse, (x',y') is pt that lines pass through
//
// that becomes
// y^2*a^2 + x^2*b^2 = x'*x*b^2 + y'*y*a^2
// use the equation for the ellipse (centered and aligned at origin)
// a^2*b^2 = x'*x*b^2 + y'*y*a^2
//
// solve for y
// plug into ellipse equation
// solve for x, which is a quadratic equation
// translate and rotate into ellipse reference frame
double cphi = Math.cos(ellipse.phi);
double sphi = Math.sin(ellipse.phi);
double tmpx = pt.x - ellipse.center.x;
double tmpy = pt.y - ellipse.center.y;
double xt = tmpx*cphi + tmpy*sphi;
double yt = -tmpx*sphi + tmpy*cphi;
// solve
double a2 = ellipse.a*ellipse.a;
double b2 = ellipse.b*ellipse.b;
// quadratic equation for the two variants.
// solving for x
double aa0 = yt*yt/b2 + xt*xt/a2;
double bb0 = -2.0*xt;
double cc0 = a2*(1.0-yt*yt/b2);
double descriminant0 = bb0*bb0 - 4.0*aa0*cc0;
// solving for y
double aa1 = xt*xt/a2 + yt*yt/b2;
double bb1 = -2.0*yt;
double cc1 = b2*(1.0-xt*xt/a2);
double descriminant1 = bb1*bb1 - 4.0*aa1*cc1;
double x0,y0, x1,y1;
if( descriminant0 < 0 && descriminant1 < 0 ) {
return false; // depends on control dependency: [if], data = [none]
} else if( descriminant0 > descriminant1 ) {
if( yt == 0 )
return false;
double right = Math.sqrt(descriminant0);
x0 = (-bb0 + right)/(2.0*aa0); // depends on control dependency: [if], data = [none]
x1 = (-bb0 - right)/(2.0*aa0); // depends on control dependency: [if], data = [none]
y0 = b2/yt - xt*x0*b2/(yt*a2); // depends on control dependency: [if], data = [none]
y1 = b2/yt - xt*x1*b2/(yt*a2); // depends on control dependency: [if], data = [none]
} else {
if( xt == 0 )
return false;
double right = Math.sqrt(descriminant1);
y0 = (-bb1 + right)/(2.0*aa1); // depends on control dependency: [if], data = [none]
y1 = (-bb1 - right)/(2.0*aa1); // depends on control dependency: [if], data = [none]
x0 = a2/xt - yt*y0*a2/(xt*b2); // depends on control dependency: [if], data = [none]
x1 = a2/xt - yt*y1*a2/(xt*b2); // depends on control dependency: [if], data = [none]
}
// convert the lines back into world space
tangentA.x = x0*cphi - y0*sphi + ellipse.center.x;
tangentA.y = x0*sphi + y0*cphi + ellipse.center.y;
tangentB.x = x1*cphi - y1*sphi + ellipse.center.x;
tangentB.y = x1*sphi + y1*cphi + ellipse.center.y;
return true;
} } |
public class class_name {
public void marshall(CreateThingRequest createThingRequest, ProtocolMarshaller protocolMarshaller) {
if (createThingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createThingRequest.getThingName(), THINGNAME_BINDING);
protocolMarshaller.marshall(createThingRequest.getThingTypeName(), THINGTYPENAME_BINDING);
protocolMarshaller.marshall(createThingRequest.getAttributePayload(), ATTRIBUTEPAYLOAD_BINDING);
protocolMarshaller.marshall(createThingRequest.getBillingGroupName(), BILLINGGROUPNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateThingRequest createThingRequest, ProtocolMarshaller protocolMarshaller) {
if (createThingRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createThingRequest.getThingName(), THINGNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThingRequest.getThingTypeName(), THINGTYPENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThingRequest.getAttributePayload(), ATTRIBUTEPAYLOAD_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createThingRequest.getBillingGroupName(), BILLINGGROUPNAME_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 {
protected boolean isResourceChanged(final HttpServletRequest request) {
try {
final long ifModifiedSince = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString());
return ifModifiedSince < getHeadersConfigurer().getLastModifiedTimestamp();
} catch (final Exception e) {
LOG.warn("Could not extract IF_MODIFIED_SINCE header for request: " + request.getRequestURI() + ". Assuming content is changed. ", e);
return true;
}
} } | public class class_name {
protected boolean isResourceChanged(final HttpServletRequest request) {
try {
final long ifModifiedSince = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.toString());
return ifModifiedSince < getHeadersConfigurer().getLastModifiedTimestamp(); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
LOG.warn("Could not extract IF_MODIFIED_SINCE header for request: " + request.getRequestURI() + ". Assuming content is changed. ", e);
return true;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public DescribeActiveReceiptRuleSetResult withRules(ReceiptRule... rules) {
if (this.rules == null) {
setRules(new com.amazonaws.internal.SdkInternalList<ReceiptRule>(rules.length));
}
for (ReceiptRule ele : rules) {
this.rules.add(ele);
}
return this;
} } | public class class_name {
public DescribeActiveReceiptRuleSetResult withRules(ReceiptRule... rules) {
if (this.rules == null) {
setRules(new com.amazonaws.internal.SdkInternalList<ReceiptRule>(rules.length)); // depends on control dependency: [if], data = [none]
}
for (ReceiptRule ele : rules) {
this.rules.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public int compareTo(TaskDetails otherTask) {
if (otherTask == null) {
return -1;
}
return new CompareToBuilder().append(this.taskKey, otherTask.getTaskKey())
.toComparison();
} } | public class class_name {
@Override
public int compareTo(TaskDetails otherTask) {
if (otherTask == null) {
return -1; // depends on control dependency: [if], data = [none]
}
return new CompareToBuilder().append(this.taskKey, otherTask.getTaskKey())
.toComparison();
} } |
public class class_name {
public Object nth(int i) {
if (i < values.size()) {
return values.get(i);
} else {
return null;
}
} } | public class class_name {
public Object nth(int i) {
if (i < values.size()) {
return values.get(i); // depends on control dependency: [if], data = [(i]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean isCipherSuiteAvailable(String cipherSuite) {
String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL);
if (converted != null) {
cipherSuite = converted;
}
return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite);
} } | public class class_name {
public static boolean isCipherSuiteAvailable(String cipherSuite) {
String converted = CipherSuiteConverter.toOpenSsl(cipherSuite, IS_BORINGSSL);
if (converted != null) {
cipherSuite = converted; // depends on control dependency: [if], data = [none]
}
return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(cipherSuite);
} } |
public class class_name {
public boolean hasCache() {
if (isCache()) {
return true;
}
if (CommonUtils.isNotEmpty(methods)) {
for (MethodConfig methodConfig : methods.values()) {
if (CommonUtils.isTrue(methodConfig.getCache())) {
return true;
}
}
}
return false;
} } | public class class_name {
public boolean hasCache() {
if (isCache()) {
return true; // depends on control dependency: [if], data = [none]
}
if (CommonUtils.isNotEmpty(methods)) {
for (MethodConfig methodConfig : methods.values()) {
if (CommonUtils.isTrue(methodConfig.getCache())) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
public static int compare(UUID uuid1, UUID uuid2) {
int timeResult = Longs.compare(uuid1.timestamp(), uuid2.timestamp());
if (timeResult != 0) {
return timeResult;
}
// if the time component is identical, break ties using the clockSeqAndNode
// component (the 64 least significant bits). the top 16 bits of the lsb are
// the "clockSeq" number which, theoretically, is an incrementing counter. in
// practice, however, (and in com.eaio.uuid) clockSeq is a random number and
// shouldn't be interpreted as meaning anything. just use it for breaking ties.
return uuid1.compareTo(uuid2);
} } | public class class_name {
public static int compare(UUID uuid1, UUID uuid2) {
int timeResult = Longs.compare(uuid1.timestamp(), uuid2.timestamp());
if (timeResult != 0) {
return timeResult; // depends on control dependency: [if], data = [none]
}
// if the time component is identical, break ties using the clockSeqAndNode
// component (the 64 least significant bits). the top 16 bits of the lsb are
// the "clockSeq" number which, theoretically, is an incrementing counter. in
// practice, however, (and in com.eaio.uuid) clockSeq is a random number and
// shouldn't be interpreted as meaning anything. just use it for breaking ties.
return uuid1.compareTo(uuid2);
} } |
public class class_name {
@Override
public EClass getIfcWorkControl() {
if (ifcWorkControlEClass == null) {
ifcWorkControlEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(771);
}
return ifcWorkControlEClass;
} } | public class class_name {
@Override
public EClass getIfcWorkControl() {
if (ifcWorkControlEClass == null) {
ifcWorkControlEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(771);
// depends on control dependency: [if], data = [none]
}
return ifcWorkControlEClass;
} } |
public class class_name {
@Override
public void setAction(final Runnable action) {
super.setAction(new Runnable() {
@Override
public void run() {
if (!isRunning) {
thread = new Thread(wrappedAction(action), "wunderboss-daemon-thread[" + name + "]");
thread.start();
isRunning = true;
}
}
});
} } | public class class_name {
@Override
public void setAction(final Runnable action) {
super.setAction(new Runnable() {
@Override
public void run() {
if (!isRunning) {
thread = new Thread(wrappedAction(action), "wunderboss-daemon-thread[" + name + "]"); // depends on control dependency: [if], data = [none]
thread.start(); // depends on control dependency: [if], data = [none]
isRunning = true; // depends on control dependency: [if], data = [none]
}
}
});
} } |
public class class_name {
private void tick(long tickIntervalMs) {
for (int i = 0; i < NUM_AVERAGES; ++i) {
stat[i].tick(tickIntervalMs);
}
} } | public class class_name {
private void tick(long tickIntervalMs) {
for (int i = 0; i < NUM_AVERAGES; ++i) {
stat[i].tick(tickIntervalMs); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public StringBuffer process(StringBuffer source) {
CharSequence result = process((CharSequence) source);
if (result instanceof StringBuffer) {
return (StringBuffer) result;
} else {
return new StringBuffer(result);
}
} } | public class class_name {
public StringBuffer process(StringBuffer source) {
CharSequence result = process((CharSequence) source);
if (result instanceof StringBuffer) {
return (StringBuffer) result; // depends on control dependency: [if], data = [none]
} else {
return new StringBuffer(result); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void unfoldJoinTrees(List body) {
for (int i = 0; i < body.size(); i++) {
Function currentAtom = (Function) body.get(i);
if (currentAtom.getFunctionSymbol().equals(datalogFactory.getSparqlJoinPredicate())) {
unfoldJoinTrees(currentAtom.getTerms());
body.remove(i);
for (int j = currentAtom.getTerms().size() - 1; j >= 0; j--) {
Term term = currentAtom.getTerm(j);
if (!body.contains(term))
body.add(i, term);
}
i -= 1;
}
}
} } | public class class_name {
private void unfoldJoinTrees(List body) {
for (int i = 0; i < body.size(); i++) {
Function currentAtom = (Function) body.get(i);
if (currentAtom.getFunctionSymbol().equals(datalogFactory.getSparqlJoinPredicate())) {
unfoldJoinTrees(currentAtom.getTerms()); // depends on control dependency: [if], data = [none]
body.remove(i); // depends on control dependency: [if], data = [none]
for (int j = currentAtom.getTerms().size() - 1; j >= 0; j--) {
Term term = currentAtom.getTerm(j);
if (!body.contains(term))
body.add(i, term);
}
i -= 1; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private List<String> getCurrentEndpointIdentifiers(Protocol protocol) throws SQLException {
List<String> endpoints = new ArrayList<>();
try {
proxy.lock.lock();
try {
// Deleted instance may remain in db for 24 hours so ignoring instances that have had no change
// for 3 minutes
Results results = new Results();
protocol.executeQuery(false, results,
"select server_id, session_id from information_schema.replica_host_status "
+ "where last_update_timestamp > now() - INTERVAL 3 MINUTE");
results.commandEnd();
ResultSet resultSet = results.getResultSet();
while (resultSet.next()) {
endpoints.add(resultSet.getString(1) + "." + clusterDnsSuffix);
}
//randomize order for distributed load-balancing
Collections.shuffle(endpoints);
} finally {
proxy.lock.unlock();
}
} catch (SQLException qe) {
logger.warning("SQL exception occurred: " + qe.getMessage());
if (protocol.getProxy().hasToHandleFailover(qe)) {
if (masterProtocol == null || masterProtocol.equals(protocol)) {
setMasterHostFail();
} else if (secondaryProtocol.equals(protocol)) {
setSecondaryHostFail();
}
addToBlacklist(protocol.getHostAddress());
reconnectFailedConnection(new SearchFilter(isMasterHostFail(), isSecondaryHostFail()));
}
}
return endpoints;
} } | public class class_name {
private List<String> getCurrentEndpointIdentifiers(Protocol protocol) throws SQLException {
List<String> endpoints = new ArrayList<>();
try {
proxy.lock.lock();
try {
// Deleted instance may remain in db for 24 hours so ignoring instances that have had no change
// for 3 minutes
Results results = new Results();
protocol.executeQuery(false, results,
"select server_id, session_id from information_schema.replica_host_status "
+ "where last_update_timestamp > now() - INTERVAL 3 MINUTE"); // depends on control dependency: [try], data = [none]
results.commandEnd(); // depends on control dependency: [try], data = [none]
ResultSet resultSet = results.getResultSet();
while (resultSet.next()) {
endpoints.add(resultSet.getString(1) + "." + clusterDnsSuffix); // depends on control dependency: [while], data = [none]
}
//randomize order for distributed load-balancing
Collections.shuffle(endpoints); // depends on control dependency: [try], data = [none]
} finally {
proxy.lock.unlock();
}
} catch (SQLException qe) {
logger.warning("SQL exception occurred: " + qe.getMessage());
if (protocol.getProxy().hasToHandleFailover(qe)) {
if (masterProtocol == null || masterProtocol.equals(protocol)) {
setMasterHostFail(); // depends on control dependency: [if], data = [none]
} else if (secondaryProtocol.equals(protocol)) {
setSecondaryHostFail(); // depends on control dependency: [if], data = [none]
}
addToBlacklist(protocol.getHostAddress()); // depends on control dependency: [if], data = [none]
reconnectFailedConnection(new SearchFilter(isMasterHostFail(), isSecondaryHostFail())); // depends on control dependency: [if], data = [none]
}
}
return endpoints;
} } |
public class class_name {
public static OptionHandler parseElement(final Element element,
final Properties props,
final Class expectedClass) throws Exception {
String clazz = subst(element.getAttribute("class"), props);
Object instance = OptionConverter.instantiateByClassName(clazz,
expectedClass, null);
if (instance instanceof OptionHandler) {
OptionHandler optionHandler = (OptionHandler) instance;
PropertySetter propSetter = new PropertySetter(optionHandler);
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if (tagName.equals("param")) {
setParameter(currentElement, propSetter, props);
} else {
parseUnrecognizedElement(instance, currentElement, props);
}
}
}
return optionHandler;
}
return null;
} } | public class class_name {
public static OptionHandler parseElement(final Element element,
final Properties props,
final Class expectedClass) throws Exception {
String clazz = subst(element.getAttribute("class"), props);
Object instance = OptionConverter.instantiateByClassName(clazz,
expectedClass, null);
if (instance instanceof OptionHandler) {
OptionHandler optionHandler = (OptionHandler) instance;
PropertySetter propSetter = new PropertySetter(optionHandler);
NodeList children = element.getChildNodes();
final int length = children.getLength();
for (int loop = 0; loop < length; loop++) {
Node currentNode = children.item(loop);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element currentElement = (Element) currentNode;
String tagName = currentElement.getTagName();
if (tagName.equals("param")) {
setParameter(currentElement, propSetter, props); // depends on control dependency: [if], data = [none]
} else {
parseUnrecognizedElement(instance, currentElement, props); // depends on control dependency: [if], data = [none]
}
}
}
return optionHandler;
}
return null;
} } |
public class class_name {
private void prepArticle(Element articleContent) {
cleanStyles(articleContent);
killBreaks(articleContent);
/* Clean out junk from the article content */
clean(articleContent, "form");
clean(articleContent, "object");
clean(articleContent, "h1");
/**
* If there is only one h2, they are probably using it as a header and
* not a subheader, so remove it since we already have a header.
*/
if (getElementsByTag(articleContent, "h2").size() == 1) {
clean(articleContent, "h2");
}
clean(articleContent, "iframe");
cleanHeaders(articleContent);
/*
* Do these last as the previous stuff may have removed junk that will
* affect these
*/
cleanConditionally(articleContent, "table");
cleanConditionally(articleContent, "ul");
cleanConditionally(articleContent, "div");
/* Remove extra paragraphs */
Elements articleParagraphs = getElementsByTag(articleContent, "p");
for (Element articleParagraph : articleParagraphs) {
int imgCount = getElementsByTag(articleParagraph, "img").size();
int embedCount = getElementsByTag(articleParagraph, "embed").size();
int objectCount = getElementsByTag(articleParagraph, "object")
.size();
if (imgCount == 0 && embedCount == 0 && objectCount == 0
&& isEmpty(getInnerText(articleParagraph, false))) {
articleParagraph.remove();
}
}
try {
articleContent.html(articleContent.html().replaceAll(
"(?i)<br[^>]*>\\s*<p", "<p"));
} catch (Exception e) {
dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.",
e);
}
} } | public class class_name {
private void prepArticle(Element articleContent) {
cleanStyles(articleContent);
killBreaks(articleContent);
/* Clean out junk from the article content */
clean(articleContent, "form");
clean(articleContent, "object");
clean(articleContent, "h1");
/**
* If there is only one h2, they are probably using it as a header and
* not a subheader, so remove it since we already have a header.
*/
if (getElementsByTag(articleContent, "h2").size() == 1) {
clean(articleContent, "h2"); // depends on control dependency: [if], data = [none]
}
clean(articleContent, "iframe");
cleanHeaders(articleContent);
/*
* Do these last as the previous stuff may have removed junk that will
* affect these
*/
cleanConditionally(articleContent, "table");
cleanConditionally(articleContent, "ul");
cleanConditionally(articleContent, "div");
/* Remove extra paragraphs */
Elements articleParagraphs = getElementsByTag(articleContent, "p");
for (Element articleParagraph : articleParagraphs) {
int imgCount = getElementsByTag(articleParagraph, "img").size();
int embedCount = getElementsByTag(articleParagraph, "embed").size();
int objectCount = getElementsByTag(articleParagraph, "object")
.size();
if (imgCount == 0 && embedCount == 0 && objectCount == 0
&& isEmpty(getInnerText(articleParagraph, false))) {
articleParagraph.remove(); // depends on control dependency: [if], data = [none]
}
}
try {
articleContent.html(articleContent.html().replaceAll(
"(?i)<br[^>]*>\\s*<p", "<p")); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.",
e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public CacheKeyTO getCacheKey(Object target, String methodName, Object[] arguments, String keyExpression,
String hfieldExpression, Object result, boolean hasRetVal) {
String key = null;
String hfield = null;
if (null != keyExpression && keyExpression.trim().length() > 0) {
try {
key = scriptParser.getDefinedCacheKey(keyExpression, target, arguments, result, hasRetVal);
if (null != hfieldExpression && hfieldExpression.trim().length() > 0) {
hfield = scriptParser.getDefinedCacheKey(hfieldExpression, target, arguments, result, hasRetVal);
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
} else {
key = CacheUtil.getDefaultCacheKey(target.getClass().getName(), methodName, arguments);
}
if (null == key || key.trim().isEmpty()) {
throw new IllegalArgumentException("cache key for " + target.getClass().getName() + "." + methodName + " is empty");
}
return new CacheKeyTO(config.getNamespace(), key, hfield);
} } | public class class_name {
public CacheKeyTO getCacheKey(Object target, String methodName, Object[] arguments, String keyExpression,
String hfieldExpression, Object result, boolean hasRetVal) {
String key = null;
String hfield = null;
if (null != keyExpression && keyExpression.trim().length() > 0) {
try {
key = scriptParser.getDefinedCacheKey(keyExpression, target, arguments, result, hasRetVal); // depends on control dependency: [try], data = [none]
if (null != hfieldExpression && hfieldExpression.trim().length() > 0) {
hfield = scriptParser.getDefinedCacheKey(hfieldExpression, target, arguments, result, hasRetVal); // depends on control dependency: [if], data = [none]
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
} // depends on control dependency: [catch], data = [none]
} else {
key = CacheUtil.getDefaultCacheKey(target.getClass().getName(), methodName, arguments); // depends on control dependency: [if], data = [none]
}
if (null == key || key.trim().isEmpty()) {
throw new IllegalArgumentException("cache key for " + target.getClass().getName() + "." + methodName + " is empty");
}
return new CacheKeyTO(config.getNamespace(), key, hfield);
} } |
public class class_name {
private static void debug(String header, HttpResponse response) {
if (logger.isTraceEnabled()) {
logger.trace(header);
logger.trace(response.toString());
}
} } | public class class_name {
private static void debug(String header, HttpResponse response) {
if (logger.isTraceEnabled()) {
logger.trace(header); // depends on control dependency: [if], data = [none]
logger.trace(response.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Terminal anyTerminal(RandEngine randEngine)
{
int variable_count = variableSet.size();
int constant_count = constantSet.size();
int r = randEngine.nextInt(variable_count + constant_count);
if (r < variable_count)
{
return (Terminal)variableSet.get(r);
}
else
{
return (Terminal)constantSet.get(r - variable_count);
}
} } | public class class_name {
public Terminal anyTerminal(RandEngine randEngine)
{
int variable_count = variableSet.size();
int constant_count = constantSet.size();
int r = randEngine.nextInt(variable_count + constant_count);
if (r < variable_count)
{
return (Terminal)variableSet.get(r); // depends on control dependency: [if], data = [(r]
}
else
{
return (Terminal)constantSet.get(r - variable_count); // depends on control dependency: [if], data = [(r]
}
} } |
public class class_name {
private byte[] pbkdf2(char[] password, byte[] salt) {
try {
PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw SeedException.wrap(e, CryptoErrorCode.UNEXPECTED_EXCEPTION);
}
} } | public class class_name {
private byte[] pbkdf2(char[] password, byte[] salt) {
try {
PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return skf.generateSecret(spec).getEncoded(); // depends on control dependency: [try], data = [none]
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw SeedException.wrap(e, CryptoErrorCode.UNEXPECTED_EXCEPTION);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String encodeBase64(final byte[] data, final boolean chunked) {
if (data != null && data.length > 0) {
if (chunked) {
return BASE64_CHUNKED_ENCODER.encodeToString(data).trim();
}
return BASE64_UNCHUNKED_ENCODER.encodeToString(data).trim();
}
return StringUtils.EMPTY;
} } | public class class_name {
public static String encodeBase64(final byte[] data, final boolean chunked) {
if (data != null && data.length > 0) {
if (chunked) {
return BASE64_CHUNKED_ENCODER.encodeToString(data).trim(); // depends on control dependency: [if], data = [none]
}
return BASE64_UNCHUNKED_ENCODER.encodeToString(data).trim(); // depends on control dependency: [if], data = [(data]
}
return StringUtils.EMPTY;
} } |
public class class_name {
@Override
protected void kNNdistanceAdjustment(MkMaxEntry entry, Map<DBID, KNNList> knnLists) {
MkMaxTreeNode<O> node = getNode(entry);
double knnDist_node = 0.;
if (node.isLeaf()) {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry leafEntry = node.getEntry(i);
leafEntry.setKnnDistance(knnLists.get(leafEntry.getRoutingObjectID()).getKNNDistance());
knnDist_node = Math.max(knnDist_node, leafEntry.getKnnDistance());
}
} else {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry dirEntry = node.getEntry(i);
kNNdistanceAdjustment(dirEntry, knnLists);
knnDist_node = Math.max(knnDist_node, dirEntry.getKnnDistance());
}
}
entry.setKnnDistance(knnDist_node);
} } | public class class_name {
@Override
protected void kNNdistanceAdjustment(MkMaxEntry entry, Map<DBID, KNNList> knnLists) {
MkMaxTreeNode<O> node = getNode(entry);
double knnDist_node = 0.;
if (node.isLeaf()) {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry leafEntry = node.getEntry(i);
leafEntry.setKnnDistance(knnLists.get(leafEntry.getRoutingObjectID()).getKNNDistance()); // depends on control dependency: [for], data = [none]
knnDist_node = Math.max(knnDist_node, leafEntry.getKnnDistance()); // depends on control dependency: [for], data = [none]
}
} else {
for (int i = 0; i < node.getNumEntries(); i++) {
MkMaxEntry dirEntry = node.getEntry(i);
kNNdistanceAdjustment(dirEntry, knnLists); // depends on control dependency: [for], data = [none]
knnDist_node = Math.max(knnDist_node, dirEntry.getKnnDistance()); // depends on control dependency: [for], data = [none]
}
}
entry.setKnnDistance(knnDist_node);
} } |
public class class_name {
public static String encodeBytesToString(byte bytes[]) {
StringBuilder string = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
// look up high nibble char
string.append(hexChar[(bytes[i] & 0xf0) >>> 4]);
// look up low nibble char
string.append(hexChar[bytes[i] & 0x0f]);
}
return string.toString();
} } | public class class_name {
public static String encodeBytesToString(byte bytes[]) {
StringBuilder string = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
// look up high nibble char
string.append(hexChar[(bytes[i] & 0xf0) >>> 4]);
// depends on control dependency: [for], data = [i]
// look up low nibble char
string.append(hexChar[bytes[i] & 0x0f]);
// depends on control dependency: [for], data = [i]
}
return string.toString();
} } |
public class class_name {
@Override
public void sawOpcode(int seen) {
try {
int blockCount = ifBlocks.countBlockEndsAtPC(getPC());
if (blockCount > 1) {
activeUnconditional = null;
} else if (blockCount == 1) {
lookingForResetOp = true;
}
if (!casePositions.isEmpty()) {
int firstCasePos = casePositions.nextSetBit(0);
if (firstCasePos == getPC()) {
casePositions.clear(firstCasePos);
activeUnconditional = null;
lookingForResetOp = false;
}
}
if (lookingForResetOp) {
if (isResetOp(seen)) {
lookingForResetOp = false;
} else {
return;
}
}
if (isBranch(seen)) {
if (activeUnconditional != null) {
activeUnconditional = null;
}
int target = getBranchTarget();
if (getBranchOffset() > 0) {
if ((seen == Const.GOTO) || (seen == Const.GOTO_W)) {
gotoBranchPCs.set(target);
} else if ((catchPCs == null) || !catchPCs.get(getNextPC())) {
ifBlocks.add(new IfBlock(getNextPC(), target));
}
} else {
ifBlocks.removeLoopBlocks(target);
}
} else if (isReturn(seen)) {
if ((activeUnconditional != null) && !gotoBranchPCs.get(activeUnconditional.getEnd())) {
int ifSize = activeUnconditional.getEnd() - activeUnconditional.getStart();
int elseSize = (getPC() - activeUnconditional.getEnd()) + 1; // +1 for the return itself
double ratio = (double) ifSize / (double) elseSize;
if (ratio > lowBugRatioLimit) {
bugReporter
.reportBug(new BugInstance(this, BugType.BL_BURYING_LOGIC.name(), ratio > normalBugRatioLimit ? NORMAL_PRIORITY : LOW_PRIORITY)
.addClass(this).addMethod(this).addSourceLineRange(this, activeUnconditional.getStart(), activeUnconditional.getEnd()));
throw new StopOpcodeParsingException();
}
activeUnconditional = null;
} else {
IfBlock blockAtPC = ifBlocks.getBlockAt(getPC());
if ((blockAtPC != null) && (getNextPC() == blockAtPC.getEnd()) && !gotoAcrossPC(getNextPC())) {
activeUnconditional = blockAtPC;
}
}
} else if ((seen == Const.TABLESWITCH) || (seen == Const.LOOKUPSWITCH)) {
int[] offsets = getSwitchOffsets();
int pc = getPC();
for (int offset : offsets) {
casePositions.set(pc + offset);
}
casePositions.set(pc + getDefaultSwitchOffset());
}
} finally {
stack.sawOpcode(this, seen);
}
} } | public class class_name {
@Override
public void sawOpcode(int seen) {
try {
int blockCount = ifBlocks.countBlockEndsAtPC(getPC());
if (blockCount > 1) {
activeUnconditional = null; // depends on control dependency: [if], data = [none]
} else if (blockCount == 1) {
lookingForResetOp = true; // depends on control dependency: [if], data = [none]
}
if (!casePositions.isEmpty()) {
int firstCasePos = casePositions.nextSetBit(0);
if (firstCasePos == getPC()) {
casePositions.clear(firstCasePos); // depends on control dependency: [if], data = [(firstCasePos]
activeUnconditional = null; // depends on control dependency: [if], data = [none]
lookingForResetOp = false; // depends on control dependency: [if], data = [none]
}
}
if (lookingForResetOp) {
if (isResetOp(seen)) {
lookingForResetOp = false; // depends on control dependency: [if], data = [none]
} else {
return; // depends on control dependency: [if], data = [none]
}
}
if (isBranch(seen)) {
if (activeUnconditional != null) {
activeUnconditional = null; // depends on control dependency: [if], data = [none]
}
int target = getBranchTarget();
if (getBranchOffset() > 0) {
if ((seen == Const.GOTO) || (seen == Const.GOTO_W)) {
gotoBranchPCs.set(target); // depends on control dependency: [if], data = [none]
} else if ((catchPCs == null) || !catchPCs.get(getNextPC())) {
ifBlocks.add(new IfBlock(getNextPC(), target)); // depends on control dependency: [if], data = [none]
}
} else {
ifBlocks.removeLoopBlocks(target); // depends on control dependency: [if], data = [none]
}
} else if (isReturn(seen)) {
if ((activeUnconditional != null) && !gotoBranchPCs.get(activeUnconditional.getEnd())) {
int ifSize = activeUnconditional.getEnd() - activeUnconditional.getStart();
int elseSize = (getPC() - activeUnconditional.getEnd()) + 1; // +1 for the return itself
double ratio = (double) ifSize / (double) elseSize;
if (ratio > lowBugRatioLimit) {
bugReporter
.reportBug(new BugInstance(this, BugType.BL_BURYING_LOGIC.name(), ratio > normalBugRatioLimit ? NORMAL_PRIORITY : LOW_PRIORITY)
.addClass(this).addMethod(this).addSourceLineRange(this, activeUnconditional.getStart(), activeUnconditional.getEnd())); // depends on control dependency: [if], data = [none]
throw new StopOpcodeParsingException();
}
activeUnconditional = null; // depends on control dependency: [if], data = [none]
} else {
IfBlock blockAtPC = ifBlocks.getBlockAt(getPC());
if ((blockAtPC != null) && (getNextPC() == blockAtPC.getEnd()) && !gotoAcrossPC(getNextPC())) {
activeUnconditional = blockAtPC; // depends on control dependency: [if], data = [none]
}
}
} else if ((seen == Const.TABLESWITCH) || (seen == Const.LOOKUPSWITCH)) {
int[] offsets = getSwitchOffsets();
int pc = getPC();
for (int offset : offsets) {
casePositions.set(pc + offset); // depends on control dependency: [for], data = [offset]
}
casePositions.set(pc + getDefaultSwitchOffset()); // depends on control dependency: [if], data = [none]
}
} finally {
stack.sawOpcode(this, seen);
}
} } |
public class class_name {
protected void printError(final Span references[], final Span predictions[],
final T referenceSample, final T predictedSample, final String sentence) {
final List<Span> falseNegatives = new ArrayList<Span>();
final List<Span> falsePositives = new ArrayList<Span>();
findErrors(references, predictions, falseNegatives, falsePositives);
if (falsePositives.size() + falseNegatives.size() > 0) {
printSamples(referenceSample, predictedSample);
printErrors(falsePositives, falseNegatives, sentence);
}
} } | public class class_name {
protected void printError(final Span references[], final Span predictions[],
final T referenceSample, final T predictedSample, final String sentence) {
final List<Span> falseNegatives = new ArrayList<Span>();
final List<Span> falsePositives = new ArrayList<Span>();
findErrors(references, predictions, falseNegatives, falsePositives);
if (falsePositives.size() + falseNegatives.size() > 0) {
printSamples(referenceSample, predictedSample); // depends on control dependency: [if], data = [none]
printErrors(falsePositives, falseNegatives, sentence); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} } | public class class_name {
public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null; // depends on control dependency: [if], data = [none]
}
else
{
setClaims(Utils.toJson(claims)); // depends on control dependency: [if], data = [(claims]
}
return this;
} } |
public class class_name {
private boolean processRaidEncodingTask(RaidBlockInfo rbi) {
ArrayList<ArrayList<DatanodeInfo>> stripeDatanodes =
new ArrayList<ArrayList<DatanodeInfo>>();
BlockInfo[] stripeBlocks = null;
RaidCodec codec = null;
StringBuilder sb = new StringBuilder();
StringBuilder dnSb = new StringBuilder();
readLock();
try {
INodeFile inode = blocksMap.getINode(rbi);
if (inode == null) {
return false; // file has been deleted already, nothing to do.
}
if (inode.getStorageType() != StorageType.RAID_STORAGE) {
LOG.error("File for block " + rbi + " is not raidable");
return false;
}
INodeRaidStorage storage = (INodeRaidStorage)inode.getStorage();
codec = storage.getCodec();
// Find out related blocks
stripeBlocks = codec.getBlocksInOneStripe(
inode.getBlocks(), rbi);
// Find out datanode locations
for (int i = 0; i < stripeBlocks.length; i++) {
ArrayList<DatanodeInfo> liveNodes =
new ArrayList<DatanodeInfo>();
stripeDatanodes.add(liveNodes);
Collection<DatanodeDescriptor> nodesCorrupt =
corruptReplicas.getNodes(stripeBlocks[i]);
StringBuilder dn = new StringBuilder();
dn.append("[");
for (Iterator<DatanodeDescriptor> it =
blocksMap.nodeIterator(stripeBlocks[i]);
it.hasNext();) {
DatanodeDescriptor node = it.next();
if (nodesCorrupt != null && nodesCorrupt.contains(node)) {
// do nothing
} else {
liveNodes.add(node);
dn.append(node);
dn.append(" ");
}
}
dn.append("]");
if (i >= codec.numParityBlocks && liveNodes.size() == 0) {
LOG.error("File for block " + rbi +
" is not raidable, not all source blocks have replicas");
return true;
}
sb.append(stripeBlocks[i]);
sb.append(" ");
dnSb.append(dn.toString());
dnSb.append(" ");
}
} finally {
readUnlock();
}
DatanodeDescriptor scheduleNode = null;
int[] toRaidIdxs = new int[codec.numParityBlocks];
// Randomly pick datanodes first
for (int i = 0; i < codec.numParityBlocks; i++) {
toRaidIdxs[i] = i;
int size = stripeDatanodes.get(i).size();
stripeDatanodes.get(i).clear();
if (size < codec.parityReplication) {
// If not enough replicas, assign targets left
for (int j = 0; j < codec.parityReplication - size; j++) {
stripeDatanodes.get(i).add(getRandomDatanode());
}
if (scheduleNode == null) {
scheduleNode = (DatanodeDescriptor)stripeDatanodes.get(i).get(0);
}
}
}
// Assign raiding task to scheduledNode
if (scheduleNode == null) {
// All parity blocks are generated, no need to raid
return false;
}
RaidTask rt = new RaidTask(codec, stripeBlocks, stripeDatanodes, toRaidIdxs);
writeLock();
try {
scheduleNode.addRaidEncodingTask(rt);
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("Stripe* NameSystem: Blocks " + sb.toString()
+ " Datanodes: " + dnSb.toString()
+ " are added to raidEncodingTasks of" + scheduleNode);
}
return false;
} finally {
writeUnlock();
}
} } | public class class_name {
private boolean processRaidEncodingTask(RaidBlockInfo rbi) {
ArrayList<ArrayList<DatanodeInfo>> stripeDatanodes =
new ArrayList<ArrayList<DatanodeInfo>>();
BlockInfo[] stripeBlocks = null;
RaidCodec codec = null;
StringBuilder sb = new StringBuilder();
StringBuilder dnSb = new StringBuilder();
readLock();
try {
INodeFile inode = blocksMap.getINode(rbi);
if (inode == null) {
return false; // file has been deleted already, nothing to do. // depends on control dependency: [if], data = [none]
}
if (inode.getStorageType() != StorageType.RAID_STORAGE) {
LOG.error("File for block " + rbi + " is not raidable"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
INodeRaidStorage storage = (INodeRaidStorage)inode.getStorage();
codec = storage.getCodec(); // depends on control dependency: [try], data = [none]
// Find out related blocks
stripeBlocks = codec.getBlocksInOneStripe(
inode.getBlocks(), rbi); // depends on control dependency: [try], data = [none]
// Find out datanode locations
for (int i = 0; i < stripeBlocks.length; i++) {
ArrayList<DatanodeInfo> liveNodes =
new ArrayList<DatanodeInfo>();
stripeDatanodes.add(liveNodes); // depends on control dependency: [for], data = [none]
Collection<DatanodeDescriptor> nodesCorrupt =
corruptReplicas.getNodes(stripeBlocks[i]);
StringBuilder dn = new StringBuilder();
dn.append("["); // depends on control dependency: [for], data = [none]
for (Iterator<DatanodeDescriptor> it =
blocksMap.nodeIterator(stripeBlocks[i]);
it.hasNext();) {
DatanodeDescriptor node = it.next();
if (nodesCorrupt != null && nodesCorrupt.contains(node)) {
// do nothing
} else {
liveNodes.add(node); // depends on control dependency: [if], data = [none]
dn.append(node); // depends on control dependency: [if], data = [none]
dn.append(" "); // depends on control dependency: [if], data = [none]
}
}
dn.append("]"); // depends on control dependency: [for], data = [none]
if (i >= codec.numParityBlocks && liveNodes.size() == 0) {
LOG.error("File for block " + rbi +
" is not raidable, not all source blocks have replicas"); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
sb.append(stripeBlocks[i]); // depends on control dependency: [for], data = [i]
sb.append(" "); // depends on control dependency: [for], data = [none]
dnSb.append(dn.toString()); // depends on control dependency: [for], data = [none]
dnSb.append(" "); // depends on control dependency: [for], data = [none]
}
} finally {
readUnlock();
}
DatanodeDescriptor scheduleNode = null;
int[] toRaidIdxs = new int[codec.numParityBlocks];
// Randomly pick datanodes first
for (int i = 0; i < codec.numParityBlocks; i++) {
toRaidIdxs[i] = i; // depends on control dependency: [for], data = [i]
int size = stripeDatanodes.get(i).size();
stripeDatanodes.get(i).clear(); // depends on control dependency: [for], data = [i]
if (size < codec.parityReplication) {
// If not enough replicas, assign targets left
for (int j = 0; j < codec.parityReplication - size; j++) {
stripeDatanodes.get(i).add(getRandomDatanode()); // depends on control dependency: [for], data = [none]
}
if (scheduleNode == null) {
scheduleNode = (DatanodeDescriptor)stripeDatanodes.get(i).get(0); // depends on control dependency: [if], data = [none]
}
}
}
// Assign raiding task to scheduledNode
if (scheduleNode == null) {
// All parity blocks are generated, no need to raid
return false; // depends on control dependency: [if], data = [none]
}
RaidTask rt = new RaidTask(codec, stripeBlocks, stripeDatanodes, toRaidIdxs);
writeLock();
try {
scheduleNode.addRaidEncodingTask(rt); // depends on control dependency: [try], data = [none]
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("Stripe* NameSystem: Blocks " + sb.toString()
+ " Datanodes: " + dnSb.toString()
+ " are added to raidEncodingTasks of" + scheduleNode); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [try], data = [none]
} finally {
writeUnlock();
}
} } |
public class class_name {
private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
if (rect.bottom - rect.top - mEventPadding * 2 < 0) return;
// Prepare the name of the event.
SpannableStringBuilder bob = new SpannableStringBuilder();
if (event.getName() != null) {
bob.append(event.getName());
bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, bob.length(), 0);
bob.append(' ');
}
// Prepare the location of the event.
if (event.getLocation() != null) {
bob.append(event.getLocation());
}
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int availableWidth = (int) (rect.right - originalLeft - mEventPadding * 2);
// Get text dimensions.
StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (availableHeight >= lineHeight) {
// Calculate available number of line counts.
int availableLineCount = availableHeight / lineHeight;
do {
// Ellipsize text to fit into event rect.
textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, availableLineCount * availableWidth, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Reduce line count.
availableLineCount--;
// Repeat until text is short enough.
} while (textLayout.getHeight() > availableHeight);
// Draw text.
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
} } | public class class_name {
private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
if (rect.bottom - rect.top - mEventPadding * 2 < 0) return;
// Prepare the name of the event.
SpannableStringBuilder bob = new SpannableStringBuilder();
if (event.getName() != null) {
bob.append(event.getName()); // depends on control dependency: [if], data = [(event.getName()]
bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, bob.length(), 0); // depends on control dependency: [if], data = [none]
bob.append(' '); // depends on control dependency: [if], data = [none]
}
// Prepare the location of the event.
if (event.getLocation() != null) {
bob.append(event.getLocation()); // depends on control dependency: [if], data = [(event.getLocation()]
}
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int availableWidth = (int) (rect.right - originalLeft - mEventPadding * 2);
// Get text dimensions.
StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, availableWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (availableHeight >= lineHeight) {
// Calculate available number of line counts.
int availableLineCount = availableHeight / lineHeight;
do {
// Ellipsize text to fit into event rect.
textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, availableLineCount * availableWidth, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Reduce line count.
availableLineCount--;
// Repeat until text is short enough.
} while (textLayout.getHeight() > availableHeight);
// Draw text.
canvas.save(); // depends on control dependency: [if], data = [none]
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding); // depends on control dependency: [if], data = [none]
textLayout.draw(canvas); // depends on control dependency: [if], data = [none]
canvas.restore(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public final void visitOpenDynamic(){
if (!isDynamic)
throw new IllegalStateException("Wrong use of dynamic() in a static view!");
openDynamic = true;
if (isCached){
HtmlVisitorStringBuilder.HtmlBlockInfo block = cacheBlocksList.get(cacheIndex);
this.write(block.html);
this.depth = block.currentDepth;
this.isClosed = block.isClosed;
++cacheIndex;
} else {
String staticBlock = substring(staticBlockIndex);
cacheBlocksList.add(new HtmlVisitorStringBuilder.HtmlBlockInfo(staticBlock, depth, isClosed));
}
} } | public class class_name {
@Override
public final void visitOpenDynamic(){
if (!isDynamic)
throw new IllegalStateException("Wrong use of dynamic() in a static view!");
openDynamic = true;
if (isCached){
HtmlVisitorStringBuilder.HtmlBlockInfo block = cacheBlocksList.get(cacheIndex);
this.write(block.html); // depends on control dependency: [if], data = [none]
this.depth = block.currentDepth; // depends on control dependency: [if], data = [none]
this.isClosed = block.isClosed; // depends on control dependency: [if], data = [none]
++cacheIndex; // depends on control dependency: [if], data = [none]
} else {
String staticBlock = substring(staticBlockIndex);
cacheBlocksList.add(new HtmlVisitorStringBuilder.HtmlBlockInfo(staticBlock, depth, isClosed)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Method findGetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)
throws IllegalArgumentException {
Method fieldGetMethod = findMethodFromNames(field, true, throwExceptions,
methodFromField(field, "get", databaseType, true), methodFromField(field, "get", databaseType, false),
methodFromField(field, "is", databaseType, true), methodFromField(field, "is", databaseType, false));
if (fieldGetMethod == null) {
return null;
}
if (fieldGetMethod.getReturnType() != field.getType()) {
if (throwExceptions) {
throw new IllegalArgumentException("Return type of get method " + fieldGetMethod.getName()
+ " does not return " + field.getType());
} else {
return null;
}
}
return fieldGetMethod;
} } | public class class_name {
public static Method findGetMethod(Field field, DatabaseType databaseType, boolean throwExceptions)
throws IllegalArgumentException {
Method fieldGetMethod = findMethodFromNames(field, true, throwExceptions,
methodFromField(field, "get", databaseType, true), methodFromField(field, "get", databaseType, false),
methodFromField(field, "is", databaseType, true), methodFromField(field, "is", databaseType, false));
if (fieldGetMethod == null) {
return null;
}
if (fieldGetMethod.getReturnType() != field.getType()) {
if (throwExceptions) {
throw new IllegalArgumentException("Return type of get method " + fieldGetMethod.getName()
+ " does not return " + field.getType());
} else {
return null; // depends on control dependency: [if], data = [none]
}
}
return fieldGetMethod;
} } |
public class class_name {
public void search(
String theTopic,
MatchSpaceKey msg,
EvalCache cache,
MessageProcessorSearchResults searchResults)
throws BadMessageFormatMatchingException,
MatchingException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"search",
new Object[] { theTopic, msg, cache, searchResults });
// If security is switched on then we need to maintain the integrity of
// the ACLs in the cache in the face of dynamic updating
if(_isBusSecure)
{
int aclVersion = _messageProcessor.
getDiscriminatorAccessChecker().
getAclRefreshVersion();
boolean searchAgain = true;
//Retrieve the searchresults from the matchspace
while(searchAgain)
{
_matchSpace.search(theTopic, // keyed on destination name
msg, cache, searchResults);
// We need to be sure of the integrity of the traversal
int newAclVersion = _messageProcessor.
getDiscriminatorAccessChecker().
getAclRefreshVersion();
// This should catch those rare cases where a traversal overlapped
// a refresh.
if(newAclVersion == aclVersion)
searchAgain = false;
else
aclVersion = newAclVersion;
}
}
else
{
_matchSpace.search(theTopic, // keyed on destination name
msg, cache, searchResults);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "search");
} } | public class class_name {
public void search(
String theTopic,
MatchSpaceKey msg,
EvalCache cache,
MessageProcessorSearchResults searchResults)
throws BadMessageFormatMatchingException,
MatchingException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"search",
new Object[] { theTopic, msg, cache, searchResults });
// If security is switched on then we need to maintain the integrity of
// the ACLs in the cache in the face of dynamic updating
if(_isBusSecure)
{
int aclVersion = _messageProcessor.
getDiscriminatorAccessChecker().
getAclRefreshVersion();
boolean searchAgain = true;
//Retrieve the searchresults from the matchspace
while(searchAgain)
{
_matchSpace.search(theTopic, // keyed on destination name
msg, cache, searchResults); // depends on control dependency: [while], data = [none]
// We need to be sure of the integrity of the traversal
int newAclVersion = _messageProcessor.
getDiscriminatorAccessChecker().
getAclRefreshVersion();
// This should catch those rare cases where a traversal overlapped
// a refresh.
if(newAclVersion == aclVersion)
searchAgain = false;
else
aclVersion = newAclVersion;
}
}
else
{
_matchSpace.search(theTopic, // keyed on destination name
msg, cache, searchResults); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "search");
} } |
public class class_name {
public static byte booleansToByte(boolean[] array) {
if (array != null && array.length > 0) {
byte b = 0;
for (int i = 0; i <= 7; i++) {
if (array[i]) {
int nn = (1 << (7 - i));
b += nn;
}
}
return b;
}
return 0;
} } | public class class_name {
public static byte booleansToByte(boolean[] array) {
if (array != null && array.length > 0) {
byte b = 0;
for (int i = 0; i <= 7; i++) {
if (array[i]) {
int nn = (1 << (7 - i));
b += nn; // depends on control dependency: [if], data = [none]
}
}
return b; // depends on control dependency: [if], data = [none]
}
return 0;
} } |
public class class_name {
public void marshall(DeleteCertificateRequest deleteCertificateRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteCertificateRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteCertificateRequest.getCertificateArn(), CERTIFICATEARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteCertificateRequest deleteCertificateRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteCertificateRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteCertificateRequest.getCertificateArn(), CERTIFICATEARN_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 void writeString(String string) {
writeAMF3();
buf.put(AMF3.TYPE_STRING);
if ("".equals(string)) {
putInteger(1);
} else {
final byte[] encoded = encodeString(string);
putString(string, encoded);
}
} } | public class class_name {
@Override
public void writeString(String string) {
writeAMF3();
buf.put(AMF3.TYPE_STRING);
if ("".equals(string)) {
putInteger(1);
// depends on control dependency: [if], data = [none]
} else {
final byte[] encoded = encodeString(string);
putString(string, encoded);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(StartRemediationExecutionRequest startRemediationExecutionRequest, ProtocolMarshaller protocolMarshaller) {
if (startRemediationExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startRemediationExecutionRequest.getConfigRuleName(), CONFIGRULENAME_BINDING);
protocolMarshaller.marshall(startRemediationExecutionRequest.getResourceKeys(), RESOURCEKEYS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StartRemediationExecutionRequest startRemediationExecutionRequest, ProtocolMarshaller protocolMarshaller) {
if (startRemediationExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startRemediationExecutionRequest.getConfigRuleName(), CONFIGRULENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startRemediationExecutionRequest.getResourceKeys(), RESOURCEKEYS_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]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.