code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public static JobID forName(String str) throws IllegalArgumentException {
if(str == null)
return null;
try {
String[] parts = str.split("_");
if(parts.length == 3) {
if(parts[0].equals(JOB)) {
return new org.apache.hadoop.mapred.JobID(parts[1],
Integer.parseInt(parts[2]));
}
}
}catch (Exception ex) {//fall below
}
throw new IllegalArgumentException("JobId string : " + str
+ " is not properly formed");
} }
|
public class class_name {
public static JobID forName(String str) throws IllegalArgumentException {
if(str == null)
return null;
try {
String[] parts = str.split("_");
if(parts.length == 3) {
if(parts[0].equals(JOB)) {
return new org.apache.hadoop.mapred.JobID(parts[1],
Integer.parseInt(parts[2])); // depends on control dependency: [if], data = [none]
}
}
}catch (Exception ex) {//fall below
}
throw new IllegalArgumentException("JobId string : " + str
+ " is not properly formed");
} }
|
public class class_name {
public boolean append(Lexeme l , int lexemeType){
if(l != null && this.getEndPosition() == l.getBeginPosition()){
this.length += l.getLength();
this.lexemeType = lexemeType;
return true;
}else {
return false;
}
} }
|
public class class_name {
public boolean append(Lexeme l , int lexemeType){
if(l != null && this.getEndPosition() == l.getBeginPosition()){
this.length += l.getLength();
// depends on control dependency: [if], data = [none]
this.lexemeType = lexemeType;
// depends on control dependency: [if], data = [none]
return true;
// depends on control dependency: [if], data = [none]
}else {
return false;
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static byte[] toByteArray(File file) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readFile(in, in.getChannel().size());
} finally {
if (in != null) {
in.close();
}
}
} }
|
public class class_name {
public static byte[] toByteArray(File file) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(file);
return readFile(in, in.getChannel().size());
} finally {
if (in != null) {
in.close(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
protected String getOrigin(Principal principal) {
if (principal instanceof Authentication) {
Authentication caller = (Authentication) principal;
StringBuilder builder = new StringBuilder();
if (caller instanceof OAuth2Authentication) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller;
builder.append("client=").append(oAuth2Authentication.getOAuth2Request().getClientId());
if (!oAuth2Authentication.isClientOnly()) {
builder.append(", ").append("user=").append(oAuth2Authentication.getName());
}
}
else {
builder.append("caller=").append(caller.getName());
}
if (caller.getDetails() != null) {
builder.append(", details=(");
try {
@SuppressWarnings("unchecked")
Map<String, Object> map =
JsonUtils.readValue((String)caller.getDetails(), new TypeReference<Map<String,Object>>(){});
if (map.containsKey("remoteAddress")) {
builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", ");
}
builder.append("type=").append(caller.getDetails().getClass().getSimpleName());
} catch (Exception e) {
// ignore
builder.append(caller.getDetails());
}
appendTokenDetails(caller, builder);
builder.append(")");
}
return builder.toString();
}
return principal == null ? null : principal.getName();
} }
|
public class class_name {
protected String getOrigin(Principal principal) {
if (principal instanceof Authentication) {
Authentication caller = (Authentication) principal;
StringBuilder builder = new StringBuilder();
if (caller instanceof OAuth2Authentication) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller;
builder.append("client=").append(oAuth2Authentication.getOAuth2Request().getClientId()); // depends on control dependency: [if], data = [none]
if (!oAuth2Authentication.isClientOnly()) {
builder.append(", ").append("user=").append(oAuth2Authentication.getName()); // depends on control dependency: [if], data = [none]
}
}
else {
builder.append("caller=").append(caller.getName()); // depends on control dependency: [if], data = [none]
}
if (caller.getDetails() != null) {
builder.append(", details=("); // depends on control dependency: [if], data = [none]
try {
@SuppressWarnings("unchecked")
Map<String, Object> map =
JsonUtils.readValue((String)caller.getDetails(), new TypeReference<Map<String,Object>>(){});
if (map.containsKey("remoteAddress")) {
builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", "); // depends on control dependency: [if], data = [none]
}
builder.append("type=").append(caller.getDetails().getClass().getSimpleName()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// ignore
builder.append(caller.getDetails());
} // depends on control dependency: [catch], data = [none]
appendTokenDetails(caller, builder); // depends on control dependency: [if], data = [none]
builder.append(")"); // depends on control dependency: [if], data = [none]
}
return builder.toString(); // depends on control dependency: [if], data = [none]
}
return principal == null ? null : principal.getName();
} }
|
public class class_name {
public static INDArray gt(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null) {
Preconditions.checkArgument(Arrays.equals(x.shape(),y.shape()),getFormattedShapeErrorMessageXy(x,y));
Preconditions.checkArgument(Arrays.equals(x.shape(),z.shape()),getFormattedShapeErrorMessageXResult(x,z));
return Nd4j.getExecutioner().execAndReturn(new OldGreaterThan(x,y,z,x.length()));
}
return Nd4j.getExecutioner().execAndReturn(new BroadcastGreaterThan(x,y,z,dimensions));
} }
|
public class class_name {
public static INDArray gt(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null) {
Preconditions.checkArgument(Arrays.equals(x.shape(),y.shape()),getFormattedShapeErrorMessageXy(x,y)); // depends on control dependency: [if], data = [none]
Preconditions.checkArgument(Arrays.equals(x.shape(),z.shape()),getFormattedShapeErrorMessageXResult(x,z)); // depends on control dependency: [if], data = [none]
return Nd4j.getExecutioner().execAndReturn(new OldGreaterThan(x,y,z,x.length())); // depends on control dependency: [if], data = [none]
}
return Nd4j.getExecutioner().execAndReturn(new BroadcastGreaterThan(x,y,z,dimensions));
} }
|
public class class_name {
private TransactionManager getTransactionManager()
{
TransactionManager retval = null;
try
{
if (log.isDebugEnabled()) log.debug("getTransactionManager called");
retval = TransactionManagerFactoryFactory.instance().getTransactionManager();
}
catch (TransactionManagerFactoryException e)
{
log.warn("Exception trying to obtain TransactionManager from Factory", e);
e.printStackTrace();
}
return retval;
} }
|
public class class_name {
private TransactionManager getTransactionManager()
{
TransactionManager retval = null;
try
{
if (log.isDebugEnabled()) log.debug("getTransactionManager called");
retval = TransactionManagerFactoryFactory.instance().getTransactionManager();
// depends on control dependency: [try], data = [none]
}
catch (TransactionManagerFactoryException e)
{
log.warn("Exception trying to obtain TransactionManager from Factory", e);
e.printStackTrace();
}
// depends on control dependency: [catch], data = [none]
return retval;
} }
|
public class class_name {
protected void valueChanged()
{
String newValue = fViewer.getDocument().get();
if (!newValue.equals(fOldValue))
{
fOldValue = newValue;
}
refreshValidState();
} }
|
public class class_name {
protected void valueChanged()
{
String newValue = fViewer.getDocument().get();
if (!newValue.equals(fOldValue))
{
fOldValue = newValue; // depends on control dependency: [if], data = [none]
}
refreshValidState();
} }
|
public class class_name {
private void putProperties(Database database) throws DevFailed {
for (TangoClass clazz : classes) {
clazz.putProperties(database);
clazz.putAttributeProperties(database);
clazz.putPipeProperties(database);
for (TangoDevice device : clazz) {
device.putProperties(database);
device.putAttributeProperties(database);
device.putPipeProperties(database);
}
}
} }
|
public class class_name {
private void putProperties(Database database) throws DevFailed {
for (TangoClass clazz : classes) {
clazz.putProperties(database);
clazz.putAttributeProperties(database);
clazz.putPipeProperties(database);
for (TangoDevice device : clazz) {
device.putProperties(database); // depends on control dependency: [for], data = [device]
device.putAttributeProperties(database); // depends on control dependency: [for], data = [device]
device.putPipeProperties(database); // depends on control dependency: [for], data = [device]
}
}
} }
|
public class class_name {
public CalendarMonth plus(Years<CalendarUnit> years) {
if (years.isEmpty()) {
return this;
}
return CalendarMonth.of(MathUtils.safeAdd(this.year, years.getAmount()), this.month);
} }
|
public class class_name {
public CalendarMonth plus(Years<CalendarUnit> years) {
if (years.isEmpty()) {
return this; // depends on control dependency: [if], data = [none]
}
return CalendarMonth.of(MathUtils.safeAdd(this.year, years.getAmount()), this.month);
} }
|
public class class_name {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
if (navigation != null) {
navigation.addProgressChangeListener(progressChangeListener);
}
} }
|
public class class_name {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
if (navigation != null) {
navigation.addProgressChangeListener(progressChangeListener); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void marshall(BatchGetQueryExecutionRequest batchGetQueryExecutionRequest, ProtocolMarshaller protocolMarshaller) {
if (batchGetQueryExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchGetQueryExecutionRequest.getQueryExecutionIds(), QUERYEXECUTIONIDS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(BatchGetQueryExecutionRequest batchGetQueryExecutionRequest, ProtocolMarshaller protocolMarshaller) {
if (batchGetQueryExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchGetQueryExecutionRequest.getQueryExecutionIds(), QUERYEXECUTIONIDS_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 {
static public BigDecimal sin(final BigDecimal x) {
if (x.compareTo(BigDecimal.ZERO) < 0) {
return sin(x.negate()).negate();
} else if (x.compareTo(BigDecimal.ZERO) == 0) {
return BigDecimal.ZERO;
} else {
/* reduce modulo 2pi
*/
BigDecimal res = mod2pi(x);
double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
int val = 2 + err2prec(FastMath.PI, errpi);
MathContext mc = new MathContext(val);
BigDecimal p = pi(mc);
mc = new MathContext(x.precision());
if (res.compareTo(p) > 0) {
/* pi<x<=2pi: sin(x)= - sin(x-pi)
*/
return sin(subtractRound(res, p)).negate();
} else if (res.multiply(new BigDecimal(2)).compareTo(p) > 0) {
/* pi/2<x<=pi: sin(x)= sin(pi-x)
*/
return sin(subtractRound(p, res));
} else {
/* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x)
* to split this further. Here, use the sine up to pi/4 and the cosine higher up.
*/
if (res.multiply(new BigDecimal(4)).compareTo(p) > 0) {
/* x>pi/4: sin(x) = cos(pi/2-x)
*/
return cos(subtractRound(p.divide(new BigDecimal(2)), res));
} else {
/* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */
BigDecimal resul = res;
/* x^i */
BigDecimal xpowi = res;
/* 2i+1 factorial */
BigInteger ifac = BigInteger.ONE;
/* The error in the result is set by the error in x itself.
*/
double xUlpDbl = res.ulp().doubleValue();
/* The error in the result is set by the error in x itself.
* We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
* x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
* 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
*/
int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2;
MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k));
for (int i = 1;; i++) {
/* TBD: at which precision will 2*i or 2*i+1 overflow?
*/
ifac = ifac.multiply(BigInteger.valueOf(2 * i));
ifac = ifac.multiply(BigInteger.valueOf(2 * i + 1));
xpowi = xpowi.multiply(res).multiply(res).negate();
BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
resul = resul.add(corr);
if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
break;
}
}
/* The error in the result is set by the error in x itself.
*/
mc = new MathContext(res.precision());
return resul.round(mc);
}
}
} /* sin */
} }
|
public class class_name {
static public BigDecimal sin(final BigDecimal x) {
if (x.compareTo(BigDecimal.ZERO) < 0) {
return sin(x.negate()).negate(); // depends on control dependency: [if], data = [none]
} else if (x.compareTo(BigDecimal.ZERO) == 0) {
return BigDecimal.ZERO; // depends on control dependency: [if], data = [none]
} else {
/* reduce modulo 2pi
*/
BigDecimal res = mod2pi(x);
double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
int val = 2 + err2prec(FastMath.PI, errpi);
MathContext mc = new MathContext(val);
BigDecimal p = pi(mc);
mc = new MathContext(x.precision()); // depends on control dependency: [if], data = [none]
if (res.compareTo(p) > 0) {
/* pi<x<=2pi: sin(x)= - sin(x-pi)
*/
return sin(subtractRound(res, p)).negate(); // depends on control dependency: [if], data = [none]
} else if (res.multiply(new BigDecimal(2)).compareTo(p) > 0) {
/* pi/2<x<=pi: sin(x)= sin(pi-x)
*/
return sin(subtractRound(p, res)); // depends on control dependency: [if], data = [none]
} else {
/* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x)
* to split this further. Here, use the sine up to pi/4 and the cosine higher up.
*/
if (res.multiply(new BigDecimal(4)).compareTo(p) > 0) {
/* x>pi/4: sin(x) = cos(pi/2-x)
*/
return cos(subtractRound(p.divide(new BigDecimal(2)), res)); // depends on control dependency: [if], data = [none]
} else {
/* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */
BigDecimal resul = res;
/* x^i */
BigDecimal xpowi = res;
/* 2i+1 factorial */
BigInteger ifac = BigInteger.ONE;
/* The error in the result is set by the error in x itself.
*/
double xUlpDbl = res.ulp().doubleValue();
/* The error in the result is set by the error in x itself.
* We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
* x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
* 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
*/
int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2;
MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k));
for (int i = 1;; i++) {
/* TBD: at which precision will 2*i or 2*i+1 overflow?
*/
ifac = ifac.multiply(BigInteger.valueOf(2 * i)); // depends on control dependency: [for], data = [i]
ifac = ifac.multiply(BigInteger.valueOf(2 * i + 1)); // depends on control dependency: [for], data = [i]
xpowi = xpowi.multiply(res).multiply(res).negate(); // depends on control dependency: [for], data = [none]
BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
resul = resul.add(corr); // depends on control dependency: [for], data = [none]
if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
break;
}
}
/* The error in the result is set by the error in x itself.
*/
mc = new MathContext(res.precision()); // depends on control dependency: [if], data = [none]
return resul.round(mc); // depends on control dependency: [if], data = [none]
}
}
} /* sin */
} }
|
public class class_name {
public boolean isAllowedCachedRight(final ContextEntry[] context,
final Tuple tuple) {
for (int i = indexed; i < constraints.length; i++) {
if ( !constraints[i].isAllowedCachedRight(tuple, context[i]) ) {
return false;
}
}
return true;
} }
|
public class class_name {
public boolean isAllowedCachedRight(final ContextEntry[] context,
final Tuple tuple) {
for (int i = indexed; i < constraints.length; i++) {
if ( !constraints[i].isAllowedCachedRight(tuple, context[i]) ) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} }
|
public class class_name {
public static void prepareSplits(final String url, final int nFolds, final String inFile, final String folder, final String outPath) {
DataDownloader dd = new DataDownloader(url, folder);
dd.downloadAndUnzip();
boolean perUser = true;
long seed = SEED;
Parser<Long, Long> parser = new MovielensParser();
DataModelIF<Long, Long> data = null;
try {
data = parser.parseData(new File(inFile));
} catch (IOException e) {
e.printStackTrace();
}
new IterativeCrossValidationSplitter<Long, Long>(nFolds, perUser, seed, outPath).split(data);
File dir = new File(outPath);
if (!dir.exists()) {
if (!dir.mkdir()) {
System.err.println("Directory " + dir + " could not be created");
return;
}
}
} }
|
public class class_name {
public static void prepareSplits(final String url, final int nFolds, final String inFile, final String folder, final String outPath) {
DataDownloader dd = new DataDownloader(url, folder);
dd.downloadAndUnzip();
boolean perUser = true;
long seed = SEED;
Parser<Long, Long> parser = new MovielensParser();
DataModelIF<Long, Long> data = null;
try {
data = parser.parseData(new File(inFile)); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
new IterativeCrossValidationSplitter<Long, Long>(nFolds, perUser, seed, outPath).split(data);
File dir = new File(outPath);
if (!dir.exists()) {
if (!dir.mkdir()) {
System.err.println("Directory " + dir + " could not be created"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public boolean equal(final Object o1,
final Object o2) {
if ( o1 instanceof InternalFactHandle ) {
return ((InternalFactHandle) o1).getId() == ((InternalFactHandle) o2).getId();
}
Object left = o1;
final InternalFactHandle handle = ((InternalFactHandle) o2);
if ( left == handle.getObject() ) {
return true;
} else if ( handle.getTraitType() == TraitTypeEnum.WRAPPED_TRAITABLE ) {
return left == ( (CoreWrapper) handle.getObject() ).getCore();
} else {
return false;
}
} }
|
public class class_name {
public boolean equal(final Object o1,
final Object o2) {
if ( o1 instanceof InternalFactHandle ) {
return ((InternalFactHandle) o1).getId() == ((InternalFactHandle) o2).getId(); // depends on control dependency: [if], data = [none]
}
Object left = o1;
final InternalFactHandle handle = ((InternalFactHandle) o2);
if ( left == handle.getObject() ) {
return true; // depends on control dependency: [if], data = [none]
} else if ( handle.getTraitType() == TraitTypeEnum.WRAPPED_TRAITABLE ) {
return left == ( (CoreWrapper) handle.getObject() ).getCore(); // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private void overrideFromEnvironmentVariables() {
String url = System.getenv("ACTIVEJDBC.URL");
String user = System.getenv("ACTIVEJDBC.USER");
String password = System.getenv("ACTIVEJDBC.PASSWORD");
String driver = System.getenv("ACTIVEJDBC.DRIVER");
if(!blank(url) && !blank(user) && !blank(password) && !blank(driver)){
connectionSpecMap.put(getEnvironment(), new ConnectionJdbcSpec(driver, url, user, password));
}
String jndi = System.getenv("ACTIVEJDBC.JNDI");
if(!blank(jndi)){
connectionSpecMap.put(getEnvironment(), new ConnectionJndiSpec(jndi));
}
} }
|
public class class_name {
private void overrideFromEnvironmentVariables() {
String url = System.getenv("ACTIVEJDBC.URL");
String user = System.getenv("ACTIVEJDBC.USER");
String password = System.getenv("ACTIVEJDBC.PASSWORD");
String driver = System.getenv("ACTIVEJDBC.DRIVER");
if(!blank(url) && !blank(user) && !blank(password) && !blank(driver)){
connectionSpecMap.put(getEnvironment(), new ConnectionJdbcSpec(driver, url, user, password)); // depends on control dependency: [if], data = [none]
}
String jndi = System.getenv("ACTIVEJDBC.JNDI");
if(!blank(jndi)){
connectionSpecMap.put(getEnvironment(), new ConnectionJndiSpec(jndi)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void clear() {
// Clears all keys, values and buckets linked lists.
for (EntryImpl<K, V> entry = _mapFirst; entry != null; entry = entry._after) {
entry._key = null;
entry._value = null;
entry._before = null;
entry._next = null;
if (entry._previous == null) { // First in bucket.
_entries[entry._index] = null;
} else {
entry._previous = null;
}
}
// Recycles all entries.
if (_mapLast != null) {
_mapLast._after = _poolFirst; // Connects to pool.
_poolFirst = _mapFirst;
_mapFirst = null;
_mapLast = null;
_size = 0;
sizeChanged();
}
} }
|
public class class_name {
public void clear() {
// Clears all keys, values and buckets linked lists.
for (EntryImpl<K, V> entry = _mapFirst; entry != null; entry = entry._after) {
entry._key = null; // depends on control dependency: [for], data = [entry]
entry._value = null; // depends on control dependency: [for], data = [entry]
entry._before = null; // depends on control dependency: [for], data = [entry]
entry._next = null; // depends on control dependency: [for], data = [entry]
if (entry._previous == null) { // First in bucket.
_entries[entry._index] = null; // depends on control dependency: [if], data = [none]
} else {
entry._previous = null; // depends on control dependency: [if], data = [none]
}
}
// Recycles all entries.
if (_mapLast != null) {
_mapLast._after = _poolFirst; // Connects to pool. // depends on control dependency: [if], data = [none]
_poolFirst = _mapFirst; // depends on control dependency: [if], data = [none]
_mapFirst = null; // depends on control dependency: [if], data = [none]
_mapLast = null; // depends on control dependency: [if], data = [none]
_size = 0; // depends on control dependency: [if], data = [none]
sizeChanged(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Symm obtain(byte[] key) throws IOException {
try {
byte[] bytes = new byte[AES.AES_KEY_SIZE/8];
int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-bytes.length);
for(int i=0;i<bytes.length;++i) {
bytes[i] = key[i+offset];
}
aes = new AES(bytes,0,bytes.length);
} catch (Exception e) {
throw new IOException(e);
}
int filled = codeset.length;
char[] seq = new char[filled];
int end = filled--;
boolean right = true;
int index;
Obtain o = new Obtain(this,key);
while(filled>=0) {
index = o.next();
if(index<0 || index>=codeset.length) {
System.out.println("uh, oh");
}
if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something)
for(int j=index;j<end;++j) {
if(seq[j]==0) {
seq[j]=codeset[filled];
--filled;
break;
}
}
right = false;
} else {
for(int j=index;j>=0;--j) {
if(seq[j]==0) {
seq[j]=codeset[filled];
--filled;
break;
}
}
right = true;
}
}
return new Symm(seq,this);
} }
|
public class class_name {
public Symm obtain(byte[] key) throws IOException {
try {
byte[] bytes = new byte[AES.AES_KEY_SIZE/8];
int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-bytes.length);
for(int i=0;i<bytes.length;++i) {
bytes[i] = key[i+offset];
}
aes = new AES(bytes,0,bytes.length);
} catch (Exception e) {
throw new IOException(e);
}
int filled = codeset.length;
char[] seq = new char[filled];
int end = filled--;
boolean right = true;
int index;
Obtain o = new Obtain(this,key);
while(filled>=0) {
index = o.next();
if(index<0 || index>=codeset.length) {
System.out.println("uh, oh"); // depends on control dependency: [if], data = [none]
}
if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something)
for(int j=index;j<end;++j) {
if(seq[j]==0) {
seq[j]=codeset[filled]; // depends on control dependency: [if], data = [none]
--filled; // depends on control dependency: [if], data = [none]
break;
}
}
right = false; // depends on control dependency: [if], data = [none]
} else {
for(int j=index;j>=0;--j) {
if(seq[j]==0) {
seq[j]=codeset[filled]; // depends on control dependency: [if], data = [none]
--filled; // depends on control dependency: [if], data = [none]
break;
}
}
right = true; // depends on control dependency: [if], data = [none]
}
}
return new Symm(seq,this);
} }
|
public class class_name {
public AccountHeader build() {
// if the user has not set a accountHeader use the default one :D
if (mAccountHeaderContainer == null) {
withAccountHeader(-1);
}
// get the header view within the container
mAccountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header);
mStatusBarGuideline = mAccountHeaderContainer.findViewById(R.id.material_drawer_statusbar_guideline);
//the default min header height by default 148dp
int defaultHeaderMinHeight = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height);
int statusBarHeight = UIUtils.getStatusBarHeight(mActivity, true);
// handle the height for the header
int height;
if (mHeight != null) {
height = mHeight.asPixel(mActivity);
} else {
if (mCompactStyle) {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact);
} else {
//calculate the header height by getting the optimal drawer width and calculating it * 9 / 16
height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO);
//if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower
//probably even if we are non translucent on > 19 devices?
if (Build.VERSION.SDK_INT < 19) {
int tempHeight = height - statusBarHeight;
//if we are lower than api 19 we are not able to have a translucent statusBar so we remove the height of the statusBar from the padding
//to prevent display issues we only reduce the height if we still fit the required minHeight of 148dp (R.dimen.material_drawer_account_header_height)
//we remove additional 8dp from the defaultMinHeaderHeight as there is some buffer in the header and to prevent to large spacings
if (tempHeight > defaultHeaderMinHeight - UIUtils.convertDpToPixel(8, mActivity)) {
height = tempHeight;
}
}
}
}
// handle everything if we have a translucent status bar which only is possible on API >= 19
if (mTranslucentStatusBar && Build.VERSION.SDK_INT >= 21) {
mStatusBarGuideline.setGuidelineBegin(statusBarHeight);
//in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact
if (mCompactStyle) {
height = height + statusBarHeight;
} else if ((height - statusBarHeight) <= defaultHeaderMinHeight) {
//if the height + statusBar of the header is lower than the required 148dp + statusBar we change the height to be able to display all the data
height = defaultHeaderMinHeight + statusBarHeight;
}
}
//set the height for the header
setHeaderHeight(height);
// get the background view
mAccountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background);
// set the background
ImageHolder.applyTo(mHeaderBackground, mAccountHeaderBackground, DrawerImageLoader.Tags.ACCOUNT_HEADER.name());
if (mHeaderBackgroundScaleType != null) {
mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType);
}
// get the text color to use for the text section
int textColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text);
int subTextColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_subtext, R.color.material_drawer_header_selection_subtext);
mAccountHeaderTextSectionBackgroundResource = UIUtils.getSelectableBackgroundRes(mActivity);
handleSelectionView(mCurrentProfile, true);
// set the arrow :D
mAccountSwitcherArrow = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_switcher);
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(subTextColor));
//get the fields for the name
mCurrentProfileView = mAccountHeader.findViewById(R.id.material_drawer_account_header_current);
mCurrentProfileName = mAccountHeader.findViewById(R.id.material_drawer_account_header_name);
mCurrentProfileEmail = mAccountHeader.findViewById(R.id.material_drawer_account_header_email);
//set the typeface for the AccountHeader
if (mNameTypeface != null) {
mCurrentProfileName.setTypeface(mNameTypeface);
} else if (mTypeface != null) {
mCurrentProfileName.setTypeface(mTypeface);
}
if (mEmailTypeface != null) {
mCurrentProfileEmail.setTypeface(mEmailTypeface);
} else if (mTypeface != null) {
mCurrentProfileEmail.setTypeface(mTypeface);
}
mCurrentProfileName.setTextColor(textColor);
mCurrentProfileEmail.setTextColor(subTextColor);
mProfileFirstView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_first);
mProfileSecondView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_second);
mProfileThirdView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_third);
//calculate the profiles to set
calculateProfiles();
//process and build the profiles
buildProfiles();
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) {
switchProfiles(mProfiles.get(selection));
}
}
}
//everything created. now set the header
if (mDrawer != null) {
mDrawer.setHeader(mAccountHeaderContainer, mPaddingBelowHeader, mDividerBelowHeader);
}
//forget the reference to the activity
mActivity = null;
return new AccountHeader(this);
} }
|
public class class_name {
public AccountHeader build() {
// if the user has not set a accountHeader use the default one :D
if (mAccountHeaderContainer == null) {
withAccountHeader(-1); // depends on control dependency: [if], data = [none]
}
// get the header view within the container
mAccountHeader = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header);
mStatusBarGuideline = mAccountHeaderContainer.findViewById(R.id.material_drawer_statusbar_guideline);
//the default min header height by default 148dp
int defaultHeaderMinHeight = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height);
int statusBarHeight = UIUtils.getStatusBarHeight(mActivity, true);
// handle the height for the header
int height;
if (mHeight != null) {
height = mHeight.asPixel(mActivity); // depends on control dependency: [if], data = [none]
} else {
if (mCompactStyle) {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact); // depends on control dependency: [if], data = [none]
} else {
//calculate the header height by getting the optimal drawer width and calculating it * 9 / 16
height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO); // depends on control dependency: [if], data = [none]
//if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower
//probably even if we are non translucent on > 19 devices?
if (Build.VERSION.SDK_INT < 19) {
int tempHeight = height - statusBarHeight;
//if we are lower than api 19 we are not able to have a translucent statusBar so we remove the height of the statusBar from the padding
//to prevent display issues we only reduce the height if we still fit the required minHeight of 148dp (R.dimen.material_drawer_account_header_height)
//we remove additional 8dp from the defaultMinHeaderHeight as there is some buffer in the header and to prevent to large spacings
if (tempHeight > defaultHeaderMinHeight - UIUtils.convertDpToPixel(8, mActivity)) {
height = tempHeight; // depends on control dependency: [if], data = [none]
}
}
}
}
// handle everything if we have a translucent status bar which only is possible on API >= 19
if (mTranslucentStatusBar && Build.VERSION.SDK_INT >= 21) {
mStatusBarGuideline.setGuidelineBegin(statusBarHeight); // depends on control dependency: [if], data = [none]
//in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact
if (mCompactStyle) {
height = height + statusBarHeight; // depends on control dependency: [if], data = [none]
} else if ((height - statusBarHeight) <= defaultHeaderMinHeight) {
//if the height + statusBar of the header is lower than the required 148dp + statusBar we change the height to be able to display all the data
height = defaultHeaderMinHeight + statusBarHeight; // depends on control dependency: [if], data = [none]
}
}
//set the height for the header
setHeaderHeight(height);
// get the background view
mAccountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_background);
// set the background
ImageHolder.applyTo(mHeaderBackground, mAccountHeaderBackground, DrawerImageLoader.Tags.ACCOUNT_HEADER.name());
if (mHeaderBackgroundScaleType != null) {
mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType); // depends on control dependency: [if], data = [(mHeaderBackgroundScaleType]
}
// get the text color to use for the text section
int textColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text);
int subTextColor = ColorHolder.color(mTextColor, mActivity, R.attr.material_drawer_header_selection_subtext, R.color.material_drawer_header_selection_subtext);
mAccountHeaderTextSectionBackgroundResource = UIUtils.getSelectableBackgroundRes(mActivity);
handleSelectionView(mCurrentProfile, true);
// set the arrow :D
mAccountSwitcherArrow = mAccountHeaderContainer.findViewById(R.id.material_drawer_account_header_text_switcher);
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeRes(R.dimen.material_drawer_account_header_dropdown).paddingRes(R.dimen.material_drawer_account_header_dropdown_padding).color(subTextColor));
//get the fields for the name
mCurrentProfileView = mAccountHeader.findViewById(R.id.material_drawer_account_header_current);
mCurrentProfileName = mAccountHeader.findViewById(R.id.material_drawer_account_header_name);
mCurrentProfileEmail = mAccountHeader.findViewById(R.id.material_drawer_account_header_email);
//set the typeface for the AccountHeader
if (mNameTypeface != null) {
mCurrentProfileName.setTypeface(mNameTypeface); // depends on control dependency: [if], data = [(mNameTypeface]
} else if (mTypeface != null) {
mCurrentProfileName.setTypeface(mTypeface); // depends on control dependency: [if], data = [(mTypeface]
}
if (mEmailTypeface != null) {
mCurrentProfileEmail.setTypeface(mEmailTypeface); // depends on control dependency: [if], data = [(mEmailTypeface]
} else if (mTypeface != null) {
mCurrentProfileEmail.setTypeface(mTypeface); // depends on control dependency: [if], data = [(mTypeface]
}
mCurrentProfileName.setTextColor(textColor);
mCurrentProfileEmail.setTextColor(subTextColor);
mProfileFirstView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_first);
mProfileSecondView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_second);
mProfileThirdView = mAccountHeader.findViewById(R.id.material_drawer_account_header_small_third);
//calculate the profiles to set
calculateProfiles();
//process and build the profiles
buildProfiles();
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) {
switchProfiles(mProfiles.get(selection)); // depends on control dependency: [if], data = [(mProfiles]
}
}
}
//everything created. now set the header
if (mDrawer != null) {
mDrawer.setHeader(mAccountHeaderContainer, mPaddingBelowHeader, mDividerBelowHeader); // depends on control dependency: [if], data = [none]
}
//forget the reference to the activity
mActivity = null;
return new AccountHeader(this);
} }
|
public class class_name {
public TextColumn addAll(List<String> stringValues) {
for (String stringValue : stringValues) {
append(stringValue);
}
return this;
} }
|
public class class_name {
public TextColumn addAll(List<String> stringValues) {
for (String stringValue : stringValues) {
append(stringValue); // depends on control dependency: [for], data = [stringValue]
}
return this;
} }
|
public class class_name {
public synchronized MessageRouterConfigListenerImpl register(BundleContext bundleContext) {
if (serviceRegistration != null) {
return this; // Already registered.
}
Dictionary<String, Object> props = new Hashtable<String, Object>(1);
props.put(Constants.SERVICE_VENDOR, "IBM");
// register the ManagedService that will handle the config
serviceRegistration = bundleContext.registerService(MessageRouterConfigListener.class, this, props);
return this;
} }
|
public class class_name {
public synchronized MessageRouterConfigListenerImpl register(BundleContext bundleContext) {
if (serviceRegistration != null) {
return this; // Already registered. // depends on control dependency: [if], data = [none]
}
Dictionary<String, Object> props = new Hashtable<String, Object>(1);
props.put(Constants.SERVICE_VENDOR, "IBM");
// register the ManagedService that will handle the config
serviceRegistration = bundleContext.registerService(MessageRouterConfigListener.class, this, props);
return this;
} }
|
public class class_name {
public synchronized static void toXML(AFPChain afpChain, StringWriter swriter,Atom[] ca1, Atom[]ca2) throws IOException{
PrintWriter writer = new PrintWriter(swriter);
PrettyXMLWriter xml = new PrettyXMLWriter(writer);
xml.openTag("AFPChain");
printXMLHeader(xml,afpChain);
// that is the initial alignment...
// we don't serialize that at the present.
//int[] blockResSize = afpChain.getBlockResSize();
//int[][][] blockResList = afpChain.getBlockResList();
// get the alignment blocks
int blockNum = afpChain.getBlockNum();
//int[] optLen = afpChain.getOptLen();
//int[] blockSize = afpChain.getBlockSize();
for(int bk = 0; bk < blockNum; bk ++) {
xml.openTag("block");
printXMLBlockHeader(xml,afpChain, bk);
if ( ca1 == null || ca2 == null) {
try {
printXMLEQRKnownPositions(xml,afpChain,bk);
} catch (StructureException ex ){
throw new IOException(ex.getMessage());
}
}
else
printXMLEQRInferPositions(xml, afpChain,bk,ca1,ca2);
printXMLMatrixShift(xml, afpChain, bk);
xml.closeTag("block");
}
xml.closeTag("AFPChain");
writer.close();
} }
|
public class class_name {
public synchronized static void toXML(AFPChain afpChain, StringWriter swriter,Atom[] ca1, Atom[]ca2) throws IOException{
PrintWriter writer = new PrintWriter(swriter);
PrettyXMLWriter xml = new PrettyXMLWriter(writer);
xml.openTag("AFPChain");
printXMLHeader(xml,afpChain);
// that is the initial alignment...
// we don't serialize that at the present.
//int[] blockResSize = afpChain.getBlockResSize();
//int[][][] blockResList = afpChain.getBlockResList();
// get the alignment blocks
int blockNum = afpChain.getBlockNum();
//int[] optLen = afpChain.getOptLen();
//int[] blockSize = afpChain.getBlockSize();
for(int bk = 0; bk < blockNum; bk ++) {
xml.openTag("block");
printXMLBlockHeader(xml,afpChain, bk);
if ( ca1 == null || ca2 == null) {
try {
printXMLEQRKnownPositions(xml,afpChain,bk); // depends on control dependency: [try], data = [none]
} catch (StructureException ex ){
throw new IOException(ex.getMessage());
} // depends on control dependency: [catch], data = [none]
}
else
printXMLEQRInferPositions(xml, afpChain,bk,ca1,ca2);
printXMLMatrixShift(xml, afpChain, bk);
xml.closeTag("block");
}
xml.closeTag("AFPChain");
writer.close();
} }
|
public class class_name {
public static void setVariableWithSingleQuotationMarks(final String variablename,
final Object object, final Map<String, Object> variables)
{
if (object != null)
{
variables.put(variablename, "'" + object + "'");
}
else
{
variables.put(variablename, "null");
}
} }
|
public class class_name {
public static void setVariableWithSingleQuotationMarks(final String variablename,
final Object object, final Map<String, Object> variables)
{
if (object != null)
{
variables.put(variablename, "'" + object + "'"); // depends on control dependency: [if], data = [none]
}
else
{
variables.put(variablename, "null"); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private static int sum(final int[] sizes) {
int sum = 0;
for (int i = sizes.length - 1; i >= 0; i--) {
sum += sizes[i];
}
return sum;
} }
|
public class class_name {
private static int sum(final int[] sizes) {
int sum = 0;
for (int i = sizes.length - 1; i >= 0; i--) {
sum += sizes[i]; // depends on control dependency: [for], data = [i]
}
return sum;
} }
|
public class class_name {
protected Iterable<DynamicValidationComponent> createValidatorComponents(Image it, File currentFile,
DynamicValidationContext context) {
final Collection<DynamicValidationComponent> components = new ArrayList<>();
if (isLocalImageReferenceValidation()) {
final int lineno = computeLineNo(it);
final URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true);
if (URISchemeType.FILE.isURL(url)) {
final DynamicValidationComponent component = createLocalImageValidatorComponent(
it, url, lineno, currentFile, context);
if (component != null) {
components.add(component);
}
}
}
return components;
} }
|
public class class_name {
protected Iterable<DynamicValidationComponent> createValidatorComponents(Image it, File currentFile,
DynamicValidationContext context) {
final Collection<DynamicValidationComponent> components = new ArrayList<>();
if (isLocalImageReferenceValidation()) {
final int lineno = computeLineNo(it);
final URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true);
if (URISchemeType.FILE.isURL(url)) {
final DynamicValidationComponent component = createLocalImageValidatorComponent(
it, url, lineno, currentFile, context);
if (component != null) {
components.add(component); // depends on control dependency: [if], data = [(component]
}
}
}
return components;
} }
|
public class class_name {
public void onChange(TopologyChangeEvent event)
{
try
{
if (rpcService.isCoordinator() && !isOnline)
{
new Thread()
{
@Override
public synchronized void run()
{
try
{
List<Object> results =
rpcService.executeCommandOnAllNodes(requestForResponsibleToSetIndexOnline, true);
for (Object result : results)
{
if (result instanceof Boolean)
{
if ((Boolean)result)
{
return;
}
}
else
{
log.error("Result is not an instance of Boolean" + result);
}
}
// node which was responsible for resuming leave the cluster, so resume component
log
.error("Node responsible for setting index back online seems to leave the cluster. Setting back online.");
searchManager.setOnline(true, false, false);
}
catch (SecurityException e1)
{
log.error("You haven't privileges to execute remote command", e1);
}
catch (RPCException e1)
{
log.error("Exception during command execution", e1);
}
catch (IOException e2)
{
log.error("Exception during setting index back online", e2);
}
}
}.start();
}
}
catch (RPCException e)
{
log.error("Can't check if node coordinator or not.");
}
} }
|
public class class_name {
public void onChange(TopologyChangeEvent event)
{
try
{
if (rpcService.isCoordinator() && !isOnline)
{
new Thread()
{
@Override
public synchronized void run()
{
try
{
List<Object> results =
rpcService.executeCommandOnAllNodes(requestForResponsibleToSetIndexOnline, true);
for (Object result : results)
{
if (result instanceof Boolean)
{
if ((Boolean)result)
{
return; // depends on control dependency: [if], data = [none]
}
}
else
{
log.error("Result is not an instance of Boolean" + result); // depends on control dependency: [if], data = [none]
}
}
// node which was responsible for resuming leave the cluster, so resume component
log
.error("Node responsible for setting index back online seems to leave the cluster. Setting back online."); // depends on control dependency: [try], data = [none]
searchManager.setOnline(true, false, false); // depends on control dependency: [try], data = [none]
}
catch (SecurityException e1)
{
log.error("You haven't privileges to execute remote command", e1);
}
catch (RPCException e1)
{
log.error("Exception during command execution", e1);
}
catch (IOException e2)
{
log.error("Exception during setting index back online", e2);
}
}
}.start();
}
}
catch (RPCException e)
{
log.error("Can't check if node coordinator or not.");
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
protected final void buildCommonPropertyParameters( CodeBlock.Builder paramBuilder, PropertyInfo property ) {
if ( property.getFormat().isPresent() ) {
JsonFormat format = property.getFormat().get();
if ( !Strings.isNullOrEmpty( format.pattern() ) ) {
paramBuilder.add( "\n.setPattern($S)", format.pattern() );
}
paramBuilder.add( "\n.setShape($T.$L)", Shape.class, format.shape().name() );
if ( !Strings.isNullOrEmpty( format.locale() ) && !JsonFormat.DEFAULT_LOCALE.equals( format.locale() ) ) {
logger.log( Type.WARN, "JsonFormat.locale is not supported by default" );
paramBuilder.add( "\n.setLocale($S)", format.locale() );
}
}
if ( property.getIgnoredProperties().isPresent() ) {
for ( String ignoredProperty : property.getIgnoredProperties().get() ) {
paramBuilder.add( "\n.addIgnoredProperty($S)", ignoredProperty );
}
}
} }
|
public class class_name {
protected final void buildCommonPropertyParameters( CodeBlock.Builder paramBuilder, PropertyInfo property ) {
if ( property.getFormat().isPresent() ) {
JsonFormat format = property.getFormat().get();
if ( !Strings.isNullOrEmpty( format.pattern() ) ) {
paramBuilder.add( "\n.setPattern($S)", format.pattern() ); // depends on control dependency: [if], data = [none]
}
paramBuilder.add( "\n.setShape($T.$L)", Shape.class, format.shape().name() ); // depends on control dependency: [if], data = [none]
if ( !Strings.isNullOrEmpty( format.locale() ) && !JsonFormat.DEFAULT_LOCALE.equals( format.locale() ) ) {
logger.log( Type.WARN, "JsonFormat.locale is not supported by default" ); // depends on control dependency: [if], data = [none]
paramBuilder.add( "\n.setLocale($S)", format.locale() ); // depends on control dependency: [if], data = [none]
}
}
if ( property.getIgnoredProperties().isPresent() ) {
for ( String ignoredProperty : property.getIgnoredProperties().get() ) {
paramBuilder.add( "\n.addIgnoredProperty($S)", ignoredProperty ); // depends on control dependency: [for], data = [ignoredProperty]
}
}
} }
|
public class class_name {
@Override
public Table<URI, URI, MatchResult> match(Set<URI> origins, Set<URI> destinations) {
ImmutableTable.Builder<URI, URI, MatchResult> builder = ImmutableTable.builder();
for (URI origin : origins) {
for (URI destination : destinations) {
builder.put(origin, destination, this.match(origin, destination));
}
}
return builder.build();
} }
|
public class class_name {
@Override
public Table<URI, URI, MatchResult> match(Set<URI> origins, Set<URI> destinations) {
ImmutableTable.Builder<URI, URI, MatchResult> builder = ImmutableTable.builder();
for (URI origin : origins) {
for (URI destination : destinations) {
builder.put(origin, destination, this.match(origin, destination)); // depends on control dependency: [for], data = [destination]
}
}
return builder.build();
} }
|
public class class_name {
private void loadIfNecessary() {
if (loadedMember != null) {
return;
}
CommandRegistry commandRegistry = parentGroup.getCommandRegistry();
Assert.isTrue(parentGroup.getCommandRegistry() != null, "Command registry must be set for group '"
+ parentGroup.getId() + "' in order to load lazy command '" + lazyCommandId + "'.");
if (commandRegistry.containsCommandGroup(lazyCommandId)) {
CommandGroup group = commandRegistry.getCommandGroup(lazyCommandId);
loadedMember = new SimpleGroupMember(parentGroup, group);
}
else if (commandRegistry.containsActionCommand(lazyCommandId)) {
ActionCommand command = commandRegistry.getActionCommand(lazyCommandId);
loadedMember = new SimpleGroupMember(parentGroup, command);
}
else {
if (logger.isWarnEnabled()) {
logger.warn("Lazy command '"
+ lazyCommandId
+ "' was asked to display; however, no backing command instance exists in registry.");
}
}
if (addedLazily && loadedMember != null) {
loadedMember.onAdded();
}
} }
|
public class class_name {
private void loadIfNecessary() {
if (loadedMember != null) {
return; // depends on control dependency: [if], data = [none]
}
CommandRegistry commandRegistry = parentGroup.getCommandRegistry();
Assert.isTrue(parentGroup.getCommandRegistry() != null, "Command registry must be set for group '"
+ parentGroup.getId() + "' in order to load lazy command '" + lazyCommandId + "'.");
if (commandRegistry.containsCommandGroup(lazyCommandId)) {
CommandGroup group = commandRegistry.getCommandGroup(lazyCommandId);
loadedMember = new SimpleGroupMember(parentGroup, group); // depends on control dependency: [if], data = [none]
}
else if (commandRegistry.containsActionCommand(lazyCommandId)) {
ActionCommand command = commandRegistry.getActionCommand(lazyCommandId);
loadedMember = new SimpleGroupMember(parentGroup, command); // depends on control dependency: [if], data = [none]
}
else {
if (logger.isWarnEnabled()) {
logger.warn("Lazy command '"
+ lazyCommandId
+ "' was asked to display; however, no backing command instance exists in registry."); // depends on control dependency: [if], data = [none]
}
}
if (addedLazily && loadedMember != null) {
loadedMember.onAdded(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public byte[] toByteArray() {
int arrSize = 1 + Long.BYTES; // first byte specifies type of data
byte type;
if (data instanceof Long) {
arrSize += Long.BYTES;
type = TYPE_LONG;
} else if (data instanceof Double) {
arrSize += Double.BYTES;
type = TYPE_DOUBLE;
} else {
arrSize += Integer.BYTES + ((String) data).length();
type = TYPE_STRING;
}
ByteBuffer buf = ByteBuffer.allocate(arrSize);
buf.putLong(time);
buf.put(type);
if (type == TYPE_LONG) {
buf.putLong((Long) data);
} else if (type == TYPE_DOUBLE) {
buf.putDouble((Double) data);
} else {
String temp = (String) data;
buf.putInt(temp.length());
buf.put(temp.getBytes());
}
buf.flip();
return buf.array();
} }
|
public class class_name {
public byte[] toByteArray() {
int arrSize = 1 + Long.BYTES; // first byte specifies type of data
byte type;
if (data instanceof Long) {
arrSize += Long.BYTES; // depends on control dependency: [if], data = [none]
type = TYPE_LONG; // depends on control dependency: [if], data = [none]
} else if (data instanceof Double) {
arrSize += Double.BYTES; // depends on control dependency: [if], data = [none]
type = TYPE_DOUBLE; // depends on control dependency: [if], data = [none]
} else {
arrSize += Integer.BYTES + ((String) data).length(); // depends on control dependency: [if], data = [none]
type = TYPE_STRING; // depends on control dependency: [if], data = [none]
}
ByteBuffer buf = ByteBuffer.allocate(arrSize);
buf.putLong(time);
buf.put(type);
if (type == TYPE_LONG) {
buf.putLong((Long) data); // depends on control dependency: [if], data = [none]
} else if (type == TYPE_DOUBLE) {
buf.putDouble((Double) data); // depends on control dependency: [if], data = [none]
} else {
String temp = (String) data;
buf.putInt(temp.length()); // depends on control dependency: [if], data = [none]
buf.put(temp.getBytes()); // depends on control dependency: [if], data = [none]
}
buf.flip();
return buf.array();
} }
|
public class class_name {
protected Recording sealRecordingMetadataFile(Recording recording, long size, double duration,
String metadataFilePath) {
recording.setSize(size); // Size in bytes
recording.setDuration(duration > 0 ? duration : 0); // Duration in seconds
if (!io.openvidu.java.client.Recording.Status.failed.equals(recording.getStatus())) {
recording.setStatus(io.openvidu.java.client.Recording.Status.stopped);
}
this.fileWriter.overwriteFile(metadataFilePath, recording.toJson().toString());
recording = this.recordingManager.updateRecordingUrl(recording);
log.info("Sealed recording metadata file at {}", metadataFilePath);
return recording;
} }
|
public class class_name {
protected Recording sealRecordingMetadataFile(Recording recording, long size, double duration,
String metadataFilePath) {
recording.setSize(size); // Size in bytes
recording.setDuration(duration > 0 ? duration : 0); // Duration in seconds
if (!io.openvidu.java.client.Recording.Status.failed.equals(recording.getStatus())) {
recording.setStatus(io.openvidu.java.client.Recording.Status.stopped); // depends on control dependency: [if], data = [none]
}
this.fileWriter.overwriteFile(metadataFilePath, recording.toJson().toString());
recording = this.recordingManager.updateRecordingUrl(recording);
log.info("Sealed recording metadata file at {}", metadataFilePath);
return recording;
} }
|
public class class_name {
public void marshall(StreamProcessor streamProcessor, ProtocolMarshaller protocolMarshaller) {
if (streamProcessor == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(streamProcessor.getName(), NAME_BINDING);
protocolMarshaller.marshall(streamProcessor.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(StreamProcessor streamProcessor, ProtocolMarshaller protocolMarshaller) {
if (streamProcessor == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(streamProcessor.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(streamProcessor.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 {
void init() {
numnegative = new int[numSamples() + 1];
numpositive = new int[numSamples() + 1];
numnegative[0] = 0;
numpositive[0] = 0;
int num = numSamples();
for (int i = 1; i <= num; i++) {
numnegative[i] = numnegative[i - 1] + (classes[i - 1] == 0 ? 1 : 0);
}
for (int i = 1; i <= num; i++) {
numpositive[i] = numpositive[i - 1] + (classes[num - i] == 0 ? 0 : 1);
}
System.err.println("total positive " + numpositive[num] + " total negative " + numnegative[num] + " total " + num);
for (int i = 1; i < numpositive.length; i++) {
//System.out.println(i + " positive " + numpositive[i] + " negative " + numnegative[i] + " classes " + classes[i - 1] + " " + classes[num - i]);
}
} }
|
public class class_name {
void init() {
numnegative = new int[numSamples() + 1];
numpositive = new int[numSamples() + 1];
numnegative[0] = 0;
numpositive[0] = 0;
int num = numSamples();
for (int i = 1; i <= num; i++) {
numnegative[i] = numnegative[i - 1] + (classes[i - 1] == 0 ? 1 : 0);
// depends on control dependency: [for], data = [i]
}
for (int i = 1; i <= num; i++) {
numpositive[i] = numpositive[i - 1] + (classes[num - i] == 0 ? 0 : 1);
// depends on control dependency: [for], data = [i]
}
System.err.println("total positive " + numpositive[num] + " total negative " + numnegative[num] + " total " + num);
for (int i = 1; i < numpositive.length; i++) {
//System.out.println(i + " positive " + numpositive[i] + " negative " + numnegative[i] + " classes " + classes[i - 1] + " " + classes[num - i]);
}
} }
|
public class class_name {
@Override
public void preparePaintComponent(final Request request) {
if (!isInitialised()) {
List<SimpleTableBean> items = new ArrayList<>();
items.add(new SimpleTableBean("A", "none", "thing"));
items.add(new SimpleTableBean("B", "some", "thing2"));
items.add(new SimpleTableBean("C", "little", "thing3"));
items.add(new SimpleTableBean("D", "lots", "thing4"));
for (WList list : lists) {
list.setData(items);
}
setInitialised(true);
}
} }
|
public class class_name {
@Override
public void preparePaintComponent(final Request request) {
if (!isInitialised()) {
List<SimpleTableBean> items = new ArrayList<>();
items.add(new SimpleTableBean("A", "none", "thing")); // depends on control dependency: [if], data = [none]
items.add(new SimpleTableBean("B", "some", "thing2")); // depends on control dependency: [if], data = [none]
items.add(new SimpleTableBean("C", "little", "thing3")); // depends on control dependency: [if], data = [none]
items.add(new SimpleTableBean("D", "lots", "thing4")); // depends on control dependency: [if], data = [none]
for (WList list : lists) {
list.setData(items); // depends on control dependency: [for], data = [list]
}
setInitialised(true); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
protected void appendWorkplaceOpenerScript(
StringBuffer html,
String requestedResource,
CmsMessageContainer message) {
String winId = "OpenCms" + System.currentTimeMillis();
html.append("<script type=\"text/javascript\">\n");
html.append("function doOnload() {\n");
// display missing resource warning if required
if (message != null) {
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(message.key(m_locale)));
html.append("\");\n");
}
// display login message if required
CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
if ((loginMessage != null) && (loginMessage.isActive())) {
String msg;
if (loginMessage.isLoginForbidden()) {
// login forbidden for normal users, current user must be Administrator
msg = Messages.get().container(
Messages.GUI_LOGIN_SUCCESS_WITH_MESSAGE_2,
loginMessage.getMessage(),
new Date(loginMessage.getTimeEnd())).key(m_locale);
} else {
// just display the message
msg = loginMessage.getMessage();
}
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(msg));
html.append("\");\n");
}
String openResource = requestedResource;
// check if user agreement should be shown
CmsLoginUserAgreement agreementInfo = new CmsLoginUserAgreement(this);
if (agreementInfo.isShowUserAgreement()) {
openResource = agreementInfo.getConfigurationVfsPath()
+ "?"
+ CmsLoginUserAgreement.PARAM_WPRES
+ "="
+ requestedResource;
}
html.append("\tvar openUri = \"");
html.append(link(openResource));
html.append("\";\n");
html.append("\tvar workplaceWin = openWorkplace(openUri, \"");
html.append(winId);
html.append("\");\n");
html.append("\tif (window.name != \"");
html.append(winId);
html.append("\") {\n");
html.append("\t\twindow.opener = workplaceWin;\n");
html.append("\t\tif (workplaceWin != null) {\n");
html.append("\t\t\twindow.close();\n");
html.append("\t\t}\n");
html.append("\t}\n");
html.append("}\n");
html.append("function openWorkplace(url, name) {\n");
Cookie wpDataCookie = getCookie(getRequest(), COOKIE_WP_DATA);
boolean useCookieData = false;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(wpDataCookie.getValue())) {
String[] winValues = CmsStringUtil.splitAsArray(wpDataCookie.getValue(), '|');
if (winValues.length == 4) {
useCookieData = true;
html.append("\tvar winLeft = ").append(winValues[0]).append(";\n");
html.append("\tvar winTop = ").append(winValues[1]).append(";\n");
html.append("\tvar winWidth = ").append(winValues[2]).append(";\n");
html.append("\tvar winHeight = ").append(winValues[3]).append(";\n");
}
}
if (!useCookieData) {
html.append("\tvar isInWin = (window.name.match(/^OpenCms\\d+$/) != null);\n");
html.append("\tvar winHeight = 0, winWidth = 0, winTop = 0, winLeft = 0;\n");
html.append("\tif (window.innerHeight) {\n");
// Mozilla
html.append("\t\twinHeight = window.innerHeight;\n");
html.append("\t\twinWidth = window.innerWidth;\n");
html.append("\t} else if (document.documentElement && document.documentElement.clientHeight) {\n");
// IE 6 "strict" mode
html.append("\t\twinHeight = document.documentElement.clientHeight;\n");
html.append("\t\twinWidth = document.documentElement.clientWidth;\n");
html.append("\t} else if (document.body && document.body.clientHeight) {\n");
// IE 5, IE 6 "relaxed" mode
html.append("\t\twinHeight = document.body.clientWidth;\n");
html.append("\t\twinWidth = document.body.clientHeight;\n");
html.append("\t}\n");
html.append("\tif (window.screenY) {\n");
// Mozilla
html.append("\t\twinTop = window.screenY;\n");
html.append("\t\twinLeft = window.screenX;\n");
html.append("\t\tif (! isInWin) {\n");
html.append("\t\t\twinTop += 25;\n");
html.append("\t\t\twinLeft += 25;\n");
html.append("\t\t}\n");
html.append("\t} else if (window.screenTop) {\n");
// IE
html.append("\t\twinTop = window.screenTop;\n");
html.append("\t\twinLeft = window.screenLeft;\n");
html.append("\t}\n");
html.append("\n");
}
if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_WORKPLACE)) {
html.append(
"\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=no,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes\";\n");
} else {
html.append(
"\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=yes,location=yes,toolbar=yes,menubar=yes,directories=no,status=yes,resizable=yes\";\n");
}
html.append("\tvar OpenCmsWin = window.open(url, name, openerStr);\n");
html.append("\n");
html.append("\ttry{\n");
html.append("\t\tif (! OpenCmsWin.opener) {\n");
html.append("\t\t\tOpenCmsWin.opener = self;\n");
html.append("\t\t}\n");
html.append("\t\tif (OpenCmsWin.focus) {\n");
html.append("\t\t\tOpenCmsWin.focus();\n");
html.append("\t\t}\n");
html.append("\t} catch (e) {}\n");
html.append("\n");
html.append("\treturn OpenCmsWin;\n");
html.append("}\n");
html.append("</script>\n");
} }
|
public class class_name {
protected void appendWorkplaceOpenerScript(
StringBuffer html,
String requestedResource,
CmsMessageContainer message) {
String winId = "OpenCms" + System.currentTimeMillis();
html.append("<script type=\"text/javascript\">\n");
html.append("function doOnload() {\n");
// display missing resource warning if required
if (message != null) {
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(message.key(m_locale)));
html.append("\");\n"); // depends on control dependency: [if], data = [none]
}
// display login message if required
CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
if ((loginMessage != null) && (loginMessage.isActive())) {
String msg;
if (loginMessage.isLoginForbidden()) {
// login forbidden for normal users, current user must be Administrator
msg = Messages.get().container(
Messages.GUI_LOGIN_SUCCESS_WITH_MESSAGE_2,
loginMessage.getMessage(),
new Date(loginMessage.getTimeEnd())).key(m_locale); // depends on control dependency: [if], data = [none]
} else {
// just display the message
msg = loginMessage.getMessage(); // depends on control dependency: [if], data = [none]
}
html.append("\talert(\"");
html.append(CmsStringUtil.escapeJavaScript(msg));
html.append("\");\n"); // depends on control dependency: [if], data = [none]
}
String openResource = requestedResource;
// check if user agreement should be shown
CmsLoginUserAgreement agreementInfo = new CmsLoginUserAgreement(this);
if (agreementInfo.isShowUserAgreement()) {
openResource = agreementInfo.getConfigurationVfsPath()
+ "?"
+ CmsLoginUserAgreement.PARAM_WPRES
+ "="
+ requestedResource; // depends on control dependency: [if], data = [none]
}
html.append("\tvar openUri = \"");
html.append(link(openResource));
html.append("\";\n");
html.append("\tvar workplaceWin = openWorkplace(openUri, \"");
html.append(winId);
html.append("\");\n");
html.append("\tif (window.name != \"");
html.append(winId);
html.append("\") {\n");
html.append("\t\twindow.opener = workplaceWin;\n");
html.append("\t\tif (workplaceWin != null) {\n");
html.append("\t\t\twindow.close();\n");
html.append("\t\t}\n");
html.append("\t}\n");
html.append("}\n");
html.append("function openWorkplace(url, name) {\n");
Cookie wpDataCookie = getCookie(getRequest(), COOKIE_WP_DATA);
boolean useCookieData = false;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(wpDataCookie.getValue())) {
String[] winValues = CmsStringUtil.splitAsArray(wpDataCookie.getValue(), '|');
if (winValues.length == 4) {
useCookieData = true;
html.append("\tvar winLeft = ").append(winValues[0]).append(";\n");
html.append("\tvar winTop = ").append(winValues[1]).append(";\n");
html.append("\tvar winWidth = ").append(winValues[2]).append(";\n");
html.append("\tvar winHeight = ").append(winValues[3]).append(";\n");
}
}
if (!useCookieData) {
html.append("\tvar isInWin = (window.name.match(/^OpenCms\\d+$/) != null);\n");
html.append("\tvar winHeight = 0, winWidth = 0, winTop = 0, winLeft = 0;\n");
html.append("\tif (window.innerHeight) {\n");
// Mozilla
html.append("\t\twinHeight = window.innerHeight;\n");
html.append("\t\twinWidth = window.innerWidth;\n");
html.append("\t} else if (document.documentElement && document.documentElement.clientHeight) {\n");
// IE 6 "strict" mode
html.append("\t\twinHeight = document.documentElement.clientHeight;\n");
html.append("\t\twinWidth = document.documentElement.clientWidth;\n");
html.append("\t} else if (document.body && document.body.clientHeight) {\n");
// IE 5, IE 6 "relaxed" mode
html.append("\t\twinHeight = document.body.clientWidth;\n");
html.append("\t\twinWidth = document.body.clientHeight;\n");
html.append("\t}\n");
html.append("\tif (window.screenY) {\n");
// Mozilla
html.append("\t\twinTop = window.screenY;\n");
html.append("\t\twinLeft = window.screenX;\n");
html.append("\t\tif (! isInWin) {\n");
html.append("\t\t\twinTop += 25;\n");
html.append("\t\t\twinLeft += 25;\n");
html.append("\t\t}\n");
html.append("\t} else if (window.screenTop) {\n");
// IE
html.append("\t\twinTop = window.screenTop;\n");
html.append("\t\twinLeft = window.screenLeft;\n");
html.append("\t}\n");
html.append("\n");
}
if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_WORKPLACE)) {
html.append(
"\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=no,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes\";\n");
} else {
html.append(
"\tvar openerStr = \"width=\" + winWidth + \",height=\" + winHeight + \",left=\" + winLeft + \",top=\" + winTop + \",scrollbars=yes,location=yes,toolbar=yes,menubar=yes,directories=no,status=yes,resizable=yes\";\n");
}
html.append("\tvar OpenCmsWin = window.open(url, name, openerStr);\n");
html.append("\n");
html.append("\ttry{\n");
html.append("\t\tif (! OpenCmsWin.opener) {\n");
html.append("\t\t\tOpenCmsWin.opener = self;\n");
html.append("\t\t}\n");
html.append("\t\tif (OpenCmsWin.focus) {\n");
html.append("\t\t\tOpenCmsWin.focus();\n");
html.append("\t\t}\n");
html.append("\t} catch (e) {}\n");
html.append("\n");
html.append("\treturn OpenCmsWin;\n");
html.append("}\n");
html.append("</script>\n");
} }
|
public class class_name {
private Container getContainer(final GeneratorContext context) {
List<Container> containers = StartupUtil
.getAllPublishedContainers(context.getServletContext());
// TODO: here we assume there is only one DWR Servlet / Container ... we
// should find a way to math the container with the DWR mapping config
for (Container container : containers) {
return container;
}
throw new RuntimeException("FATAL: unable to find DWR Container!");
} }
|
public class class_name {
private Container getContainer(final GeneratorContext context) {
List<Container> containers = StartupUtil
.getAllPublishedContainers(context.getServletContext());
// TODO: here we assume there is only one DWR Servlet / Container ... we
// should find a way to math the container with the DWR mapping config
for (Container container : containers) {
return container; // depends on control dependency: [for], data = [container]
}
throw new RuntimeException("FATAL: unable to find DWR Container!");
} }
|
public class class_name {
public static String format(Instance inst, String[] labels, String[] gold) {
StringBuilder sb = new StringBuilder();
String[][] data = (String[][]) inst.getSource();
int feaNum = data.length;
int seqNum = data[0].length;
for (int i = 0; i < seqNum; i++) {
for (int j = 0; j < feaNum; j++) {
sb.append(data[j][i]);
sb.append("\t");
}
sb.append(labels[i]);
sb.append("\t");
sb.append(gold[i]);
sb.append("\n");
}
return sb.toString();
} }
|
public class class_name {
public static String format(Instance inst, String[] labels, String[] gold) {
StringBuilder sb = new StringBuilder();
String[][] data = (String[][]) inst.getSource();
int feaNum = data.length;
int seqNum = data[0].length;
for (int i = 0; i < seqNum; i++) {
for (int j = 0; j < feaNum; j++) {
sb.append(data[j][i]);
// depends on control dependency: [for], data = [j]
sb.append("\t");
// depends on control dependency: [for], data = [none]
}
sb.append(labels[i]);
// depends on control dependency: [for], data = [i]
sb.append("\t");
// depends on control dependency: [for], data = [none]
sb.append(gold[i]);
// depends on control dependency: [for], data = [i]
sb.append("\n");
// depends on control dependency: [for], data = [none]
}
return sb.toString();
} }
|
public class class_name {
public static <T> T cast(Object value, Class<T> type) {
if (null == value) {
return null;
}
if (!type.isAssignableFrom(value.getClass())) {
if (is(type, int.class, Integer.class)) {
value = Integer.parseInt(value.toString());
} else if (is(type, long.class, Long.class)) {
value = Long.parseLong(value.toString());
} else if (is(type, float.class, Float.class)) {
value = Float.parseFloat(value.toString());
} else if (is(type, double.class, Double.class)) {
value = Double.parseDouble(value.toString());
} else if (is(type, boolean.class, Boolean.class)) {
value = Boolean.parseBoolean(value.toString());
} else if (is(type, String.class)) {
value = value.toString();
}
}
return (T) value;
} }
|
public class class_name {
public static <T> T cast(Object value, Class<T> type) {
if (null == value) {
return null; // depends on control dependency: [if], data = [none]
}
if (!type.isAssignableFrom(value.getClass())) {
if (is(type, int.class, Integer.class)) {
value = Integer.parseInt(value.toString()); // depends on control dependency: [if], data = [none]
} else if (is(type, long.class, Long.class)) {
value = Long.parseLong(value.toString()); // depends on control dependency: [if], data = [none]
} else if (is(type, float.class, Float.class)) {
value = Float.parseFloat(value.toString()); // depends on control dependency: [if], data = [none]
} else if (is(type, double.class, Double.class)) {
value = Double.parseDouble(value.toString()); // depends on control dependency: [if], data = [none]
} else if (is(type, boolean.class, Boolean.class)) {
value = Boolean.parseBoolean(value.toString()); // depends on control dependency: [if], data = [none]
} else if (is(type, String.class)) {
value = value.toString(); // depends on control dependency: [if], data = [none]
}
}
return (T) value;
} }
|
public class class_name {
public StrBuilder delete(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
final int len = endIndex - startIndex;
if (len > 0) {
deleteImpl(startIndex, endIndex, len);
}
return this;
} }
|
public class class_name {
public StrBuilder delete(final int startIndex, int endIndex) {
endIndex = validateRange(startIndex, endIndex);
final int len = endIndex - startIndex;
if (len > 0) {
deleteImpl(startIndex, endIndex, len); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
@CheckReturnValue
public MessageAction clearFiles(Consumer<InputStream> finalizer)
{
Checks.notNull(finalizer, "Finalizer");
for (Iterator<InputStream> it = files.values().iterator(); it.hasNext(); )
{
finalizer.accept(it.next());
it.remove();
}
clearResources();
return this;
} }
|
public class class_name {
@CheckReturnValue
public MessageAction clearFiles(Consumer<InputStream> finalizer)
{
Checks.notNull(finalizer, "Finalizer");
for (Iterator<InputStream> it = files.values().iterator(); it.hasNext(); )
{
finalizer.accept(it.next()); // depends on control dependency: [for], data = [it]
it.remove(); // depends on control dependency: [for], data = [it]
}
clearResources();
return this;
} }
|
public class class_name {
@Override
public void trainOnInstanceImpl(Instance instance) {
if (m_weights == null) {
int length;
if (instance.classAttribute().isNominal()) {
length = instance.numClasses();
} else {
length = 1;
}
m_weights = new DoubleVector[length];
m_bias = new double[length];
for (int i = 0; i < m_weights.length; i++){
m_weights[i] = new DoubleVector();
m_bias[i] = 0.0;
}
}
for (int i = 0; i < m_weights.length; i++){
this.trainOnInstanceImpl(instance, i);
}
m_t++;
} }
|
public class class_name {
@Override
public void trainOnInstanceImpl(Instance instance) {
if (m_weights == null) {
int length;
if (instance.classAttribute().isNominal()) {
length = instance.numClasses(); // depends on control dependency: [if], data = [none]
} else {
length = 1; // depends on control dependency: [if], data = [none]
}
m_weights = new DoubleVector[length]; // depends on control dependency: [if], data = [none]
m_bias = new double[length]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < m_weights.length; i++){
m_weights[i] = new DoubleVector(); // depends on control dependency: [for], data = [i]
m_bias[i] = 0.0; // depends on control dependency: [for], data = [i]
}
}
for (int i = 0; i < m_weights.length; i++){
this.trainOnInstanceImpl(instance, i); // depends on control dependency: [for], data = [i]
}
m_t++;
} }
|
public class class_name {
public static Date parseDate(String datetimeStr) {
if (StringUtils.isEmpty(datetimeStr)) {
return null;
}
datetimeStr = datetimeStr.trim();
if (datetimeStr.contains("-")) {
if (datetimeStr.contains(":")) {
datetimeStr = datetimeStr.replace(" ", "T");
}
} else if (datetimeStr.contains(":")) {
datetimeStr = "T" + datetimeStr;
}
DateTime dateTime = new DateTime(datetimeStr, dateTimeZone);
return dateTime.toDate();
} }
|
public class class_name {
public static Date parseDate(String datetimeStr) {
if (StringUtils.isEmpty(datetimeStr)) {
return null; // depends on control dependency: [if], data = [none]
}
datetimeStr = datetimeStr.trim();
if (datetimeStr.contains("-")) {
if (datetimeStr.contains(":")) {
datetimeStr = datetimeStr.replace(" ", "T"); // depends on control dependency: [if], data = [none]
}
} else if (datetimeStr.contains(":")) {
datetimeStr = "T" + datetimeStr; // depends on control dependency: [if], data = [none]
}
DateTime dateTime = new DateTime(datetimeStr, dateTimeZone);
return dateTime.toDate();
} }
|
public class class_name {
public static boolean[] unbox(final Boolean[] a, final boolean valueForNull) {
if (a == null) {
return null;
}
return unbox(a, 0, a.length, valueForNull);
} }
|
public class class_name {
public static boolean[] unbox(final Boolean[] a, final boolean valueForNull) {
if (a == null) {
return null;
// depends on control dependency: [if], data = [none]
}
return unbox(a, 0, a.length, valueForNull);
} }
|
public class class_name {
public RandomVariable expand(int numberOfPaths) {
if(isDeterministic()) {
// Expand random variable to a vector of path values
double[] clone = new double[numberOfPaths];
Arrays.fill(clone,valueIfNonStochastic);
return new RandomVariableFromDoubleArray(time,clone);
}
return new RandomVariableFromDoubleArray(time,getRealizations());
} }
|
public class class_name {
public RandomVariable expand(int numberOfPaths) {
if(isDeterministic()) {
// Expand random variable to a vector of path values
double[] clone = new double[numberOfPaths];
Arrays.fill(clone,valueIfNonStochastic); // depends on control dependency: [if], data = [none]
return new RandomVariableFromDoubleArray(time,clone); // depends on control dependency: [if], data = [none]
}
return new RandomVariableFromDoubleArray(time,getRealizations());
} }
|
public class class_name {
public DescribeJobFlowsResult withJobFlows(JobFlowDetail... jobFlows) {
if (this.jobFlows == null) {
setJobFlows(new com.amazonaws.internal.SdkInternalList<JobFlowDetail>(jobFlows.length));
}
for (JobFlowDetail ele : jobFlows) {
this.jobFlows.add(ele);
}
return this;
} }
|
public class class_name {
public DescribeJobFlowsResult withJobFlows(JobFlowDetail... jobFlows) {
if (this.jobFlows == null) {
setJobFlows(new com.amazonaws.internal.SdkInternalList<JobFlowDetail>(jobFlows.length)); // depends on control dependency: [if], data = [none]
}
for (JobFlowDetail ele : jobFlows) {
this.jobFlows.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
private byte[] replaceInXml(CmsFile cmsFile) throws Exception {
Exception e = null;
CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), cmsFile);
Pattern pattern = Pattern.compile(m_settings.getSearchpattern());
// loop over the locales of the content
boolean modified = false;
boolean matched = false;
String requestedLocale = m_settings.getLocale();
for (Locale locale : xmlContent.getLocales()) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(requestedLocale)
&& !locale.toString().equalsIgnoreCase(requestedLocale)) {
// does not match the requested locale, skip it
continue;
}
// loop over the available element paths of the current content locale
List<String> paths = xmlContent.getNames(locale);
for (String xpath : paths) {
// try to get the value extraction for the current element path
I_CmsXmlContentValue value = xmlContent.getValue(xpath, locale);
if (value.isSimpleType()) {
try {
String currPath = value.getPath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_settings.getXpath())
|| currPath.equals(m_settings.getXpath())
|| (CmsXmlUtils.removeXpath(currPath).equals(m_settings.getXpath()))) {
// xpath match
String oldVal = value.getStringValue(getCms());
Matcher matcher = pattern.matcher(oldVal);
matcher = Pattern.compile(m_settings.getSearchpattern()).matcher(oldVal);
if (matcher.find()) {
matched = true;
m_matchedResources.add(cmsFile);
if (m_replace) {
String newVal = matcher.replaceAll(m_settings.getReplacepattern());
if (!oldVal.equals(newVal)) {
value.setStringValue(getCms(), newVal);
modified = true;
}
}
}
}
} catch (Exception ex) {
// log and go on
LOG.error(ex.getMessage(), ex);
e = ex;
}
}
}
}
if (e != null) {
throw e;
}
if (matched) {
getReport().println(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
} else {
getReport().println(
Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
I_CmsReport.FORMAT_NOTE);
}
if (modified) {
return xmlContent.marshal();
}
return null;
} }
|
public class class_name {
private byte[] replaceInXml(CmsFile cmsFile) throws Exception {
Exception e = null;
CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), cmsFile);
Pattern pattern = Pattern.compile(m_settings.getSearchpattern());
// loop over the locales of the content
boolean modified = false;
boolean matched = false;
String requestedLocale = m_settings.getLocale();
for (Locale locale : xmlContent.getLocales()) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(requestedLocale)
&& !locale.toString().equalsIgnoreCase(requestedLocale)) {
// does not match the requested locale, skip it
continue;
}
// loop over the available element paths of the current content locale
List<String> paths = xmlContent.getNames(locale);
for (String xpath : paths) {
// try to get the value extraction for the current element path
I_CmsXmlContentValue value = xmlContent.getValue(xpath, locale);
if (value.isSimpleType()) {
try {
String currPath = value.getPath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_settings.getXpath())
|| currPath.equals(m_settings.getXpath())
|| (CmsXmlUtils.removeXpath(currPath).equals(m_settings.getXpath()))) {
// xpath match
String oldVal = value.getStringValue(getCms());
Matcher matcher = pattern.matcher(oldVal);
matcher = Pattern.compile(m_settings.getSearchpattern()).matcher(oldVal); // depends on control dependency: [if], data = [none]
if (matcher.find()) {
matched = true; // depends on control dependency: [if], data = [none]
m_matchedResources.add(cmsFile); // depends on control dependency: [if], data = [none]
if (m_replace) {
String newVal = matcher.replaceAll(m_settings.getReplacepattern());
if (!oldVal.equals(newVal)) {
value.setStringValue(getCms(), newVal); // depends on control dependency: [if], data = [none]
modified = true; // depends on control dependency: [if], data = [none]
}
}
}
}
} catch (Exception ex) {
// log and go on
LOG.error(ex.getMessage(), ex);
e = ex;
} // depends on control dependency: [catch], data = [none]
}
}
}
if (e != null) {
throw e;
}
if (matched) {
getReport().println(Messages.get().container(Messages.RPT_SOURCESEARCH_MATCHED_0), I_CmsReport.FORMAT_OK);
} else {
getReport().println(
Messages.get().container(Messages.RPT_SOURCESEARCH_NOT_MATCHED_0),
I_CmsReport.FORMAT_NOTE);
}
if (modified) {
return xmlContent.marshal();
}
return null;
} }
|
public class class_name {
private Message pollPrefetchQueue() {
final Message message = this.prefetchedMessages.poll();
if (message != null) {
// message lastReceivedOffset should be up-to-date upon each poll - as recreateLink will depend on this
this.lastReceivedMessage = message;
this.sendFlow(1);
}
return message;
} }
|
public class class_name {
private Message pollPrefetchQueue() {
final Message message = this.prefetchedMessages.poll();
if (message != null) {
// message lastReceivedOffset should be up-to-date upon each poll - as recreateLink will depend on this
this.lastReceivedMessage = message; // depends on control dependency: [if], data = [none]
this.sendFlow(1); // depends on control dependency: [if], data = [none]
}
return message;
} }
|
public class class_name {
public <V> T get(Functor<T, V> functor, V argument) throws Exception {
T result = _value;
if (isMissing(result)) synchronized(this) {
result = _value;
if (isMissing(result)) {
_value = result = functor.invoke(argument);
}
}
return result;
} }
|
public class class_name {
public <V> T get(Functor<T, V> functor, V argument) throws Exception {
T result = _value;
if (isMissing(result)) synchronized(this) {
result = _value;
if (isMissing(result)) {
_value = result = functor.invoke(argument);
// depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
private String handleUrls(String description) {
String result = description;
String[] urls = extractUrls(description);
if (urls.length > 0) {
for (String url : urls) {
String copy = url;
boolean trailingAcc = false;
if (!copy.startsWith("{")) {
copy = "<a>" + copy + "</a>";
} else if (copy.startsWith("{http")) {
if ('}' == result.charAt(result.indexOf(copy) + copy.length() + 2)) {
trailingAcc = true;
copy = "<a>" + copy.substring(1) + "</a>";
} else {
copy = "<a href=\"" + copy.replace("{", "").replace("}", "\">") + "</a>";
}
} else if (copy.startsWith("{./")) {
copy = "<a href=\"http://codenarc.sourceforge.net/" + copy.replace("{./", "").replace("}", "\">") + "</a>";
}
result = result.replace("{{" + url + "}}" + (trailingAcc ? "}" : ""), copy);
}
}
return result;
} }
|
public class class_name {
private String handleUrls(String description) {
String result = description;
String[] urls = extractUrls(description);
if (urls.length > 0) {
for (String url : urls) {
String copy = url;
boolean trailingAcc = false;
if (!copy.startsWith("{")) {
copy = "<a>" + copy + "</a>"; // depends on control dependency: [if], data = [none]
} else if (copy.startsWith("{http")) {
if ('}' == result.charAt(result.indexOf(copy) + copy.length() + 2)) {
trailingAcc = true; // depends on control dependency: [if], data = [none]
copy = "<a>" + copy.substring(1) + "</a>"; // depends on control dependency: [if], data = [none]
} else {
copy = "<a href=\"" + copy.replace("{", "").replace("}", "\">") + "</a>"; // depends on control dependency: [if], data = [none]
}
} else if (copy.startsWith("{./")) {
copy = "<a href=\"http://codenarc.sourceforge.net/" + copy.replace("{./", "").replace("}", "\">") + "</a>";
}
result = result.replace("{{" + url + "}}" + (trailingAcc ? "}" : ""), copy); // depends on control dependency: [for], data = [url]
}
}
return result;
} }
|
public class class_name {
@Override
public boolean contains(KType key) {
if (Intrinsics.isEmpty(key)) {
return hasEmptyKey;
} else {
final KType [] keys = Intrinsics.<KType[]> cast(this.keys);
final int mask = this.mask;
int slot = hashKey(key) & mask;
KType existing;
while (!Intrinsics.isEmpty(existing = keys[slot])) {
if (Intrinsics.equals(this, key, existing)) {
return true;
}
slot = (slot + 1) & mask;
}
return false;
}
} }
|
public class class_name {
@Override
public boolean contains(KType key) {
if (Intrinsics.isEmpty(key)) {
return hasEmptyKey; // depends on control dependency: [if], data = [none]
} else {
final KType [] keys = Intrinsics.<KType[]> cast(this.keys);
final int mask = this.mask;
int slot = hashKey(key) & mask;
KType existing;
while (!Intrinsics.isEmpty(existing = keys[slot])) {
if (Intrinsics.equals(this, key, existing)) {
return true; // depends on control dependency: [if], data = [none]
}
slot = (slot + 1) & mask; // depends on control dependency: [while], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void marshall(IdentityDescription identityDescription, ProtocolMarshaller protocolMarshaller) {
if (identityDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(identityDescription.getIdentityId(), IDENTITYID_BINDING);
protocolMarshaller.marshall(identityDescription.getLogins(), LOGINS_BINDING);
protocolMarshaller.marshall(identityDescription.getCreationDate(), CREATIONDATE_BINDING);
protocolMarshaller.marshall(identityDescription.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(IdentityDescription identityDescription, ProtocolMarshaller protocolMarshaller) {
if (identityDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(identityDescription.getIdentityId(), IDENTITYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(identityDescription.getLogins(), LOGINS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(identityDescription.getCreationDate(), CREATIONDATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(identityDescription.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void drawLineBaseRatio(double[]... coord) {
int[][] sc = new int[coord.length][];
for (int i = 0; i < sc.length; i++) {
sc[i] = projection.screenProjectionBaseRatio(coord[i]);
}
drawLine(sc);
} }
|
public class class_name {
public void drawLineBaseRatio(double[]... coord) {
int[][] sc = new int[coord.length][];
for (int i = 0; i < sc.length; i++) {
sc[i] = projection.screenProjectionBaseRatio(coord[i]); // depends on control dependency: [for], data = [i]
}
drawLine(sc);
} }
|
public class class_name {
private void handleElementCollectionAttribute(CQLTranslator translator, Attribute attribute,
StringBuilder typeQueryBuilder)
{
String dataType = CassandraValidationClassMapper.getValidationClass(attribute.getJavaType(), true);
// CQL Type of collection column
String collectionCqlType = translator.getCQLType(dataType);
// Collection Column Name
String collectionColumnName = new String(((AbstractAttribute) attribute).getJPAColumnName());
// Generic Type list
StringBuilder genericTypesBuilder = null;
List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute.getJavaMember());
if (!genericClasses.isEmpty())
{
genericTypesBuilder = new StringBuilder();
if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2)
{
genericTypesBuilder.append(Constants.STR_LT);
if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey);
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType));
}
genericTypesBuilder.append(Constants.SPACE_COMMA);
if (genericClasses.get(1).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(1).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey);
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType));
}
genericTypesBuilder.append(Constants.STR_GT);
}
else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals(dataType))
&& genericClasses.size() == 1)
{
genericTypesBuilder.append(Constants.STR_LT);
if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey);
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType));
}
genericTypesBuilder.append(Constants.STR_GT);
}
else
{
throw new SchemaGenerationException("Incorrect collection field definition for "
+ ((AbstractAttribute) attribute).getJPAColumnName()
+ ". Generic Types must be defined correctly.");
}
}
if (genericTypesBuilder != null)
{
collectionCqlType += genericTypesBuilder.toString();
}
translator.appendColumnName(typeQueryBuilder, collectionColumnName, collectionCqlType);
typeQueryBuilder.append(Constants.SPACE_COMMA);
} }
|
public class class_name {
private void handleElementCollectionAttribute(CQLTranslator translator, Attribute attribute,
StringBuilder typeQueryBuilder)
{
String dataType = CassandraValidationClassMapper.getValidationClass(attribute.getJavaType(), true);
// CQL Type of collection column
String collectionCqlType = translator.getCQLType(dataType);
// Collection Column Name
String collectionColumnName = new String(((AbstractAttribute) attribute).getJPAColumnName());
// Generic Type list
StringBuilder genericTypesBuilder = null;
List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute.getJavaMember());
if (!genericClasses.isEmpty())
{
genericTypesBuilder = new StringBuilder(); // depends on control dependency: [if], data = [none]
if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2)
{
genericTypesBuilder.append(Constants.STR_LT); // depends on control dependency: [if], data = [none]
if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey); // depends on control dependency: [if], data = [none]
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType)); // depends on control dependency: [if], data = [none]
}
genericTypesBuilder.append(Constants.SPACE_COMMA); // depends on control dependency: [if], data = [none]
if (genericClasses.get(1).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(1).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey); // depends on control dependency: [if], data = [none]
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType)); // depends on control dependency: [if], data = [none]
}
genericTypesBuilder.append(Constants.STR_GT); // depends on control dependency: [if], data = [none]
}
else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals(dataType))
&& genericClasses.size() == 1)
{
genericTypesBuilder.append(Constants.STR_LT); // depends on control dependency: [if], data = [none]
if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)
{
String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
+ genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;
genericTypesBuilder.append(frozenKey); // depends on control dependency: [if], data = [none]
}
else
{
String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);
genericTypesBuilder.append(translator.getCQLType(keyDataType)); // depends on control dependency: [if], data = [none]
}
genericTypesBuilder.append(Constants.STR_GT); // depends on control dependency: [if], data = [none]
}
else
{
throw new SchemaGenerationException("Incorrect collection field definition for "
+ ((AbstractAttribute) attribute).getJPAColumnName()
+ ". Generic Types must be defined correctly.");
}
}
if (genericTypesBuilder != null)
{
collectionCqlType += genericTypesBuilder.toString(); // depends on control dependency: [if], data = [none]
}
translator.appendColumnName(typeQueryBuilder, collectionColumnName, collectionCqlType);
typeQueryBuilder.append(Constants.SPACE_COMMA);
} }
|
public class class_name {
public static ConverterInitializer newInstance(State state, WorkUnitStream workUnits) {
int branches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1);
if (branches == 1) {
return newInstance(state, workUnits, branches, 0);
}
List<ConverterInitializer> cis = Lists.newArrayList();
for (int branchId = 0; branchId < branches; branchId++) {
cis.add(newInstance(state, workUnits, branches, branchId));
}
return new MultiConverterInitializer(cis);
} }
|
public class class_name {
public static ConverterInitializer newInstance(State state, WorkUnitStream workUnits) {
int branches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1);
if (branches == 1) {
return newInstance(state, workUnits, branches, 0); // depends on control dependency: [if], data = [none]
}
List<ConverterInitializer> cis = Lists.newArrayList();
for (int branchId = 0; branchId < branches; branchId++) {
cis.add(newInstance(state, workUnits, branches, branchId)); // depends on control dependency: [for], data = [branchId]
}
return new MultiConverterInitializer(cis);
} }
|
public class class_name {
private void loadUser(String username)
{
try
{
if (null==_con)
connectDatabase();
if (null==_con)
throw new SQLException("Can't connect to database");
PreparedStatement stat = _con.prepareStatement(_userSql);
stat.setObject(1, username);
ResultSet rs = stat.executeQuery();
if (rs.next())
{
Object key = rs.getObject(_userTableKey);
put(username, rs.getString(_userTablePasswordField));
stat.close();
stat = _con.prepareStatement(_roleSql);
stat.setObject(1, key);
rs = stat.executeQuery();
while (rs.next())
addUserToRole(username, rs.getString(_roleTableRoleField));
stat.close();
}
}
catch (SQLException e)
{
log.warn("UserRealm " + getName()
+ " could not load user information from database", e);
connectDatabase();
}
} }
|
public class class_name {
private void loadUser(String username)
{
try
{
if (null==_con)
connectDatabase();
if (null==_con)
throw new SQLException("Can't connect to database");
PreparedStatement stat = _con.prepareStatement(_userSql);
stat.setObject(1, username); // depends on control dependency: [try], data = [none]
ResultSet rs = stat.executeQuery();
if (rs.next())
{
Object key = rs.getObject(_userTableKey);
put(username, rs.getString(_userTablePasswordField)); // depends on control dependency: [if], data = [none]
stat.close(); // depends on control dependency: [if], data = [none]
stat = _con.prepareStatement(_roleSql); // depends on control dependency: [if], data = [none]
stat.setObject(1, key); // depends on control dependency: [if], data = [none]
rs = stat.executeQuery(); // depends on control dependency: [if], data = [none]
while (rs.next())
addUserToRole(username, rs.getString(_roleTableRoleField));
stat.close(); // depends on control dependency: [if], data = [none]
}
}
catch (SQLException e)
{
log.warn("UserRealm " + getName()
+ " could not load user information from database", e);
connectDatabase();
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public void publish(String channel, Tree message) {
if (client != null) {
try {
int pos = channel.indexOf('.');
if (channel.indexOf('.', pos + 1) > -1) {
// Send to queue directly
if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) {
logger.info("Submitting message to queue \"" + channel + "\":\r\n" + message.toString());
}
this.channel.basicPublish("", channel, mandatory, immediate, messageProperties,
serializer.write(message));
} else {
// Send to exchange
if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) {
logger.info("Submitting message to exchange \"" + channel + "\":\r\n" + message.toString());
}
this.channel.basicPublish(channel, "", mandatory, immediate, messageProperties,
serializer.write(message));
}
} catch (Exception cause) {
logger.warn("Unable to send message to AMQP server!", cause);
}
}
} }
|
public class class_name {
@Override
public void publish(String channel, Tree message) {
if (client != null) {
try {
int pos = channel.indexOf('.');
if (channel.indexOf('.', pos + 1) > -1) {
// Send to queue directly
if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) {
logger.info("Submitting message to queue \"" + channel + "\":\r\n" + message.toString()); // depends on control dependency: [if], data = [none]
}
this.channel.basicPublish("", channel, mandatory, immediate, messageProperties,
serializer.write(message)); // depends on control dependency: [if], data = [none]
} else {
// Send to exchange
if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) {
logger.info("Submitting message to exchange \"" + channel + "\":\r\n" + message.toString()); // depends on control dependency: [if], data = [none]
}
this.channel.basicPublish(channel, "", mandatory, immediate, messageProperties,
serializer.write(message)); // depends on control dependency: [if], data = [none]
}
} catch (Exception cause) {
logger.warn("Unable to send message to AMQP server!", cause);
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
private void recursiveLogResult(StringBuilder buf, Hierarchy<Result> hier, Result result, int depth) {
if(result == null) {
buf.append("null");
LOG.warning("null result!");
return;
}
if(depth > 50) {
LOG.warning("Probably infinitely nested results, aborting!");
return;
}
for(int i = 0; i < depth; i++) {
buf.append(' ');
}
buf.append(result.getClass().getSimpleName()).append(": ").append(result.getLongName()) //
.append(" (").append(result.getShortName()).append(")\n");
if(hier.numChildren(result) > 0) {
for(It<Result> iter = hier.iterChildren(result); iter.valid(); iter.advance()) {
recursiveLogResult(buf, hier, iter.get(), depth + 1);
}
}
} }
|
public class class_name {
private void recursiveLogResult(StringBuilder buf, Hierarchy<Result> hier, Result result, int depth) {
if(result == null) {
buf.append("null"); // depends on control dependency: [if], data = [none]
LOG.warning("null result!"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if(depth > 50) {
LOG.warning("Probably infinitely nested results, aborting!"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
for(int i = 0; i < depth; i++) {
buf.append(' '); // depends on control dependency: [for], data = [none]
}
buf.append(result.getClass().getSimpleName()).append(": ").append(result.getLongName()) //
.append(" (").append(result.getShortName()).append(")\n");
if(hier.numChildren(result) > 0) {
for(It<Result> iter = hier.iterChildren(result); iter.valid(); iter.advance()) {
recursiveLogResult(buf, hier, iter.get(), depth + 1); // depends on control dependency: [for], data = [iter]
}
}
} }
|
public class class_name {
public static float toFloatValue(Object o, float defaultValue) {
if (o instanceof Character) return (((Character) o).charValue());
else if (o instanceof Boolean) return ((((Boolean) o).booleanValue()) ? 1F : 0F);
else if (o instanceof Number) return (((Number) o).floatValue());
else if (o instanceof CharSequence) return (float) toDoubleValue(o.toString(), defaultValue);
else if (o instanceof Character) return (float) (((Character) o).charValue());
else if (o instanceof Castable) {
return (float) ((Castable) o).castToDoubleValue(defaultValue);
}
else if (o instanceof ObjectWrap) return toFloatValue(((ObjectWrap) o).getEmbededObject(toFloat(defaultValue)), defaultValue);
return defaultValue;
} }
|
public class class_name {
public static float toFloatValue(Object o, float defaultValue) {
if (o instanceof Character) return (((Character) o).charValue());
else if (o instanceof Boolean) return ((((Boolean) o).booleanValue()) ? 1F : 0F);
else if (o instanceof Number) return (((Number) o).floatValue());
else if (o instanceof CharSequence) return (float) toDoubleValue(o.toString(), defaultValue);
else if (o instanceof Character) return (float) (((Character) o).charValue());
else if (o instanceof Castable) {
return (float) ((Castable) o).castToDoubleValue(defaultValue); // depends on control dependency: [if], data = [none]
}
else if (o instanceof ObjectWrap) return toFloatValue(((ObjectWrap) o).getEmbededObject(toFloat(defaultValue)), defaultValue);
return defaultValue;
} }
|
public class class_name {
public JobScheduleTerminateHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
} }
|
public class class_name {
public JobScheduleTerminateHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null; // depends on control dependency: [if], data = [none]
} else {
this.lastModified = new DateTimeRfc1123(lastModified); // depends on control dependency: [if], data = [(lastModified]
}
return this;
} }
|
public class class_name {
private String formatCoef(double coef) {
double tol = 1e-6; // rounding tolerance
// zero case
if( Math.abs(coef) < tol) {
return "0";
}
// integer case
long num = Math.round(coef);
if( Math.abs(num - coef) < tol) {
return Long.toString(num);
}
// Other small cases
for(int denom = 2; denom < 12; denom++ ) {
num = Math.round(coef*denom);
if( num - coef*denom < tol ) {
return String.format("%d/%d",num, denom);
}
}
// Give up and use floating point;
return String.format("%.3f", coef);
} }
|
public class class_name {
private String formatCoef(double coef) {
double tol = 1e-6; // rounding tolerance
// zero case
if( Math.abs(coef) < tol) {
return "0"; // depends on control dependency: [if], data = [none]
}
// integer case
long num = Math.round(coef);
if( Math.abs(num - coef) < tol) {
return Long.toString(num); // depends on control dependency: [if], data = [none]
}
// Other small cases
for(int denom = 2; denom < 12; denom++ ) {
num = Math.round(coef*denom); // depends on control dependency: [for], data = [denom]
if( num - coef*denom < tol ) {
return String.format("%d/%d",num, denom); // depends on control dependency: [if], data = [none]
}
}
// Give up and use floating point;
return String.format("%.3f", coef);
} }
|
public class class_name {
protected void encodeData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
final JavascriptVarBuilder jsData = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsRowKeys = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsStyle = new JavascriptVarBuilder(null, true);
final JavascriptVarBuilder jsRowStyle = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsReadOnly = new JavascriptVarBuilder(null, true);
final JavascriptVarBuilder jsRowHeaders = new JavascriptVarBuilder(null, false);
final boolean isCustomHeader = sheet.getRowHeaderValueExpression() != null;
final List<Object> values = sheet.getSortedValues();
int row = 0;
for (final Object value : values) {
context.getExternalContext().getRequestMap().put(sheet.getVar(), value);
final String rowKey = sheet.getRowKeyValueAsString(context);
jsRowKeys.appendArrayValue(rowKey, true);
encodeRow(context, rowKey, jsData, jsRowStyle, jsStyle, jsReadOnly, sheet, row);
// In case of custom row header evaluate the value expression for every row to
// set the header
if (sheet.isShowRowHeaders() && isCustomHeader) {
final String rowHeader = sheet.getRowHeaderValueAsString(context);
jsRowHeaders.appendArrayValue(rowHeader, true);
}
row++;
}
sheet.setRowVar(context, null);
wb.nativeAttr("data", jsData.closeVar().toString());
wb.nativeAttr("styles", jsStyle.closeVar().toString());
wb.nativeAttr("rowStyles", jsRowStyle.closeVar().toString());
wb.nativeAttr("readOnlyCells", jsReadOnly.closeVar().toString());
wb.nativeAttr("rowKeys", jsRowKeys.closeVar().toString());
// add the row header as a native attribute
if (!isCustomHeader) {
wb.nativeAttr("rowHeaders", sheet.isShowRowHeaders().toString());
}
else {
wb.nativeAttr("rowHeaders", jsRowHeaders.closeVar().toString());
}
} }
|
public class class_name {
protected void encodeData(final FacesContext context, final Sheet sheet, final WidgetBuilder wb)
throws IOException {
final JavascriptVarBuilder jsData = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsRowKeys = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsStyle = new JavascriptVarBuilder(null, true);
final JavascriptVarBuilder jsRowStyle = new JavascriptVarBuilder(null, false);
final JavascriptVarBuilder jsReadOnly = new JavascriptVarBuilder(null, true);
final JavascriptVarBuilder jsRowHeaders = new JavascriptVarBuilder(null, false);
final boolean isCustomHeader = sheet.getRowHeaderValueExpression() != null;
final List<Object> values = sheet.getSortedValues();
int row = 0;
for (final Object value : values) {
context.getExternalContext().getRequestMap().put(sheet.getVar(), value);
final String rowKey = sheet.getRowKeyValueAsString(context);
jsRowKeys.appendArrayValue(rowKey, true);
encodeRow(context, rowKey, jsData, jsRowStyle, jsStyle, jsReadOnly, sheet, row);
// In case of custom row header evaluate the value expression for every row to
// set the header
if (sheet.isShowRowHeaders() && isCustomHeader) {
final String rowHeader = sheet.getRowHeaderValueAsString(context);
jsRowHeaders.appendArrayValue(rowHeader, true); // depends on control dependency: [if], data = [none]
}
row++;
}
sheet.setRowVar(context, null);
wb.nativeAttr("data", jsData.closeVar().toString());
wb.nativeAttr("styles", jsStyle.closeVar().toString());
wb.nativeAttr("rowStyles", jsRowStyle.closeVar().toString());
wb.nativeAttr("readOnlyCells", jsReadOnly.closeVar().toString());
wb.nativeAttr("rowKeys", jsRowKeys.closeVar().toString());
// add the row header as a native attribute
if (!isCustomHeader) {
wb.nativeAttr("rowHeaders", sheet.isShowRowHeaders().toString());
}
else {
wb.nativeAttr("rowHeaders", jsRowHeaders.closeVar().toString());
}
} }
|
public class class_name {
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf) {
this.stormConf = stormConf;
int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");
if (maxWorkers > 0) {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory), maxWorkers);
} else {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory));
}
reconnector = new ReconnectRunnable();
new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
} }
|
public class class_name {
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf) {
this.stormConf = stormConf;
int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");
if (maxWorkers > 0) {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory), maxWorkers); // depends on control dependency: [if], data = [none]
} else {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory)); // depends on control dependency: [if], data = [none]
}
reconnector = new ReconnectRunnable();
new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
} }
|
public class class_name {
private static String guessDumpDate(String fileName) {
Pattern p = Pattern.compile("([0-9]{8})");
Matcher m = p.matcher(fileName);
if (m.find()) {
return m.group(1);
} else {
logger.info("Could not guess date of the dump file \"" + fileName
+ "\". Defaulting to YYYYMMDD.");
return "YYYYMMDD";
}
} }
|
public class class_name {
private static String guessDumpDate(String fileName) {
Pattern p = Pattern.compile("([0-9]{8})");
Matcher m = p.matcher(fileName);
if (m.find()) {
return m.group(1); // depends on control dependency: [if], data = [none]
} else {
logger.info("Could not guess date of the dump file \"" + fileName
+ "\". Defaulting to YYYYMMDD."); // depends on control dependency: [if], data = [none]
return "YYYYMMDD"; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
protected void getLinkForTypeVariable(Content link, LinkInfo linkInfo, Type type) {
link.addContent(getTypeAnnotationLinks(linkInfo));
linkInfo.isTypeBound = true;
final Doc owner = type.asTypeVariable().owner();
if ((!linkInfo.excludeTypeParameterLinks) && owner instanceof ClassDoc) {
linkInfo.classDoc = (ClassDoc) owner;
final Content label = newContent();
label.addContent(type.typeName());
linkInfo.label = label;
link.addContent(getClassLink(linkInfo));
} else {
link.addContent(type.typeName());
}
final Type[] bounds = type.asTypeVariable().bounds();
if (!linkInfo.excludeTypeBounds) {
linkInfo.excludeTypeBounds = true;
final SARLFeatureAccess kw = Utils.getKeywords();
for (int i = 0; i < bounds.length; ++i) {
link.addContent(i > 0 ? " " + kw.getAmpersandKeyword() + " " //$NON-NLS-1$ //$NON-NLS-2$
: " " + kw.getExtendsKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$
setBoundsLinkInfo(linkInfo, bounds[i]);
link.addContent(getLink(linkInfo));
}
}
} }
|
public class class_name {
protected void getLinkForTypeVariable(Content link, LinkInfo linkInfo, Type type) {
link.addContent(getTypeAnnotationLinks(linkInfo));
linkInfo.isTypeBound = true;
final Doc owner = type.asTypeVariable().owner();
if ((!linkInfo.excludeTypeParameterLinks) && owner instanceof ClassDoc) {
linkInfo.classDoc = (ClassDoc) owner; // depends on control dependency: [if], data = [none]
final Content label = newContent();
label.addContent(type.typeName()); // depends on control dependency: [if], data = [none]
linkInfo.label = label; // depends on control dependency: [if], data = [none]
link.addContent(getClassLink(linkInfo)); // depends on control dependency: [if], data = [none]
} else {
link.addContent(type.typeName()); // depends on control dependency: [if], data = [none]
}
final Type[] bounds = type.asTypeVariable().bounds();
if (!linkInfo.excludeTypeBounds) {
linkInfo.excludeTypeBounds = true; // depends on control dependency: [if], data = [none]
final SARLFeatureAccess kw = Utils.getKeywords();
for (int i = 0; i < bounds.length; ++i) {
link.addContent(i > 0 ? " " + kw.getAmpersandKeyword() + " " //$NON-NLS-1$ //$NON-NLS-2$
: " " + kw.getExtendsKeyword() + " "); //$NON-NLS-1$ //$NON-NLS-2$ // depends on control dependency: [for], data = [i]
setBoundsLinkInfo(linkInfo, bounds[i]); // depends on control dependency: [for], data = [i]
link.addContent(getLink(linkInfo)); // depends on control dependency: [for], data = [none]
}
}
} }
|
public class class_name {
public final ObjectType getPrototype() {
// lazy initialization of the prototype field
if (prototypeSlot == null) {
String refName = getReferenceName();
if (refName == null) {
// Someone is trying to access the prototype of a structural function.
// We don't want to give real properties to this prototype, because
// then it would propagate to all structural functions.
setPrototypeNoCheck(registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE), null);
} else {
setPrototype(
new PrototypeObjectType(
registry,
getReferenceName() + ".prototype",
registry.getNativeObjectType(OBJECT_TYPE),
isNativeObjectType(),
null),
null);
}
}
return (ObjectType) prototypeSlot.getType();
} }
|
public class class_name {
public final ObjectType getPrototype() {
// lazy initialization of the prototype field
if (prototypeSlot == null) {
String refName = getReferenceName();
if (refName == null) {
// Someone is trying to access the prototype of a structural function.
// We don't want to give real properties to this prototype, because
// then it would propagate to all structural functions.
setPrototypeNoCheck(registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE), null); // depends on control dependency: [if], data = [null)]
} else {
setPrototype(
new PrototypeObjectType(
registry,
getReferenceName() + ".prototype",
registry.getNativeObjectType(OBJECT_TYPE),
isNativeObjectType(),
null),
null); // depends on control dependency: [if], data = [none]
}
}
return (ObjectType) prototypeSlot.getType();
} }
|
public class class_name {
public Object toNeo4JProperty(Object source)
{
if (source instanceof BigDecimal || source instanceof BigInteger)
{
return source.toString();
}
else if ((source instanceof Calendar) || (source instanceof GregorianCalendar))
{
return PropertyAccessorHelper.fromSourceToTargetClass(String.class, Date.class,
((Calendar) source).getTime());
}
if (source instanceof Date)
{
Class<?> sourceClass = source.getClass();
return PropertyAccessorHelper.fromSourceToTargetClass(String.class, sourceClass, source);
}
return source;
} }
|
public class class_name {
public Object toNeo4JProperty(Object source)
{
if (source instanceof BigDecimal || source instanceof BigInteger)
{
return source.toString(); // depends on control dependency: [if], data = [none]
}
else if ((source instanceof Calendar) || (source instanceof GregorianCalendar))
{
return PropertyAccessorHelper.fromSourceToTargetClass(String.class, Date.class,
((Calendar) source).getTime()); // depends on control dependency: [if], data = [none]
}
if (source instanceof Date)
{
Class<?> sourceClass = source.getClass();
return PropertyAccessorHelper.fromSourceToTargetClass(String.class, sourceClass, source); // depends on control dependency: [if], data = [none]
}
return source;
} }
|
public class class_name {
public static String replaceChars(final String s, final char[] sub, final char[] with) {
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
char c = str[i];
for (int j = 0; j < sub.length; j++) {
if (c == sub[j]) {
str[i] = with[j];
break;
}
}
}
return new String(str);
} }
|
public class class_name {
public static String replaceChars(final String s, final char[] sub, final char[] with) {
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
char c = str[i];
for (int j = 0; j < sub.length; j++) {
if (c == sub[j]) {
str[i] = with[j]; // depends on control dependency: [if], data = [none]
break;
}
}
}
return new String(str);
} }
|
public class class_name {
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigInteger min, @Nonnull final BigInteger max) {
Check.notNull(number, "number");
Check.notNull(min, "min");
Check.notNull(max, "max");
BigInteger bigInteger = null;
if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) {
bigInteger = BigInteger.valueOf(number.longValue());
} else if (number instanceof Float || number instanceof Double) {
bigInteger = new BigDecimal(number.doubleValue()).toBigInteger();
} else if (number instanceof BigInteger) {
bigInteger = (BigInteger) number;
} else if (number instanceof BigDecimal) {
bigInteger = ((BigDecimal) number).toBigInteger();
} else {
throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': "
+ number.getClass().getName());
}
return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0;
} }
|
public class class_name {
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigInteger min, @Nonnull final BigInteger max) {
Check.notNull(number, "number");
Check.notNull(min, "min");
Check.notNull(max, "max");
BigInteger bigInteger = null;
if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) {
bigInteger = BigInteger.valueOf(number.longValue()); // depends on control dependency: [if], data = [none]
} else if (number instanceof Float || number instanceof Double) {
bigInteger = new BigDecimal(number.doubleValue()).toBigInteger(); // depends on control dependency: [if], data = [none]
} else if (number instanceof BigInteger) {
bigInteger = (BigInteger) number; // depends on control dependency: [if], data = [none]
} else if (number instanceof BigDecimal) {
bigInteger = ((BigDecimal) number).toBigInteger(); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': "
+ number.getClass().getName());
}
return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0;
} }
|
public class class_name {
public static UpdateDescription fromBsonDocument(final BsonDocument document) {
keyPresent(Fields.UPDATED_FIELDS_FIELD, document);
keyPresent(Fields.REMOVED_FIELDS_FIELD, document);
final BsonArray removedFieldsArr =
document.getArray(Fields.REMOVED_FIELDS_FIELD);
final Set<String> removedFields = new HashSet<>(removedFieldsArr.size());
for (final BsonValue field : removedFieldsArr) {
removedFields.add(field.asString().getValue());
}
return new UpdateDescription(document.getDocument(Fields.UPDATED_FIELDS_FIELD), removedFields);
} }
|
public class class_name {
public static UpdateDescription fromBsonDocument(final BsonDocument document) {
keyPresent(Fields.UPDATED_FIELDS_FIELD, document);
keyPresent(Fields.REMOVED_FIELDS_FIELD, document);
final BsonArray removedFieldsArr =
document.getArray(Fields.REMOVED_FIELDS_FIELD);
final Set<String> removedFields = new HashSet<>(removedFieldsArr.size());
for (final BsonValue field : removedFieldsArr) {
removedFields.add(field.asString().getValue()); // depends on control dependency: [for], data = [field]
}
return new UpdateDescription(document.getDocument(Fields.UPDATED_FIELDS_FIELD), removedFields);
} }
|
public class class_name {
public Element toElement(final ExcelDatastore datastore, final String filename) {
final Element ds = getDocument().createElement("excel-datastore");
ds.setAttribute("name", datastore.getName());
if (!Strings.isNullOrEmpty(datastore.getDescription())) {
ds.setAttribute("description", datastore.getDescription());
}
appendElement(ds, "filename", filename);
if (datastore.getCustomColumnNames() != null && datastore.getCustomColumnNames().size() > 0) {
final Element customColumnNamesElement = getDocument().createElement("custom-column-names");
ds.appendChild(customColumnNamesElement);
datastore.getCustomColumnNames()
.forEach(columnName -> appendElement(customColumnNamesElement, "column-name", columnName));
}
return ds;
} }
|
public class class_name {
public Element toElement(final ExcelDatastore datastore, final String filename) {
final Element ds = getDocument().createElement("excel-datastore");
ds.setAttribute("name", datastore.getName());
if (!Strings.isNullOrEmpty(datastore.getDescription())) {
ds.setAttribute("description", datastore.getDescription()); // depends on control dependency: [if], data = [none]
}
appendElement(ds, "filename", filename);
if (datastore.getCustomColumnNames() != null && datastore.getCustomColumnNames().size() > 0) {
final Element customColumnNamesElement = getDocument().createElement("custom-column-names");
ds.appendChild(customColumnNamesElement); // depends on control dependency: [if], data = [none]
datastore.getCustomColumnNames()
.forEach(columnName -> appendElement(customColumnNamesElement, "column-name", columnName)); // depends on control dependency: [if], data = [none]
}
return ds;
} }
|
public class class_name {
public void onChangeMode(IndexerIoMode mode)
{
if (mode == IndexerIoMode.READ_WRITE)
{
// Now is read-write. Index list is actual and shouldn't be refreshed.
// Remove listener to avoid asserting if ioMode is RO on each cache event
cache.removeListener(this);
// re-read from FS current actual list.
try
{
if (!multiIndex.isStopped())
{
super.read();
}
}
catch (IOException e)
{
LOG.error("Cannot read the list of index names", e);
}
}
else
{
// Currently READ_ONLY is set, so new lists should be fired to multiIndex.
cache.addListener(this);
}
} }
|
public class class_name {
public void onChangeMode(IndexerIoMode mode)
{
if (mode == IndexerIoMode.READ_WRITE)
{
// Now is read-write. Index list is actual and shouldn't be refreshed.
// Remove listener to avoid asserting if ioMode is RO on each cache event
cache.removeListener(this);
// depends on control dependency: [if], data = [none]
// re-read from FS current actual list.
try
{
if (!multiIndex.isStopped())
{
super.read();
// depends on control dependency: [if], data = [none]
}
}
catch (IOException e)
{
LOG.error("Cannot read the list of index names", e);
}
// depends on control dependency: [catch], data = [none]
}
else
{
// Currently READ_ONLY is set, so new lists should be fired to multiIndex.
cache.addListener(this);
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private synchronized Jwt getJwt(ICacheStrategy cacheStrategy, Jwt.Key key) {
Jwt result = cacheStrategy.getCachedJwt(key);
if(result == null) {
//cache an empty JWT first.
result = new Jwt(key);
cacheStrategy.cacheJwt(key, result);
}
return result;
} }
|
public class class_name {
private synchronized Jwt getJwt(ICacheStrategy cacheStrategy, Jwt.Key key) {
Jwt result = cacheStrategy.getCachedJwt(key);
if(result == null) {
//cache an empty JWT first.
result = new Jwt(key); // depends on control dependency: [if], data = [none]
cacheStrategy.cacheJwt(key, result); // depends on control dependency: [if], data = [none]
}
return result;
} }
|
public class class_name {
void _prepareResponseDataOnlyOnce(HttpServletRequest req) {
if (req.getAttribute(KEY_FILE) == null) {
String pathInfo = req.getPathInfo();
if (pathInfo == null)
pathInfo = "";
String fileSeparator = System.getProperty("file.separator");
String filePath = pathInfo.replaceAll(Pattern.quote("/"), fileSeparator);
String mappedDirPath = getMappedDirPath();
File file = new File(mappedDirPath, filePath);
boolean isDirectory = file.isDirectory();
req.setAttribute(KEY_IS_DIR, isDirectory);
if (isDirectory)
file = new File(mappedDirPath, getIndexFilename());
req.setAttribute(KEY_FILE, file);
req.setAttribute(KEY_MIME, __getMimeType(file));
req.setAttribute(KEY_LAST_MODIFIED, file.exists() ? file.lastModified() : 0);
}
} }
|
public class class_name {
void _prepareResponseDataOnlyOnce(HttpServletRequest req) {
if (req.getAttribute(KEY_FILE) == null) {
String pathInfo = req.getPathInfo();
if (pathInfo == null)
pathInfo = "";
String fileSeparator = System.getProperty("file.separator");
String filePath = pathInfo.replaceAll(Pattern.quote("/"), fileSeparator);
String mappedDirPath = getMappedDirPath();
File file = new File(mappedDirPath, filePath);
boolean isDirectory = file.isDirectory();
req.setAttribute(KEY_IS_DIR, isDirectory); // depends on control dependency: [if], data = [none]
if (isDirectory)
file = new File(mappedDirPath, getIndexFilename());
req.setAttribute(KEY_FILE, file); // depends on control dependency: [if], data = [none]
req.setAttribute(KEY_MIME, __getMimeType(file)); // depends on control dependency: [if], data = [none]
req.setAttribute(KEY_LAST_MODIFIED, file.exists() ? file.lastModified() : 0); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static String urlEncode(String value) {
if (value == null) {
return value;
}
try {
value = URLEncoder.encode(value, CommonWebConstants.UTF_8);
} catch (UnsupportedEncodingException e) {
// Do nothing - UTF-8 should always be supported
}
return value;
} }
|
public class class_name {
public static String urlEncode(String value) {
if (value == null) {
return value; // depends on control dependency: [if], data = [none]
}
try {
value = URLEncoder.encode(value, CommonWebConstants.UTF_8); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
// Do nothing - UTF-8 should always be supported
} // depends on control dependency: [catch], data = [none]
return value;
} }
|
public class class_name {
@Override
public StringBuffer postProcessBundle(BundleProcessingStatus status, StringBuffer bundleData) {
StringBuffer processedBundle = null;
try {
if (LOGGER.isDebugEnabled())
LOGGER.debug("postprocessing bundle:" + status.getCurrentBundle().getId());
processedBundle = doPostProcessBundle(status, bundleData);
} catch (IOException e) {
throw new BundlingProcessException("Unexpected IOException during execution of a postprocessor.", e);
}
if (null != nextProcessor) {
processedBundle = nextProcessor.postProcessBundle(status, processedBundle);
}
return processedBundle;
} }
|
public class class_name {
@Override
public StringBuffer postProcessBundle(BundleProcessingStatus status, StringBuffer bundleData) {
StringBuffer processedBundle = null;
try {
if (LOGGER.isDebugEnabled())
LOGGER.debug("postprocessing bundle:" + status.getCurrentBundle().getId());
processedBundle = doPostProcessBundle(status, bundleData); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new BundlingProcessException("Unexpected IOException during execution of a postprocessor.", e);
} // depends on control dependency: [catch], data = [none]
if (null != nextProcessor) {
processedBundle = nextProcessor.postProcessBundle(status, processedBundle); // depends on control dependency: [if], data = [none]
}
return processedBundle;
} }
|
public class class_name {
@Override
public final void setDeliveryDelay(long value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setDeliveryDelay", Long.valueOf(value));
if ((value >= MfpConstants.MIN_DELIVERY_DELAY) && (value <= MfpConstants.MAX_DELIVERY_DELAY)) {
super.setDeliveryDelay(value);
}
else {
IllegalArgumentException e = new IllegalArgumentException(Long.toString(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "setDeliveryDelay", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "setDeliveryDelay");
} }
|
public class class_name {
@Override
public final void setDeliveryDelay(long value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setDeliveryDelay", Long.valueOf(value));
if ((value >= MfpConstants.MIN_DELIVERY_DELAY) && (value <= MfpConstants.MAX_DELIVERY_DELAY)) {
super.setDeliveryDelay(value); // depends on control dependency: [if], data = [none]
}
else {
IllegalArgumentException e = new IllegalArgumentException(Long.toString(value));
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "setDeliveryDelay", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "setDeliveryDelay");
} }
|
public class class_name {
public @NotNull StringAssert isEqualToIgnoringCase(String expected) {
if (actual == null && expected == null) {
return this;
}
isNotNull();
if (actual.equalsIgnoreCase(expected)) {
return this;
}
failIfCustomMessageIsSet();
throw failure(format("<%s> should be equal to :<%s> ignoring case", actual, expected));
} }
|
public class class_name {
public @NotNull StringAssert isEqualToIgnoringCase(String expected) {
if (actual == null && expected == null) {
return this; // depends on control dependency: [if], data = [none]
}
isNotNull();
if (actual.equalsIgnoreCase(expected)) {
return this; // depends on control dependency: [if], data = [none]
}
failIfCustomMessageIsSet();
throw failure(format("<%s> should be equal to :<%s> ignoring case", actual, expected));
} }
|
public class class_name {
protected void waitForActiveJobsAndSubJobsToStop() {
// Don't wait if nothing to wait for...
if (executingSubWorkUnits.isEmpty() && executingJobs.isEmpty()) {
return;
}
try {
// Hard-coded 2 seconds, until we have a config property
Thread.sleep(2 * 1000);
} catch (InterruptedException ie) {
// Let it interrupt
}
if (!executingJobs.isEmpty()) {
logger.log(Level.INFO, "jobs.running.at.shutdown", executingJobs.keySet());
}
if (!executingSubWorkUnits.isEmpty()) {
logger.fine("The following job executions were still running at the time of deactivation: " + executingSubWorkUnits.keySet().toString());
}
} }
|
public class class_name {
protected void waitForActiveJobsAndSubJobsToStop() {
// Don't wait if nothing to wait for...
if (executingSubWorkUnits.isEmpty() && executingJobs.isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
try {
// Hard-coded 2 seconds, until we have a config property
Thread.sleep(2 * 1000); // depends on control dependency: [try], data = [none]
} catch (InterruptedException ie) {
// Let it interrupt
} // depends on control dependency: [catch], data = [none]
if (!executingJobs.isEmpty()) {
logger.log(Level.INFO, "jobs.running.at.shutdown", executingJobs.keySet()); // depends on control dependency: [if], data = [none]
}
if (!executingSubWorkUnits.isEmpty()) {
logger.fine("The following job executions were still running at the time of deactivation: " + executingSubWorkUnits.keySet().toString()); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static String enumToString(final Enum<?> value) {
if (value == null) {
return null;
}
final String underscored = value.name();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < underscored.length(); i++) {
final char c = underscored.charAt(i);
if (c == '_') {
sb.append(Character.toUpperCase(underscored.charAt(++i)));
} else {
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
} }
|
public class class_name {
public static String enumToString(final Enum<?> value) {
if (value == null) {
return null; // depends on control dependency: [if], data = [none]
}
final String underscored = value.name();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < underscored.length(); i++) {
final char c = underscored.charAt(i);
if (c == '_') {
sb.append(Character.toUpperCase(underscored.charAt(++i))); // depends on control dependency: [if], data = [none]
} else {
sb.append(Character.toLowerCase(c)); // depends on control dependency: [if], data = [(c]
}
}
return sb.toString();
} }
|
public class class_name {
public <T> void addListItem(PropertyListKey<T> property, T value) {
List<T> list = get(property);
list.add(value);
if (!contains(property)) {
set(property, list);
}
} }
|
public class class_name {
public <T> void addListItem(PropertyListKey<T> property, T value) {
List<T> list = get(property);
list.add(value);
if (!contains(property)) {
set(property, list); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private void computeBucketSize2_SaBucket(int leftPtr, int rightPtr, int offset, int q) {
int suffix1 = suffixArray[leftPtr] + offset;
int suffix2 = suffixArray[rightPtr] + offset;
while (sufPtrMap[suffix1] == sufPtrMap[suffix2]) {
suffix1 += q;
suffix2 += q;
}
if (sufPtrMap[suffix1] > sufPtrMap[suffix2]) {
int tmpSwap = suffixArray[leftPtr];
suffixArray[leftPtr] = suffixArray[rightPtr];
suffixArray[rightPtr] = tmpSwap;
}
sufPtrMap[suffixArray[leftPtr]] = leftPtr;
sufPtrMap[suffixArray[rightPtr]] = rightPtr;
} }
|
public class class_name {
private void computeBucketSize2_SaBucket(int leftPtr, int rightPtr, int offset, int q) {
int suffix1 = suffixArray[leftPtr] + offset;
int suffix2 = suffixArray[rightPtr] + offset;
while (sufPtrMap[suffix1] == sufPtrMap[suffix2]) {
suffix1 += q; // depends on control dependency: [while], data = [none]
suffix2 += q; // depends on control dependency: [while], data = [none]
}
if (sufPtrMap[suffix1] > sufPtrMap[suffix2]) {
int tmpSwap = suffixArray[leftPtr];
suffixArray[leftPtr] = suffixArray[rightPtr]; // depends on control dependency: [if], data = [none]
suffixArray[rightPtr] = tmpSwap; // depends on control dependency: [if], data = [none]
}
sufPtrMap[suffixArray[leftPtr]] = leftPtr;
sufPtrMap[suffixArray[rightPtr]] = rightPtr;
} }
|
public class class_name {
private void registerOffsetMetrics(
MetricGroup consumerMetricGroup,
List<KafkaTopicPartitionState<KPH>> partitionOffsetStates) {
for (KafkaTopicPartitionState<KPH> ktp : partitionOffsetStates) {
MetricGroup topicPartitionGroup = consumerMetricGroup
.addGroup(OFFSETS_BY_TOPIC_METRICS_GROUP, ktp.getTopic())
.addGroup(OFFSETS_BY_PARTITION_METRICS_GROUP, Integer.toString(ktp.getPartition()));
topicPartitionGroup.gauge(CURRENT_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET));
topicPartitionGroup.gauge(COMMITTED_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET));
legacyCurrentOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET));
legacyCommittedOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET));
}
} }
|
public class class_name {
private void registerOffsetMetrics(
MetricGroup consumerMetricGroup,
List<KafkaTopicPartitionState<KPH>> partitionOffsetStates) {
for (KafkaTopicPartitionState<KPH> ktp : partitionOffsetStates) {
MetricGroup topicPartitionGroup = consumerMetricGroup
.addGroup(OFFSETS_BY_TOPIC_METRICS_GROUP, ktp.getTopic())
.addGroup(OFFSETS_BY_PARTITION_METRICS_GROUP, Integer.toString(ktp.getPartition()));
topicPartitionGroup.gauge(CURRENT_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); // depends on control dependency: [for], data = [ktp]
topicPartitionGroup.gauge(COMMITTED_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); // depends on control dependency: [for], data = [ktp]
legacyCurrentOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); // depends on control dependency: [for], data = [ktp]
legacyCommittedOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); // depends on control dependency: [for], data = [ktp]
}
} }
|
public class class_name {
protected void processLegacyRequest(HyperionContext hyperionContext)
{
EndpointRequest request = hyperionContext.getEndpointRequest();
EndpointResponse response = hyperionContext.getEndpointResponse();
ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
EntityPlugin plugin = hyperionContext.getEntityPlugin();
PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);
Set<String> fieldSet = persistenceContext.getRequestedFields();
if(fieldSet != null)
fieldSet.add("id");
RequestContext<ApiObject<Serializable>> requestContext = null;
try
{
requestContext = marshaller.unmarshallWithContext(request.getInputStream(), apiVersionPlugin.getApiClass());
}
catch (MarshallingException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST, hyperionContext.getLocale(),
e.getMessage()),e);
}
ApiObject clientObject = requestContext.getRequestObject();
List<Serializable> ids = convertIds(hyperionContext, plugin);
if(ids.size() != 1)
throw new BadRequestException(messageSource.getErrorMessage(ERROR_SINGLE_ID_REQUIRED,hyperionContext.getLocale()));
persistenceContext.setProvidedFields(requestContext.getProvidedFields());
ApiObject saved = (ApiObject) plugin.getPersistenceOperations().updateItems(
Collections.singletonList(clientObject),
persistenceContext).get(0);
processChangeEvents(hyperionContext,persistenceContext);
response.setResponseCode(200);
hyperionContext.setResult(saved);
} }
|
public class class_name {
protected void processLegacyRequest(HyperionContext hyperionContext)
{
EndpointRequest request = hyperionContext.getEndpointRequest();
EndpointResponse response = hyperionContext.getEndpointResponse();
ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
EntityPlugin plugin = hyperionContext.getEntityPlugin();
PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);
Set<String> fieldSet = persistenceContext.getRequestedFields();
if(fieldSet != null)
fieldSet.add("id");
RequestContext<ApiObject<Serializable>> requestContext = null;
try
{
requestContext = marshaller.unmarshallWithContext(request.getInputStream(), apiVersionPlugin.getApiClass()); // depends on control dependency: [try], data = [none]
}
catch (MarshallingException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST, hyperionContext.getLocale(),
e.getMessage()),e);
} // depends on control dependency: [catch], data = [none]
ApiObject clientObject = requestContext.getRequestObject();
List<Serializable> ids = convertIds(hyperionContext, plugin);
if(ids.size() != 1)
throw new BadRequestException(messageSource.getErrorMessage(ERROR_SINGLE_ID_REQUIRED,hyperionContext.getLocale()));
persistenceContext.setProvidedFields(requestContext.getProvidedFields());
ApiObject saved = (ApiObject) plugin.getPersistenceOperations().updateItems(
Collections.singletonList(clientObject),
persistenceContext).get(0);
processChangeEvents(hyperionContext,persistenceContext);
response.setResponseCode(200);
hyperionContext.setResult(saved);
} }
|
public class class_name {
public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) {
int dKJPerMol = -1;
for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) {
BondEnergy bondEnergy = entry.getValue();
String atom1 = bondEnergy.getSymbolFirstAtom();
String atom2 = bondEnergy.getSymbolSecondAtom();
if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol()))
|| (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1
.equalsIgnoreCase(targetAtom.getSymbol()))) {
Order order = bondEnergy.getBondOrder();
if (order.compareTo(bondOrder) == 0) {
dKJPerMol = bondEnergy.getEnergy();
}
}
}
return dKJPerMol;
} }
|
public class class_name {
public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) {
int dKJPerMol = -1;
for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) {
BondEnergy bondEnergy = entry.getValue();
String atom1 = bondEnergy.getSymbolFirstAtom();
String atom2 = bondEnergy.getSymbolSecondAtom();
if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol()))
|| (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1
.equalsIgnoreCase(targetAtom.getSymbol()))) {
Order order = bondEnergy.getBondOrder();
if (order.compareTo(bondOrder) == 0) {
dKJPerMol = bondEnergy.getEnergy(); // depends on control dependency: [if], data = [none]
}
}
}
return dKJPerMol;
} }
|
public class class_name {
public void startMetricReporting(Configuration configuration) {
Properties props = new Properties();
for (Map.Entry<String, String> entry : configuration) {
props.put(entry.getKey(), entry.getValue());
}
startMetricReporting(props);
} }
|
public class class_name {
public void startMetricReporting(Configuration configuration) {
Properties props = new Properties();
for (Map.Entry<String, String> entry : configuration) {
props.put(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
startMetricReporting(props);
} }
|
public class class_name {
public ListDeploymentsResult withDeployments(Deployment... deployments) {
if (this.deployments == null) {
setDeployments(new java.util.ArrayList<Deployment>(deployments.length));
}
for (Deployment ele : deployments) {
this.deployments.add(ele);
}
return this;
} }
|
public class class_name {
public ListDeploymentsResult withDeployments(Deployment... deployments) {
if (this.deployments == null) {
setDeployments(new java.util.ArrayList<Deployment>(deployments.length)); // depends on control dependency: [if], data = [none]
}
for (Deployment ele : deployments) {
this.deployments.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
public static PropertiesBuilder from(Map<String, ?> map) {
Properties properties = new Properties();
for (Map.Entry<String, ?> entry : map.entrySet()) {
properties.setProperty(entry.getKey(), String.valueOf(entry.getValue()));
}
return from(properties);
} }
|
public class class_name {
public static PropertiesBuilder from(Map<String, ?> map) {
Properties properties = new Properties();
for (Map.Entry<String, ?> entry : map.entrySet()) {
properties.setProperty(entry.getKey(), String.valueOf(entry.getValue())); // depends on control dependency: [for], data = [entry]
}
return from(properties);
} }
|
public class class_name {
public final boolean verifyAudience(Collection<String> trustedClientIds) {
Collection<String> audience = getPayload().getAudienceAsList();
if (audience.isEmpty()) {
return false;
}
return trustedClientIds.containsAll(audience);
} }
|
public class class_name {
public final boolean verifyAudience(Collection<String> trustedClientIds) {
Collection<String> audience = getPayload().getAudienceAsList();
if (audience.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
return trustedClientIds.containsAll(audience);
} }
|
public class class_name {
protected void reBuffer()
{
resetBuffer();
try
{
int read = buffer.length;
if (bufferOffset + read > fileLength)
{
if (bufferOffset >= fileLength)
return;
read = (int) (fileLength - bufferOffset);
}
channel.position(bufferOffset); // setting channel position
int offset = 0;
while (read > 0)
{
int n = super.read(buffer, offset, read);
if (n < 0)
throw new IllegalStateException();
read -= n;
offset += n;
}
validBufferBytes = offset;
}
catch (IOException e)
{
throw new FSReadError(e, filePath);
}
} }
|
public class class_name {
protected void reBuffer()
{
resetBuffer();
try
{
int read = buffer.length;
if (bufferOffset + read > fileLength)
{
if (bufferOffset >= fileLength)
return;
read = (int) (fileLength - bufferOffset); // depends on control dependency: [if], data = [none]
}
channel.position(bufferOffset); // setting channel position // depends on control dependency: [try], data = [none]
int offset = 0;
while (read > 0)
{
int n = super.read(buffer, offset, read);
if (n < 0)
throw new IllegalStateException();
read -= n; // depends on control dependency: [while], data = [none]
offset += n; // depends on control dependency: [while], data = [none]
}
validBufferBytes = offset; // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
throw new FSReadError(e, filePath);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private InternetAddress pullFromGroups(final Matcher m) {
InternetAddress currentInternetAddress;
final String[] parts = _calcMatcherParts(m);
if (parts[1] == null || parts[2] == null) {
return null;
}
// if for some reason you want to require that the result be re-parsable by
// InternetAddress, you
// could uncomment the appropriate stuff below, but note that not all the utility
// functions use pullFromGroups; some call getMatcherParts directly.
try {
//currentInternetAddress = new InternetAddress(parts[0] + " <" + parts[1] + "@" +
// parts[2]+ ">", true);
// so it parses it OK, but since javamail doesn't extract too well
// we make sure that the consistent parts
// are correct
currentInternetAddress = new InternetAddress();
currentInternetAddress.setPersonal(parts[0]);
currentInternetAddress.setAddress(parts[1] + "@" + parts[2]);
} catch (final UnsupportedEncodingException uee) {
currentInternetAddress = null;
}
return currentInternetAddress;
} }
|
public class class_name {
private InternetAddress pullFromGroups(final Matcher m) {
InternetAddress currentInternetAddress;
final String[] parts = _calcMatcherParts(m);
if (parts[1] == null || parts[2] == null) {
return null; // depends on control dependency: [if], data = [none]
}
// if for some reason you want to require that the result be re-parsable by
// InternetAddress, you
// could uncomment the appropriate stuff below, but note that not all the utility
// functions use pullFromGroups; some call getMatcherParts directly.
try {
//currentInternetAddress = new InternetAddress(parts[0] + " <" + parts[1] + "@" +
// parts[2]+ ">", true);
// so it parses it OK, but since javamail doesn't extract too well
// we make sure that the consistent parts
// are correct
currentInternetAddress = new InternetAddress(); // depends on control dependency: [try], data = [none]
currentInternetAddress.setPersonal(parts[0]); // depends on control dependency: [try], data = [none]
currentInternetAddress.setAddress(parts[1] + "@" + parts[2]); // depends on control dependency: [try], data = [none]
} catch (final UnsupportedEncodingException uee) {
currentInternetAddress = null;
} // depends on control dependency: [catch], data = [none]
return currentInternetAddress;
} }
|
public class class_name {
public String format(String key,
Object object) {
if (traceNLS != null) {
return traceNLS.getFormattedMessage(key, new Object[] { object }, defaultMessage);
} else {
return objectsToString(key, object);
}
} }
|
public class class_name {
public String format(String key,
Object object) {
if (traceNLS != null) {
return traceNLS.getFormattedMessage(key, new Object[] { object }, defaultMessage); // depends on control dependency: [if], data = [none]
} else {
return objectsToString(key, object); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private Bearer getBearer(final HttpServletRequest req) {
final String authorizationHeader = req.getHeader(Headers.AUTHORIZATION.getName());
if (StringUtils.isNotBlank(authorizationHeader)) {
final String bearerToken =
authorizationHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());
return bearerService.parseBearerToken(bearerToken);
}
return MissingModelElement.BEARER;
} }
|
public class class_name {
private Bearer getBearer(final HttpServletRequest req) {
final String authorizationHeader = req.getHeader(Headers.AUTHORIZATION.getName());
if (StringUtils.isNotBlank(authorizationHeader)) {
final String bearerToken =
authorizationHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());
return bearerService.parseBearerToken(bearerToken); // depends on control dependency: [if], data = [none]
}
return MissingModelElement.BEARER;
} }
|
public class class_name {
public InetAddress
getAddress() {
try {
if (name == null)
return InetAddress.getByAddress(address);
else
return InetAddress.getByAddress(name.toString(),
address);
} catch (UnknownHostException e) {
return null;
}
} }
|
public class class_name {
public InetAddress
getAddress() {
try {
if (name == null)
return InetAddress.getByAddress(address);
else
return InetAddress.getByAddress(name.toString(),
address);
} catch (UnknownHostException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void processCharacter(StringBuilder sb, char nextChar) {
if ((escapechar != NO_ESCAPE_CHARACTER) && checkCharactersToEscape(nextChar)) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
} }
|
public class class_name {
private void processCharacter(StringBuilder sb, char nextChar) {
if ((escapechar != NO_ESCAPE_CHARACTER) && checkCharactersToEscape(nextChar)) {
sb.append(escapechar).append(nextChar); // depends on control dependency: [if], data = [none]
} else {
sb.append(nextChar); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static void iterateChildrenNonBreakable (@Nonnull final IHCNode aNode,
@Nonnull final IHCIteratorNonBreakableCallback aCallback)
{
ValueEnforcer.notNull (aNode, "node");
ValueEnforcer.notNull (aCallback, "callback");
final ICommonsList <IHCNode> aParentNodes = new CommonsArrayList <> ();
final ICommonsList <IHCNode> aNodes = new CommonsArrayList <> ();
if (aNode.hasChildren ())
for (final IHCNode aChild : aNode.getChildren ())
{
// Remember nodes for later processing
aParentNodes.add (aNode);
aNodes.add (aChild);
}
_iterateTreeNonBreakable (aParentNodes, aNodes, aCallback);
} }
|
public class class_name {
public static void iterateChildrenNonBreakable (@Nonnull final IHCNode aNode,
@Nonnull final IHCIteratorNonBreakableCallback aCallback)
{
ValueEnforcer.notNull (aNode, "node");
ValueEnforcer.notNull (aCallback, "callback");
final ICommonsList <IHCNode> aParentNodes = new CommonsArrayList <> ();
final ICommonsList <IHCNode> aNodes = new CommonsArrayList <> ();
if (aNode.hasChildren ())
for (final IHCNode aChild : aNode.getChildren ())
{
// Remember nodes for later processing
aParentNodes.add (aNode); // depends on control dependency: [for], data = [none]
aNodes.add (aChild); // depends on control dependency: [for], data = [aChild]
}
_iterateTreeNonBreakable (aParentNodes, aNodes, aCallback);
} }
|
public class class_name {
public static Function<Service<HttpRequest, HttpResponse>,
HttpEncodingService> contentEncodingDecorator(@Nullable String[] mimeTypes,
@Nullable String[] excludedUserAgents,
long minBytesToForceChunkedAndEncoding) {
final Predicate<MediaType> encodableContentTypePredicate;
if (mimeTypes == null || mimeTypes.length == 0) {
encodableContentTypePredicate = contentType -> true;
} else {
final List<MediaType> encodableContentTypes =
Arrays.stream(mimeTypes).map(MediaType::parse).collect(toImmutableList());
encodableContentTypePredicate = contentType ->
encodableContentTypes.stream().anyMatch(contentType::is);
}
final Predicate<HttpHeaders> encodableRequestHeadersPredicate;
if (excludedUserAgents == null || excludedUserAgents.length == 0) {
encodableRequestHeadersPredicate = headers -> true;
} else {
final List<Pattern> patterns =
Arrays.stream(excludedUserAgents).map(Pattern::compile).collect(toImmutableList());
encodableRequestHeadersPredicate = headers -> {
// No User-Agent header will be converted to an empty string.
final String userAgent = headers.get(HttpHeaderNames.USER_AGENT, "");
return patterns.stream().noneMatch(pattern -> pattern.matcher(userAgent).matches());
};
}
return delegate -> new HttpEncodingService(delegate,
encodableContentTypePredicate,
encodableRequestHeadersPredicate,
minBytesToForceChunkedAndEncoding);
} }
|
public class class_name {
public static Function<Service<HttpRequest, HttpResponse>,
HttpEncodingService> contentEncodingDecorator(@Nullable String[] mimeTypes,
@Nullable String[] excludedUserAgents,
long minBytesToForceChunkedAndEncoding) {
final Predicate<MediaType> encodableContentTypePredicate;
if (mimeTypes == null || mimeTypes.length == 0) {
encodableContentTypePredicate = contentType -> true; // depends on control dependency: [if], data = [none]
} else {
final List<MediaType> encodableContentTypes =
Arrays.stream(mimeTypes).map(MediaType::parse).collect(toImmutableList());
encodableContentTypePredicate = contentType ->
encodableContentTypes.stream().anyMatch(contentType::is); // depends on control dependency: [if], data = [none]
}
final Predicate<HttpHeaders> encodableRequestHeadersPredicate;
if (excludedUserAgents == null || excludedUserAgents.length == 0) {
encodableRequestHeadersPredicate = headers -> true; // depends on control dependency: [if], data = [none]
} else {
final List<Pattern> patterns =
Arrays.stream(excludedUserAgents).map(Pattern::compile).collect(toImmutableList());
encodableRequestHeadersPredicate = headers -> {
// No User-Agent header will be converted to an empty string.
final String userAgent = headers.get(HttpHeaderNames.USER_AGENT, "");
return patterns.stream().noneMatch(pattern -> pattern.matcher(userAgent).matches()); // depends on control dependency: [if], data = [none]
};
}
return delegate -> new HttpEncodingService(delegate,
encodableContentTypePredicate,
encodableRequestHeadersPredicate,
minBytesToForceChunkedAndEncoding);
} }
|
public class class_name {
public boolean isOwnedBy(String possibleOwner) {
boolean retval = false;
if (this.owner != null) {
retval = (this.owner.compareTo(possibleOwner) == 0);
}
return retval;
} }
|
public class class_name {
public boolean isOwnedBy(String possibleOwner) {
boolean retval = false;
if (this.owner != null) {
retval = (this.owner.compareTo(possibleOwner) == 0); // depends on control dependency: [if], data = [(this.owner]
}
return retval;
} }
|
public class class_name {
public java.util.List<String> getDeploy() {
if (deploy == null) {
deploy = new com.amazonaws.internal.SdkInternalList<String>();
}
return deploy;
} }
|
public class class_name {
public java.util.List<String> getDeploy() {
if (deploy == null) {
deploy = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return deploy;
} }
|
public class class_name {
private Boolean setAllRingBondsSingleOrder(List<Integer> ringGroup, IRingSet ringSet) {
for (Integer i : ringGroup) {
for (IBond bond : ringSet.getAtomContainer(i).bonds()) {
bond.setOrder(IBond.Order.SINGLE);
}
}
return true;
} }
|
public class class_name {
private Boolean setAllRingBondsSingleOrder(List<Integer> ringGroup, IRingSet ringSet) {
for (Integer i : ringGroup) {
for (IBond bond : ringSet.getAtomContainer(i).bonds()) {
bond.setOrder(IBond.Order.SINGLE); // depends on control dependency: [for], data = [bond]
}
}
return true;
} }
|
public class class_name {
protected void resolveStreamEncoding()
throws IOException, WstxException
{
// Let's first set defaults:
mBytesPerChar = 0;
mBigEndian = true;
/* Ok; first just need 4 bytes for determining bytes-per-char from
* BOM or first char(s) of likely xml declaration:
*/
if (ensureLoaded(4)) {
bomblock:
do { // BOM/auto-detection block
int quartet = (mByteBuffer[0] << 24)
| ((mByteBuffer[1] & 0xFF) << 16)
| ((mByteBuffer[2] & 0xFF) << 8)
| (mByteBuffer[3] & 0xFF);
/* Handling of (usually) optional BOM (required for
* multi-byte formats); first 32-bit charsets:
*/
switch (quartet) {
case 0x0000FEFF:
mBigEndian = true;
mInputPtr = mBytesPerChar = 4;
break bomblock;
case 0xFFFE0000: // UCS-4, LE?
mInputPtr = mBytesPerChar = 4;
mBigEndian = false;
break bomblock;
case 0x0000FFFE: // UCS-4, in-order...
reportWeirdUCS4("2143");
break bomblock;
case 0x0FEFF0000: // UCS-4, in-order...
reportWeirdUCS4("3412");
break bomblock;
}
// Ok, if not, how about 16-bit encoding BOMs?
int msw = quartet >>> 16;
if (msw == 0xFEFF) { // UTF-16, BE
mInputPtr = mBytesPerChar = 2;
mBigEndian = true;
break;
}
if (msw == 0xFFFE) { // UTF-16, LE
mInputPtr = mBytesPerChar = 2;
mBigEndian = false;
break;
}
// And if not, then UTF-8 BOM?
if ((quartet >>> 8) == 0xEFBBBF) { // UTF-8
mInputPtr = 3;
mBytesPerChar = 1;
mBigEndian = true; // doesn't really matter
break;
}
/* And if that wasn't succesful, how about auto-detection
* for '<?xm' (or subset for multi-byte encodings) marker?
*/
// Note: none of these consume bytes... so ptr remains at 0
switch (quartet) {
case 0x0000003c: // UCS-4, BE?
mBigEndian = true;
mBytesPerChar = 4;
break bomblock;
case 0x3c000000: // UCS-4, LE?
mBytesPerChar = 4;
mBigEndian = false;
break bomblock;
case 0x00003c00: // UCS-4, in-order...
reportWeirdUCS4("2143");
break bomblock;
case 0x003c0000: // UCS-4, in-order...
reportWeirdUCS4("3412");
break bomblock;
case 0x003c003f: // UTF-16, BE
mBytesPerChar = 2;
mBigEndian = true;
break bomblock;
case 0x3c003f00: // UTF-16, LE
mBytesPerChar = 2;
mBigEndian = false;
break bomblock;
case 0x3c3f786d: // UTF-8, Ascii, ISO-Latin
mBytesPerChar = 1;
mBigEndian = true; // doesn't really matter
break bomblock;
case 0x4c6fa794:
mBytesPerChar = -1;
mEBCDIC = true;
/* For xml declaration handling we can basically
* use any of EBCDIC variants, since declaration
* must not contain control or punctuation characters
* that would differ
*/
mSingleByteTranslation = EBCDICCodec.getCp037Mapping();
break bomblock;
}
/* Otherwise it's either single-byte doc without xml
* declaration, or corrupt input...
*/
} while (false); // BOM/auto-detection block
mHadBOM = (mInputPtr > 0);
// Let's update location markers to ignore BOM.
mInputProcessed = -mInputPtr;
mInputRowStart = mInputPtr;
}
/* Hmmh. If we haven't figured it out, let's just assume
* UTF-8 as per XML specs:
*/
mByteSizeFound = (mBytesPerChar != 0);
if (!mByteSizeFound) {
mBytesPerChar = 1;
mBigEndian = true; // doesn't matter
}
} }
|
public class class_name {
protected void resolveStreamEncoding()
throws IOException, WstxException
{
// Let's first set defaults:
mBytesPerChar = 0;
mBigEndian = true;
/* Ok; first just need 4 bytes for determining bytes-per-char from
* BOM or first char(s) of likely xml declaration:
*/
if (ensureLoaded(4)) {
bomblock:
do { // BOM/auto-detection block
int quartet = (mByteBuffer[0] << 24)
| ((mByteBuffer[1] & 0xFF) << 16)
| ((mByteBuffer[2] & 0xFF) << 8)
| (mByteBuffer[3] & 0xFF);
/* Handling of (usually) optional BOM (required for
* multi-byte formats); first 32-bit charsets:
*/
switch (quartet) {
case 0x0000FEFF:
mBigEndian = true;
mInputPtr = mBytesPerChar = 4;
break bomblock;
case 0xFFFE0000: // UCS-4, LE?
mInputPtr = mBytesPerChar = 4;
mBigEndian = false;
break bomblock;
case 0x0000FFFE: // UCS-4, in-order...
reportWeirdUCS4("2143");
break bomblock;
case 0x0FEFF0000: // UCS-4, in-order...
reportWeirdUCS4("3412");
break bomblock;
}
// Ok, if not, how about 16-bit encoding BOMs?
int msw = quartet >>> 16;
if (msw == 0xFEFF) { // UTF-16, BE
mInputPtr = mBytesPerChar = 2; // depends on control dependency: [if], data = [none]
mBigEndian = true; // depends on control dependency: [if], data = [none]
break;
}
if (msw == 0xFFFE) { // UTF-16, LE
mInputPtr = mBytesPerChar = 2; // depends on control dependency: [if], data = [none]
mBigEndian = false; // depends on control dependency: [if], data = [none]
break;
}
// And if not, then UTF-8 BOM?
if ((quartet >>> 8) == 0xEFBBBF) { // UTF-8
mInputPtr = 3; // depends on control dependency: [if], data = [none]
mBytesPerChar = 1; // depends on control dependency: [if], data = [none]
mBigEndian = true; // doesn't really matter // depends on control dependency: [if], data = [none]
break;
}
/* And if that wasn't succesful, how about auto-detection
* for '<?xm' (or subset for multi-byte encodings) marker?
*/
// Note: none of these consume bytes... so ptr remains at 0
switch (quartet) {
case 0x0000003c: // UCS-4, BE?
mBigEndian = true;
mBytesPerChar = 4;
break bomblock;
case 0x3c000000: // UCS-4, LE?
mBytesPerChar = 4;
mBigEndian = false;
break bomblock;
case 0x00003c00: // UCS-4, in-order...
reportWeirdUCS4("2143");
break bomblock;
case 0x003c0000: // UCS-4, in-order...
reportWeirdUCS4("3412");
break bomblock;
case 0x003c003f: // UTF-16, BE
mBytesPerChar = 2;
mBigEndian = true;
break bomblock;
case 0x3c003f00: // UTF-16, LE
mBytesPerChar = 2;
mBigEndian = false;
break bomblock;
case 0x3c3f786d: // UTF-8, Ascii, ISO-Latin
mBytesPerChar = 1;
mBigEndian = true; // doesn't really matter
break bomblock;
case 0x4c6fa794:
mBytesPerChar = -1;
mEBCDIC = true;
/* For xml declaration handling we can basically
* use any of EBCDIC variants, since declaration
* must not contain control or punctuation characters
* that would differ
*/
mSingleByteTranslation = EBCDICCodec.getCp037Mapping();
break bomblock;
}
/* Otherwise it's either single-byte doc without xml
* declaration, or corrupt input...
*/
} while (false); // BOM/auto-detection block
mHadBOM = (mInputPtr > 0);
// Let's update location markers to ignore BOM.
mInputProcessed = -mInputPtr;
mInputRowStart = mInputPtr;
}
/* Hmmh. If we haven't figured it out, let's just assume
* UTF-8 as per XML specs:
*/
mByteSizeFound = (mBytesPerChar != 0);
if (!mByteSizeFound) {
mBytesPerChar = 1;
mBigEndian = true; // doesn't matter
}
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.