code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void setURI( String uriString, boolean encoded ) throws URISyntaxException
{
if ( uriString == null )
{
setScheme( null );
setUserInfo( null );
setHost( null );
setPort( UNDEFINED_PORT );
setPath( null );
setQuery( null );
setFragment( null );
}
else
{
URI uri = null;
if ( encoded )
{
// Get (parse) the components using java.net.URI
uri = new URI( uriString );
}
else
{
// Parse, then encode this string into its components using URI
uri = encodeURI( uriString );
}
setURI( uri );
}
} } | public class class_name {
public void setURI( String uriString, boolean encoded ) throws URISyntaxException
{
if ( uriString == null )
{
setScheme( null );
setUserInfo( null );
setHost( null );
setPort( UNDEFINED_PORT );
setPath( null );
setQuery( null );
setFragment( null );
}
else
{
URI uri = null;
if ( encoded )
{
// Get (parse) the components using java.net.URI
uri = new URI( uriString ); // depends on control dependency: [if], data = [none]
}
else
{
// Parse, then encode this string into its components using URI
uri = encodeURI( uriString ); // depends on control dependency: [if], data = [none]
}
setURI( uri );
}
} } |
public class class_name {
private static final int count_flip(final int[] perm_flip)
{
// cache first element, avoid swapping perm[0] and perm[k]
int v0 = perm_flip[0];
int tmp;
int flip_count = 0;
do
{
for (int i = 1, j = v0 - 1; i < j; ++i, --j)
{
tmp = perm_flip[i];
perm_flip[i] = perm_flip[j];
perm_flip[j] = tmp;
}
tmp = perm_flip[v0];
perm_flip[v0] = v0;
v0 = tmp;
flip_count++;
} while (v0 != 0); // first element == '1' ?
return flip_count;
} } | public class class_name {
private static final int count_flip(final int[] perm_flip)
{
// cache first element, avoid swapping perm[0] and perm[k]
int v0 = perm_flip[0];
int tmp;
int flip_count = 0;
do
{
for (int i = 1, j = v0 - 1; i < j; ++i, --j)
{
tmp = perm_flip[i]; // depends on control dependency: [for], data = [i]
perm_flip[i] = perm_flip[j]; // depends on control dependency: [for], data = [i]
perm_flip[j] = tmp; // depends on control dependency: [for], data = [none]
}
tmp = perm_flip[v0];
perm_flip[v0] = v0;
v0 = tmp;
flip_count++;
} while (v0 != 0); // first element == '1' ?
return flip_count;
} } |
public class class_name {
public void setDefaultHeader(String name, Object value) {
if (defaultHeaders == null) {
defaultHeaders = new HashMap<String, Object>();
}
if (value == null) {
defaultHeaders.remove(name);
} else {
defaultHeaders.put(name, value);
}
} } | public class class_name {
public void setDefaultHeader(String name, Object value) {
if (defaultHeaders == null) {
defaultHeaders = new HashMap<String, Object>(); // depends on control dependency: [if], data = [none]
}
if (value == null) {
defaultHeaders.remove(name); // depends on control dependency: [if], data = [none]
} else {
defaultHeaders.put(name, value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static long getDateQuot(String time1, String time2) {
long quot = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = ft.parse(time1);
Date date2 = ft.parse(time2);
quot = date2.getTime() - date1.getTime();
quot = quot / 1000 / 60 / 60 / 24;
} catch (ParseException e) {
e.printStackTrace();
}
return quot;
} } | public class class_name {
public static long getDateQuot(String time1, String time2) {
long quot = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = ft.parse(time1);
Date date2 = ft.parse(time2);
quot = date2.getTime() - date1.getTime(); // depends on control dependency: [try], data = [none]
quot = quot / 1000 / 60 / 60 / 24; // depends on control dependency: [try], data = [none]
} catch (ParseException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return quot;
} } |
public class class_name {
public void optimize(final SQLStatementRule rule, final SQLStatement sqlStatement) {
Optional<SQLStatementOptimizer> optimizer = rule.getOptimizer();
if (optimizer.isPresent()) {
optimizer.get().optimize(sqlStatement, shardingTableMetaData);
}
} } | public class class_name {
public void optimize(final SQLStatementRule rule, final SQLStatement sqlStatement) {
Optional<SQLStatementOptimizer> optimizer = rule.getOptimizer();
if (optimizer.isPresent()) {
optimizer.get().optimize(sqlStatement, shardingTableMetaData); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setNewInstanceResolver(final Object newInstanceResolver) {
if (newInstanceResolver instanceof NewInstanceResolver) {
this.newInstanceResolver = (NewInstanceResolver) newInstanceResolver;
} else if (newInstanceResolver instanceof Closure) {
final ObjectGraphBuilder self = this;
this.newInstanceResolver = new NewInstanceResolver() {
public Object newInstance(Class klass, Map attributes)
throws InstantiationException, IllegalAccessException {
Closure cls = (Closure) newInstanceResolver;
cls.setDelegate(self);
return cls.call(klass, attributes);
}
};
} else {
this.newInstanceResolver = new DefaultNewInstanceResolver();
}
} } | public class class_name {
public void setNewInstanceResolver(final Object newInstanceResolver) {
if (newInstanceResolver instanceof NewInstanceResolver) {
this.newInstanceResolver = (NewInstanceResolver) newInstanceResolver; // depends on control dependency: [if], data = [none]
} else if (newInstanceResolver instanceof Closure) {
final ObjectGraphBuilder self = this;
this.newInstanceResolver = new NewInstanceResolver() {
public Object newInstance(Class klass, Map attributes)
throws InstantiationException, IllegalAccessException {
Closure cls = (Closure) newInstanceResolver;
cls.setDelegate(self);
return cls.call(klass, attributes);
}
}; // depends on control dependency: [if], data = [none]
} else {
this.newInstanceResolver = new DefaultNewInstanceResolver(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean isWord(String token) {
if (token.length() == 1) {
char c = token.charAt(0);
if (!Character.isLetter(c)) {
return false;
}
}
return true;
} } | public class class_name {
private boolean isWord(String token) {
if (token.length() == 1) {
char c = token.charAt(0);
if (!Character.isLetter(c)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public Stream<T> filter(final Func1<? super T, Boolean> func) {
return new Stream<T>() {
@Override
public Iterator<T> iterator() {
return new ReadOnlyIterator<T>() {
Iterator<? extends T> iterator = Stream.this.iterator();
T next;
boolean hasNext;
private void process() {
while (!hasNext && iterator.hasNext()) {
final T n = iterator.next();
if (func.call(n)) {
next = n;
hasNext = true;
}
}
}
@Override
public boolean hasNext() {
process();
return hasNext;
}
@Override
public T next() {
process();
hasNext = false;
return next;
}
};
}
};
} } | public class class_name {
public Stream<T> filter(final Func1<? super T, Boolean> func) {
return new Stream<T>() {
@Override
public Iterator<T> iterator() {
return new ReadOnlyIterator<T>() {
Iterator<? extends T> iterator = Stream.this.iterator();
T next;
boolean hasNext;
private void process() {
while (!hasNext && iterator.hasNext()) {
final T n = iterator.next();
if (func.call(n)) {
next = n; // depends on control dependency: [if], data = [none]
hasNext = true; // depends on control dependency: [if], data = [none]
}
}
}
@Override
public boolean hasNext() {
process();
return hasNext;
}
@Override
public T next() {
process();
hasNext = false;
return next;
}
};
}
};
} } |
public class class_name {
private static Neurons[] makeNeurons(final DeepLearningModel.DeepLearningModelInfo minfo, boolean training) {
DataInfo dinfo = minfo.data_info();
final DeepLearning params = minfo.get_params();
final int[] h = params.hidden;
Neurons[] neurons = new Neurons[h.length + 2]; // input + hidden + output
// input
neurons[0] = new Neurons.Input(minfo.units[0], dinfo);
// hidden
for( int i = 0; i < h.length + (params.autoencoder ? 1 : 0); i++ ) {
int n = params.autoencoder && i == h.length ? minfo.units[0] : h[i];
switch( params.activation ) {
case Tanh:
neurons[i+1] = new Neurons.Tanh(n);
break;
case TanhWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Tanh(n) : new Neurons.TanhDropout(n);
break;
case Rectifier:
neurons[i+1] = new Neurons.Rectifier(n);
break;
case RectifierWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Rectifier(n) : new Neurons.RectifierDropout(n);
break;
case Maxout:
neurons[i+1] = new Neurons.Maxout(n);
break;
case MaxoutWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Maxout(n) : new Neurons.MaxoutDropout(n);
break;
}
}
if(!params.autoencoder) {
if (params.classification)
neurons[neurons.length - 1] = new Neurons.Softmax(minfo.units[minfo.units.length - 1]);
else
neurons[neurons.length - 1] = new Neurons.Linear(1);
}
//copy parameters from NN, and set previous/input layer links
for( int i = 0; i < neurons.length; i++ ) {
neurons[i].init(neurons, i, params, minfo, training);
neurons[i]._input = neurons[0];
}
// // debugging
// for (Neurons n : neurons) Log.info(n.toString());
return neurons;
} } | public class class_name {
private static Neurons[] makeNeurons(final DeepLearningModel.DeepLearningModelInfo minfo, boolean training) {
DataInfo dinfo = minfo.data_info();
final DeepLearning params = minfo.get_params();
final int[] h = params.hidden;
Neurons[] neurons = new Neurons[h.length + 2]; // input + hidden + output
// input
neurons[0] = new Neurons.Input(minfo.units[0], dinfo);
// hidden
for( int i = 0; i < h.length + (params.autoencoder ? 1 : 0); i++ ) {
int n = params.autoencoder && i == h.length ? minfo.units[0] : h[i];
switch( params.activation ) {
case Tanh:
neurons[i+1] = new Neurons.Tanh(n);
break;
case TanhWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Tanh(n) : new Neurons.TanhDropout(n);
break;
case Rectifier:
neurons[i+1] = new Neurons.Rectifier(n);
break;
case RectifierWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Rectifier(n) : new Neurons.RectifierDropout(n);
break;
case Maxout:
neurons[i+1] = new Neurons.Maxout(n);
break;
case MaxoutWithDropout:
neurons[i+1] = params.autoencoder && i == h.length ? new Neurons.Maxout(n) : new Neurons.MaxoutDropout(n);
break;
}
}
if(!params.autoencoder) {
if (params.classification)
neurons[neurons.length - 1] = new Neurons.Softmax(minfo.units[minfo.units.length - 1]);
else
neurons[neurons.length - 1] = new Neurons.Linear(1);
}
//copy parameters from NN, and set previous/input layer links
for( int i = 0; i < neurons.length; i++ ) {
neurons[i].init(neurons, i, params, minfo, training); // depends on control dependency: [for], data = [i]
neurons[i]._input = neurons[0]; // depends on control dependency: [for], data = [i]
}
// // debugging
// for (Neurons n : neurons) Log.info(n.toString());
return neurons;
} } |
public class class_name {
public EClass getIfcRelServicesBuildings() {
if (ifcRelServicesBuildingsEClass == null) {
ifcRelServicesBuildingsEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(483);
}
return ifcRelServicesBuildingsEClass;
} } | public class class_name {
public EClass getIfcRelServicesBuildings() {
if (ifcRelServicesBuildingsEClass == null) {
ifcRelServicesBuildingsEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(483);
// depends on control dependency: [if], data = [none]
}
return ifcRelServicesBuildingsEClass;
} } |
public class class_name {
public static int getType(Number val)
{
if (val instanceof Integer)
{
return INT;
}
else if (val instanceof Long)
{
return LONG;
}
else if (val instanceof Short)
{
return SHORT;
}
else if (val instanceof Byte)
{
return BYTE;
}
else if (val instanceof Double)
{
return DOUBLE;
}
else if (val instanceof Float)
{
return FLOAT;
} else
throw new IllegalArgumentException();
} } | public class class_name {
public static int getType(Number val)
{
if (val instanceof Integer)
{
return INT; // depends on control dependency: [if], data = [none]
}
else if (val instanceof Long)
{
return LONG; // depends on control dependency: [if], data = [none]
}
else if (val instanceof Short)
{
return SHORT; // depends on control dependency: [if], data = [none]
}
else if (val instanceof Byte)
{
return BYTE; // depends on control dependency: [if], data = [none]
}
else if (val instanceof Double)
{
return DOUBLE; // depends on control dependency: [if], data = [none]
}
else if (val instanceof Float)
{
return FLOAT; // depends on control dependency: [if], data = [none]
} else
throw new IllegalArgumentException();
} } |
public class class_name {
public static StringBuilder describeParameterizable(StringBuilder buf, Class<?> pcls, int width, String indent) throws ClassInstantiationException {
println(buf, width, "Description for class " + pcls.getName());
Title title = pcls.getAnnotation(Title.class);
if(title != null && title.value() != null && !title.value().isEmpty()) {
println(buf, width, title.value());
}
Description desc = pcls.getAnnotation(Description.class);
if(desc != null && desc.value() != null && !desc.value().isEmpty()) {
println(buf, width, desc.value());
}
for(Reference ref : pcls.getAnnotationsByType(Reference.class)) {
if(!ref.prefix().isEmpty()) {
println(buf, width, ref.prefix());
}
println(buf, width, ref.authors());
println(buf, width, ref.title());
println(buf, width, ref.booktitle());
if(ref.url().length() > 0) {
println(buf, width, ref.url());
}
}
SerializedParameterization config = new SerializedParameterization();
TrackParameters track = new TrackParameters(config);
@SuppressWarnings("unused")
Object p = ClassGenericsUtil.tryInstantiate(Object.class, pcls, track);
Collection<TrackedParameter> options = track.getAllParameters();
if(!options.isEmpty()) {
OptionUtil.formatForConsole(buf, width, options);
}
return buf;
} } | public class class_name {
public static StringBuilder describeParameterizable(StringBuilder buf, Class<?> pcls, int width, String indent) throws ClassInstantiationException {
println(buf, width, "Description for class " + pcls.getName());
Title title = pcls.getAnnotation(Title.class);
if(title != null && title.value() != null && !title.value().isEmpty()) {
println(buf, width, title.value());
}
Description desc = pcls.getAnnotation(Description.class);
if(desc != null && desc.value() != null && !desc.value().isEmpty()) {
println(buf, width, desc.value());
}
for(Reference ref : pcls.getAnnotationsByType(Reference.class)) {
if(!ref.prefix().isEmpty()) {
println(buf, width, ref.prefix()); // depends on control dependency: [if], data = [none]
}
println(buf, width, ref.authors());
println(buf, width, ref.title());
println(buf, width, ref.booktitle());
if(ref.url().length() > 0) {
println(buf, width, ref.url()); // depends on control dependency: [if], data = [none]
}
}
SerializedParameterization config = new SerializedParameterization();
TrackParameters track = new TrackParameters(config);
@SuppressWarnings("unused")
Object p = ClassGenericsUtil.tryInstantiate(Object.class, pcls, track);
Collection<TrackedParameter> options = track.getAllParameters();
if(!options.isEmpty()) {
OptionUtil.formatForConsole(buf, width, options);
}
return buf;
} } |
public class class_name {
public EClass getSTO() {
if (stoEClass == null) {
stoEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(340);
}
return stoEClass;
} } | public class class_name {
public EClass getSTO() {
if (stoEClass == null) {
stoEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(340); // depends on control dependency: [if], data = [none]
}
return stoEClass;
} } |
public class class_name {
public static List<String> validateDictionaries(NaaccrDictionary baseDictionary, Collection<NaaccrDictionary> userDictionaries) {
// validate the base dictionary
List<String> errors = new ArrayList<>(validateBaseDictionary(baseDictionary));
// validate each user dictionary
Map<String, String> idsDejaVu = new HashMap<>();
Map<Integer, String> numbersDejaVue = new HashMap<>();
for (NaaccrDictionary userDictionary : userDictionaries) {
errors.addAll(validateUserDictionary(userDictionary, baseDictionary.getNaaccrVersion()));
// make sure the provided version (if one is provided) agrees with the base version
if (userDictionary.getNaaccrVersion() != null && !baseDictionary.getNaaccrVersion().equals(userDictionary.getNaaccrVersion()))
errors.add("user-defined dictionary '" + userDictionary.getDictionaryUri() + "' doesn't define the same version as the base dictionary");
// validate the items
String dictId = userDictionary.getDictionaryUri();
for (NaaccrDictionaryItem item : userDictionary.getItems()) {
// NAACCR IDs defined in user dictionaries cannot be the same as the base NAACCR IDs
if (baseDictionary.getItemByNaaccrId(item.getNaaccrId()) != null)
errors.add("user-defined dictionary '" + dictId + "' cannot use same NAACCR ID as a base item: " + item.getNaaccrId());
// NAACCR Numbers defined in user dictionaries cannot be the same as the base NAACCR Numbers
if (baseDictionary.getItemByNaaccrNum(item.getNaaccrNum()) != null)
errors.add("user-defined dictionary '" + dictId + "' cannot use same NAACCR Number as a base item: " + item.getNaaccrNum());
// NAACCR IDs must be unique among all user dictionaries
if (idsDejaVu.containsKey(item.getNaaccrId()))
errors.add("user-defined dictionary '" + dictId + "' and '" + idsDejaVu.get(item.getNaaccrId()) + "' both define NAACCR ID '" + item.getNaaccrId() + "'");
idsDejaVu.put(item.getNaaccrId(), dictId);
// NAACCR Numbers must be unique among all user dictionaries
if (numbersDejaVue.containsKey(item.getNaaccrNum()))
errors.add("user-defined dictionary '" + dictId + "' and '" + numbersDejaVue.get(item.getNaaccrNum()) + "' both define NAACCR ID '" + item.getNaaccrNum() + "'");
numbersDejaVue.put(item.getNaaccrNum(), dictId);
}
}
// make sure there is no overlapping with the start columns (for the items that have them)
List<NaaccrDictionaryItem> items = mergeDictionaries(baseDictionary, userDictionaries.toArray(new NaaccrDictionary[0])).getItems().stream()
.filter(i -> i.getStartColumn() != null)
.sorted(Comparator.comparing(NaaccrDictionaryItem::getStartColumn))
.collect(Collectors.toList());
NaaccrDictionaryItem currentItem = null;
for (NaaccrDictionaryItem item : items) {
if (currentItem != null && item.getStartColumn() <= currentItem.getStartColumn() + currentItem.getLength() - 1)
errors.add("user-defined dictionaries define overlapping columns for items '" + currentItem.getNaaccrId() + "' and '" + item.getNaaccrId() + "'");
currentItem = item;
}
return errors;
} } | public class class_name {
public static List<String> validateDictionaries(NaaccrDictionary baseDictionary, Collection<NaaccrDictionary> userDictionaries) {
// validate the base dictionary
List<String> errors = new ArrayList<>(validateBaseDictionary(baseDictionary));
// validate each user dictionary
Map<String, String> idsDejaVu = new HashMap<>();
Map<Integer, String> numbersDejaVue = new HashMap<>();
for (NaaccrDictionary userDictionary : userDictionaries) {
errors.addAll(validateUserDictionary(userDictionary, baseDictionary.getNaaccrVersion())); // depends on control dependency: [for], data = [userDictionary]
// make sure the provided version (if one is provided) agrees with the base version
if (userDictionary.getNaaccrVersion() != null && !baseDictionary.getNaaccrVersion().equals(userDictionary.getNaaccrVersion()))
errors.add("user-defined dictionary '" + userDictionary.getDictionaryUri() + "' doesn't define the same version as the base dictionary");
// validate the items
String dictId = userDictionary.getDictionaryUri();
for (NaaccrDictionaryItem item : userDictionary.getItems()) {
// NAACCR IDs defined in user dictionaries cannot be the same as the base NAACCR IDs
if (baseDictionary.getItemByNaaccrId(item.getNaaccrId()) != null)
errors.add("user-defined dictionary '" + dictId + "' cannot use same NAACCR ID as a base item: " + item.getNaaccrId());
// NAACCR Numbers defined in user dictionaries cannot be the same as the base NAACCR Numbers
if (baseDictionary.getItemByNaaccrNum(item.getNaaccrNum()) != null)
errors.add("user-defined dictionary '" + dictId + "' cannot use same NAACCR Number as a base item: " + item.getNaaccrNum());
// NAACCR IDs must be unique among all user dictionaries
if (idsDejaVu.containsKey(item.getNaaccrId()))
errors.add("user-defined dictionary '" + dictId + "' and '" + idsDejaVu.get(item.getNaaccrId()) + "' both define NAACCR ID '" + item.getNaaccrId() + "'");
idsDejaVu.put(item.getNaaccrId(), dictId); // depends on control dependency: [for], data = [none]
// NAACCR Numbers must be unique among all user dictionaries
if (numbersDejaVue.containsKey(item.getNaaccrNum()))
errors.add("user-defined dictionary '" + dictId + "' and '" + numbersDejaVue.get(item.getNaaccrNum()) + "' both define NAACCR ID '" + item.getNaaccrNum() + "'");
numbersDejaVue.put(item.getNaaccrNum(), dictId); // depends on control dependency: [for], data = [none]
}
}
// make sure there is no overlapping with the start columns (for the items that have them)
List<NaaccrDictionaryItem> items = mergeDictionaries(baseDictionary, userDictionaries.toArray(new NaaccrDictionary[0])).getItems().stream()
.filter(i -> i.getStartColumn() != null)
.sorted(Comparator.comparing(NaaccrDictionaryItem::getStartColumn))
.collect(Collectors.toList());
NaaccrDictionaryItem currentItem = null;
for (NaaccrDictionaryItem item : items) {
if (currentItem != null && item.getStartColumn() <= currentItem.getStartColumn() + currentItem.getLength() - 1)
errors.add("user-defined dictionaries define overlapping columns for items '" + currentItem.getNaaccrId() + "' and '" + item.getNaaccrId() + "'");
currentItem = item;
}
return errors;
} } |
public class class_name {
@PostMapping(value = "/v1/services", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createService(@RequestBody final RegisteredService service,
final HttpServletRequest request, final HttpServletResponse response) {
try {
val auth = authenticateRequest(request, response);
if (isAuthenticatedPrincipalAuthorized(auth)) {
this.servicesManager.save(service);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>("Request is not authorized", HttpStatus.FORBIDDEN);
} catch (final AuthenticationException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
} } | public class class_name {
@PostMapping(value = "/v1/services", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createService(@RequestBody final RegisteredService service,
final HttpServletRequest request, final HttpServletResponse response) {
try {
val auth = authenticateRequest(request, response);
if (isAuthenticatedPrincipalAuthorized(auth)) {
this.servicesManager.save(service); // depends on control dependency: [if], data = [none]
return new ResponseEntity<>(HttpStatus.OK); // depends on control dependency: [if], data = [none]
}
return new ResponseEntity<>("Request is not authorized", HttpStatus.FORBIDDEN); // depends on control dependency: [try], data = [none]
} catch (final AuthenticationException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
} catch (final Exception e) { // depends on control dependency: [catch], data = [none]
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void decode(FacesContext context, UIComponent component) {
Icon icon = (Icon) component;
if (icon.isDisabled() || icon.isReadonly()) {
return;
}
decodeBehaviors(context, icon); // moved to AJAXRenderer
new AJAXRenderer().decode(context, component);
} } | public class class_name {
@Override
public void decode(FacesContext context, UIComponent component) {
Icon icon = (Icon) component;
if (icon.isDisabled() || icon.isReadonly()) {
return; // depends on control dependency: [if], data = [none]
}
decodeBehaviors(context, icon); // moved to AJAXRenderer
new AJAXRenderer().decode(context, component);
} } |
public class class_name {
public void addPattern(Pattern pattern) {
if (patterns == null) {
patterns = new ArrayList<Pattern>();
}
patterns.add(pattern);
} } | public class class_name {
public void addPattern(Pattern pattern) {
if (patterns == null) {
patterns = new ArrayList<Pattern>(); // depends on control dependency: [if], data = [none]
}
patterns.add(pattern);
} } |
public class class_name {
public void handle(Data key, String sourceUuid, UUID partitionUuid, long sequence) {
// apply invalidation if it's not originated by local member/client (because local
// Near Caches are invalidated immediately there is no need to invalidate them twice)
if (!localUuid.equals(sourceUuid)) {
// sourceUuid is allowed to be `null`
if (key == null) {
nearCache.clear();
} else {
nearCache.invalidate(serializeKeys ? key : serializationService.toObject(key));
}
}
int partitionId = getPartitionIdOrDefault(key);
checkOrRepairUuid(partitionId, partitionUuid);
checkOrRepairSequence(partitionId, sequence, false);
} } | public class class_name {
public void handle(Data key, String sourceUuid, UUID partitionUuid, long sequence) {
// apply invalidation if it's not originated by local member/client (because local
// Near Caches are invalidated immediately there is no need to invalidate them twice)
if (!localUuid.equals(sourceUuid)) {
// sourceUuid is allowed to be `null`
if (key == null) {
nearCache.clear(); // depends on control dependency: [if], data = [none]
} else {
nearCache.invalidate(serializeKeys ? key : serializationService.toObject(key)); // depends on control dependency: [if], data = [(key]
}
}
int partitionId = getPartitionIdOrDefault(key);
checkOrRepairUuid(partitionId, partitionUuid);
checkOrRepairSequence(partitionId, sequence, false);
} } |
public class class_name {
public static void onesI(long[] v, int bits) {
final int fillWords = bits >>> LONG_LOG2_SIZE;
final int fillBits = bits & LONG_LOG2_MASK;
Arrays.fill(v, 0, fillWords, LONG_ALL_BITS);
if(fillBits > 0) {
v[fillWords] = (1L << fillBits) - 1;
}
if(fillWords + 1 < v.length) {
Arrays.fill(v, fillWords + 1, v.length, 0L);
}
} } | public class class_name {
public static void onesI(long[] v, int bits) {
final int fillWords = bits >>> LONG_LOG2_SIZE;
final int fillBits = bits & LONG_LOG2_MASK;
Arrays.fill(v, 0, fillWords, LONG_ALL_BITS);
if(fillBits > 0) {
v[fillWords] = (1L << fillBits) - 1; // depends on control dependency: [if], data = [none]
}
if(fillWords + 1 < v.length) {
Arrays.fill(v, fillWords + 1, v.length, 0L); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static CmsSelectWidgetOption getWidgetOptionForType(CmsObject cms, String typeName) {
String niceTypeName = typeName;
try {
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
niceTypeName = CmsWorkplaceMessages.getResourceTypeName(locale, typeName);
} catch (@SuppressWarnings("unused") Exception e) {
// resource type name will be used as a fallback
}
CmsSelectWidgetOption option = new CmsSelectWidgetOption(
CmsFormatterChangeSet.keyForType(typeName),
false,
getMessage(cms, Messages.GUI_SCHEMA_FORMATTER_OPTION_1, niceTypeName));
return option;
} } | public class class_name {
public static CmsSelectWidgetOption getWidgetOptionForType(CmsObject cms, String typeName) {
String niceTypeName = typeName;
try {
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
niceTypeName = CmsWorkplaceMessages.getResourceTypeName(locale, typeName); // depends on control dependency: [try], data = [none]
} catch (@SuppressWarnings("unused") Exception e) {
// resource type name will be used as a fallback
} // depends on control dependency: [catch], data = [none]
CmsSelectWidgetOption option = new CmsSelectWidgetOption(
CmsFormatterChangeSet.keyForType(typeName),
false,
getMessage(cms, Messages.GUI_SCHEMA_FORMATTER_OPTION_1, niceTypeName));
return option;
} } |
public class class_name {
public synchronized void removeHandler(String handlerId) {
handlerEventMap.remove(handlerId);
Tr.event(tc, "Removed Asynchronous Handler: " + handlerId);
if (handlerEventMap.isEmpty()) {
ringBuffer = null;
Tr.event(tc, "ringBuffer for this BufferManagerImpl has now been set to null");
}
} } | public class class_name {
public synchronized void removeHandler(String handlerId) {
handlerEventMap.remove(handlerId);
Tr.event(tc, "Removed Asynchronous Handler: " + handlerId);
if (handlerEventMap.isEmpty()) {
ringBuffer = null; // depends on control dependency: [if], data = [none]
Tr.event(tc, "ringBuffer for this BufferManagerImpl has now been set to null"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static TechnologyReference parseFromIDAndVersion(String idAndVersion)
{
if (idAndVersion.contains(":"))
{
String tech = StringUtils.substringBefore(idAndVersion, ":");
String versionRangeString = StringUtils.substringAfter(idAndVersion, ":");
if (!versionRangeString.matches("^[(\\[].*[)\\]]"))
versionRangeString = "[" + versionRangeString + "]";
VersionRange versionRange = Versions.parseVersionRange(versionRangeString);
return new TechnologyReference(tech, versionRange);
}
return new TechnologyReference(idAndVersion);
} } | public class class_name {
public static TechnologyReference parseFromIDAndVersion(String idAndVersion)
{
if (idAndVersion.contains(":"))
{
String tech = StringUtils.substringBefore(idAndVersion, ":");
String versionRangeString = StringUtils.substringAfter(idAndVersion, ":");
if (!versionRangeString.matches("^[(\\[].*[)\\]]"))
versionRangeString = "[" + versionRangeString + "]";
VersionRange versionRange = Versions.parseVersionRange(versionRangeString);
return new TechnologyReference(tech, versionRange); // depends on control dependency: [if], data = [none]
}
return new TechnologyReference(idAndVersion);
} } |
public class class_name {
public final float getDragSpeed() {
if (hasThresholdBeenReached()) {
long interval = System.currentTimeMillis() - dragStartTime;
return Math.abs(getDragDistance()) / (float) interval;
} else {
return -1;
}
} } | public class class_name {
public final float getDragSpeed() {
if (hasThresholdBeenReached()) {
long interval = System.currentTimeMillis() - dragStartTime;
return Math.abs(getDragDistance()) / (float) interval; // depends on control dependency: [if], data = [none]
} else {
return -1; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String getExceptionMessage(List throwables)
{
if (throwables == null)
{
return null;
}
for (int i = throwables.size()-1; i>0; i--)
{
Throwable t = (Throwable) throwables.get(i);
if (t.getMessage() != null)
{
return t.getMessage();
}
}
return null;
} } | public class class_name {
public static String getExceptionMessage(List throwables)
{
if (throwables == null)
{
return null; // depends on control dependency: [if], data = [none]
}
for (int i = throwables.size()-1; i>0; i--)
{
Throwable t = (Throwable) throwables.get(i);
if (t.getMessage() != null)
{
return t.getMessage(); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public final void add(final T session) {
// note: alignment is optional before 4.0
if (session.isIoAligned()) {
verifyInIoThread(session, session.getIoThread());
}
add0(session);
} } | public class class_name {
@Override
public final void add(final T session) {
// note: alignment is optional before 4.0
if (session.isIoAligned()) {
verifyInIoThread(session, session.getIoThread()); // depends on control dependency: [if], data = [none]
}
add0(session);
} } |
public class class_name {
private Object convertObjectToArray(Object value) {
if (value instanceof CharSequence) {
if (targetComponentType == char.class || targetComponentType == Character.class) {
return convertArrayToArray(value.toString().toCharArray());
}
// 单纯字符串情况下按照逗号分隔后劈开
final String[] strings = StrUtil.split(value.toString(), StrUtil.COMMA);
return convertArrayToArray(strings);
}
final ConverterRegistry converter = ConverterRegistry.getInstance();
Object result = null;
if (value instanceof List) {
// List转数组
final List<?> list = (List<?>) value;
result = Array.newInstance(targetComponentType, list.size());
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
}
} else if (value instanceof Collection) {
// 集合转数组
final Collection<?> collection = (Collection<?>) value;
result = Array.newInstance(targetComponentType, collection.size());
int i = 0;
for (Object element : collection) {
Array.set(result, i, converter.convert(targetComponentType, element));
i++;
}
} else if (value instanceof Iterable) {
// 可循环对象转数组,可循环对象无法获取长度,因此先转为List后转为数组
final List<?> list = IterUtil.toList((Iterable<?>) value);
result = Array.newInstance(targetComponentType, list.size());
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
}
} else if (value instanceof Iterator) {
// 可循环对象转数组,可循环对象无法获取长度,因此先转为List后转为数组
final List<?> list = IterUtil.toList((Iterator<?>) value);
result = Array.newInstance(targetComponentType, list.size());
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
}
} else {
// everything else:
result = convertToSingleElementArray(value);
}
return result;
} } | public class class_name {
private Object convertObjectToArray(Object value) {
if (value instanceof CharSequence) {
if (targetComponentType == char.class || targetComponentType == Character.class) {
return convertArrayToArray(value.toString().toCharArray());
// depends on control dependency: [if], data = [none]
}
// 单纯字符串情况下按照逗号分隔后劈开
final String[] strings = StrUtil.split(value.toString(), StrUtil.COMMA);
return convertArrayToArray(strings);
// depends on control dependency: [if], data = [none]
}
final ConverterRegistry converter = ConverterRegistry.getInstance();
Object result = null;
if (value instanceof List) {
// List转数组
final List<?> list = (List<?>) value;
result = Array.newInstance(targetComponentType, list.size());
// depends on control dependency: [if], data = [none]
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
// depends on control dependency: [for], data = [i]
}
} else if (value instanceof Collection) {
// 集合转数组
final Collection<?> collection = (Collection<?>) value;
result = Array.newInstance(targetComponentType, collection.size());
// depends on control dependency: [if], data = [none]
int i = 0;
for (Object element : collection) {
Array.set(result, i, converter.convert(targetComponentType, element));
// depends on control dependency: [for], data = [element]
i++;
// depends on control dependency: [for], data = [none]
}
} else if (value instanceof Iterable) {
// 可循环对象转数组,可循环对象无法获取长度,因此先转为List后转为数组
final List<?> list = IterUtil.toList((Iterable<?>) value);
result = Array.newInstance(targetComponentType, list.size());
// depends on control dependency: [if], data = [none]
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
// depends on control dependency: [for], data = [i]
}
} else if (value instanceof Iterator) {
// 可循环对象转数组,可循环对象无法获取长度,因此先转为List后转为数组
final List<?> list = IterUtil.toList((Iterator<?>) value);
result = Array.newInstance(targetComponentType, list.size());
// depends on control dependency: [if], data = [none]
for (int i = 0; i < list.size(); i++) {
Array.set(result, i, converter.convert(targetComponentType, list.get(i)));
// depends on control dependency: [for], data = [i]
}
} else {
// everything else:
result = convertToSingleElementArray(value);
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public void clear() {
// clear properties
List<String> ownProps = getOwnProperties();
for (String key : properties.keySet().toArray(new String[]{})) {
if (ownProps.contains(key)) {
Object value = properties.get(key);
if (value instanceof JsonCollection) {
JsonCollection entity = (JsonCollection)value;
entity.clear();
} else {
remove(key);
}
} else {
remove(key);
}
}
// clear fields
for (Field field : getFields(this.getClass())) {
if (field != null && JsonCollection.class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true);
JsonCollection entity = (JsonCollection) field.get(this);
entity.clear();
} catch (Exception e) {
log.error(e);
}
}
}
// clear sort order
sortOrder.clear();
} } | public class class_name {
public void clear() {
// clear properties
List<String> ownProps = getOwnProperties();
for (String key : properties.keySet().toArray(new String[]{})) {
if (ownProps.contains(key)) {
Object value = properties.get(key);
if (value instanceof JsonCollection) {
JsonCollection entity = (JsonCollection)value;
entity.clear(); // depends on control dependency: [if], data = [none]
} else {
remove(key); // depends on control dependency: [if], data = [none]
}
} else {
remove(key); // depends on control dependency: [if], data = [none]
}
}
// clear fields
for (Field field : getFields(this.getClass())) {
if (field != null && JsonCollection.class.isAssignableFrom(field.getType())) {
try {
field.setAccessible(true); // depends on control dependency: [try], data = [none]
JsonCollection entity = (JsonCollection) field.get(this);
entity.clear(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.error(e);
} // depends on control dependency: [catch], data = [none]
}
}
// clear sort order
sortOrder.clear();
} } |
public class class_name {
@Override
public void process(ResponseBuilder rb) throws IOException {
// System.out
// .println(System.nanoTime() + " - " + Thread.currentThread().getId()
// + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false)
// + " PROCESS " + rb.stage + " " + rb.req.getParamString());
MtasSolrStatus solrStatus = Objects
.requireNonNull((MtasSolrStatus) rb.req.getContext().get(MtasSolrStatus.class), "couldn't find status");
solrStatus.setStage(rb.stage);
try {
if (rb.req.getParams().getBool(PARAM_MTAS, false)) {
try {
ComponentFields mtasFields = getMtasFields(rb);
if (mtasFields != null) {
DocSet docSet = rb.getResults().docSet;
DocList docList = rb.getResults().docList;
if (mtasFields.doStats || mtasFields.doDocument || mtasFields.doKwic || mtasFields.doList
|| mtasFields.doGroup || mtasFields.doFacet || mtasFields.doCollection
|| mtasFields.doTermVector || mtasFields.doPrefix || mtasFields.doStatus
|| mtasFields.doVersion) {
SolrIndexSearcher searcher = rb.req.getSearcher();
ArrayList<Integer> docSetList = null;
ArrayList<Integer> docListList = null;
// initialise docSetList
if (docSet != null) {
docSetList = new ArrayList<>();
Iterator<Integer> docSetIterator = docSet.iterator();
while (docSetIterator.hasNext()) {
docSetList.add(docSetIterator.next());
}
Collections.sort(docSetList);
}
// initialise docListList
if (docList != null) {
docListList = new ArrayList<>();
Iterator<Integer> docListIterator = docList.iterator();
while (docListIterator.hasNext()) {
docListList.add(docListIterator.next());
}
Collections.sort(docListList);
}
solrStatus.status().addSubs(mtasFields.list.keySet());
for (String field : mtasFields.list.keySet()) {
try {
CodecUtil.collectField(field, searcher, searcher.getRawReader(), docListList,
docSetList, mtasFields.list.get(field), solrStatus.status());
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
log.error(e);
throw new IOException(e);
}
}
for (ComponentCollection collection : mtasFields.collection) {
CodecUtil.collectCollection(searcher.getRawReader(), docSetList, collection);
}
NamedList<Object> mtasResponse = new SimpleOrderedMap<>();
if (mtasFields.doVersion) {
SimpleOrderedMap<Object> versionResponse = searchVersion.create(mtasFields.version,
false);
mtasResponse.add(MtasSolrComponentVersion.NAME, versionResponse);
}
if (mtasFields.doStatus) {
// add to response
SimpleOrderedMap<Object> statusResponse = searchStatus.create(mtasFields.status, false);
if (statusResponse != null) {
mtasResponse.add(MtasSolrComponentStatus.NAME,
searchStatus.create(mtasFields.status, false));
}
}
if (mtasFields.doDocument) {
ArrayList<NamedList<?>> mtasDocumentResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentDocument document : mtasFields.list.get(field).documentList) {
mtasDocumentResponses.add(searchDocument.create(document, false));
}
}
// add to response
mtasResponse.add(MtasSolrComponentDocument.NAME, mtasDocumentResponses);
}
if (mtasFields.doKwic) {
ArrayList<NamedList<?>> mtasKwicResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentKwic kwic : mtasFields.list.get(field).kwicList) {
mtasKwicResponses.add(searchKwic.create(kwic, false));
}
}
// add to response
mtasResponse.add(MtasSolrComponentKwic.NAME, mtasKwicResponses);
}
if (mtasFields.doFacet) {
ArrayList<NamedList<?>> mtasFacetResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentFacet facet : mtasFields.list.get(field).facetList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasFacetResponses.add(searchFacet.create(facet, true));
} else {
mtasFacetResponses.add(searchFacet.create(facet, false));
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentFacet.NAME, mtasFacetResponses);
}
if (mtasFields.doCollection) {
ArrayList<NamedList<?>> mtasCollectionResponses = new ArrayList<>();
for (ComponentCollection collection : mtasFields.collection) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasCollectionResponses.add(searchCollection.create(collection, true));
} else {
mtasCollectionResponses.add(searchCollection.create(collection, false));
}
}
// add to response
mtasResponse.add(MtasSolrComponentCollection.NAME, mtasCollectionResponses);
}
if (mtasFields.doList) {
ArrayList<NamedList<?>> mtasListResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentList list : mtasFields.list.get(field).listList) {
mtasListResponses.add(searchList.create(list, false));
}
}
// add to response
mtasResponse.add(MtasSolrComponentList.NAME, mtasListResponses);
}
if (mtasFields.doGroup) {
ArrayList<NamedList<?>> mtasGroupResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentGroup group : mtasFields.list.get(field).groupList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasGroupResponses.add(searchGroup.create(group, true));
} else {
mtasGroupResponses.add(searchGroup.create(group, false));
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentGroup.NAME, mtasGroupResponses);
}
if (mtasFields.doTermVector) {
ArrayList<NamedList<?>> mtasTermVectorResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentTermVector termVector : mtasFields.list.get(field).termVectorList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasTermVectorResponses.add(searchTermvector.create(termVector, true));
} else {
mtasTermVectorResponses.add(searchTermvector.create(termVector, false));
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentTermvector.NAME, mtasTermVectorResponses);
}
if (mtasFields.doPrefix) {
ArrayList<NamedList<?>> mtasPrefixResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
if (mtasFields.list.get(field).prefix != null) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasPrefixResponses
.add(searchPrefix.create(mtasFields.list.get(field).prefix, true));
} else {
mtasPrefixResponses
.add(searchPrefix.create(mtasFields.list.get(field).prefix, false));
}
}
}
mtasResponse.add(MtasSolrComponentPrefix.NAME, mtasPrefixResponses);
}
if (mtasFields.doStats) {
NamedList<Object> mtasStatsResponse = new SimpleOrderedMap<>();
if (mtasFields.doStatsPositions || mtasFields.doStatsTokens
|| mtasFields.doStatsSpans) {
if (mtasFields.doStatsTokens) {
ArrayList<Object> mtasStatsTokensResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentToken token : mtasFields.list.get(field).statsTokenList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsTokensResponses.add(searchStats.create(token, true));
} else {
mtasStatsTokensResponses.add(searchStats.create(token, false));
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_TOKENS,
mtasStatsTokensResponses);
}
if (mtasFields.doStatsPositions) {
ArrayList<Object> mtasStatsPositionsResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentPosition position : mtasFields.list
.get(field).statsPositionList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsPositionsResponses.add(searchStats.create(position, true));
} else {
mtasStatsPositionsResponses
.add(searchStats.create(position, false));
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_POSITIONS,
mtasStatsPositionsResponses);
}
if (mtasFields.doStatsSpans) {
ArrayList<Object> mtasStatsSpansResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentSpan span : mtasFields.list.get(field).statsSpanList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsSpansResponses.add(searchStats.create(span, true));
} else {
mtasStatsSpansResponses.add(searchStats.create(span, false));
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_SPANS,
mtasStatsSpansResponses);
}
// add to response
mtasResponse.add(MtasSolrComponentStats.NAME, mtasStatsResponse);
}
}
// add to response
if (mtasResponse.size() > 0) {
rb.rsp.add(NAME, mtasResponse);
}
}
}
} catch (IOException e) {
errorStatus(solrStatus, e);
}
}
if (!solrStatus.error()) {
// always set status segments
if (solrStatus.status().numberSegmentsTotal == null) {
solrStatus.status().numberSegmentsTotal = rb.req.getSearcher().getRawReader().leaves().size();
solrStatus.status().numberSegmentsFinished = solrStatus.status().numberSegmentsTotal;
}
// always try to set number of documents
if (solrStatus.status().numberDocumentsTotal == null) {
SolrIndexSearcher searcher;
if ((searcher = rb.req.getSearcher()) != null) {
solrStatus.status().numberDocumentsTotal = (long) searcher.numDocs();
if (rb.getResults().docList != null) {
solrStatus.status().numberDocumentsFinished = rb.getResults().docList.matches();
solrStatus.status().numberDocumentsFound = rb.getResults().docList.matches();
} else if (rb.getResults().docSet != null) {
solrStatus.status().numberDocumentsFinished = (long) rb.getResults().docSet.size();
solrStatus.status().numberDocumentsFound = (long) rb.getResults().docSet.size();
}
}
}
}
} catch (ExitableDirectoryReader.ExitingReaderException e) {
solrStatus.setError(e.getMessage());
} finally {
checkStatus(solrStatus);
finishStatus(solrStatus);
}
} } | public class class_name {
@Override
public void process(ResponseBuilder rb) throws IOException {
// System.out
// .println(System.nanoTime() + " - " + Thread.currentThread().getId()
// + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false)
// + " PROCESS " + rb.stage + " " + rb.req.getParamString());
MtasSolrStatus solrStatus = Objects
.requireNonNull((MtasSolrStatus) rb.req.getContext().get(MtasSolrStatus.class), "couldn't find status");
solrStatus.setStage(rb.stage);
try {
if (rb.req.getParams().getBool(PARAM_MTAS, false)) {
try {
ComponentFields mtasFields = getMtasFields(rb);
if (mtasFields != null) {
DocSet docSet = rb.getResults().docSet;
DocList docList = rb.getResults().docList;
if (mtasFields.doStats || mtasFields.doDocument || mtasFields.doKwic || mtasFields.doList
|| mtasFields.doGroup || mtasFields.doFacet || mtasFields.doCollection
|| mtasFields.doTermVector || mtasFields.doPrefix || mtasFields.doStatus
|| mtasFields.doVersion) {
SolrIndexSearcher searcher = rb.req.getSearcher();
ArrayList<Integer> docSetList = null;
ArrayList<Integer> docListList = null;
// initialise docSetList
if (docSet != null) {
docSetList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
Iterator<Integer> docSetIterator = docSet.iterator();
while (docSetIterator.hasNext()) {
docSetList.add(docSetIterator.next()); // depends on control dependency: [while], data = [none]
}
Collections.sort(docSetList); // depends on control dependency: [if], data = [(docSet]
}
// initialise docListList
if (docList != null) {
docListList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
Iterator<Integer> docListIterator = docList.iterator();
while (docListIterator.hasNext()) {
docListList.add(docListIterator.next()); // depends on control dependency: [while], data = [none]
}
Collections.sort(docListList); // depends on control dependency: [if], data = [(docList]
}
solrStatus.status().addSubs(mtasFields.list.keySet()); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
try {
CodecUtil.collectField(field, searcher, searcher.getRawReader(), docListList,
docSetList, mtasFields.list.get(field), solrStatus.status()); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
log.error(e);
throw new IOException(e);
} // depends on control dependency: [catch], data = [none]
}
for (ComponentCollection collection : mtasFields.collection) {
CodecUtil.collectCollection(searcher.getRawReader(), docSetList, collection); // depends on control dependency: [for], data = [collection]
}
NamedList<Object> mtasResponse = new SimpleOrderedMap<>();
if (mtasFields.doVersion) {
SimpleOrderedMap<Object> versionResponse = searchVersion.create(mtasFields.version,
false);
mtasResponse.add(MtasSolrComponentVersion.NAME, versionResponse); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doStatus) {
// add to response
SimpleOrderedMap<Object> statusResponse = searchStatus.create(mtasFields.status, false);
if (statusResponse != null) {
mtasResponse.add(MtasSolrComponentStatus.NAME,
searchStatus.create(mtasFields.status, false)); // depends on control dependency: [if], data = [none]
}
}
if (mtasFields.doDocument) {
ArrayList<NamedList<?>> mtasDocumentResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentDocument document : mtasFields.list.get(field).documentList) {
mtasDocumentResponses.add(searchDocument.create(document, false)); // depends on control dependency: [for], data = [document]
}
}
// add to response
mtasResponse.add(MtasSolrComponentDocument.NAME, mtasDocumentResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doKwic) {
ArrayList<NamedList<?>> mtasKwicResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentKwic kwic : mtasFields.list.get(field).kwicList) {
mtasKwicResponses.add(searchKwic.create(kwic, false)); // depends on control dependency: [for], data = [kwic]
}
}
// add to response
mtasResponse.add(MtasSolrComponentKwic.NAME, mtasKwicResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doFacet) {
ArrayList<NamedList<?>> mtasFacetResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentFacet facet : mtasFields.list.get(field).facetList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasFacetResponses.add(searchFacet.create(facet, true)); // depends on control dependency: [if], data = [none]
} else {
mtasFacetResponses.add(searchFacet.create(facet, false)); // depends on control dependency: [if], data = [none]
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentFacet.NAME, mtasFacetResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doCollection) {
ArrayList<NamedList<?>> mtasCollectionResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (ComponentCollection collection : mtasFields.collection) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasCollectionResponses.add(searchCollection.create(collection, true)); // depends on control dependency: [if], data = [none]
} else {
mtasCollectionResponses.add(searchCollection.create(collection, false)); // depends on control dependency: [if], data = [none]
}
}
// add to response
mtasResponse.add(MtasSolrComponentCollection.NAME, mtasCollectionResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doList) {
ArrayList<NamedList<?>> mtasListResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentList list : mtasFields.list.get(field).listList) {
mtasListResponses.add(searchList.create(list, false)); // depends on control dependency: [for], data = [list]
}
}
// add to response
mtasResponse.add(MtasSolrComponentList.NAME, mtasListResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doGroup) {
ArrayList<NamedList<?>> mtasGroupResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentGroup group : mtasFields.list.get(field).groupList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasGroupResponses.add(searchGroup.create(group, true)); // depends on control dependency: [if], data = [none]
} else {
mtasGroupResponses.add(searchGroup.create(group, false)); // depends on control dependency: [if], data = [none]
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentGroup.NAME, mtasGroupResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doTermVector) {
ArrayList<NamedList<?>> mtasTermVectorResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
for (ComponentTermVector termVector : mtasFields.list.get(field).termVectorList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasTermVectorResponses.add(searchTermvector.create(termVector, true)); // depends on control dependency: [if], data = [none]
} else {
mtasTermVectorResponses.add(searchTermvector.create(termVector, false)); // depends on control dependency: [if], data = [none]
}
}
}
// add to response
mtasResponse.add(MtasSolrComponentTermvector.NAME, mtasTermVectorResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doPrefix) {
ArrayList<NamedList<?>> mtasPrefixResponses = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String field : mtasFields.list.keySet()) {
if (mtasFields.list.get(field).prefix != null) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasPrefixResponses
.add(searchPrefix.create(mtasFields.list.get(field).prefix, true)); // depends on control dependency: [if], data = [none]
} else {
mtasPrefixResponses
.add(searchPrefix.create(mtasFields.list.get(field).prefix, false)); // depends on control dependency: [if], data = [none]
}
}
}
mtasResponse.add(MtasSolrComponentPrefix.NAME, mtasPrefixResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doStats) {
NamedList<Object> mtasStatsResponse = new SimpleOrderedMap<>();
if (mtasFields.doStatsPositions || mtasFields.doStatsTokens
|| mtasFields.doStatsSpans) {
if (mtasFields.doStatsTokens) {
ArrayList<Object> mtasStatsTokensResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentToken token : mtasFields.list.get(field).statsTokenList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsTokensResponses.add(searchStats.create(token, true)); // depends on control dependency: [if], data = [none]
} else {
mtasStatsTokensResponses.add(searchStats.create(token, false)); // depends on control dependency: [if], data = [none]
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_TOKENS,
mtasStatsTokensResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doStatsPositions) {
ArrayList<Object> mtasStatsPositionsResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentPosition position : mtasFields.list
.get(field).statsPositionList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsPositionsResponses.add(searchStats.create(position, true)); // depends on control dependency: [if], data = [none]
} else {
mtasStatsPositionsResponses
.add(searchStats.create(position, false)); // depends on control dependency: [if], data = [none]
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_POSITIONS,
mtasStatsPositionsResponses); // depends on control dependency: [if], data = [none]
}
if (mtasFields.doStatsSpans) {
ArrayList<Object> mtasStatsSpansResponses = new ArrayList<>();
for (String field : mtasFields.list.keySet()) {
for (ComponentSpan span : mtasFields.list.get(field).statsSpanList) {
if (rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) {
mtasStatsSpansResponses.add(searchStats.create(span, true)); // depends on control dependency: [if], data = [none]
} else {
mtasStatsSpansResponses.add(searchStats.create(span, false)); // depends on control dependency: [if], data = [none]
}
}
}
mtasStatsResponse.add(MtasSolrComponentStats.NAME_SPANS,
mtasStatsSpansResponses); // depends on control dependency: [if], data = [none]
}
// add to response
mtasResponse.add(MtasSolrComponentStats.NAME, mtasStatsResponse); // depends on control dependency: [if], data = [none]
}
}
// add to response
if (mtasResponse.size() > 0) {
rb.rsp.add(NAME, mtasResponse); // depends on control dependency: [if], data = [none]
}
}
}
} catch (IOException e) {
errorStatus(solrStatus, e);
} // depends on control dependency: [catch], data = [none]
}
if (!solrStatus.error()) {
// always set status segments
if (solrStatus.status().numberSegmentsTotal == null) {
solrStatus.status().numberSegmentsTotal = rb.req.getSearcher().getRawReader().leaves().size(); // depends on control dependency: [if], data = [none]
solrStatus.status().numberSegmentsFinished = solrStatus.status().numberSegmentsTotal; // depends on control dependency: [if], data = [none]
}
// always try to set number of documents
if (solrStatus.status().numberDocumentsTotal == null) {
SolrIndexSearcher searcher;
if ((searcher = rb.req.getSearcher()) != null) {
solrStatus.status().numberDocumentsTotal = (long) searcher.numDocs(); // depends on control dependency: [if], data = [none]
if (rb.getResults().docList != null) {
solrStatus.status().numberDocumentsFinished = rb.getResults().docList.matches(); // depends on control dependency: [if], data = [none]
solrStatus.status().numberDocumentsFound = rb.getResults().docList.matches(); // depends on control dependency: [if], data = [none]
} else if (rb.getResults().docSet != null) {
solrStatus.status().numberDocumentsFinished = (long) rb.getResults().docSet.size(); // depends on control dependency: [if], data = [none]
solrStatus.status().numberDocumentsFound = (long) rb.getResults().docSet.size(); // depends on control dependency: [if], data = [none]
}
}
}
}
} catch (ExitableDirectoryReader.ExitingReaderException e) {
solrStatus.setError(e.getMessage());
} finally {
checkStatus(solrStatus);
finishStatus(solrStatus);
}
} } |
public class class_name {
public static Pair<Grouper<RowBasedKey>, Accumulator<AggregateResult, Row>> createGrouperAccumulatorPair(
final GroupByQuery query,
final boolean isInputRaw,
final Map<String, ValueType> rawInputRowSignature,
final GroupByQueryConfig config,
final Supplier<ByteBuffer> bufferSupplier,
@Nullable final ReferenceCountingResourceHolder<ByteBuffer> combineBufferHolder,
final int concurrencyHint,
final LimitedTemporaryStorage temporaryStorage,
final ObjectMapper spillMapper,
final AggregatorFactory[] aggregatorFactories,
@Nullable final ListeningExecutorService grouperSorter,
final int priority,
final boolean hasQueryTimeout,
final long queryTimeoutAt,
final int mergeBufferSize
)
{
// concurrencyHint >= 1 for concurrent groupers, -1 for single-threaded
Preconditions.checkArgument(concurrencyHint >= 1 || concurrencyHint == -1, "invalid concurrencyHint");
final List<ValueType> valueTypes = DimensionHandlerUtils.getValueTypesFromDimensionSpecs(query.getDimensions());
final GroupByQueryConfig querySpecificConfig = config.withOverrides(query);
final boolean includeTimestamp = GroupByStrategyV2.getUniversalTimestamp(query) == null;
final ThreadLocal<Row> columnSelectorRow = new ThreadLocal<>();
final ColumnSelectorFactory columnSelectorFactory = query.getVirtualColumns().wrap(
RowBasedColumnSelectorFactory.create(
columnSelectorRow,
rawInputRowSignature
)
);
final boolean willApplyLimitPushDown = query.isApplyLimitPushDown();
final DefaultLimitSpec limitSpec = willApplyLimitPushDown ? (DefaultLimitSpec) query.getLimitSpec() : null;
boolean sortHasNonGroupingFields = false;
if (willApplyLimitPushDown) {
sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields(
limitSpec,
query.getDimensions()
);
}
final Grouper.KeySerdeFactory<RowBasedKey> keySerdeFactory = new RowBasedKeySerdeFactory(
includeTimestamp,
query.getContextSortByDimsFirst(),
query.getDimensions(),
querySpecificConfig.getMaxMergingDictionarySize() / (concurrencyHint == -1 ? 1 : concurrencyHint),
valueTypes,
aggregatorFactories,
limitSpec
);
final Grouper<RowBasedKey> grouper;
if (concurrencyHint == -1) {
grouper = new SpillingGrouper<>(
bufferSupplier,
keySerdeFactory,
columnSelectorFactory,
aggregatorFactories,
querySpecificConfig.getBufferGrouperMaxSize(),
querySpecificConfig.getBufferGrouperMaxLoadFactor(),
querySpecificConfig.getBufferGrouperInitialBuckets(),
temporaryStorage,
spillMapper,
true,
limitSpec,
sortHasNonGroupingFields,
mergeBufferSize
);
} else {
final Grouper.KeySerdeFactory<RowBasedKey> combineKeySerdeFactory = new RowBasedKeySerdeFactory(
includeTimestamp,
query.getContextSortByDimsFirst(),
query.getDimensions(),
querySpecificConfig.getMaxMergingDictionarySize(), // use entire dictionary space for combining key serde
valueTypes,
aggregatorFactories,
limitSpec
);
grouper = new ConcurrentGrouper<>(
querySpecificConfig,
bufferSupplier,
combineBufferHolder,
keySerdeFactory,
combineKeySerdeFactory,
columnSelectorFactory,
aggregatorFactories,
temporaryStorage,
spillMapper,
concurrencyHint,
limitSpec,
sortHasNonGroupingFields,
grouperSorter,
priority,
hasQueryTimeout,
queryTimeoutAt
);
}
final int keySize = includeTimestamp ? query.getDimensions().size() + 1 : query.getDimensions().size();
final ValueExtractFunction valueExtractFn = makeValueExtractFunction(
query,
isInputRaw,
includeTimestamp,
columnSelectorFactory,
valueTypes
);
final Accumulator<AggregateResult, Row> accumulator = new Accumulator<AggregateResult, Row>()
{
@Override
public AggregateResult accumulate(
final AggregateResult priorResult,
final Row row
)
{
BaseQuery.checkInterrupted();
if (priorResult != null && !priorResult.isOk()) {
// Pass-through error returns without doing more work.
return priorResult;
}
if (!grouper.isInitialized()) {
grouper.init();
}
columnSelectorRow.set(row);
final Comparable[] key = new Comparable[keySize];
valueExtractFn.apply(row, key);
final AggregateResult aggregateResult = grouper.aggregate(new RowBasedKey(key));
columnSelectorRow.set(null);
return aggregateResult;
}
};
return new Pair<>(grouper, accumulator);
} } | public class class_name {
public static Pair<Grouper<RowBasedKey>, Accumulator<AggregateResult, Row>> createGrouperAccumulatorPair(
final GroupByQuery query,
final boolean isInputRaw,
final Map<String, ValueType> rawInputRowSignature,
final GroupByQueryConfig config,
final Supplier<ByteBuffer> bufferSupplier,
@Nullable final ReferenceCountingResourceHolder<ByteBuffer> combineBufferHolder,
final int concurrencyHint,
final LimitedTemporaryStorage temporaryStorage,
final ObjectMapper spillMapper,
final AggregatorFactory[] aggregatorFactories,
@Nullable final ListeningExecutorService grouperSorter,
final int priority,
final boolean hasQueryTimeout,
final long queryTimeoutAt,
final int mergeBufferSize
)
{
// concurrencyHint >= 1 for concurrent groupers, -1 for single-threaded
Preconditions.checkArgument(concurrencyHint >= 1 || concurrencyHint == -1, "invalid concurrencyHint");
final List<ValueType> valueTypes = DimensionHandlerUtils.getValueTypesFromDimensionSpecs(query.getDimensions());
final GroupByQueryConfig querySpecificConfig = config.withOverrides(query);
final boolean includeTimestamp = GroupByStrategyV2.getUniversalTimestamp(query) == null;
final ThreadLocal<Row> columnSelectorRow = new ThreadLocal<>();
final ColumnSelectorFactory columnSelectorFactory = query.getVirtualColumns().wrap(
RowBasedColumnSelectorFactory.create(
columnSelectorRow,
rawInputRowSignature
)
);
final boolean willApplyLimitPushDown = query.isApplyLimitPushDown();
final DefaultLimitSpec limitSpec = willApplyLimitPushDown ? (DefaultLimitSpec) query.getLimitSpec() : null;
boolean sortHasNonGroupingFields = false;
if (willApplyLimitPushDown) {
sortHasNonGroupingFields = DefaultLimitSpec.sortingOrderHasNonGroupingFields(
limitSpec,
query.getDimensions()
); // depends on control dependency: [if], data = [none]
}
final Grouper.KeySerdeFactory<RowBasedKey> keySerdeFactory = new RowBasedKeySerdeFactory(
includeTimestamp,
query.getContextSortByDimsFirst(),
query.getDimensions(),
querySpecificConfig.getMaxMergingDictionarySize() / (concurrencyHint == -1 ? 1 : concurrencyHint),
valueTypes,
aggregatorFactories,
limitSpec
);
final Grouper<RowBasedKey> grouper;
if (concurrencyHint == -1) {
grouper = new SpillingGrouper<>(
bufferSupplier,
keySerdeFactory,
columnSelectorFactory,
aggregatorFactories,
querySpecificConfig.getBufferGrouperMaxSize(),
querySpecificConfig.getBufferGrouperMaxLoadFactor(),
querySpecificConfig.getBufferGrouperInitialBuckets(),
temporaryStorage,
spillMapper,
true,
limitSpec,
sortHasNonGroupingFields,
mergeBufferSize
); // depends on control dependency: [if], data = [none]
} else {
final Grouper.KeySerdeFactory<RowBasedKey> combineKeySerdeFactory = new RowBasedKeySerdeFactory(
includeTimestamp,
query.getContextSortByDimsFirst(),
query.getDimensions(),
querySpecificConfig.getMaxMergingDictionarySize(), // use entire dictionary space for combining key serde
valueTypes,
aggregatorFactories,
limitSpec
);
grouper = new ConcurrentGrouper<>(
querySpecificConfig,
bufferSupplier,
combineBufferHolder,
keySerdeFactory,
combineKeySerdeFactory,
columnSelectorFactory,
aggregatorFactories,
temporaryStorage,
spillMapper,
concurrencyHint,
limitSpec,
sortHasNonGroupingFields,
grouperSorter,
priority,
hasQueryTimeout,
queryTimeoutAt
); // depends on control dependency: [if], data = [none]
}
final int keySize = includeTimestamp ? query.getDimensions().size() + 1 : query.getDimensions().size();
final ValueExtractFunction valueExtractFn = makeValueExtractFunction(
query,
isInputRaw,
includeTimestamp,
columnSelectorFactory,
valueTypes
);
final Accumulator<AggregateResult, Row> accumulator = new Accumulator<AggregateResult, Row>()
{
@Override
public AggregateResult accumulate(
final AggregateResult priorResult,
final Row row
)
{
BaseQuery.checkInterrupted();
if (priorResult != null && !priorResult.isOk()) {
// Pass-through error returns without doing more work.
return priorResult; // depends on control dependency: [if], data = [none]
}
if (!grouper.isInitialized()) {
grouper.init(); // depends on control dependency: [if], data = [none]
}
columnSelectorRow.set(row);
final Comparable[] key = new Comparable[keySize];
valueExtractFn.apply(row, key);
final AggregateResult aggregateResult = grouper.aggregate(new RowBasedKey(key));
columnSelectorRow.set(null);
return aggregateResult;
}
};
return new Pair<>(grouper, accumulator);
} } |
public class class_name {
public static String printLine(String... values) {
// set up a CSVUtils
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter);
// check for null values an "null" as strings and convert them
// into the strings "null" and "\"null\""
for (int i = 0; i < values.length; i++) {
if (values[i] == null) {
values[i] = "null";
} else if (values[i].equals("null")) {
values[i] = "\"null\"";
}
}
// convert to CSV
csvPrinter.println(values);
// as the resulting string has \r\n at the end, we will trim that away
return stringWriter.toString().trim();
} } | public class class_name {
public static String printLine(String... values) {
// set up a CSVUtils
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter);
// check for null values an "null" as strings and convert them
// into the strings "null" and "\"null\""
for (int i = 0; i < values.length; i++) {
if (values[i] == null) {
values[i] = "null"; // depends on control dependency: [if], data = [none]
} else if (values[i].equals("null")) {
values[i] = "\"null\""; // depends on control dependency: [if], data = [none]
}
}
// convert to CSV
csvPrinter.println(values);
// as the resulting string has \r\n at the end, we will trim that away
return stringWriter.toString().trim();
} } |
public class class_name {
public V put(K key, V value) {
//remove possible existing with same value
if (backward.containsKey(value)) {
K oldKey = backward.get(value);
forward.remove(oldKey);
}
if (forward.containsKey(key)) {
V oldValue = forward.get(key);
backward.remove(oldValue);
}
backward.put(value, key);
return forward.put(key, value);
} } | public class class_name {
public V put(K key, V value) {
//remove possible existing with same value
if (backward.containsKey(value)) {
K oldKey = backward.get(value);
forward.remove(oldKey); // depends on control dependency: [if], data = [none]
}
if (forward.containsKey(key)) {
V oldValue = forward.get(key);
backward.remove(oldValue); // depends on control dependency: [if], data = [none]
}
backward.put(value, key);
return forward.put(key, value);
} } |
public class class_name {
public void transferStart(QueueListener eventsToTransfer)
{
while (!eventsToTransfer.isEmpty()) {
Event event = eventsToTransfer.removeLast();
this.previousEvents.offerFirst(event);
}
} } | public class class_name {
public void transferStart(QueueListener eventsToTransfer)
{
while (!eventsToTransfer.isEmpty()) {
Event event = eventsToTransfer.removeLast();
this.previousEvents.offerFirst(event); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
private boolean iterateExtended(ValueIterator.Element result,
int limit)
{
while (m_current_ < limit) {
String name = m_name_.getExtendedOr10Name(m_current_);
if (name != null && name.length() > 0) {
result.integer = m_current_;
result.value = name;
return false;
}
++ m_current_;
}
return true;
} } | public class class_name {
private boolean iterateExtended(ValueIterator.Element result,
int limit)
{
while (m_current_ < limit) {
String name = m_name_.getExtendedOr10Name(m_current_);
if (name != null && name.length() > 0) {
result.integer = m_current_; // depends on control dependency: [if], data = [none]
result.value = name; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
++ m_current_; // depends on control dependency: [while], data = [none]
}
return true;
} } |
public class class_name {
public <X extends Exception> void replaceAll(Try.BiFunction<? super K, ? super V, ? extends V, X> function) throws X {
List<K> keyToRemove = null;
V newVal = null;
for (Map.Entry<K, V> entry : valueMap.entrySet()) {
newVal = function.apply(entry.getKey(), entry.getValue());
if (N.isNullOrEmpty(newVal)) {
if (keyToRemove == null) {
keyToRemove = new ArrayList<>();
}
keyToRemove.add(entry.getKey());
} else {
try {
entry.setValue(newVal);
} catch (IllegalStateException ise) {
throw new ConcurrentModificationException(ise);
}
}
}
if (N.notNullOrEmpty(keyToRemove)) {
for (K key : keyToRemove) {
valueMap.remove(key);
}
}
} } | public class class_name {
public <X extends Exception> void replaceAll(Try.BiFunction<? super K, ? super V, ? extends V, X> function) throws X {
List<K> keyToRemove = null;
V newVal = null;
for (Map.Entry<K, V> entry : valueMap.entrySet()) {
newVal = function.apply(entry.getKey(), entry.getValue());
if (N.isNullOrEmpty(newVal)) {
if (keyToRemove == null) {
keyToRemove = new ArrayList<>();
// depends on control dependency: [if], data = [none]
}
keyToRemove.add(entry.getKey());
} else {
try {
entry.setValue(newVal);
// depends on control dependency: [try], data = [none]
} catch (IllegalStateException ise) {
throw new ConcurrentModificationException(ise);
}
// depends on control dependency: [catch], data = [none]
}
}
if (N.notNullOrEmpty(keyToRemove)) {
for (K key : keyToRemove) {
valueMap.remove(key);
}
}
} } |
public class class_name {
public static List<IFileCompareResultBean> findEqualFiles(final File source, final File compare)
{
final List<File> allSourceFiles = FileSearchExtensions.findFilesRecursive(source, "*");
final List<File> allCompareFiles = FileSearchExtensions.findFilesRecursive(compare, "*");
final List<IFileCompareResultBean> equalFiles = new ArrayList<IFileCompareResultBean>();
for (int i = 0; i < allSourceFiles.size(); i++)
{
final File toCompare = allSourceFiles.get(i);
for (int j = 0; j < allCompareFiles.size(); j++)
{
final File file = allCompareFiles.get(j);
if (toCompare.equals(file))
{
continue;
}
final IFileCompareResultBean compareResultBean = CompareFileExtensions
.simpleCompareFiles(toCompare, file);
final boolean equal = CompareFileExtensions.validateEquality(compareResultBean);
// if equal is true and the list does not contain the same
// compareResultBean then add it.
if (equal && !equalFiles.contains(compareResultBean))
{
equalFiles.add(compareResultBean);
}
}
}
return equalFiles;
} } | public class class_name {
public static List<IFileCompareResultBean> findEqualFiles(final File source, final File compare)
{
final List<File> allSourceFiles = FileSearchExtensions.findFilesRecursive(source, "*");
final List<File> allCompareFiles = FileSearchExtensions.findFilesRecursive(compare, "*");
final List<IFileCompareResultBean> equalFiles = new ArrayList<IFileCompareResultBean>();
for (int i = 0; i < allSourceFiles.size(); i++)
{
final File toCompare = allSourceFiles.get(i);
for (int j = 0; j < allCompareFiles.size(); j++)
{
final File file = allCompareFiles.get(j);
if (toCompare.equals(file))
{
continue;
}
final IFileCompareResultBean compareResultBean = CompareFileExtensions
.simpleCompareFiles(toCompare, file);
final boolean equal = CompareFileExtensions.validateEquality(compareResultBean);
// if equal is true and the list does not contain the same
// compareResultBean then add it.
if (equal && !equalFiles.contains(compareResultBean))
{
equalFiles.add(compareResultBean); // depends on control dependency: [if], data = [none]
}
}
}
return equalFiles;
} } |
public class class_name {
public static SequenceQuality create(QualityFormat format, byte[] data, int from, int length, boolean check) {
if (from + length >= data.length || from < 0 || length < 0)
throw new IllegalArgumentException();
//For performance
final byte valueOffset = format.getOffset(),
minValue = format.getMinValue(),
maxValue = format.getMaxValue();
byte[] res = new byte[length];
int pointer = from;
for (int i = 0; i < length; i++) {
res[i] = (byte) (data[pointer++] - valueOffset);
if (check &&
(res[i] < minValue || res[i] > maxValue))
throw new WrongQualityFormat(((char) (data[i])) + " [" + res[i] + "]");
}
return new SequenceQuality(res, true);
} } | public class class_name {
public static SequenceQuality create(QualityFormat format, byte[] data, int from, int length, boolean check) {
if (from + length >= data.length || from < 0 || length < 0)
throw new IllegalArgumentException();
//For performance
final byte valueOffset = format.getOffset(),
minValue = format.getMinValue(),
maxValue = format.getMaxValue();
byte[] res = new byte[length];
int pointer = from;
for (int i = 0; i < length; i++) {
res[i] = (byte) (data[pointer++] - valueOffset); // depends on control dependency: [for], data = [i]
if (check &&
(res[i] < minValue || res[i] > maxValue))
throw new WrongQualityFormat(((char) (data[i])) + " [" + res[i] + "]");
}
return new SequenceQuality(res, true);
} } |
public class class_name {
public static String stream2compStreamName(String old) {
String[] parts = old.split(DELIM);
if (parts.length >= 7) {
parts[0] = MetaType.COMPONENT_STREAM.getV() + parts[0].charAt(1);
//parts[parts.length - 3] = EMPTY; retain stream name
parts[parts.length - 4] = "0"; // task
parts[parts.length - 1] = getMergeMetricName(parts[parts.length - 1]);
}
return concat(parts);
} } | public class class_name {
public static String stream2compStreamName(String old) {
String[] parts = old.split(DELIM);
if (parts.length >= 7) {
parts[0] = MetaType.COMPONENT_STREAM.getV() + parts[0].charAt(1); // depends on control dependency: [if], data = [none]
//parts[parts.length - 3] = EMPTY; retain stream name
parts[parts.length - 4] = "0"; // task // depends on control dependency: [if], data = [none]
parts[parts.length - 1] = getMergeMetricName(parts[parts.length - 1]); // depends on control dependency: [if], data = [none]
}
return concat(parts);
} } |
public class class_name {
protected String createIssueMessage(Issue issue) {
final IssueMessageFormatter formatter = getIssueMessageFormatter();
final org.eclipse.emf.common.util.URI uriToProblem = issue.getUriToProblem();
if (formatter != null) {
final String message = formatter.format(issue, uriToProblem);
if (message != null) {
return message;
}
}
if (uriToProblem != null) {
final org.eclipse.emf.common.util.URI resourceUri = uriToProblem.trimFragment();
return MessageFormat.format(Messages.SarlBatchCompiler_4,
issue.getSeverity(), resourceUri.lastSegment(),
resourceUri.isFile() ? resourceUri.toFileString() : "", //$NON-NLS-1$
issue.getLineNumber(), issue.getColumn(), issue.getCode(), issue.getMessage());
}
return MessageFormat.format(Messages.SarlBatchCompiler_5,
issue.getSeverity(), issue.getLineNumber(), issue.getColumn(), issue.getCode(), issue.getMessage());
} } | public class class_name {
protected String createIssueMessage(Issue issue) {
final IssueMessageFormatter formatter = getIssueMessageFormatter();
final org.eclipse.emf.common.util.URI uriToProblem = issue.getUriToProblem();
if (formatter != null) {
final String message = formatter.format(issue, uriToProblem);
if (message != null) {
return message; // depends on control dependency: [if], data = [none]
}
}
if (uriToProblem != null) {
final org.eclipse.emf.common.util.URI resourceUri = uriToProblem.trimFragment();
return MessageFormat.format(Messages.SarlBatchCompiler_4,
issue.getSeverity(), resourceUri.lastSegment(),
resourceUri.isFile() ? resourceUri.toFileString() : "", //$NON-NLS-1$
issue.getLineNumber(), issue.getColumn(), issue.getCode(), issue.getMessage()); // depends on control dependency: [if], data = [none]
}
return MessageFormat.format(Messages.SarlBatchCompiler_5,
issue.getSeverity(), issue.getLineNumber(), issue.getColumn(), issue.getCode(), issue.getMessage());
} } |
public class class_name {
public LeafNode<K, V> nextNode() {
if (rightid == NULL_ID) {
return null;
}
return (LeafNode<K, V>) tree.getNode(rightid);
} } | public class class_name {
public LeafNode<K, V> nextNode() {
if (rightid == NULL_ID) {
return null; // depends on control dependency: [if], data = [none]
}
return (LeafNode<K, V>) tree.getNode(rightid);
} } |
public class class_name {
public static RealVector parseRecord(Record r, Map<Object, Integer> featureIdsReference) {
if(featureIdsReference.isEmpty()) {
throw new IllegalArgumentException("The featureIdsReference map should not be empty.");
}
int d = featureIdsReference.size();
//create an Map-backed vector only if we have available info about configuration.
RealVector v = (storageEngine != null)?new MapRealVector(d):new OpenMapRealVector(d);
boolean addConstantColumn = featureIdsReference.containsKey(Dataframe.COLUMN_NAME_CONSTANT);
if(addConstantColumn) {
v.setEntry(0, 1.0); //add the constant column
}
for(Map.Entry<Object, Object> entry : r.getX().entrySet()) {
Object feature = entry.getKey();
Double value = TypeInference.toDouble(entry.getValue());
if(value!=null) {
Integer featureId = featureIdsReference.get(feature);
if(featureId!=null) {//if the feature exists
v.setEntry(featureId, value);
}
}
else {
//else the X matrix maintains the 0.0 default value
}
}
return v;
} } | public class class_name {
public static RealVector parseRecord(Record r, Map<Object, Integer> featureIdsReference) {
if(featureIdsReference.isEmpty()) {
throw new IllegalArgumentException("The featureIdsReference map should not be empty.");
}
int d = featureIdsReference.size();
//create an Map-backed vector only if we have available info about configuration.
RealVector v = (storageEngine != null)?new MapRealVector(d):new OpenMapRealVector(d);
boolean addConstantColumn = featureIdsReference.containsKey(Dataframe.COLUMN_NAME_CONSTANT);
if(addConstantColumn) {
v.setEntry(0, 1.0); //add the constant column // depends on control dependency: [if], data = [none]
}
for(Map.Entry<Object, Object> entry : r.getX().entrySet()) {
Object feature = entry.getKey();
Double value = TypeInference.toDouble(entry.getValue());
if(value!=null) {
Integer featureId = featureIdsReference.get(feature);
if(featureId!=null) {//if the feature exists
v.setEntry(featureId, value); // depends on control dependency: [if], data = [(featureId]
}
}
else {
//else the X matrix maintains the 0.0 default value
}
}
return v;
} } |
public class class_name {
public void resetCompleters() {
final ConsoleReader reader = getReader();
if (reader != null) {
Collection<Completer> completers = reader.getCompleters();
for (Completer completer : completers) {
reader.removeCompleter(completer);
}
// for some unknown reason / bug in JLine you have to iterate over twice to clear the completers (WTF)
completers = reader.getCompleters();
for (Completer completer : completers) {
reader.removeCompleter(completer);
}
}
} } | public class class_name {
public void resetCompleters() {
final ConsoleReader reader = getReader();
if (reader != null) {
Collection<Completer> completers = reader.getCompleters();
for (Completer completer : completers) {
reader.removeCompleter(completer); // depends on control dependency: [for], data = [completer]
}
// for some unknown reason / bug in JLine you have to iterate over twice to clear the completers (WTF)
completers = reader.getCompleters(); // depends on control dependency: [if], data = [none]
for (Completer completer : completers) {
reader.removeCompleter(completer); // depends on control dependency: [for], data = [completer]
}
}
} } |
public class class_name {
public Object use(GroovyObject object, Closure closure) {
// grab existing meta (usually adaptee but we may have nested use calls)
MetaClass origMetaClass = object.getMetaClass();
object.setMetaClass(this);
try {
return closure.call();
} finally {
object.setMetaClass(origMetaClass);
}
} } | public class class_name {
public Object use(GroovyObject object, Closure closure) {
// grab existing meta (usually adaptee but we may have nested use calls)
MetaClass origMetaClass = object.getMetaClass();
object.setMetaClass(this);
try {
return closure.call(); // depends on control dependency: [try], data = [none]
} finally {
object.setMetaClass(origMetaClass);
}
} } |
public class class_name {
@Override
public void claimWork() throws InterruptedException
{
synchronized (cluster.allWorkUnits) {
for (String workUnit : getUnclaimed()) {
if (isPeggedToMe(workUnit)) {
claimWorkPeggedToMe(workUnit);
}
}
final double evenD= evenDistribution();
LinkedList<String> unclaimed = new LinkedList<String>(getUnclaimed());
while (myLoad() <= evenD && !unclaimed.isEmpty()) {
final String workUnit = unclaimed.poll();
if (config.useSoftHandoff && cluster.containsHandoffRequest(workUnit)
&& isFairGame(workUnit) && attemptToClaim(workUnit, true)) {
LOG.info(workUnit);
handoffListener.finishHandoff(workUnit);
} else if (isFairGame(workUnit)) {
attemptToClaim(workUnit);
}
}
}
} } | public class class_name {
@Override
public void claimWork() throws InterruptedException
{
synchronized (cluster.allWorkUnits) {
for (String workUnit : getUnclaimed()) {
if (isPeggedToMe(workUnit)) {
claimWorkPeggedToMe(workUnit); // depends on control dependency: [if], data = [none]
}
}
final double evenD= evenDistribution();
LinkedList<String> unclaimed = new LinkedList<String>(getUnclaimed());
while (myLoad() <= evenD && !unclaimed.isEmpty()) {
final String workUnit = unclaimed.poll();
if (config.useSoftHandoff && cluster.containsHandoffRequest(workUnit)
&& isFairGame(workUnit) && attemptToClaim(workUnit, true)) {
LOG.info(workUnit); // depends on control dependency: [if], data = [none]
handoffListener.finishHandoff(workUnit); // depends on control dependency: [if], data = [none]
} else if (isFairGame(workUnit)) {
attemptToClaim(workUnit); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public static double min(double... nums) {
double min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > min) {
min = nums[i];
}
}
return min;
} } | public class class_name {
public static double min(double... nums) {
double min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > min) {
min = nums[i]; // depends on control dependency: [if], data = [none]
}
}
return min;
} } |
public class class_name {
public void updateExecutionState(final ExecutionState executionState) {
final Iterator<ExecutionVertex> it = this.vertices.iterator();
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
vertex.updateExecutionState(executionState);
}
} } | public class class_name {
public void updateExecutionState(final ExecutionState executionState) {
final Iterator<ExecutionVertex> it = this.vertices.iterator();
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
vertex.updateExecutionState(executionState); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
protected static double[] average(double[] base, double[] target)
{
int dataNum = base.length;
double[] average = new double[dataNum];
for (int index = 0; index < dataNum; index++)
{
average[index] = (base[index] + target[index]) / 2.0;
}
return average;
} } | public class class_name {
protected static double[] average(double[] base, double[] target)
{
int dataNum = base.length;
double[] average = new double[dataNum];
for (int index = 0; index < dataNum; index++)
{
average[index] = (base[index] + target[index]) / 2.0; // depends on control dependency: [for], data = [index]
}
return average;
} } |
public class class_name {
public static LineSymbolizer lineSymbolizerFromRule( Rule rule ) {
List<Symbolizer> symbolizers = rule.symbolizers();
LineSymbolizer lineSymbolizer = null;
for( Symbolizer symbolizer : symbolizers ) {
if (symbolizer instanceof LineSymbolizer) {
lineSymbolizer = (LineSymbolizer) symbolizer;
break;
}
}
if (lineSymbolizer == null) {
throw new IllegalArgumentException();
}
return lineSymbolizer;
} } | public class class_name {
public static LineSymbolizer lineSymbolizerFromRule( Rule rule ) {
List<Symbolizer> symbolizers = rule.symbolizers();
LineSymbolizer lineSymbolizer = null;
for( Symbolizer symbolizer : symbolizers ) {
if (symbolizer instanceof LineSymbolizer) {
lineSymbolizer = (LineSymbolizer) symbolizer; // depends on control dependency: [if], data = [none]
break;
}
}
if (lineSymbolizer == null) {
throw new IllegalArgumentException();
}
return lineSymbolizer;
} } |
public class class_name {
public final void addLeftWing(final String pLeftWing, final StringBuffer pSb,
final String pDigGrSep, final Integer pDigitsInGroup) {
for (int i = 0; i < pLeftWing.length(); i++) {
char ch = pLeftWing.charAt(i);
pSb.append(ch);
int idxFl = pLeftWing.length() - i;
if (pDigitsInGroup == 2) {
//hard-coded Indian style 12,12,14,334
if (idxFl == 4) {
pSb.append(pDigGrSep);
} else {
idxFl -= 3;
}
}
if (idxFl >= pDigitsInGroup) {
int gc = idxFl / pDigitsInGroup;
if (gc > 0) {
int rem;
if (gc == 1) {
rem = idxFl % pDigitsInGroup;
} else {
rem = idxFl % (pDigitsInGroup * gc);
}
if (rem == 1) {
pSb.append(pDigGrSep);
}
}
}
}
} } | public class class_name {
public final void addLeftWing(final String pLeftWing, final StringBuffer pSb,
final String pDigGrSep, final Integer pDigitsInGroup) {
for (int i = 0; i < pLeftWing.length(); i++) {
char ch = pLeftWing.charAt(i);
pSb.append(ch); // depends on control dependency: [for], data = [none]
int idxFl = pLeftWing.length() - i;
if (pDigitsInGroup == 2) {
//hard-coded Indian style 12,12,14,334
if (idxFl == 4) {
pSb.append(pDigGrSep); // depends on control dependency: [if], data = [none]
} else {
idxFl -= 3; // depends on control dependency: [if], data = [none]
}
}
if (idxFl >= pDigitsInGroup) {
int gc = idxFl / pDigitsInGroup;
if (gc > 0) {
int rem;
if (gc == 1) {
rem = idxFl % pDigitsInGroup; // depends on control dependency: [if], data = [none]
} else {
rem = idxFl % (pDigitsInGroup * gc); // depends on control dependency: [if], data = [none]
}
if (rem == 1) {
pSb.append(pDigGrSep); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
protected void updateFieldValidationStatus(I_CmsFormField field, CmsValidationResult result) {
if (result.hasNewValue()) {
if (field.getModel() != null) {
field.getModel().setValue(result.getNewValue(), true);
}
field.getWidget().setFormValueAsString(result.getNewValue());
}
String errorMessage = result.getErrorMessage();
field.getWidget().setErrorMessage(result.getErrorMessage());
field.setValidationStatus(
errorMessage == null ? I_CmsFormField.ValidationStatus.valid : I_CmsFormField.ValidationStatus.invalid);
} } | public class class_name {
protected void updateFieldValidationStatus(I_CmsFormField field, CmsValidationResult result) {
if (result.hasNewValue()) {
if (field.getModel() != null) {
field.getModel().setValue(result.getNewValue(), true); // depends on control dependency: [if], data = [none]
}
field.getWidget().setFormValueAsString(result.getNewValue()); // depends on control dependency: [if], data = [none]
}
String errorMessage = result.getErrorMessage();
field.getWidget().setErrorMessage(result.getErrorMessage());
field.setValidationStatus(
errorMessage == null ? I_CmsFormField.ValidationStatus.valid : I_CmsFormField.ValidationStatus.invalid);
} } |
public class class_name {
public void setMinFrame(final String markerName) {
if (composition == null) {
lazyCompositionTasks.add(new LazyCompositionTask() {
@Override
public void run(LottieComposition composition) {
setMinFrame(markerName);
}
});
return;
}
Marker marker = composition.getMarker(markerName);
if (marker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + markerName + ".");
}
setMinFrame((int) marker.startFrame);
} } | public class class_name {
public void setMinFrame(final String markerName) {
if (composition == null) {
lazyCompositionTasks.add(new LazyCompositionTask() {
@Override
public void run(LottieComposition composition) {
setMinFrame(markerName);
}
}); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Marker marker = composition.getMarker(markerName);
if (marker == null) {
throw new IllegalArgumentException("Cannot find marker with name " + markerName + ".");
}
setMinFrame((int) marker.startFrame);
} } |
public class class_name {
public static String tooltip(Field field) {
final String tooltip = field.getTooltip();
if (tooltip == null) {
return "";
}
return "<img class='tooltip' title='" + tooltip + "' alt='?' src='"
+ getContextPath() + "/templates/"
+ getTemplate() + "/img/tooltip.gif' />";
} } | public class class_name {
public static String tooltip(Field field) {
final String tooltip = field.getTooltip();
if (tooltip == null) {
return ""; // depends on control dependency: [if], data = [none]
}
return "<img class='tooltip' title='" + tooltip + "' alt='?' src='"
+ getContextPath() + "/templates/"
+ getTemplate() + "/img/tooltip.gif' />";
} } |
public class class_name {
protected boolean isValidCommandName(String name) {
if (Strings.isNullOrBlank(name) || ignoreCommands.contains(name)) {
return false;
}
for (String prefix : ignoreCommandPrefixes) {
if (name.startsWith(prefix)) {
return false;
}
}
return true;
} } | public class class_name {
protected boolean isValidCommandName(String name) {
if (Strings.isNullOrBlank(name) || ignoreCommands.contains(name)) {
return false; // depends on control dependency: [if], data = [none]
}
for (String prefix : ignoreCommandPrefixes) {
if (name.startsWith(prefix)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public java.lang.String getInstanceTag() {
java.lang.Object ref = instanceTag_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
instanceTag_ = s;
return s;
}
} } | public class class_name {
public java.lang.String getInstanceTag() {
java.lang.Object ref = instanceTag_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref; // depends on control dependency: [if], data = [none]
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
instanceTag_ = s; // depends on control dependency: [if], data = [none]
return s; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Bbox getBounds(Geometry geometry) {
if (geometry == null) {
throw new IllegalArgumentException("Cannot get bounds for null geometry.");
}
if (isEmpty(geometry)) {
return null;
}
Bbox bbox = null;
if (geometry.getGeometries() != null) {
bbox = getBounds(geometry.getGeometries()[0]);
for (int i = 1; i < geometry.getGeometries().length; i++) {
bbox = BboxService.union(bbox, getBounds(geometry.getGeometries()[i]));
}
}
if (geometry.getCoordinates() != null) {
double minX = Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
double maxX = -Double.MAX_VALUE;
double maxY = -Double.MAX_VALUE;
for (Coordinate coordinate : geometry.getCoordinates()) {
if (coordinate.getX() < minX) {
minX = coordinate.getX();
}
if (coordinate.getY() < minY) {
minY = coordinate.getY();
}
if (coordinate.getX() > maxX) {
maxX = coordinate.getX();
}
if (coordinate.getY() > maxY) {
maxY = coordinate.getY();
}
}
if (bbox == null) {
bbox = new Bbox(minX, minY, maxX - minX, maxY - minY);
} else {
bbox = BboxService.union(bbox, new Bbox(minX, minY, maxX - minX, maxY - minY));
}
}
return bbox;
} } | public class class_name {
public static Bbox getBounds(Geometry geometry) {
if (geometry == null) {
throw new IllegalArgumentException("Cannot get bounds for null geometry.");
}
if (isEmpty(geometry)) {
return null; // depends on control dependency: [if], data = [none]
}
Bbox bbox = null;
if (geometry.getGeometries() != null) {
bbox = getBounds(geometry.getGeometries()[0]); // depends on control dependency: [if], data = [(geometry.getGeometries()]
for (int i = 1; i < geometry.getGeometries().length; i++) {
bbox = BboxService.union(bbox, getBounds(geometry.getGeometries()[i])); // depends on control dependency: [for], data = [i]
}
}
if (geometry.getCoordinates() != null) {
double minX = Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
double maxX = -Double.MAX_VALUE;
double maxY = -Double.MAX_VALUE;
for (Coordinate coordinate : geometry.getCoordinates()) {
if (coordinate.getX() < minX) {
minX = coordinate.getX(); // depends on control dependency: [if], data = [none]
}
if (coordinate.getY() < minY) {
minY = coordinate.getY(); // depends on control dependency: [if], data = [none]
}
if (coordinate.getX() > maxX) {
maxX = coordinate.getX(); // depends on control dependency: [if], data = [none]
}
if (coordinate.getY() > maxY) {
maxY = coordinate.getY(); // depends on control dependency: [if], data = [none]
}
}
if (bbox == null) {
bbox = new Bbox(minX, minY, maxX - minX, maxY - minY); // depends on control dependency: [if], data = [none]
} else {
bbox = BboxService.union(bbox, new Bbox(minX, minY, maxX - minX, maxY - minY)); // depends on control dependency: [if], data = [(bbox]
}
}
return bbox;
} } |
public class class_name {
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
} } | public class class_name {
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND; // depends on control dependency: [if], data = [none]
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
} } |
public class class_name {
private static void printAsXML(Rule rule, StringBuilder xmlStringBuilder) {
if (rule.version != null) {
xmlStringBuilder.append(" <!-- since " + rule.version + " -->");
xmlStringBuilder.append(LINE_SEPARATOR);
}
xmlStringBuilder.append(" <rule>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <key>" + rule.fixedRuleKey() + "</key>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <severity>" + rule.severity + "</severity>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <name><![CDATA[" + rule.name + "]]></name>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <internalKey><![CDATA[" + rule.internalKey + "]]></internalKey>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <description><![CDATA[" + rule.description + "]]></description>");
xmlStringBuilder.append(LINE_SEPARATOR);
if (!rule.tags.isEmpty()) {
for (String tag : rule.tags) {
xmlStringBuilder.append(" <tag>" + tag + "</tag>");
xmlStringBuilder.append(LINE_SEPARATOR);
}
}
if (!rule.parameters.isEmpty()) {
List<RuleParameter> sortedParameters = Lists.newArrayList(rule.parameters);
Collections.sort(sortedParameters, new Comparator<RuleParameter>() {
@Override
public int compare(RuleParameter o1, RuleParameter o2) {
return o1.key.compareTo(o2.key);
}
});
for (RuleParameter parameter : sortedParameters) {
xmlStringBuilder.append(" <param>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <key>" + parameter.key + "</key>");
xmlStringBuilder.append(LINE_SEPARATOR);
if (StringUtils.isNotBlank(parameter.description)) {
xmlStringBuilder.append(" <description><![CDATA[" + parameter.description + "]]></description>");
xmlStringBuilder.append(LINE_SEPARATOR);
}
if (StringUtils.isNotBlank(parameter.defaultValue) && !"null".equals(parameter.defaultValue)) {
xmlStringBuilder.append(" <defaultValue>" + parameter.defaultValue + "</defaultValue>");
xmlStringBuilder.append(LINE_SEPARATOR);
}
xmlStringBuilder.append(" </param>");
xmlStringBuilder.append(LINE_SEPARATOR);
}
}
xmlStringBuilder.append(" </rule>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(LINE_SEPARATOR);
} } | public class class_name {
private static void printAsXML(Rule rule, StringBuilder xmlStringBuilder) {
if (rule.version != null) {
xmlStringBuilder.append(" <!-- since " + rule.version + " -->");
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
}
xmlStringBuilder.append(" <rule>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <key>" + rule.fixedRuleKey() + "</key>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <severity>" + rule.severity + "</severity>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <name><![CDATA[" + rule.name + "]]></name>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <internalKey><![CDATA[" + rule.internalKey + "]]></internalKey>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(" <description><![CDATA[" + rule.description + "]]></description>");
xmlStringBuilder.append(LINE_SEPARATOR);
if (!rule.tags.isEmpty()) {
for (String tag : rule.tags) {
xmlStringBuilder.append(" <tag>" + tag + "</tag>"); // depends on control dependency: [for], data = [tag]
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [for], data = [none]
}
}
if (!rule.parameters.isEmpty()) {
List<RuleParameter> sortedParameters = Lists.newArrayList(rule.parameters);
Collections.sort(sortedParameters, new Comparator<RuleParameter>() {
@Override
public int compare(RuleParameter o1, RuleParameter o2) {
return o1.key.compareTo(o2.key);
}
}); // depends on control dependency: [if], data = [none]
for (RuleParameter parameter : sortedParameters) {
xmlStringBuilder.append(" <param>"); // depends on control dependency: [for], data = [none]
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [for], data = [none]
xmlStringBuilder.append(" <key>" + parameter.key + "</key>");
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [for], data = [none]
if (StringUtils.isNotBlank(parameter.description)) {
xmlStringBuilder.append(" <description><![CDATA[" + parameter.description + "]]></description>"); // depends on control dependency: [if], data = [none]
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isNotBlank(parameter.defaultValue) && !"null".equals(parameter.defaultValue)) {
xmlStringBuilder.append(" <defaultValue>" + parameter.defaultValue + "</defaultValue>"); // depends on control dependency: [if], data = [none]
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
}
xmlStringBuilder.append(" </param>");
xmlStringBuilder.append(LINE_SEPARATOR); // depends on control dependency: [for], data = [none]
}
}
xmlStringBuilder.append(" </rule>");
xmlStringBuilder.append(LINE_SEPARATOR);
xmlStringBuilder.append(LINE_SEPARATOR);
} } |
public class class_name {
public Form getAncestor(
Form formToGetAncestorForParam,
boolean includeFieldDataParam,
boolean includeTableFieldsParam
) {
if(DISABLE_WS) {
this.mode = Mode.RESTfulActive;
}
//ANCESTOR...
try {
//When mode is null or [WebSocketActive]...
if(this.getAncestorClient == null &&
Mode.RESTfulActive != this.mode) {
this.getAncestorClient = new SQLUtilWebSocketGetAncestorClient(
this.baseURL,
null,
this.loggedInUser.getServiceTicketAsHexUpper(),
this.timeoutMillis,
includeFieldDataParam,
includeTableFieldsParam,
COMPRESS_RSP,
COMPRESS_RSP_CHARSET);
this.mode = Mode.WebSocketActive;
}
} catch (FluidClientException clientExcept) {
if(clientExcept.getErrorCode() !=
FluidClientException.ErrorCode.WEB_SOCKET_DEPLOY_ERROR) {
throw clientExcept;
}
this.mode = Mode.RESTfulActive;
}
Form formToUse = (formToGetAncestorForParam == null) ? null:
new Form(formToGetAncestorForParam.getId());
return (this.getAncestorClient == null) ?
this.sqlUtilClient.getAncestor(
formToUse,
includeFieldDataParam,
includeTableFieldsParam):
this.getAncestorClient.getAncestorSynchronized(formToUse);
} } | public class class_name {
public Form getAncestor(
Form formToGetAncestorForParam,
boolean includeFieldDataParam,
boolean includeTableFieldsParam
) {
if(DISABLE_WS) {
this.mode = Mode.RESTfulActive; // depends on control dependency: [if], data = [none]
}
//ANCESTOR...
try {
//When mode is null or [WebSocketActive]...
if(this.getAncestorClient == null &&
Mode.RESTfulActive != this.mode) {
this.getAncestorClient = new SQLUtilWebSocketGetAncestorClient(
this.baseURL,
null,
this.loggedInUser.getServiceTicketAsHexUpper(),
this.timeoutMillis,
includeFieldDataParam,
includeTableFieldsParam,
COMPRESS_RSP,
COMPRESS_RSP_CHARSET); // depends on control dependency: [if], data = [none]
this.mode = Mode.WebSocketActive; // depends on control dependency: [if], data = [none]
}
} catch (FluidClientException clientExcept) {
if(clientExcept.getErrorCode() !=
FluidClientException.ErrorCode.WEB_SOCKET_DEPLOY_ERROR) {
throw clientExcept;
}
this.mode = Mode.RESTfulActive;
} // depends on control dependency: [catch], data = [none]
Form formToUse = (formToGetAncestorForParam == null) ? null:
new Form(formToGetAncestorForParam.getId());
return (this.getAncestorClient == null) ?
this.sqlUtilClient.getAncestor(
formToUse,
includeFieldDataParam,
includeTableFieldsParam):
this.getAncestorClient.getAncestorSynchronized(formToUse);
} } |
public class class_name {
@Override
public List<VariableMatch> matchVariables(VariableNumMap inputVariables) {
// All of the fixed variables must be matched in order to return anything.
if (!inputVariables.containsAll(fixedVariables)) {
return Collections.emptyList();
}
// Special case: if there aren't any templates, then only the fixed
// variables should be returned.
if (plateStarts.length == 0) {
return Arrays.asList(VariableMatch.identity(fixedVariables));
}
int maxPlateReplication = -1;
int[] inputVarNums = inputVariables.getVariableNumsArray();
int numVars = inputVarNums.length;
int numMatchers = plateStarts.length;
for (int i = 0; i < numMatchers; i++) {
for (int j = 0; j < numVars; j++) {
if (inputVarNums[j] >= plateStarts[i] && inputVarNums[j] < plateEnds[i]) {
int withinPlateIndex = inputVarNums[j] - plateStarts[i];
int plateReplicationNum = withinPlateIndex / plateReplicationSizes[i];
int replicationIndex = plateReplicationNum - plateMatchIndexOffsets[i];
maxPlateReplication = Math.max(replicationIndex, maxPlateReplication);
}
}
}
// Aggregate pattern matches for each variable.
int[] templateVarNums = templateVariables.getVariableNumsArray();
int[][] variableMatches = new int[maxPlateReplication + 1][];
for (int i = 0; i < numMatchers; i++) {
for (int j = 0; j < numVars; j++) {
if (inputVarNums[j] >= plateStarts[i] && inputVarNums[j] < plateEnds[i]) {
// The variable is within the plate we're matching.
int withinPlateIndex = inputVarNums[j] - plateStarts[i];
int plateReplicationNum = withinPlateIndex / plateReplicationSizes[i];
int varOffset = withinPlateIndex % plateReplicationSizes[i];
if (varOffset == plateVarOffsets[i]) {
// The variable matches the pattern.
int replicationIndex = plateReplicationNum - plateMatchIndexOffsets[i];
if (variableMatches[replicationIndex] == null) {
variableMatches[replicationIndex] = new int[templateVarNums.length];
Arrays.fill(variableMatches[replicationIndex], -1);
}
variableMatches[replicationIndex][i] = inputVarNums[j];
}
}
}
}
// Eliminate any partial matches which do not contain a match for every
// variable prefix.
List<VariableMatch> validMatches = Lists.newArrayList();
int numMatches = variableMatches.length;
for (int i = 0; i < numMatches; i++) {
int[] matchBuilder = variableMatches[i];
if (matchBuilder != null && Ints.indexOf(matchBuilder, -1) == -1) {
VariableNumMap matchedVariables = inputVariables.intersection(matchBuilder);
VariableRelabeling fixedVariableRelabeling = VariableRelabeling.identity(fixedVariables);
int[] templateCopy = Arrays.copyOf(templateVarNums, templateVarNums.length);
IntBiMap mapping = IntBiMap.fromUnsortedKeyValues(matchBuilder, templateCopy);
VariableRelabeling matchedRelabeling = new VariableRelabeling(matchedVariables,
templateVariables, mapping);
VariableMatch match = new VariableMatch(matchedVariables.union(fixedVariables),
templateVariables.union(fixedVariables), fixedVariableRelabeling.union(matchedRelabeling));
validMatches.add(match);
}
}
return validMatches;
} } | public class class_name {
@Override
public List<VariableMatch> matchVariables(VariableNumMap inputVariables) {
// All of the fixed variables must be matched in order to return anything.
if (!inputVariables.containsAll(fixedVariables)) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
// Special case: if there aren't any templates, then only the fixed
// variables should be returned.
if (plateStarts.length == 0) {
return Arrays.asList(VariableMatch.identity(fixedVariables)); // depends on control dependency: [if], data = [none]
}
int maxPlateReplication = -1;
int[] inputVarNums = inputVariables.getVariableNumsArray();
int numVars = inputVarNums.length;
int numMatchers = plateStarts.length;
for (int i = 0; i < numMatchers; i++) {
for (int j = 0; j < numVars; j++) {
if (inputVarNums[j] >= plateStarts[i] && inputVarNums[j] < plateEnds[i]) {
int withinPlateIndex = inputVarNums[j] - plateStarts[i];
int plateReplicationNum = withinPlateIndex / plateReplicationSizes[i];
int replicationIndex = plateReplicationNum - plateMatchIndexOffsets[i];
maxPlateReplication = Math.max(replicationIndex, maxPlateReplication); // depends on control dependency: [if], data = [none]
}
}
}
// Aggregate pattern matches for each variable.
int[] templateVarNums = templateVariables.getVariableNumsArray();
int[][] variableMatches = new int[maxPlateReplication + 1][];
for (int i = 0; i < numMatchers; i++) {
for (int j = 0; j < numVars; j++) {
if (inputVarNums[j] >= plateStarts[i] && inputVarNums[j] < plateEnds[i]) {
// The variable is within the plate we're matching.
int withinPlateIndex = inputVarNums[j] - plateStarts[i];
int plateReplicationNum = withinPlateIndex / plateReplicationSizes[i];
int varOffset = withinPlateIndex % plateReplicationSizes[i];
if (varOffset == plateVarOffsets[i]) {
// The variable matches the pattern.
int replicationIndex = plateReplicationNum - plateMatchIndexOffsets[i];
if (variableMatches[replicationIndex] == null) {
variableMatches[replicationIndex] = new int[templateVarNums.length]; // depends on control dependency: [if], data = [none]
Arrays.fill(variableMatches[replicationIndex], -1); // depends on control dependency: [if], data = [(variableMatches[replicationIndex]]
}
variableMatches[replicationIndex][i] = inputVarNums[j]; // depends on control dependency: [if], data = [none]
}
}
}
}
// Eliminate any partial matches which do not contain a match for every
// variable prefix.
List<VariableMatch> validMatches = Lists.newArrayList();
int numMatches = variableMatches.length;
for (int i = 0; i < numMatches; i++) {
int[] matchBuilder = variableMatches[i];
if (matchBuilder != null && Ints.indexOf(matchBuilder, -1) == -1) {
VariableNumMap matchedVariables = inputVariables.intersection(matchBuilder);
VariableRelabeling fixedVariableRelabeling = VariableRelabeling.identity(fixedVariables);
int[] templateCopy = Arrays.copyOf(templateVarNums, templateVarNums.length);
IntBiMap mapping = IntBiMap.fromUnsortedKeyValues(matchBuilder, templateCopy);
VariableRelabeling matchedRelabeling = new VariableRelabeling(matchedVariables,
templateVariables, mapping);
VariableMatch match = new VariableMatch(matchedVariables.union(fixedVariables),
templateVariables.union(fixedVariables), fixedVariableRelabeling.union(matchedRelabeling));
validMatches.add(match); // depends on control dependency: [if], data = [none]
}
}
return validMatches;
} } |
public class class_name {
public void marshall(PredictRequest predictRequest, ProtocolMarshaller protocolMarshaller) {
if (predictRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(predictRequest.getMLModelId(), MLMODELID_BINDING);
protocolMarshaller.marshall(predictRequest.getRecord(), RECORD_BINDING);
protocolMarshaller.marshall(predictRequest.getPredictEndpoint(), PREDICTENDPOINT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(PredictRequest predictRequest, ProtocolMarshaller protocolMarshaller) {
if (predictRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(predictRequest.getMLModelId(), MLMODELID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(predictRequest.getRecord(), RECORD_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(predictRequest.getPredictEndpoint(), PREDICTENDPOINT_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 EventJournalConfig findMapEventJournalConfig(String name) {
name = getBaseName(name);
final EventJournalConfig config = lookupByPattern(configPatternMatcher, mapEventJournalConfigs, name);
if (config != null) {
return config.getAsReadOnly();
}
return getMapEventJournalConfig("default").getAsReadOnly();
} } | public class class_name {
public EventJournalConfig findMapEventJournalConfig(String name) {
name = getBaseName(name);
final EventJournalConfig config = lookupByPattern(configPatternMatcher, mapEventJournalConfigs, name);
if (config != null) {
return config.getAsReadOnly(); // depends on control dependency: [if], data = [none]
}
return getMapEventJournalConfig("default").getAsReadOnly();
} } |
public class class_name {
@Override
public String execute(EditXmlInputs inputs) throws Exception {
Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
NodeList nodeList = XmlUtils.readNode(doc, inputs.getXpath1(), XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath()));
Node childNode = null;
Node node;
if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
childNode = XmlUtils.stringToNode(inputs.getValue(), doc.getXmlEncoding(), inputs.getParsingFeatures());
}
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
childNode = doc.importNode(childNode, true);
node.setTextContent(Constants.Inputs.EMPTY_STRING);
node.appendChild(childNode);
} else if (Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
node.setTextContent(inputs.getValue());
} else if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
String attribute = ((Element) node).getAttribute(inputs.getName());
if ((attribute != null) && (!StringUtils.isEmpty(attribute))) {
((Element) node).setAttribute(inputs.getName(), inputs.getValue());
}
}
}
return DocumentUtils.documentToString(doc);
} } | public class class_name {
@Override
public String execute(EditXmlInputs inputs) throws Exception {
Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
NodeList nodeList = XmlUtils.readNode(doc, inputs.getXpath1(), XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath()));
Node childNode = null;
Node node;
if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
childNode = XmlUtils.stringToNode(inputs.getValue(), doc.getXmlEncoding(), inputs.getParsingFeatures());
}
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
childNode = doc.importNode(childNode, true);
node.setTextContent(Constants.Inputs.EMPTY_STRING);
node.appendChild(childNode);
} else if (Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
node.setTextContent(inputs.getValue());
} else if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
String attribute = ((Element) node).getAttribute(inputs.getName());
if ((attribute != null) && (!StringUtils.isEmpty(attribute))) {
((Element) node).setAttribute(inputs.getName(), inputs.getValue()); // depends on control dependency: [if], data = [none]
}
}
}
return DocumentUtils.documentToString(doc);
} } |
public class class_name {
public void setVTLDevices(java.util.Collection<VTLDevice> vTLDevices) {
if (vTLDevices == null) {
this.vTLDevices = null;
return;
}
this.vTLDevices = new com.amazonaws.internal.SdkInternalList<VTLDevice>(vTLDevices);
} } | public class class_name {
public void setVTLDevices(java.util.Collection<VTLDevice> vTLDevices) {
if (vTLDevices == null) {
this.vTLDevices = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.vTLDevices = new com.amazonaws.internal.SdkInternalList<VTLDevice>(vTLDevices);
} } |
public class class_name {
public Queue<SessionSchedulable> getScheduleQueue() {
if (scheduleQueue == null) {
scheduleQueue =
createSessionQueue(configManager.getPoolComparator(poolInfo));
}
return scheduleQueue;
} } | public class class_name {
public Queue<SessionSchedulable> getScheduleQueue() {
if (scheduleQueue == null) {
scheduleQueue =
createSessionQueue(configManager.getPoolComparator(poolInfo)); // depends on control dependency: [if], data = [none]
}
return scheduleQueue;
} } |
public class class_name {
private IndexTreePath<E> choosePath(AbstractMTree<?, N, E, ?> tree, E object, IndexTreePath<E> subtree) {
N node = tree.getNode(subtree.getEntry());
// leaf
if(node.isLeaf()) {
return subtree;
}
// Initialize from first:
int bestIdx = 0;
E bestEntry = node.getEntry(0);
double bestDistance = tree.distance(object.getRoutingObjectID(), bestEntry.getRoutingObjectID());
// Iterate over remaining
for(int i = 1; i < node.getNumEntries(); i++) {
E entry = node.getEntry(i);
double distance = tree.distance(object.getRoutingObjectID(), entry.getRoutingObjectID());
if(distance < bestDistance) {
bestIdx = i;
bestEntry = entry;
bestDistance = distance;
}
}
return choosePath(tree, object, new IndexTreePath<>(subtree, bestEntry, bestIdx));
} } | public class class_name {
private IndexTreePath<E> choosePath(AbstractMTree<?, N, E, ?> tree, E object, IndexTreePath<E> subtree) {
N node = tree.getNode(subtree.getEntry());
// leaf
if(node.isLeaf()) {
return subtree; // depends on control dependency: [if], data = [none]
}
// Initialize from first:
int bestIdx = 0;
E bestEntry = node.getEntry(0);
double bestDistance = tree.distance(object.getRoutingObjectID(), bestEntry.getRoutingObjectID());
// Iterate over remaining
for(int i = 1; i < node.getNumEntries(); i++) {
E entry = node.getEntry(i);
double distance = tree.distance(object.getRoutingObjectID(), entry.getRoutingObjectID());
if(distance < bestDistance) {
bestIdx = i; // depends on control dependency: [if], data = [none]
bestEntry = entry; // depends on control dependency: [if], data = [none]
bestDistance = distance; // depends on control dependency: [if], data = [none]
}
}
return choosePath(tree, object, new IndexTreePath<>(subtree, bestEntry, bestIdx));
} } |
public class class_name {
public int executeForChangedRowCount(String sql, Object[] bindArgs,
CancellationSignal cancellationSignal) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
int changedRows = 0;
final int cookie = mRecentOperations.beginOperation("executeForChangedRowCount",
sql, bindArgs);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
throwIfStatementForbidden(statement);
bindArguments(statement, bindArgs);
applyBlockGuardPolicy(statement);
attachCancellationSignal(cancellationSignal);
try {
changedRows = nativeExecuteForChangedRowCount(
mConnectionPtr, statement.mStatementPtr);
return changedRows;
} finally {
detachCancellationSignal(cancellationSignal);
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally {
if (mRecentOperations.endOperationDeferLog(cookie)) {
mRecentOperations.logOperation(cookie, "changedRows=" + changedRows);
}
}
} } | public class class_name {
public int executeForChangedRowCount(String sql, Object[] bindArgs,
CancellationSignal cancellationSignal) {
if (sql == null) {
throw new IllegalArgumentException("sql must not be null.");
}
int changedRows = 0;
final int cookie = mRecentOperations.beginOperation("executeForChangedRowCount",
sql, bindArgs);
try {
final PreparedStatement statement = acquirePreparedStatement(sql);
try {
throwIfStatementForbidden(statement); // depends on control dependency: [try], data = [none]
bindArguments(statement, bindArgs); // depends on control dependency: [try], data = [none]
applyBlockGuardPolicy(statement); // depends on control dependency: [try], data = [none]
attachCancellationSignal(cancellationSignal); // depends on control dependency: [try], data = [none]
try {
changedRows = nativeExecuteForChangedRowCount(
mConnectionPtr, statement.mStatementPtr); // depends on control dependency: [try], data = [none]
return changedRows; // depends on control dependency: [try], data = [none]
} finally {
detachCancellationSignal(cancellationSignal);
}
} finally {
releasePreparedStatement(statement);
}
} catch (RuntimeException ex) {
mRecentOperations.failOperation(cookie, ex);
throw ex;
} finally { // depends on control dependency: [catch], data = [none]
if (mRecentOperations.endOperationDeferLog(cookie)) {
mRecentOperations.logOperation(cookie, "changedRows=" + changedRows); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static CompareType getCompareType( String expression ) {
CompareType result = CompareType.EQ;
CharacterIterator iter = new StringCharacterIterator(expression);
final int fistIndex = 0;
final int lastIndex = expression.length() - 1;
boolean skipNext = false;
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
if (skipNext) {
skipNext = false;
continue;
}
if (c == '_') {
return CompareType.REGEXP;
}
if (c == '%') {
if (result != CompareType.EQ) {
// pattern like '%abcdfe%' -> only regexp can handle this;
return CompareType.REGEXP;
}
int index = iter.getIndex();
if (index == fistIndex) {
result = CompareType.ENDS_WITH;
} else if (index == lastIndex) {
result = CompareType.STARTS_WITH;
} else {
return CompareType.REGEXP;
}
}
if (c == '\\') skipNext = true;
}
return result;
} } | public class class_name {
private static CompareType getCompareType( String expression ) {
CompareType result = CompareType.EQ;
CharacterIterator iter = new StringCharacterIterator(expression);
final int fistIndex = 0;
final int lastIndex = expression.length() - 1;
boolean skipNext = false;
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
if (skipNext) {
skipNext = false; // depends on control dependency: [if], data = [none]
continue;
}
if (c == '_') {
return CompareType.REGEXP; // depends on control dependency: [if], data = [none]
}
if (c == '%') {
if (result != CompareType.EQ) {
// pattern like '%abcdfe%' -> only regexp can handle this;
return CompareType.REGEXP; // depends on control dependency: [if], data = [none]
}
int index = iter.getIndex();
if (index == fistIndex) {
result = CompareType.ENDS_WITH; // depends on control dependency: [if], data = [none]
} else if (index == lastIndex) {
result = CompareType.STARTS_WITH; // depends on control dependency: [if], data = [none]
} else {
return CompareType.REGEXP; // depends on control dependency: [if], data = [none]
}
}
if (c == '\\') skipNext = true;
}
return result;
} } |
public class class_name {
public EEnum getIfcProjectedOrTrueLengthEnum() {
if (ifcProjectedOrTrueLengthEnumEEnum == null) {
ifcProjectedOrTrueLengthEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(876);
}
return ifcProjectedOrTrueLengthEnumEEnum;
} } | public class class_name {
public EEnum getIfcProjectedOrTrueLengthEnum() {
if (ifcProjectedOrTrueLengthEnumEEnum == null) {
ifcProjectedOrTrueLengthEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(876);
// depends on control dependency: [if], data = [none]
}
return ifcProjectedOrTrueLengthEnumEEnum;
} } |
public class class_name {
public void setKeys(java.util.Collection<DimensionKeyDescription> keys) {
if (keys == null) {
this.keys = null;
return;
}
this.keys = new java.util.ArrayList<DimensionKeyDescription>(keys);
} } | public class class_name {
public void setKeys(java.util.Collection<DimensionKeyDescription> keys) {
if (keys == null) {
this.keys = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.keys = new java.util.ArrayList<DimensionKeyDescription>(keys);
} } |
public class class_name {
public void marshall(WorkspaceConnectionStatus workspaceConnectionStatus, ProtocolMarshaller protocolMarshaller) {
if (workspaceConnectionStatus == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(workspaceConnectionStatus.getWorkspaceId(), WORKSPACEID_BINDING);
protocolMarshaller.marshall(workspaceConnectionStatus.getConnectionState(), CONNECTIONSTATE_BINDING);
protocolMarshaller.marshall(workspaceConnectionStatus.getConnectionStateCheckTimestamp(), CONNECTIONSTATECHECKTIMESTAMP_BINDING);
protocolMarshaller.marshall(workspaceConnectionStatus.getLastKnownUserConnectionTimestamp(), LASTKNOWNUSERCONNECTIONTIMESTAMP_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(WorkspaceConnectionStatus workspaceConnectionStatus, ProtocolMarshaller protocolMarshaller) {
if (workspaceConnectionStatus == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(workspaceConnectionStatus.getWorkspaceId(), WORKSPACEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(workspaceConnectionStatus.getConnectionState(), CONNECTIONSTATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(workspaceConnectionStatus.getConnectionStateCheckTimestamp(), CONNECTIONSTATECHECKTIMESTAMP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(workspaceConnectionStatus.getLastKnownUserConnectionTimestamp(), LASTKNOWNUSERCONNECTIONTIMESTAMP_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private String convertURItoURL(String uri) {
int indexScheme = uri.indexOf("://");
if (-1 != indexScheme) {
int indexQuery = uri.indexOf('?');
if (-1 == indexQuery || indexScheme < indexQuery) {
// already a full url
return uri;
}
}
StringBuilder sb = new StringBuilder();
String scheme = this.request.getScheme();
sb.append(scheme).append("://");
sb.append(this.request.getServerName());
int port = this.request.getServerPort();
if ("http".equalsIgnoreCase(scheme) && 80 != port) {
sb.append(':').append(port);
} else if ("https".equalsIgnoreCase(scheme) && 443 != port) {
sb.append(':').append(port);
}
String data = this.request.getContextPath();
if (!"".equals(data)) {
sb.append(data);
}
if (0 == uri.length()) {
sb.append('/');
} else if (uri.charAt(0) == '/') {
// relative to servlet container root...
sb.append(uri);
} else {
// relative to current URI,
data = this.request.getServletPath();
if (!"".equals(data)) {
sb.append(data);
}
data = this.request.getPathInfo();
if (null != data) {
sb.append(data);
}
sb.append('/');
sb.append(uri);
// TODO: webcontainer converted "/./" and "/../" info too
}
return sb.toString();
} } | public class class_name {
private String convertURItoURL(String uri) {
int indexScheme = uri.indexOf("://");
if (-1 != indexScheme) {
int indexQuery = uri.indexOf('?');
if (-1 == indexQuery || indexScheme < indexQuery) {
// already a full url
return uri; // depends on control dependency: [if], data = [none]
}
}
StringBuilder sb = new StringBuilder();
String scheme = this.request.getScheme();
sb.append(scheme).append("://");
sb.append(this.request.getServerName());
int port = this.request.getServerPort();
if ("http".equalsIgnoreCase(scheme) && 80 != port) {
sb.append(':').append(port);
} else if ("https".equalsIgnoreCase(scheme) && 443 != port) {
sb.append(':').append(port);
}
String data = this.request.getContextPath();
if (!"".equals(data)) {
sb.append(data);
}
if (0 == uri.length()) {
sb.append('/');
} else if (uri.charAt(0) == '/') {
// relative to servlet container root...
sb.append(uri);
} else {
// relative to current URI,
data = this.request.getServletPath();
if (!"".equals(data)) {
sb.append(data);
}
data = this.request.getPathInfo();
if (null != data) {
sb.append(data);
}
sb.append('/');
sb.append(uri);
// TODO: webcontainer converted "/./" and "/../" info too
}
return sb.toString();
} } |
public class class_name {
public String toMMCIF() {
StringBuilder sb = new StringBuilder();
String molecId1 = getMoleculeIds().getFirst();
String molecId2 = getMoleculeIds().getSecond();
if (isSymRelated()) {
// if both chains are named equally we want to still named them differently in the output mmcif file
// so that molecular viewers can handle properly the 2 chains as separate entities
molecId2 = molecId2 + "_" +getTransforms().getSecond().getTransformId();
}
sb.append(SimpleMMcifParser.MMCIF_TOP_HEADER).append("BioJava_interface_").append(getId()).append(System.getProperty("line.separator"));
sb.append(FileConvert.getAtomSiteHeader());
// we reassign atom ids if sym related (otherwise atom ids would be duplicated and some molecular viewers can't cope with that)
int atomId = 1;
List<AtomSite> atomSites = new ArrayList<>();
for (Atom atom:this.molecules.getFirst()) {
if (isSymRelated()) {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId1, molecId1, atomId));
} else {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId1, molecId1));
}
atomId++;
}
for (Atom atom:this.molecules.getSecond()) {
if (isSymRelated()) {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId2, molecId2, atomId));
} else {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId2, molecId2));
}
atomId++;
}
sb.append(MMCIFFileTools.toMMCIF(atomSites,AtomSite.class));
return sb.toString();
} } | public class class_name {
public String toMMCIF() {
StringBuilder sb = new StringBuilder();
String molecId1 = getMoleculeIds().getFirst();
String molecId2 = getMoleculeIds().getSecond();
if (isSymRelated()) {
// if both chains are named equally we want to still named them differently in the output mmcif file
// so that molecular viewers can handle properly the 2 chains as separate entities
molecId2 = molecId2 + "_" +getTransforms().getSecond().getTransformId(); // depends on control dependency: [if], data = [none]
}
sb.append(SimpleMMcifParser.MMCIF_TOP_HEADER).append("BioJava_interface_").append(getId()).append(System.getProperty("line.separator"));
sb.append(FileConvert.getAtomSiteHeader());
// we reassign atom ids if sym related (otherwise atom ids would be duplicated and some molecular viewers can't cope with that)
int atomId = 1;
List<AtomSite> atomSites = new ArrayList<>();
for (Atom atom:this.molecules.getFirst()) {
if (isSymRelated()) {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId1, molecId1, atomId));
} else {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId1, molecId1));
}
atomId++;
}
for (Atom atom:this.molecules.getSecond()) {
if (isSymRelated()) {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId2, molecId2, atomId));
} else {
atomSites.add(MMCIFFileTools.convertAtomToAtomSite(atom, 1, molecId2, molecId2));
}
atomId++;
}
sb.append(MMCIFFileTools.toMMCIF(atomSites,AtomSite.class));
return sb.toString();
} } |
public class class_name {
public void clearPersistedFiles(List<Long> persistedFiles) {
synchronized (mLock) {
for (long persistedId : persistedFiles) {
mPersistedUfsFingerprints.remove(persistedId);
}
}
} } | public class class_name {
public void clearPersistedFiles(List<Long> persistedFiles) {
synchronized (mLock) {
for (long persistedId : persistedFiles) {
mPersistedUfsFingerprints.remove(persistedId); // depends on control dependency: [for], data = [persistedId]
}
}
} } |
public class class_name {
public DoubleVector[] chooseSeeds(int numCentroids, Matrix dataPoints) {
int[] centroids = new int[numCentroids];
// Select the first centroid randomly.
DoubleVector[] centers = new DoubleVector[numCentroids];
int centroidIndex = (int) Math.round(
Math.random()*(dataPoints.rows()-1));
centers[0] = dataPoints.getRowVector(centroidIndex);
// Compute the distance each data point has with the first centroid.
double[] distances = new double[dataPoints.rows()];
computeDistances(distances, false, dataPoints, centers[0]);
// For each of the remaining centroids, select one of the data points,
// p, with probability
// p(dist(p, last_centroid)^2/sum_p(dist(p, last_centroid)^2))
// This is an attempt to pick the data point which is furthest away from
// the previously selected data point.
for (int i = 1; i < numCentroids; ++i) {
double sum = distanceSum(distances);
double probability = Math.random();
centroidIndex = chooseWithProbability(distances, sum, probability);
centers[i] = dataPoints.getRowVector(centroidIndex);
computeDistances(distances, true, dataPoints, centers[i]);
}
return centers;
} } | public class class_name {
public DoubleVector[] chooseSeeds(int numCentroids, Matrix dataPoints) {
int[] centroids = new int[numCentroids];
// Select the first centroid randomly.
DoubleVector[] centers = new DoubleVector[numCentroids];
int centroidIndex = (int) Math.round(
Math.random()*(dataPoints.rows()-1));
centers[0] = dataPoints.getRowVector(centroidIndex);
// Compute the distance each data point has with the first centroid.
double[] distances = new double[dataPoints.rows()];
computeDistances(distances, false, dataPoints, centers[0]);
// For each of the remaining centroids, select one of the data points,
// p, with probability
// p(dist(p, last_centroid)^2/sum_p(dist(p, last_centroid)^2))
// This is an attempt to pick the data point which is furthest away from
// the previously selected data point.
for (int i = 1; i < numCentroids; ++i) {
double sum = distanceSum(distances);
double probability = Math.random();
centroidIndex = chooseWithProbability(distances, sum, probability); // depends on control dependency: [for], data = [none]
centers[i] = dataPoints.getRowVector(centroidIndex); // depends on control dependency: [for], data = [i]
computeDistances(distances, true, dataPoints, centers[i]); // depends on control dependency: [for], data = [i]
}
return centers;
} } |
public class class_name {
public void marshall(KinesisVideoStream kinesisVideoStream, ProtocolMarshaller protocolMarshaller) {
if (kinesisVideoStream == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(kinesisVideoStream.getArn(), ARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(KinesisVideoStream kinesisVideoStream, ProtocolMarshaller protocolMarshaller) {
if (kinesisVideoStream == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(kinesisVideoStream.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void persistRows(Map<HTableInterface, List<HBaseDataWrapper>> rows) throws IOException
{
List<Put> dataSet = new ArrayList<Put>(rows.size());
for (HTableInterface hTable : rows.keySet())
{
List<HBaseDataWrapper> row = rows.get(hTable);
for (HBaseDataWrapper data : row)
{
dataSet.add(preparePut(data.getColumnFamily(), data.getRowKey(), data.getColumns(), data.getValues()));
}
hTable.put(dataSet);
dataSet.clear();
}
} } | public class class_name {
@Override
public void persistRows(Map<HTableInterface, List<HBaseDataWrapper>> rows) throws IOException
{
List<Put> dataSet = new ArrayList<Put>(rows.size());
for (HTableInterface hTable : rows.keySet())
{
List<HBaseDataWrapper> row = rows.get(hTable);
for (HBaseDataWrapper data : row)
{
dataSet.add(preparePut(data.getColumnFamily(), data.getRowKey(), data.getColumns(), data.getValues())); // depends on control dependency: [for], data = [data]
}
hTable.put(dataSet);
dataSet.clear();
}
} } |
public class class_name {
public static StringBuilder appendSpace(StringBuilder buf, int spaces) {
for(int i = spaces; i > 0; i -= SPACEPADDING.length) {
buf.append(SPACEPADDING, 0, i < SPACEPADDING.length ? i : SPACEPADDING.length);
}
return buf;
} } | public class class_name {
public static StringBuilder appendSpace(StringBuilder buf, int spaces) {
for(int i = spaces; i > 0; i -= SPACEPADDING.length) {
buf.append(SPACEPADDING, 0, i < SPACEPADDING.length ? i : SPACEPADDING.length); // depends on control dependency: [for], data = [i]
}
return buf;
} } |
public class class_name {
private void resetMenuItems(boolean enable) {
for (int i = 0; i < severityItemList.length; ++i) {
MenuItem menuItem = severityItemList[i];
menuItem.setEnabled(enable);
menuItem.setSelection(false);
}
} } | public class class_name {
private void resetMenuItems(boolean enable) {
for (int i = 0; i < severityItemList.length; ++i) {
MenuItem menuItem = severityItemList[i];
menuItem.setEnabled(enable); // depends on control dependency: [for], data = [none]
menuItem.setSelection(false); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private static Chainr getChainr( ChainrInstantiator chainrInstantiator, Object chainrSpec ) {
Chainr chainr;
if (chainrInstantiator == null ) {
chainr = Chainr.fromSpec( chainrSpec );
}
else {
chainr = Chainr.fromSpec( chainrSpec, chainrInstantiator );
}
return chainr;
} } | public class class_name {
private static Chainr getChainr( ChainrInstantiator chainrInstantiator, Object chainrSpec ) {
Chainr chainr;
if (chainrInstantiator == null ) {
chainr = Chainr.fromSpec( chainrSpec ); // depends on control dependency: [if], data = [none]
}
else {
chainr = Chainr.fromSpec( chainrSpec, chainrInstantiator ); // depends on control dependency: [if], data = [none]
}
return chainr;
} } |
public class class_name {
public static Throwable trySetAccessible(AccessibleObject object, boolean checkAccessible) {
if (checkAccessible && !PlatformDependent0.isExplicitTryReflectionSetAccessible()) {
return new UnsupportedOperationException("Reflective setAccessible(true) disabled");
}
try {
object.setAccessible(true);
return null;
} catch (SecurityException e) {
return e;
} catch (RuntimeException e) {
return handleInaccessibleObjectException(e);
}
} } | public class class_name {
public static Throwable trySetAccessible(AccessibleObject object, boolean checkAccessible) {
if (checkAccessible && !PlatformDependent0.isExplicitTryReflectionSetAccessible()) {
return new UnsupportedOperationException("Reflective setAccessible(true) disabled"); // depends on control dependency: [if], data = [none]
}
try {
object.setAccessible(true); // depends on control dependency: [try], data = [none]
return null; // depends on control dependency: [try], data = [none]
} catch (SecurityException e) {
return e;
} catch (RuntimeException e) { // depends on control dependency: [catch], data = [none]
return handleInaccessibleObjectException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
if (!isUpdate)
{
r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
.insert(populateRmap(entityMetadata, entity)).run(connection);
}
else
{
r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
.update(populateRmap(entityMetadata, entity)).run(connection);
}
} } | public class class_name {
@Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
if (!isUpdate)
{
r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
.insert(populateRmap(entityMetadata, entity)).run(connection); // depends on control dependency: [if], data = [none]
}
else
{
r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
.update(populateRmap(entityMetadata, entity)).run(connection); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void parseBody() {
if (currentStatus == MultiPartStatus.PREEPILOGUE || currentStatus == MultiPartStatus.EPILOGUE) {
if (isLastChunk) {
currentStatus = MultiPartStatus.EPILOGUE;
}
return;
}
parseBodyMultipart();
} } | public class class_name {
private void parseBody() {
if (currentStatus == MultiPartStatus.PREEPILOGUE || currentStatus == MultiPartStatus.EPILOGUE) {
if (isLastChunk) {
currentStatus = MultiPartStatus.EPILOGUE; // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
parseBodyMultipart();
} } |
public class class_name {
public String getWorldGroupName(String world) {
String result = DEFAULT_GROUP_NAME;
for (Entry<String, WorldGroup> entry : list.entrySet()) {
if (entry.getValue().worldExist(world)) {
result = entry.getKey();
}
}
return result;
} } | public class class_name {
public String getWorldGroupName(String world) {
String result = DEFAULT_GROUP_NAME;
for (Entry<String, WorldGroup> entry : list.entrySet()) {
if (entry.getValue().worldExist(world)) {
result = entry.getKey(); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
static String htmlEncodeRequestName(String requestId, String requestName) {
if (requestId.startsWith(Counter.SQL_COUNTER_NAME)) {
final String htmlEncoded = htmlEncodeButNotSpace(requestName);
// highlight SQL keywords
return SQL_KEYWORDS_PATTERN.matcher(htmlEncoded)
.replaceAll("<span class='sqlKeyword'>$1</span>");
}
return htmlEncodeButNotSpace(requestName);
} } | public class class_name {
static String htmlEncodeRequestName(String requestId, String requestName) {
if (requestId.startsWith(Counter.SQL_COUNTER_NAME)) {
final String htmlEncoded = htmlEncodeButNotSpace(requestName);
// highlight SQL keywords
return SQL_KEYWORDS_PATTERN.matcher(htmlEncoded)
.replaceAll("<span class='sqlKeyword'>$1</span>");
// depends on control dependency: [if], data = [none]
}
return htmlEncodeButNotSpace(requestName);
} } |
public class class_name {
public List<RDN> rdns() {
List<RDN> list = rdnList;
if (list == null) {
list = Collections.unmodifiableList(Arrays.asList(names));
rdnList = list;
}
return list;
} } | public class class_name {
public List<RDN> rdns() {
List<RDN> list = rdnList;
if (list == null) {
list = Collections.unmodifiableList(Arrays.asList(names)); // depends on control dependency: [if], data = [none]
rdnList = list; // depends on control dependency: [if], data = [none]
}
return list;
} } |
public class class_name {
protected Map<String, List<Object>> resolveAttributesFromPrincipalAttributeRepository(final Principal principal, final RegisteredService registeredService) {
val repository = ObjectUtils.defaultIfNull(this.principalAttributesRepository,
getPrincipalAttributesRepositoryFromApplicationContext());
if (repository != null) {
LOGGER.debug("Using principal attribute repository [{}] to retrieve attributes", repository);
return repository.getAttributes(principal, registeredService);
}
return principal.getAttributes();
} } | public class class_name {
protected Map<String, List<Object>> resolveAttributesFromPrincipalAttributeRepository(final Principal principal, final RegisteredService registeredService) {
val repository = ObjectUtils.defaultIfNull(this.principalAttributesRepository,
getPrincipalAttributesRepositoryFromApplicationContext());
if (repository != null) {
LOGGER.debug("Using principal attribute repository [{}] to retrieve attributes", repository); // depends on control dependency: [if], data = [none]
return repository.getAttributes(principal, registeredService); // depends on control dependency: [if], data = [none]
}
return principal.getAttributes();
} } |
public class class_name {
public static Field getField(Class clazz, String fieldName) {
if (Map.class.isAssignableFrom(clazz)) {
return new Field(new MapField(fieldName));
}
java.lang.reflect.Field field = null;
while (field == null && clazz != null) {
try {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
} catch (Exception e) {
clazz = clazz.getSuperclass();
}
}
return new Field(field);
} } | public class class_name {
public static Field getField(Class clazz, String fieldName) {
if (Map.class.isAssignableFrom(clazz)) {
return new Field(new MapField(fieldName)); // depends on control dependency: [if], data = [none]
}
java.lang.reflect.Field field = null;
while (field == null && clazz != null) {
try {
field = clazz.getDeclaredField(fieldName); // depends on control dependency: [try], data = [none]
field.setAccessible(true); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
clazz = clazz.getSuperclass();
} // depends on control dependency: [catch], data = [none]
}
return new Field(field);
} } |
public class class_name {
@GuardedBy("lock")
private void beginWaitingFor(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
// push guard onto activeGuards
guard.next = activeGuards;
activeGuards = guard;
}
} } | public class class_name {
@GuardedBy("lock")
private void beginWaitingFor(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
// push guard onto activeGuards
guard.next = activeGuards; // depends on control dependency: [if], data = [none]
activeGuards = guard; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setRow(int i, Vector row) {
if (columns != row.length()) {
fail("Wrong vector length: " + row.length() + ". Should be: " + columns + ".");
}
for (int j = 0; j < row.length(); j++) {
set(i, j, row.get(j));
}
} } | public class class_name {
public void setRow(int i, Vector row) {
if (columns != row.length()) {
fail("Wrong vector length: " + row.length() + ". Should be: " + columns + "."); // depends on control dependency: [if], data = [none]
}
for (int j = 0; j < row.length(); j++) {
set(i, j, row.get(j)); // depends on control dependency: [for], data = [j]
}
} } |
public class class_name {
public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)
{
//
// Retrieve the LHS value
//
FieldType field = m_leftValue;
Object lhs;
if (field == null)
{
lhs = null;
}
else
{
lhs = container.getCurrentValue(field);
switch (field.getDataType())
{
case DATE:
{
if (lhs != null)
{
lhs = DateHelper.getDayStartDate((Date) lhs);
}
break;
}
case DURATION:
{
if (lhs != null)
{
Duration dur = (Duration) lhs;
lhs = dur.convertUnits(TimeUnit.HOURS, m_properties);
}
else
{
lhs = Duration.getInstance(0, TimeUnit.HOURS);
}
break;
}
case STRING:
{
lhs = lhs == null ? "" : lhs;
break;
}
default:
{
break;
}
}
}
//
// Retrieve the RHS values
//
Object[] rhs;
if (m_symbolicValues == true)
{
rhs = processSymbolicValues(m_workingRightValues, container, promptValues);
}
else
{
rhs = m_workingRightValues;
}
//
// Evaluate
//
boolean result;
switch (m_operator)
{
case AND:
case OR:
{
result = evaluateLogicalOperator(container, promptValues);
break;
}
default:
{
result = m_operator.evaluate(lhs, rhs);
break;
}
}
return result;
} } | public class class_name {
public boolean evaluate(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)
{
//
// Retrieve the LHS value
//
FieldType field = m_leftValue;
Object lhs;
if (field == null)
{
lhs = null; // depends on control dependency: [if], data = [none]
}
else
{
lhs = container.getCurrentValue(field); // depends on control dependency: [if], data = [(field]
switch (field.getDataType())
{
case DATE:
{
if (lhs != null)
{
lhs = DateHelper.getDayStartDate((Date) lhs); // depends on control dependency: [if], data = [none]
}
break;
}
case DURATION:
{
if (lhs != null)
{
Duration dur = (Duration) lhs;
lhs = dur.convertUnits(TimeUnit.HOURS, m_properties); // depends on control dependency: [if], data = [none]
}
else
{
lhs = Duration.getInstance(0, TimeUnit.HOURS); // depends on control dependency: [if], data = [none]
}
break;
}
case STRING:
{
lhs = lhs == null ? "" : lhs;
break;
}
default:
{
break;
}
}
}
//
// Retrieve the RHS values
//
Object[] rhs;
if (m_symbolicValues == true)
{
rhs = processSymbolicValues(m_workingRightValues, container, promptValues);
}
else
{
rhs = m_workingRightValues;
}
//
// Evaluate
//
boolean result;
switch (m_operator)
{
case AND:
case OR:
{
result = evaluateLogicalOperator(container, promptValues);
break;
}
default:
{
result = m_operator.evaluate(lhs, rhs);
break;
}
}
return result;
} } |
public class class_name {
public GridBagConstraints getGBConstraints()
{
if (m_gbconstraints == null)
m_gbconstraints = new GridBagConstraints();
else
{ // Set back to default values
m_gbconstraints.gridx = GridBagConstraints.RELATIVE;
m_gbconstraints.gridy = GridBagConstraints.RELATIVE;
m_gbconstraints.gridwidth = 1;
m_gbconstraints.gridheight = 1;
m_gbconstraints.weightx = 0;
m_gbconstraints.weighty = 0;
m_gbconstraints.anchor = GridBagConstraints.CENTER;
m_gbconstraints.fill = GridBagConstraints.NONE;
m_gbconstraints.insets.bottom = 0;
m_gbconstraints.insets.left = 0;
m_gbconstraints.insets.right = 0;
m_gbconstraints.insets.top = 0;
m_gbconstraints.ipadx = 0;
m_gbconstraints.ipady = 0;
}
return m_gbconstraints;
} } | public class class_name {
public GridBagConstraints getGBConstraints()
{
if (m_gbconstraints == null)
m_gbconstraints = new GridBagConstraints();
else
{ // Set back to default values
m_gbconstraints.gridx = GridBagConstraints.RELATIVE; // depends on control dependency: [if], data = [none]
m_gbconstraints.gridy = GridBagConstraints.RELATIVE; // depends on control dependency: [if], data = [none]
m_gbconstraints.gridwidth = 1; // depends on control dependency: [if], data = [none]
m_gbconstraints.gridheight = 1; // depends on control dependency: [if], data = [none]
m_gbconstraints.weightx = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.weighty = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.anchor = GridBagConstraints.CENTER; // depends on control dependency: [if], data = [none]
m_gbconstraints.fill = GridBagConstraints.NONE; // depends on control dependency: [if], data = [none]
m_gbconstraints.insets.bottom = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.insets.left = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.insets.right = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.insets.top = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.ipadx = 0; // depends on control dependency: [if], data = [none]
m_gbconstraints.ipady = 0; // depends on control dependency: [if], data = [none]
}
return m_gbconstraints;
} } |
public class class_name {
@Override
public EClass getIfcFilterType() {
if (ifcFilterTypeEClass == null) {
ifcFilterTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(272);
}
return ifcFilterTypeEClass;
} } | public class class_name {
@Override
public EClass getIfcFilterType() {
if (ifcFilterTypeEClass == null) {
ifcFilterTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(272);
// depends on control dependency: [if], data = [none]
}
return ifcFilterTypeEClass;
} } |
public class class_name {
public void setStickyFooterItemAtPosition(@NonNull IDrawerItem drawerItem, int position) {
if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) {
mDrawerBuilder.mStickyDrawerItems.set(position, drawerItem);
}
DrawerUtils.rebuildStickyFooterView(mDrawerBuilder);
} } | public class class_name {
public void setStickyFooterItemAtPosition(@NonNull IDrawerItem drawerItem, int position) {
if (mDrawerBuilder.mStickyDrawerItems != null && mDrawerBuilder.mStickyDrawerItems.size() > position) {
mDrawerBuilder.mStickyDrawerItems.set(position, drawerItem); // depends on control dependency: [if], data = [none]
}
DrawerUtils.rebuildStickyFooterView(mDrawerBuilder);
} } |
public class class_name {
private VariableHandler.URLStruction _getVTPLTemplateStructionStopCache(ESInfo dslinfo, String dsl)
{
String ikey = dsl;
String okey = dslinfo.getTemplateName();
MissingStaticCache<String,VariableHandler.URLStruction> sqlstructionMap = this.parserVTPLTempateStructionsMissingCache.get(okey);
if(sqlstructionMap == null)
{
try
{
this.vtplLock.lock();
sqlstructionMap = this.parserVTPLTempateStructionsMissingCache.get(okey);
if(sqlstructionMap == null)
{
sqlstructionMap = new MissingStaticCache<String,VariableHandler.URLStruction>(perKeyDSLStructionCacheSize);
parserVTPLTempateStructionsMissingCache.put(okey,sqlstructionMap);
}
}
finally {
vtplLock.unlock();
}
}
if(sqlstructionMap.stopCache()){
if(logger.isWarnEnabled()){
logDslStructionWarn(dslinfo,dsl,okey,sqlstructionMap.getMissesMax());
}
return VariableHandler.parserStruction(dsl,tempateStructionBuiler);
}
VariableHandler.URLStruction urlStruction = sqlstructionMap.get(ikey);
if(urlStruction == null){
try
{
this.vtplLock.lock();
urlStruction = sqlstructionMap.get(ikey);
if(urlStruction == null){
sqlstructionMap.increamentMissing();
urlStruction = VariableHandler.parserStruction(dsl,tempateStructionBuiler);
if(!sqlstructionMap.stopCache()){
sqlstructionMap.put(ikey,urlStruction);
}
else{
if(logger.isWarnEnabled()){
logDslStructionWarn(dslinfo,dsl,okey,sqlstructionMap.getMissesMax());
}
}
}
}
finally {
this.vtplLock.unlock();
}
}
// System.out.println("before gc longtermSize:"+sqlstructionMap.longtermSize());
// System.out.println("before gc edensize:"+sqlstructionMap.edenSize());
// System.gc();
// System.out.println("after gc edensize:"+sqlstructionMap.edenSize());
// System.out.println("after gc longtermSize:"+sqlstructionMap.longtermSize());
return urlStruction;
} } | public class class_name {
private VariableHandler.URLStruction _getVTPLTemplateStructionStopCache(ESInfo dslinfo, String dsl)
{
String ikey = dsl;
String okey = dslinfo.getTemplateName();
MissingStaticCache<String,VariableHandler.URLStruction> sqlstructionMap = this.parserVTPLTempateStructionsMissingCache.get(okey);
if(sqlstructionMap == null)
{
try
{
this.vtplLock.lock(); // depends on control dependency: [try], data = [none]
sqlstructionMap = this.parserVTPLTempateStructionsMissingCache.get(okey); // depends on control dependency: [try], data = [none]
if(sqlstructionMap == null)
{
sqlstructionMap = new MissingStaticCache<String,VariableHandler.URLStruction>(perKeyDSLStructionCacheSize); // depends on control dependency: [if], data = [none]
parserVTPLTempateStructionsMissingCache.put(okey,sqlstructionMap); // depends on control dependency: [if], data = [none]
}
}
finally {
vtplLock.unlock();
}
}
if(sqlstructionMap.stopCache()){
if(logger.isWarnEnabled()){
logDslStructionWarn(dslinfo,dsl,okey,sqlstructionMap.getMissesMax()); // depends on control dependency: [if], data = [none]
}
return VariableHandler.parserStruction(dsl,tempateStructionBuiler); // depends on control dependency: [if], data = [none]
}
VariableHandler.URLStruction urlStruction = sqlstructionMap.get(ikey);
if(urlStruction == null){
try
{
this.vtplLock.lock(); // depends on control dependency: [try], data = [none]
urlStruction = sqlstructionMap.get(ikey); // depends on control dependency: [try], data = [none]
if(urlStruction == null){
sqlstructionMap.increamentMissing(); // depends on control dependency: [if], data = [none]
urlStruction = VariableHandler.parserStruction(dsl,tempateStructionBuiler); // depends on control dependency: [if], data = [none]
if(!sqlstructionMap.stopCache()){
sqlstructionMap.put(ikey,urlStruction); // depends on control dependency: [if], data = [none]
}
else{
if(logger.isWarnEnabled()){
logDslStructionWarn(dslinfo,dsl,okey,sqlstructionMap.getMissesMax()); // depends on control dependency: [if], data = [none]
}
}
}
}
finally {
this.vtplLock.unlock();
}
}
// System.out.println("before gc longtermSize:"+sqlstructionMap.longtermSize());
// System.out.println("before gc edensize:"+sqlstructionMap.edenSize());
// System.gc();
// System.out.println("after gc edensize:"+sqlstructionMap.edenSize());
// System.out.println("after gc longtermSize:"+sqlstructionMap.longtermSize());
return urlStruction;
} } |
public class class_name {
public static String formatTypeName(ClassNode cNode) {
if (cNode.isArray()) {
ClassNode it = cNode;
int dim = 0;
while (it.isArray()) {
dim++;
it = it.getComponentType();
}
StringBuilder sb = new StringBuilder(it.getName().length() + 2 * dim);
sb.append(it.getName());
for (int i = 0; i < dim; i++) {
sb.append("[]");
}
return sb.toString();
}
return cNode.getName();
} } | public class class_name {
public static String formatTypeName(ClassNode cNode) {
if (cNode.isArray()) {
ClassNode it = cNode;
int dim = 0;
while (it.isArray()) {
dim++; // depends on control dependency: [while], data = [none]
it = it.getComponentType(); // depends on control dependency: [while], data = [none]
}
StringBuilder sb = new StringBuilder(it.getName().length() + 2 * dim);
sb.append(it.getName()); // depends on control dependency: [if], data = [none]
for (int i = 0; i < dim; i++) {
sb.append("[]"); // depends on control dependency: [for], data = [none]
}
return sb.toString(); // depends on control dependency: [if], data = [none]
}
return cNode.getName();
} } |
public class class_name {
public static void processBundles(final ConfigurationContext context) {
final List<GuiceyBundle> bundles = context.getEnabledBundles();
final List<Class<? extends GuiceyBundle>> installedBundles = Lists.newArrayList();
final GuiceyBootstrap guiceyBootstrap = new GuiceyBootstrap(context, bundles);
// iterating while no new bundles registered
while (!bundles.isEmpty()) {
final List<GuiceyBundle> processingBundles = Lists.newArrayList(removeDuplicates(bundles));
bundles.clear();
for (GuiceyBundle bundle : removeTypes(processingBundles, installedBundles)) {
final Class<? extends GuiceyBundle> bundleType = bundle.getClass();
Preconditions.checkState(!installedBundles.contains(bundleType),
"State error: duplicate bundle '%s' registration", bundleType.getName());
// disabled bundles are not processed (so nothing will be registered from it)
// important to check here because transitive bundles may appear to be disabled
if (context.isBundleEnabled(bundleType)) {
context.setScope(bundleType);
bundle.initialize(guiceyBootstrap);
context.closeScope();
}
installedBundles.add(bundleType);
}
}
context.lifecycle().bundlesProcessed(context.getEnabledBundles(), context.getDisabledBundles());
} } | public class class_name {
public static void processBundles(final ConfigurationContext context) {
final List<GuiceyBundle> bundles = context.getEnabledBundles();
final List<Class<? extends GuiceyBundle>> installedBundles = Lists.newArrayList();
final GuiceyBootstrap guiceyBootstrap = new GuiceyBootstrap(context, bundles);
// iterating while no new bundles registered
while (!bundles.isEmpty()) {
final List<GuiceyBundle> processingBundles = Lists.newArrayList(removeDuplicates(bundles));
bundles.clear(); // depends on control dependency: [while], data = [none]
for (GuiceyBundle bundle : removeTypes(processingBundles, installedBundles)) {
final Class<? extends GuiceyBundle> bundleType = bundle.getClass();
Preconditions.checkState(!installedBundles.contains(bundleType),
"State error: duplicate bundle '%s' registration", bundleType.getName());
// disabled bundles are not processed (so nothing will be registered from it)
// important to check here because transitive bundles may appear to be disabled
if (context.isBundleEnabled(bundleType)) {
context.setScope(bundleType); // depends on control dependency: [if], data = [none]
bundle.initialize(guiceyBootstrap); // depends on control dependency: [if], data = [none]
context.closeScope(); // depends on control dependency: [if], data = [none]
}
installedBundles.add(bundleType); // depends on control dependency: [for], data = [bundle]
}
}
context.lifecycle().bundlesProcessed(context.getEnabledBundles(), context.getDisabledBundles());
} } |
public class class_name {
public void addAllowedPrefix(String prefix) {
if (prefix.endsWith(".")) {
prefix = prefix.substring(0, prefix.length() - 1);
}
LOG.debug("Allowed prefix: {}", prefix);
String packageRegex = START + dotsToRegex(prefix) + SEP;
LOG.debug("Prefix regex: {}", packageRegex);
patternList.add(Pattern.compile(packageRegex).matcher(""));
} } | public class class_name {
public void addAllowedPrefix(String prefix) {
if (prefix.endsWith(".")) {
prefix = prefix.substring(0, prefix.length() - 1); // depends on control dependency: [if], data = [none]
}
LOG.debug("Allowed prefix: {}", prefix);
String packageRegex = START + dotsToRegex(prefix) + SEP;
LOG.debug("Prefix regex: {}", packageRegex);
patternList.add(Pattern.compile(packageRegex).matcher(""));
} } |
public class class_name {
public Schema loadSchema( Connection pConnection, Diagram pRootDiagram ) throws SQLException
{
Schema lSchema = new Schema();
String lSql = "select table_name from user_tables";
CallableStatement lTableStatement = pConnection.prepareCall( lSql );
ResultSet lTableResultSet = lTableStatement.executeQuery();
while( lTableResultSet.next() )
{
if( pRootDiagram.isTableIncluded( lTableResultSet.getString( 1 ) ) )
{
Main.log( "Loading Table: " + lTableResultSet.getString( 1 ) );
Table lTable = new Table( lTableResultSet.getString( 1 ) );
lSchema.addTable( lTable );
CallableStatement lColumnStatement = pConnection.prepareCall( "select column_name from user_tab_columns where table_name = :1 order by column_id" );
lColumnStatement.setString( 1, lTable.getName() );
ResultSet lColumnResultSet = lColumnStatement.executeQuery();
while( lColumnResultSet.next() )
{
lTable.addColumn( new Column( lColumnResultSet.getString( 1 ) ) );
}
lColumnResultSet.close();
lColumnStatement.close();
}
}
lTableResultSet.close();
lTableStatement.close();
String lFkSql = " select /*+ full(o)*/ "
+ " o.constraint_name fk_name, "
+ " o.table_name tab_from, "
+ " o_fk_cols.column_name col_from, "
+ " i.table_name tab_to, "
+ " i_fk_cols.column_name col_to, "
+ " nvl "
+ " ( "
+ " ( "
+ " select distinct "
+ " 'N' "
+ " from user_cons_columns ox_fk_cols, "
+ " user_tab_columns "
+ " where ox_fk_cols.constraint_name = o.constraint_name "
+ " and ox_fk_cols.table_name = o.table_name "
+ " and user_tab_columns.column_name = ox_fk_cols.column_name "
+ " and ox_fk_cols.table_name = user_tab_columns.table_name "
+ " and nullable = 'N' "
+ " ), "
+ " 'Y' "
+ " ) as nullable, "
+ " nvl "
+ " ( "
+ " ( "
+ " select distinct "
+ " 'Y' "
+ " from user_constraints o_uk "
+ " where o_uk.table_name = o.table_name "
+ " and o_uk.constraint_type = 'U' "
+ " and not exists "
+ " ( "
+ " select 1 "
+ " from user_cons_columns o_uk_cols "
+ " where o_uk_cols.constraint_name = o_uk.constraint_name "
+ " and o_uk_cols.table_name = o_uk.table_name "
+ " and not exists "
+ " ( "
+ " select 1 "
+ " from user_cons_columns ox_fk_cols "
+ " where ox_fk_cols.constraint_name = o.constraint_name "
+ " and ox_fk_cols.table_name = o.table_name "
+ " and ox_fk_cols.column_name = o_uk_cols.column_name "
+ " ) "
+ " ) "
+ " ), "
+ " 'N' "
+ " ) as uk_on_fk "
+ " from user_constraints o, "
+ " user_constraints i, "
+ " user_cons_columns o_fk_cols, "
+ " user_tab_columns, "
+ " user_cons_columns i_fk_cols "
+ " where o.constraint_type = 'R' "
+ " and i.constraint_name = o.r_constraint_name "
+ " and o_fk_cols.constraint_name = o.constraint_name "
+ " and o_fk_cols.column_name = user_tab_columns.column_name "
+ " and o.table_name = user_tab_columns.table_name "
+ " and i_fk_cols.constraint_name = i.constraint_name "
+ " and i_fk_cols.table_name = i.table_name "
+ " order by 1,2 ";
CallableStatement lFkStatement = pConnection.prepareCall( lFkSql );
ResultSet lFkResultSet = lFkStatement.executeQuery();
Association lAssociation = null;
while( lFkResultSet.next() )
{
Table lTableFrom = lSchema.findTable( lFkResultSet.getString( "tab_from" ) );
Table lTableTo = lSchema.findTable( lFkResultSet.getString( "tab_to" ) );
if( lTableFrom != null && lTableTo != null )
{
String lConstraintName = lFkResultSet.getString( "fk_name" );
if( lAssociation == null || !lAssociation.getAssociationName().equals( lConstraintName ) )
{
lAssociation = new Association( lConstraintName, lTableFrom, lTableTo, true, 0, lFkResultSet.getString( "uk_on_fk" ).equals( "N" ) ? Association.MULTIPLICITY_N : 1, lFkResultSet.getString(
"nullable" ).equals( "N" ) ? 1 : 0, 1 );
lSchema.addAssociation( lAssociation );
}
lAssociation.addColumnFrom( lFkResultSet.getString( "col_from" ) );
lAssociation.addColumnTo( lFkResultSet.getString( "col_to" ) );
}
}
lFkResultSet.close();
lFkStatement.close();
return lSchema;
} } | public class class_name {
public Schema loadSchema( Connection pConnection, Diagram pRootDiagram ) throws SQLException
{
Schema lSchema = new Schema();
String lSql = "select table_name from user_tables";
CallableStatement lTableStatement = pConnection.prepareCall( lSql );
ResultSet lTableResultSet = lTableStatement.executeQuery();
while( lTableResultSet.next() )
{
if( pRootDiagram.isTableIncluded( lTableResultSet.getString( 1 ) ) )
{
Main.log( "Loading Table: " + lTableResultSet.getString( 1 ) );
Table lTable = new Table( lTableResultSet.getString( 1 ) );
lSchema.addTable( lTable );
CallableStatement lColumnStatement = pConnection.prepareCall( "select column_name from user_tab_columns where table_name = :1 order by column_id" );
lColumnStatement.setString( 1, lTable.getName() );
ResultSet lColumnResultSet = lColumnStatement.executeQuery();
while( lColumnResultSet.next() )
{
lTable.addColumn( new Column( lColumnResultSet.getString( 1 ) ) );
}
lColumnResultSet.close();
lColumnStatement.close();
}
}
lTableResultSet.close();
lTableStatement.close();
String lFkSql = " select /*+ full(o)*/ "
+ " o.constraint_name fk_name, "
+ " o.table_name tab_from, "
+ " o_fk_cols.column_name col_from, "
+ " i.table_name tab_to, "
+ " i_fk_cols.column_name col_to, "
+ " nvl "
+ " ( "
+ " ( "
+ " select distinct "
+ " 'N' "
+ " from user_cons_columns ox_fk_cols, "
+ " user_tab_columns "
+ " where ox_fk_cols.constraint_name = o.constraint_name "
+ " and ox_fk_cols.table_name = o.table_name "
+ " and user_tab_columns.column_name = ox_fk_cols.column_name "
+ " and ox_fk_cols.table_name = user_tab_columns.table_name "
+ " and nullable = 'N' "
+ " ), "
+ " 'Y' "
+ " ) as nullable, "
+ " nvl "
+ " ( "
+ " ( "
+ " select distinct "
+ " 'Y' "
+ " from user_constraints o_uk "
+ " where o_uk.table_name = o.table_name "
+ " and o_uk.constraint_type = 'U' "
+ " and not exists "
+ " ( "
+ " select 1 "
+ " from user_cons_columns o_uk_cols "
+ " where o_uk_cols.constraint_name = o_uk.constraint_name "
+ " and o_uk_cols.table_name = o_uk.table_name "
+ " and not exists "
+ " ( "
+ " select 1 "
+ " from user_cons_columns ox_fk_cols "
+ " where ox_fk_cols.constraint_name = o.constraint_name "
+ " and ox_fk_cols.table_name = o.table_name "
+ " and ox_fk_cols.column_name = o_uk_cols.column_name "
+ " ) "
+ " ) "
+ " ), "
+ " 'N' "
+ " ) as uk_on_fk "
+ " from user_constraints o, "
+ " user_constraints i, "
+ " user_cons_columns o_fk_cols, "
+ " user_tab_columns, "
+ " user_cons_columns i_fk_cols "
+ " where o.constraint_type = 'R' "
+ " and i.constraint_name = o.r_constraint_name "
+ " and o_fk_cols.constraint_name = o.constraint_name "
+ " and o_fk_cols.column_name = user_tab_columns.column_name "
+ " and o.table_name = user_tab_columns.table_name "
+ " and i_fk_cols.constraint_name = i.constraint_name "
+ " and i_fk_cols.table_name = i.table_name "
+ " order by 1,2 ";
CallableStatement lFkStatement = pConnection.prepareCall( lFkSql );
ResultSet lFkResultSet = lFkStatement.executeQuery();
Association lAssociation = null;
while( lFkResultSet.next() )
{
Table lTableFrom = lSchema.findTable( lFkResultSet.getString( "tab_from" ) );
Table lTableTo = lSchema.findTable( lFkResultSet.getString( "tab_to" ) );
if( lTableFrom != null && lTableTo != null )
{
String lConstraintName = lFkResultSet.getString( "fk_name" );
if( lAssociation == null || !lAssociation.getAssociationName().equals( lConstraintName ) )
{
lAssociation = new Association( lConstraintName, lTableFrom, lTableTo, true, 0, lFkResultSet.getString( "uk_on_fk" ).equals( "N" ) ? Association.MULTIPLICITY_N : 1, lFkResultSet.getString(
"nullable" ).equals( "N" ) ? 1 : 0, 1 ); // depends on control dependency: [if], data = [none]
lSchema.addAssociation( lAssociation ); // depends on control dependency: [if], data = [( lAssociation]
}
lAssociation.addColumnFrom( lFkResultSet.getString( "col_from" ) );
lAssociation.addColumnTo( lFkResultSet.getString( "col_to" ) );
}
}
lFkResultSet.close();
lFkStatement.close();
return lSchema;
} } |
public class class_name {
private void addPropertiesToModel(List<Property> localProperties, Item parent) {
for (Property property : localProperties) {
Item propertyItem = new Item(property, parent);
model.add(propertyItem);
// add any sub-properties
Property[] subProperties = property.getSubProperties();
if (subProperties != null && subProperties.length > 0) {
addPropertiesToModel(Arrays.asList(subProperties), propertyItem);
}
}
} } | public class class_name {
private void addPropertiesToModel(List<Property> localProperties, Item parent) {
for (Property property : localProperties) {
Item propertyItem = new Item(property, parent);
model.add(propertyItem); // depends on control dependency: [for], data = [property]
// add any sub-properties
Property[] subProperties = property.getSubProperties();
if (subProperties != null && subProperties.length > 0) {
addPropertiesToModel(Arrays.asList(subProperties), propertyItem); // depends on control dependency: [if], data = [(subProperties]
}
}
} } |
public class class_name {
public KeyAreaInfo getKeyArea(int iKeySeq)
{
if (iKeySeq == -1)
iKeySeq = this.getDefaultOrder();
else
iKeySeq -= Constants.MAIN_KEY_AREA;
try {
if (m_vKeyAreaList != null)
if ((iKeySeq >= 0) && (iKeySeq < m_vKeyAreaList.size()))
return (KeyAreaInfo)m_vKeyAreaList.elementAt(iKeySeq);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
}
return null; // Not found
} } | public class class_name {
public KeyAreaInfo getKeyArea(int iKeySeq)
{
if (iKeySeq == -1)
iKeySeq = this.getDefaultOrder();
else
iKeySeq -= Constants.MAIN_KEY_AREA;
try {
if (m_vKeyAreaList != null)
if ((iKeySeq >= 0) && (iKeySeq < m_vKeyAreaList.size()))
return (KeyAreaInfo)m_vKeyAreaList.elementAt(iKeySeq);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
} // depends on control dependency: [catch], data = [none]
return null; // Not found
} } |
public class class_name {
public boolean moveTo(N newParent) {
if (newParent == null) {
return false;
}
return moveTo(newParent, newParent.getChildCount());
} } | public class class_name {
public boolean moveTo(N newParent) {
if (newParent == null) {
return false; // depends on control dependency: [if], data = [none]
}
return moveTo(newParent, newParent.getChildCount());
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.