id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
9812178_36 | public static Schooljaar parse(String value)
{
Pattern[] patterns = new Pattern[] {officieel, kort};
for (Pattern pattern : patterns)
{
Matcher matcher = pattern.matcher(value);
if (!matcher.matches())
{
continue;
}
String startJaar = matcher.group(1);
if (startJaar == null)
return null;
TimeUtil kalender = TimeUtil.getInstance();
Date date = kalender.parseDateString(String.format("01-08-%s", startJaar));
return Schooljaar.valueOf(date);
}
return null;
} |
9818626_1 | @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace")
public String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName)
throws ProcessException {
// first off, decide what is the target store
WorkspaceInfo ws;
if (workspace != null) {
ws = catalog.getWorkspaceByName(workspace);
if (ws == null) {
throw new ProcessException("Could not find workspace " + workspace);
}
} else {
ws = catalog.getDefaultWorkspace();
if (ws == null) {
throw new ProcessException(
"The catalog is empty, could not find a default workspace");
}
}
//create a builder to help build catalog objects
CatalogBuilder cb = new CatalogBuilder(catalog);
cb.setWorkspace( ws );
// ok, find the target store
StoreInfo storeInfo = null;
boolean add = false;
if (store != null) {
if (features != null)
{
storeInfo = catalog.getDataStoreByName(ws.getName(), store);
}
else if (coverage != null)
{
storeInfo = catalog.getCoverageStoreByName(ws.getName(), store);
}
if (storeInfo == null) {
throw new ProcessException("Could not find store " + store + " in workspace "
+ workspace);
// TODO: support store creation
}
} else if (features != null) {
storeInfo = catalog.getDefaultDataStore(ws);
if (storeInfo == null) {
throw new ProcessException("Could not find a default store in workspace "
+ ws.getName());
}
} else if (coverage != null) {
//create a new coverage store
LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString()));
storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString()));
add = true;
store = (name != null ? name : coverage.getName().toString());
if (storeInfo == null) {
throw new ProcessException("Could not find a default store in workspace " + ws.getName());
}
}
// check the target style if any
StyleInfo targetStyle = null;
if (styleName != null) {
targetStyle = catalog.getStyleByName(styleName);
if (targetStyle == null) {
throw new ProcessException("Could not find style " + styleName);
}
}
if (features != null)
{
// check if the target layer and the target feature type are not
// already there (this is a half-assed attempt as we don't have
// an API telling us how the feature type name will be changed
// by DataStore.createSchema(...), but better than fully importing
// the data into the target store to find out we cannot create the layer...)
String tentativeTargetName = null;
if (name != null) {
tentativeTargetName = ws.getName() + ":" + name;
} else {
tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName();
}
if (catalog.getLayer(tentativeTargetName) != null) {
throw new ProcessException("Target layer " + tentativeTargetName + " already exists");
}
// check the target crs
String targetSRSCode = null;
if (srs != null) {
try {
Integer code = CRS.lookupEpsgCode(srs, true);
if (code == null) {
throw new WPSException("Could not find a EPSG code for " + srs);
}
targetSRSCode = "EPSG:" + code;
} catch (Exception e) {
throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
}
} else {
// check we can extract a code from the original data
GeometryDescriptor gd = features.getSchema().getGeometryDescriptor();
if (gd == null) {
// data is geometryless, we need a fake SRS
targetSRSCode = "EPSG:4326";
srsHandling = ProjectionPolicy.FORCE_DECLARED;
} else {
CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem();
if (nativeCrs == null) {
throw new ProcessException("The original data has no native CRS, "
+ "you need to specify the srs parameter");
} else {
try {
Integer code = CRS.lookupEpsgCode(nativeCrs, true);
if (code == null) {
throw new ProcessException("Could not find an EPSG code for data "
+ "native spatial reference system: " + nativeCrs);
} else {
targetSRSCode = "EPSG:" + code;
}
} catch (Exception e) {
throw new ProcessException("Failed to loookup an official EPSG code for "
+ "the source data native " + "spatial reference system", e);
}
}
}
}
// import the data into the target store
SimpleFeatureType targetType;
try {
targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo);
} catch (IOException e) {
throw new ProcessException("Failed to import data into the target store", e);
}
// now import the newly created layer into GeoServer
try {
cb.setStore(storeInfo);
// build the typeInfo and set CRS if necessary
FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName());
if (targetSRSCode != null) {
typeInfo.setSRS(targetSRSCode);
}
if (srsHandling != null) {
typeInfo.setProjectionPolicy(srsHandling);
}
// compute the bounds
cb.setupBounds(typeInfo);
// build the layer and set a style
LayerInfo layerInfo = cb.buildLayer(typeInfo);
if (targetStyle != null) {
layerInfo.setDefaultStyle(targetStyle);
}
catalog.add(typeInfo);
catalog.add(layerInfo);
return layerInfo.prefixedName();
} catch (Exception e) {
throw new ProcessException(
"Failed to complete the import inside the GeoServer catalog", e);
}
}
else if (coverage != null)
{
try {
final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store);
final File file = File.createTempFile(store, ".tif", directory);
((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() );
((CoverageStoreInfo)storeInfo).setType("GeoTIFF");
// check the target crs
CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem();
String targetSRSCode = null;
if (srs != null) {
try {
Integer code = CRS.lookupEpsgCode(srs, true);
if (code == null) {
throw new WPSException("Could not find a EPSG code for " + srs);
}
targetSRSCode = "EPSG:" + code;
} catch (Exception e) {
throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
}
} else {
// check we can extract a code from the original data
if (cvCrs == null) {
// data is geometryless, we need a fake SRS
targetSRSCode = "EPSG:4326";
srsHandling = ProjectionPolicy.FORCE_DECLARED;
srs = DefaultGeographicCRS.WGS84;
} else {
CoordinateReferenceSystem nativeCrs = cvCrs;
if (nativeCrs == null) {
throw new ProcessException("The original data has no native CRS, "
+ "you need to specify the srs parameter");
} else {
try {
Integer code = CRS.lookupEpsgCode(nativeCrs, true);
if (code == null) {
throw new ProcessException("Could not find an EPSG code for data "
+ "native spatial reference system: " + nativeCrs);
} else {
targetSRSCode = "EPSG:" + code;
srs = CRS.decode(targetSRSCode, true);
}
} catch (Exception e) {
throw new ProcessException("Failed to loookup an official EPSG code for "
+ "the source data native " + "spatial reference system", e);
}
}
}
}
MathTransform tx = CRS.findMathTransform(cvCrs, srs);
if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs))
{
coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST));
}
GeoTiffWriter writer = new GeoTiffWriter(file);
// setting the write parameters for this geotiff
final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(
DEFAULT_WRITE_PARAMS);
final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray(
new GeneralParameterValue[1]);
try {
writer.write(coverage, wps);
} finally {
try {
writer.dispose();
} catch (Exception e) {
// we tried, no need to fuss around this one
}
}
//add or update the datastore info
if ( add ) {
catalog.add( (CoverageStoreInfo)storeInfo );
}
else {
catalog.save( (CoverageStoreInfo)storeInfo );
}
cb.setStore( (CoverageStoreInfo)storeInfo );
GridCoverage2DReader reader = new GeoTiffReader(file);
if ( reader == null ) {
throw new ProcessException( "Could not aquire reader for coverage." );
}
// coverage read params
final Map customParameters = new HashMap();
/*String useJAIImageReadParam = "USE_JAI_IMAGEREAD";
if (useJAIImageReadParam != null) {
customParameters.put(AbstractGridFormat.USE_JAI_IMAGEREAD.getName().toString(), Boolean.valueOf(useJAIImageReadParam));
}*/
CoverageInfo cinfo = cb.buildCoverage( reader, customParameters );
//check if the name of the coverage was specified
if ( name != null ) {
cinfo.setName( name );
}
if ( !add ) {
//update the existing
CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() );
if ( existing == null ) {
//grab the first if there is only one
List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo );
if ( coverages.size() == 1 ) {
existing = coverages.get(0);
}
if ( coverages.size() == 0 ) {
//no coverages yet configured, change add flag and continue on
add = true;
}
else {
// multiple coverages, and one to configure not specified
throw new ProcessException( "Unable to determine coverage to configure.");
}
}
if ( existing != null ) {
cb.updateCoverage(existing,cinfo);
catalog.save( existing );
cinfo = existing;
}
}
//do some post configuration, if srs is not known or unset, transform to 4326
if ("UNKNOWN".equals(cinfo.getSRS())) {
//CoordinateReferenceSystem sourceCRS = cinfo.getBoundingBox().getCoordinateReferenceSystem();
//CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326", true);
//ReferencedEnvelope re = cinfo.getBoundingBox().transform(targetCRS, true);
cinfo.setSRS( "EPSG:4326" );
//cinfo.setCRS( targetCRS );
//cinfo.setBoundingBox( re );
}
//add/save
if ( add ) {
catalog.add( cinfo );
LayerInfo layerInfo = cb.buildLayer( cinfo );
if ( styleName != null && targetStyle != null ) {
layerInfo.setDefaultStyle( targetStyle );
}
//JD: commenting this out, these sorts of edits should be handled
// with a second PUT request on the created coverage
/*
String styleName = form.getFirstValue("style");
if ( styleName != null ) {
StyleInfo style = catalog.getStyleByName( styleName );
if ( style != null ) {
layerInfo.setDefaultStyle( style );
if ( !layerInfo.getStyles().contains( style ) ) {
layerInfo.getStyles().add( style );
}
}
else {
LOGGER.warning( "Client specified style '" + styleName + "'but no such style exists.");
}
}
String path = form.getFirstValue( "path");
if ( path != null ) {
layerInfo.setPath( path );
}
*/
boolean valid = true;
try {
if (!catalog.validate(layerInfo, true).isEmpty()) {
valid = false;
}
} catch (Exception e) {
valid = false;
}
layerInfo.setEnabled(valid);
catalog.add(layerInfo);
return layerInfo.prefixedName();
}
else {
catalog.save( cinfo );
LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName());
if ( styleName != null && targetStyle != null ) {
layerInfo.setDefaultStyle( targetStyle );
}
return layerInfo.prefixedName();
}
} catch (MalformedURLException e) {
throw new ProcessException( "URL Error", e );
} catch (IOException e) {
throw new ProcessException( "I/O Exception", e );
catch (Exception e) {
e.printStackTrace();
throw new ProcessException( "Exception", e );
}
return null;
} |
9821876_552 | @Override
public Double convert(String value, Class<? extends Double> type) {
if (isNullOrEmpty(value)) {
return null;
}
try {
return getNumberFormat().parse(value).doubleValue();
} catch (ParseException e) {
throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value));
}
} |
9854553_37 | public static String determineQualifiedName(String className) {
String readableClassName = StringUtils.removeWhitespace(className);
if (readableClassName == null) {
throw new IllegalArgumentException("readableClassName must not be null.");
} else if (readableClassName.endsWith("[]")) {
StringBuilder classNameBuffer = new StringBuilder();
while (readableClassName.endsWith("[]")) {
readableClassName = readableClassName.substring(0, readableClassName.length() - 2);
classNameBuffer.append("[");
}
String abbreviation = PRIMITIVE_MAPPING.get(readableClassName);
if (abbreviation == null) {
classNameBuffer.append("L").append(readableClassName).append(";");
} else {
classNameBuffer.append(abbreviation);
}
readableClassName = classNameBuffer.toString();
}
return readableClassName;
} |
9882334_4 | public HttpRequestBuilder post() {
return new RB(Method.POST);
} |
9884445_95 | @Override
public void handle(EntityMetaData metaData, Annotation annotation, Method method) {
Class<?> elementType = getElementType(method.getGenericReturnType());
CollectionMetaData collectionMetaData = new CollectionMetaData(metaData.getEntityClass(), getGetterName(method, false),
elementType, method.getReturnType(), isEntity(elementType));
metaData.addCollection(collectionMetaData);
} |
9897034_1 | public Beer findBeerById(final long id) {
return beerRepository.findOne(id);
} |
9909566_12 | public void write(final RpslObject object, final List<Tag> tags) throws IOException {
if (exportFilter.shouldExport(object)) {
final String filename = filenameStrategy.getFilename(object.getType());
if (filename != null) {
final Writer writer = getWriter(filename);
final RpslObject decoratedObject = decorationStrategy.decorate(object);
if (decoratedObject != null) {
writer.write('\n');
decoratedObject.writeTo(writer);
if (!tags.isEmpty()) {
writer.write('\n');
writer.write(new TagResponseObject(decoratedObject.getKey(), tags).toString());
}
}
}
}
} |
9910980_2 | public void execute() throws MojoExecutionException {
getLog().info("Running BPMN-MIWG test suite...");
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
try {
Collection<String> inputFolders = new LinkedList<String>();
if (!resources.isEmpty()) {
for (Resource resource : resources) {
String folderName = resource.getDirectory();
inputFolders.add(folderName);
}
}
Collection<AnalysisJob> jobs = BpmnFileScanner
.buildListOfAnalysisJobs(new StandardScanParameters(application,
null, inputFolders, outputDirectory.getCanonicalPath()));
AnalysisFacade.executeAnalysisJobs(jobs,
outputDirectory.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
//Generate the submissions.json
try (FileWriter out = new FileWriter(new File(outputDirectory, "submissions.json"))) {
JSONObject submissions = new RepoScanner().getSubmissionsFromRepo("bpmn-miwg/bpmn-miwg-test-suite");
submissions.writeJSONString(out);
} catch (Exception e) {
e.printStackTrace();
}
} |
9917257_48 | @Override
public Cluster create(CassandraServiceInfo serviceInfo,
ServiceConnectorConfig serviceConnectorConfig) {
Builder builder = Cluster.builder()
.addContactPoints(serviceInfo.getContactPoints().toArray(new String[0]))
.withPort(serviceInfo.getPort());
if (StringUtils.hasText(serviceInfo.getUsername())) {
builder.withCredentials(serviceInfo.getUsername(), serviceInfo.getPassword());
}
if (serviceConnectorConfig instanceof CassandraClusterConfig) {
CassandraClusterConfig config = (CassandraClusterConfig) serviceConnectorConfig;
if (config.getCompression() != null) {
builder.withCompression(config.getCompression());
}
builder.withPoolingOptions(config.getPoolingOptions());
builder.withSocketOptions(config.getSocketOptions());
builder.withQueryOptions(config.getQueryOptions());
builder.withNettyOptions(config.getNettyOptions());
builder.withLoadBalancingPolicy(config.getLoadBalancingPolicy());
builder.withReconnectionPolicy(config.getReconnectionPolicy());
builder.withRetryPolicy(config.getRetryPolicy());
if (config.getProtocolVersion() != null) {
builder.withProtocolVersion(config.getProtocolVersion());
}
if (!config.isMetricsEnabled()) {
builder.withoutMetrics();
}
if (!config.isJmxReportingEnabled()) {
builder.withoutJMXReporting();
}
}
return builder.build();
} |
9922054_3 | public void loadDataFromRpc() {
MyServiceAsync service = GWT.create(MyService.class);
service.getData(new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
data.setText(result);
}
@Override
public void onFailure(Throwable caught) {}
});
} |
9922058_6 | void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle)
throws UnableToCompleteException {
writeBindMethodHeader(writer, target.getQualifiedSourceName());
for (JMethod method : target.getInheritableMethods()) {
EventHandler annotation = method.getAnnotation(EventHandler.class);
if (annotation != null) {
writeHandlerForBindMethod(annotation, writer, method, typeOracle);
}
}
writeBindMethodFooter(writer);
} |
9941578_49 | NetworkStatus retrieveNetworkStatus() {
if (merlinsBeard.isConnected()) {
return NetworkStatus.newAvailableInstance();
} else {
return NetworkStatus.newUnavailableInstance();
}
} |
9949199_0 | @NotNull
@Override
public AuthorScore score(BookImportContext context) {
try {
File file = context.getFile();
String dirName = file.getParentFile().getName();
String[] rawTokens = splitAuthorPairTokens(dirName);
String[] tokens = trim(rawTokens);
List<Author> authors = new ArrayList<>();
for (String token : tokens) {
String[] rawNameTokens = splitAuthorNameTokens(token);
String[] nameTokens = trim(rawNameTokens);
if (nameTokens.length == 2) {
Name name = new PersonNameCategorizer().categorize(nameTokens);
Author author = new Author(name.getFirstName(), name.getLastName());
authors.add(author);
}
}
return new AuthorScore(authors, ParentDirectoryAuthorScoreStrategy.class);
} catch (Exception e) {
log.error("Could not determine score for {}", context);
return new AuthorScore(Collections.<Author>emptyList(), ParentDirectoryAuthorScoreStrategy.class);
}
} |
9965237_0 | public static Buffer decompress(byte[] in) {
return decompress(in, 0, in.length, null);
} |
10016717_11 | @PreAuthorize("hasPermission(#spanner, 'owner')")
public void update(Spanner spanner) {
restTemplate.put("/{0}", spanner, spanner.getId());
} |
10035739_213 | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" ");
buffer.append("(");
boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().size() == 1;
boolean isPrimaryKeyAutoIncrement = false;
Iterator<String> columnIterator = statement.getColumns().iterator();
while (columnIterator.hasNext()) {
String column = columnIterator.next();
buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column));
buffer.append(" ").append(statement.getColumnTypes().get(column));
AutoIncrementConstraint autoIncrementConstraint = null;
for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
autoIncrementConstraint = currentAutoIncrementConstraint;
break;
}
}
boolean isAutoIncrementColumn = autoIncrementConstraint != null;
boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null
&& statement.getPrimaryKeyConstraint().getColumns().contains(column);
isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement
|| isPrimaryKeyColumn && isAutoIncrementColumn;
if ((database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyColumn &&
isAutoIncrementColumn) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
buffer.append(" PRIMARY KEY AUTOINCREMENT");
if (statement.getDefaultValue(column) != null) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column));
}
buffer.append(" DEFAULT ");
buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database));
}
if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) {
// TODO: check if database supports auto increment on non primary key column
if (database.supportsAutoIncrement()) {
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
} else {
LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName())));
}
}
if (statement.getNotNullColumns().contains(column)) {
buffer.append(" NOT NULL");
} else {
if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) {
if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) {
//don't append null
} else {
buffer.append(" NULL");
}
}
}
if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) {
buffer.append(" PRIMARY KEY");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
// TODO informixdb
if (!( (database instanceof SQLiteDatabase) &&
isSinglePrimaryKeyColumn &&
isPrimaryKeyAutoIncrement) &&
!((database instanceof InformixDatabase) &&
isSinglePrimaryKeyColumn
)) {
// ...skip this code block for sqlite if a single column primary key
// with an autoincrement constraint exists.
// This constraint is added after the column type.
if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) {
if (!(database instanceof InformixDatabase)) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if (database instanceof OracleDatabase &&
statement.getPrimaryKeyConstraint().getTablespace() != null) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) {
referencesString = database.getDefaultSchemaName()+"."+referencesString;
}
buffer.append(" FOREIGN KEY (")
.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
.append(") REFERENCES ")
.append(referencesString);
if (fkConstraint.isDeleteCascade()) {
buffer.append(" ON DELETE CASCADE");
}
if ((database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
if (fkConstraint.isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (fkConstraint.isDeferrable()) {
buffer.append(" DEFERRABLE");
}
buffer.append(",");
}
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(",");
}
if (constraints != null && constraints.getCheck() != null) {
buffer.append(constraints.getCheck()).append(" ");
}
}
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
if (StringUtils.trimToNull(tablespace) != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase) {
buffer.append(" ON ").append(tablespace);
} else if (database instanceof DB2Database) {
buffer.append(" IN ").append(tablespace);
} else {
buffer.append(" TABLESPACE ").append(tablespace);
}
}
if (statement.getTablespace() != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
sql += " ON " + statement.getTablespace();
} else if (database instanceof DB2Database || database instanceof InformixDatabase) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
return new Sql[] {
new UnparsedSql(sql)
};
} |
10040960_712 | public ListenableFuture<Image> createImage(final ImageTemplate template) {
ListenableFuture<Image> future = delegate.createImage(template);
// Populate the default image credentials, if missing
future = Futures.transform(future, new Function<Image, Image>() {
@Override
public Image apply(Image input) {
if (input.getDefaultCredentials() != null) {
return input;
}
// If the image has been created by cloning a node, then try to
// populate the known node credentials as the default image
// credentials
if (template instanceof CloneImageTemplate) {
final CloneImageTemplate cloneImageTemplate = (CloneImageTemplate) template;
Credentials nodeCredentials = credentialStore.get("node#" + cloneImageTemplate.getSourceNodeId());
if (nodeCredentials != null) {
logger.info(">> Adding node(%s) credentials to image(%s)...", cloneImageTemplate.getSourceNodeId(),
cloneImageTemplate.getName());
return ImageBuilder.fromImage(input)
.defaultCredentials(LoginCredentials.fromCredentials(nodeCredentials)).build();
}
}
// If no credentials are known for the node, populate the default
// credentials using the defined strategy
logger.info(">> Adding default image credentials to image(%s)...", template.getName());
return addDefaultCredentialsToImage.apply(input);
}
});
Futures.addCallback(future, new FutureCallback<Image>() {
@Override
public void onSuccess(Image result) {
imageCache.registerImage(result);
}
@Override
public void onFailure(Throwable t) {
}
});
return future;
} |
10057936_5 | @NonNull @Override public Request transformRequest(@NonNull Request request) {
if (request.resourceId != 0) {
return request; // Don't transform resource requests.
}
Uri uri = request.uri;
if (uri == null) {
throw new IllegalArgumentException("Null uri passed to " + getClass().getCanonicalName());
}
String scheme = uri.getScheme();
if (!"https".equals(scheme) && !"http".equals(scheme)) {
return request; // Thumbor only supports remote images.
}
// Only transform requests that have resizes unless `alwaysTransform` is set.
if (!request.hasSize() && !alwaysTransform) {
return request;
}
// Start building a new request for us to mutate.
Request.Builder newRequest = request.newBuilder();
// Create the url builder to use.
ThumborUrlBuilder urlBuilder = thumbor.buildImage(uri.toString());
// Resize the image to the target size if it has a size.
if (request.hasSize()) {
urlBuilder.resize(request.targetWidth, request.targetHeight);
newRequest.clearResize();
}
// If the center inside flag is set, perform that with Thumbor as well.
if (request.centerInside) {
urlBuilder.fitIn();
newRequest.clearCenterInside();
}
// If the Android version is modern enough use WebP for downloading.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
urlBuilder.filter(format(ImageFormat.WEBP));
}
// Update the request with the completed Thumbor URL.
newRequest.setUri(Uri.parse(urlBuilder.toUrl()));
return newRequest.build();
} |
10062583_26 | public static Key.Builder makeKey(Object... elements) {
Key.Builder key = Key.newBuilder();
PartitionId partitionId = null;
for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) {
PathElement.Builder pathElement = PathElement.newBuilder();
Object element = elements[pathIndex];
if (element instanceof Key) {
Key subKey = (Key) element;
if (partitionId == null) {
partitionId = subKey.getPartitionId();
} else if (!partitionId.equals(subKey.getPartitionId())) {
throw new IllegalArgumentException("Partition IDs did not match, found: "
+ partitionId + " and " + subKey.getPartitionId());
}
key.addAllPath(((Key) element).getPathList());
// We increment by 2, but since we got a Key argument we're only consuming 1 element in this
// iteration of the loop. Decrement the index so that when we jump by 2 we end up in the
// right spot.
pathIndex--;
} else {
String kind;
try {
kind = (String) element;
} catch (ClassCastException e) {
throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass());
}
pathElement.setKind(kind);
if (pathIndex + 1 < elements.length) {
Object value = elements[pathIndex + 1];
if (value instanceof String) {
pathElement.setName((String) value);
} else if (value instanceof Long) {
pathElement.setId((Long) value);
} else if (value instanceof Integer) {
pathElement.setId((Integer) value);
} else if (value instanceof Short) {
pathElement.setId((Short) value);
} else {
throw new IllegalArgumentException(
"Expected string or integer, got: " + value.getClass());
}
}
key.addPath(pathElement);
}
}
if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) {
key.setPartitionId(partitionId);
}
return key;
} |
10064418_31 | public static Builder builder() {
return new Builder();
} |
10065023_0 | public int execute(FlowContext ctx) throws FlowExecutionException {
String name = (String) ctx.get(IN_NAME);
String message = "Hello World! ";
if (name != null) {
message += name;
}
logger.debug("Message: {}", message);
ctx.put(OUT_MESSAGE, message);
return NEXT;
} |
10075325_3 | public void updateStatusError(String errorMessage) {
StatusType status = StatusType.Factory.newInstance();
net.opengis.ows.x11.ExceptionReportDocument.ExceptionReport excRep = status
.addNewProcessFailed().addNewExceptionReport();
excRep.setVersion("1.0.0");
ExceptionType excType = excRep.addNewException();
excType.addNewExceptionText().setStringValue(errorMessage);
excType.setExceptionCode(ExceptionReport.NO_APPLICABLE_CODE);
updateStatus(status);
} |
10079780_0 | public static ShellMode from(String... arguments) {
if (runInBatchMode(arguments)) {
return new BatchMode(extractCommand(arguments));
}
return new InteractiveMode();
} |
10081109_107 | public Rollup getRollup() {
return rollup;
} |
10085184_0 | public static List<RemoteRepository> getRemoteRepositories(MavenContainer container, Settings settings)
{
Set<RemoteRepository> remoteRepos = new HashSet<>();
remoteRepos.addAll(container.getEnabledRepositoriesFromProfile(settings));
// central repository is added if there is no central mirror
String centralRepoURL = getCentralMirrorURL(settings).orElse(MAVEN_CENTRAL_REPO);
remoteRepos.add(convertToMavenRepo("central", centralRepoURL, settings));
return new ArrayList<>(remoteRepos);
} |
10113030_56 | public GoogleMap getMap() {
return mMap;
} |
10116915_0 | @SuppressWarnings("unchecked")
public void setFirst(@Nonnull ExternalTaskExecutionInfo task) {
insertElementAt(task, 0);
for (int i = 1; i < size(); i++) {
if (task.equals(getElementAt(i))) {
remove(i);
break;
}
}
ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
} |
10144081_34 | public <T> T nextObject(final Class<T> type) {
return doPopulateBean(type, new RandomizationContext(type, parameters));
} |
10172073_6 | @Override
public boolean isCounterExample(A hypothesis, Iterable<? extends I> inputs, @Nullable D output) {
return EmptinessOracle.super.isCounterExample(hypothesis, inputs, output);
} |
10189028_10 | public List<ConsistentReportDO> queryConsistentReport(Map params) {
return consistentReportDao.queryConsistentReport(params);
} |
10192655_5 | public static SushiEvent generateEventFromXML(String filePath) throws XMLParsingException {
Document doc = readXMLDocument(filePath);
return generateEvent(doc, null);
} |
10195984_2 | public static <A extends Annotation,I> Index<A,I> load(Class<A> annotation, Class<I> instanceType) throws IllegalArgumentException {
return load(annotation, instanceType, Thread.currentThread().getContextClassLoader());
} |
10227537_1 | public static void configureAuthentication(String role) {
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(role);
Authentication authentication = new UsernamePasswordAuthenticationToken(
USERNAME,
role,
authorities
);
SecurityContextHolder.getContext().setAuthentication(authentication);
} |
10230369_33 | public static <T> ImmutableList<T> load(Class<? extends T> service, ClassLoader loader) {
String resourceName = "META-INF/services/" + service.getName();
List<URL> resourceUrls;
try {
resourceUrls = Collections.list(loader.getResources(resourceName));
} catch (IOException e) {
throw new ServiceConfigurationError("Could not look up " + resourceName, e);
}
ImmutableList.Builder<T> providers = ImmutableList.builder();
for (URL resourceUrl : resourceUrls) {
try {
providers.addAll(providersFromUrl(resourceUrl, service, loader));
} catch (IOException e) {
throw new ServiceConfigurationError("Could not read " + resourceUrl, e);
}
}
return providers.build();
} |
10262572_39 | @Nullable
public static String getCleanContentType (@Nullable final String sContentType)
{
final ContentType aCT = parseContentType (sContentType);
return aCT != null ? aCT.toString () : null;
} |
10264172_22 | @Override
public double evaluate(final double[] x) {
if (x.length > 1) {
throw new AIFHError("The inverse squared link function can only accept one parameter.");
}
return -Math.pow(x[0], -2);
} |
10269178_27 | public ScenarioDiffInfo compare(final String baseUseCaseName, final String baseScenarioName) {
this.baseUseCaseName = baseUseCaseName;
this.baseScenarioName = baseScenarioName;
final List<Step> baseSteps = loadSteps(parameters.getBaseBranchName(), parameters.getBaseBuildName());
this.comparisonSteps = loadSteps(parameters.getComparisonConfiguration().getComparisonBranchName(),
parameters.getComparisonConfiguration().getComparisonBuildName());
final List<StepLink> baseStepLinks = stepAndPagesAggregator.calculateStepLinks(baseSteps, baseUseCaseName,
baseScenarioName);
final List<StepLink> comparisonStepLinks = stepAndPagesAggregator.calculateStepLinks(comparisonSteps,
baseUseCaseName, baseScenarioName);
final ScenarioDiffInfo scenarioDiffInfo = new ScenarioDiffInfo(baseScenarioName);
calculateDiffInfo(baseStepLinks, comparisonStepLinks, scenarioDiffInfo);
LOGGER.info(getLogMessage(scenarioDiffInfo,
"Scenario " + parameters.getBaseBranchName() + "/" + parameters.getBaseBuildName() + "/" + baseUseCaseName + "/" + baseScenarioName));
return scenarioDiffInfo;
} |
10277647_3 | static void parse(final String instructions,
final Set<PosixFilePermission> toAdd,
final Set<PosixFilePermission> toRemove) {
for (final String instruction : COMMA.split(instructions)) {
parseOne(instruction, toAdd, toRemove);
}
} |
10285025_16 | public static Class<?> getElementsClassOf(Class<?> clazz) {
if (clazz.isArray()) {
return clazz.getComponentType();
}
if (Collection.class.isAssignableFrom(clazz)) {
// TODO check for annotation
logger.warn("In Java its not possible to discover de Generic type of a collection like: {}", clazz);
return Object.class;
}
return clazz;
} |
10288113_13 | public boolean hasBackupDB() {
return dbProvider.getDBFile() != null;
} |
10288749_43 | public static void notEmpty(String string, String errorMessage) {
if (string.isEmpty()) {
throw new IllegalArgumentException(errorMessage);
}
} |
10294926_3 | void entryptPassword(User user, String plainPassword) {
byte[] salt = Digests.generateSalt(SALT_SIZE);
user.setSalt(Encodes.encodeHex(salt));
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
user.setPassword(Encodes.encodeHex(hashPassword));
} |
10300045_0 | @Override
public int compare(EventAdapter.Item event1, EventAdapter.Item event2) {
if (event1.getEvent().getStart() == null) {
if (event2.getEvent().getStart() == null) {
return 0;
} else {
return 1;
}
} else if (event2.getEvent().getStart() == null) {
return -1;
} else {
return event1.getEvent().getStart().compareTo(event2.getEvent().getStart());
}
} |
10311319_20 | @Override
public synchronized void close() throws IOException {
if (this.fileChannel.isOpen()) {
long start = System.nanoTime();
this.fileChannel.close();
this.fileLifecycleListener.onEvent(EventType.CLOSE, this.path, System.nanoTime() - start);
}
} |
10325227_3 | public void handle(ServiceDescriptorProto service) throws IOException {
ImmutableList.Builder<ServiceHandlerData.Method> methods = ImmutableList.builder();
for (MethodDescriptorProto method : service.getMethodList()) {
ServiceHandlerData.Method methodData = new ServiceHandlerData.Method(
method.getName(),
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, method.getName()),
types.lookup(method.getInputType()).toString(),
types.lookup(method.getOutputType()).toString());
methods.add(methodData);
}
String fullName = Joiner.on('.').skipNulls().join(protoPackage, service.getName());
ServiceHandlerData.Service serviceData = new ServiceHandlerData.Service(
service.getName(), fullName, methods.build());
ServiceHandlerData data = new ServiceHandlerData(javaPackage, multipleFiles, serviceData);
String template = Resources.toString(Resources.getResource(this.getClass(),
"service_class.mvel"), Charsets.UTF_8);
String serviceFile = (String) TemplateRuntime.eval(template,
ImmutableMap.<String, Object>of("handler", data));
CodeGeneratorResponse.Builder response = CodeGeneratorResponse.newBuilder();
CodeGeneratorResponse.File.Builder file = CodeGeneratorResponse.File.newBuilder();
file.setContent(serviceFile);
file.setName(javaPackage.replace('.', '/') + '/' + service.getName() + ".java");
if (!multipleFiles) {
file.setName(javaPackage.replace('.', '/') + '/' + outerClassName + ".java");
file.setInsertionPoint("outer_class_scope");
}
response.addFile(file);
response.build().writeTo(output);
} |
10329015_9 | public static PointArray newInstance(final long length) {
return StructuredArray.newInstance(PointArray.class, Point.class, length);
} |
10329619_35 | public static Map<String, String> decodeOAuthHeader(String header) {
Map<String, String> headerValues = new HashMap<String, String>();
if (header != null) {
Matcher m = OAUTH_HEADER.matcher(header);
if (m.matches()) {
if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) {
for (String nvp : m.group(2).split("\\s*,\\s*")) {
m = NVP.matcher(nvp);
if (m.matches()) {
String name = decodePercent(m.group(1));
String value = decodePercent(m.group(2));
headerValues.put(name, value);
}
}
}
}
}
return headerValues;
} |
10354997_2 | @Override
public DetectedLanguage classify(CharSequence str, boolean normalizeConfidence) {
// Compute the features and apply NB
reset();
append(str);
return classify(normalizeConfidence);
} |
10359213_76 | public String getHttpEndpoint() {
return "http://" + getMyHostname() + ":" + httpPort;
} |
10361643_1246 | @Override
public String nameFromSimpleTypeRestriction(final QName simpleType, final QName base) {
return nameFromSchemaTypeName(simpleType).concat(" restricts ").concat(nameFromSchemaTypeName(base));
} |
10367500_9 | public final String getPortfolioReview() {
final StringBuilder sb = new StringBuilder();
sb.append("<table class=\"shareValueTableDetails\">");
for (final Equity equity : getEquities()) {
sb.append("<tr><td width=200px><b>")
.append(equity.getCurrentName())
.append("</b></td><td width=180px>")
.append(equity.getQuantity())
.append(" * ")
.append(equity.getCompany().getQuote());
if (equity.getCompany().getCurrency() != getCurrency()) {
sb.append(" * ").append(getCurrency().getParity(equity.getCompany().getCurrency()));
}
sb.append("</td><td>").append(equity.getValue()).append(" (").append(getCurrency().getCode()).append(")</td></tr>");
}
sb.append("<tr><td colspan=3><b>Liquidity:</b> ").append(getLiquidity()).append(" (").append(getCurrency().getCode()).append(")</td></tr>");
sb.append("<tr><td colspan=3><b>Total:</b> ").append(new BigDecimal(getTotalValue(), mathContext).doubleValue()).append(" (").append(getCurrency().getCode()).append(")</td></tr>");
sb.append("</table>");
return sb.toString();
} |
10385460_0 | @Override
public Integer getObject() {
try {
int time = new java.util.Date().hashCode();
int ipAddress = InetAddress.getLocalHost().hashCode();
int rand = metaPrng.nextInt();
int seed = (ipAddress & 0xffff) |
((time & 0x00ff) << 32) | (rand & 0x0f000000);
logger.info("seed = " + seed);
return seed;
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
} |
10400052_81 | public static boolean empty(Object[] array) {
return array == null || array.length == 0;
} |
10410163_2 | public static Offset at(HorizontalOffset horizontal, VerticalOffset vertical) {
return new InternalOffsets.OffsetImpl(horizontal, vertical);
} |
10422484_9 | public static Map<String,String> processResults(String responseBody) {
JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627);
try {
JSONObject object = (JSONObject)parser.parse(responseBody);
Object results = object.get("docs");
if(results!=null && results instanceof JSONArray) {
return parseDocs((JSONArray)results);
}else {
return Collections.EMPTY_MAP;
}
} catch (Exception e){
return Collections.EMPTY_MAP;
}
} |
10429628_1 | @Override
public int nextInt(int n) {
if (n == 5) {
return getNextValueOf(fives, indexInFives++);
} else if (n == 9) {
return getNextValueOf(nines, indexInNines++);
}
throw new UnsupportedOperationException("not expected invocation of nextInt(" + n + ")");
} |
10445803_57 | public static boolean empty(String[] arr) {
if (arr == null || arr.length == 0) {
return true;
}
for (String s : arr) {
if (s != null && !"".equals(s)) {
return false;
}
}
return true;
} |
10448161_121 | public static float[] scale(float[] a1, float b) {
validateArray(a1);
float[] mul = new float[a1.length];
for (int i = 0; i < a1.length; i++) {
mul[i] = a1[i] * b;
}
return mul;
} |
10455939_33 | public double getNDGC() {
if (observations.isEmpty()) {
return 0.0;
}
TIntDoubleMap actual = new TIntDoubleHashMap();
for (KnownSim ks : known.getMostSimilar()) {
actual.put(ks.wpId2, ks.similarity);
}
int ranks[] = new int[observations.size()];
double scores[] = new double[observations.size()];
double s = 0.0;
for (int i = 0; i < observations.size(); i++) {
Observation o = observations.get(i);
double k = (o.rank == 1) ? 1 : Math.log(o.rank + 1);
s += actual.get(o.id) / k;
scores[i] = actual.get(o.id);
ranks[i] = o.rank;
}
Arrays.sort(ranks);
Arrays.sort(scores);
ArrayUtils.reverse(scores);
double t = 0;
for (int i = 0; i < scores.length; i++) {
double k = (ranks[i] == 1) ? 1 : Math.log(ranks[i] + 1);
t += scores[i] / k;
}
return s / t;
} |
10472733_48 | public Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid) {
Encounter encounter = new Encounter();
encounter.setProvider(getDummyProvider(providerId));
encounter.setUuid(getEncounterUUID());
encounter.setLocation(getDummyLocation(locationId));
encounter.setEncounterType(getDummyEncounterType(formUuid));
encounter.setEncounterDatetime(encounterDateTime);
encounter.setUserSystemId(userSystemId);
encounter.setFormDataUuid(formDataUuid);
encounter.setPatient(patient);
return encounter;
} |
10472781_49 | public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod)
{
Method exactMethod = extractMethod(clazz, sourceMethod);
if (exactMethod == null)
{
String methodName = sourceMethod.getName();
Class<?>[] parameterTypes = sourceMethod.getParameterTypes();
for (Method method : clazz.getMethods())
{
if (method.getName().equals(methodName) &&
allSameType(method.getParameterTypes(), parameterTypes))
{
return method;
}
}
return null;
}
else
{
return exactMethod;
}
} |
10476504_0 | public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate,
String authorization) {
validateSubscription(pluginReqisterQuery);
checkAuthServiceAvailable();
return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> {
JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization);
JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO);
return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED);
});
} |
10503489_2 | @Override
public void run(TaskMonitor taskMonitor) throws Exception {
taskMonitor.setTitle("Loading InCites Network ...");
this.locationMap = new IncitesInstitutionLocationMap();
OPCPackage pkg;
try {
MonitoredFileInputStream fileInputStream = new MonitoredFileInputStream(file, taskMonitor, "Parsing InCites XLSX ...");
pkg = OPCPackage.open(fileInputStream);
XSSFWorkbook workbook = new XSSFWorkbook(pkg);
int numSheets = workbook.getNumberOfSheets();
this.parseFacultyXLSX(pkg, numSheets);
this.parsePubsXLSX(pkg, numSheets);
this.calculateSummary();
if (getIgnoredRows() >= 1) {
logger.log(Level.WARNING, "Some rows could not be parsed.");
}
if (getIdentifiedFacultyList().size() == 0) {
logger.log(Level.WARNING, "Unable to identify faculty. Please verify that InCites data file is valid");
}
ArrayList<Publication> pubList = getPubList();
if (pubList == null) {
//this.appManager.getUserPanelRef().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
logger.log(Level.SEVERE, "Invalid file. This InCites file is corrupt.");
return;
}
// Add summary attributes
socialNetwork.setPublications(getPubList());
socialNetwork.setFaculty(getFacultySet());
socialNetwork.setUnidentifiedFaculty(getUnidentifiedFacultyList());
socialNetwork.setUnidentified_faculty(getUnidentifiedFacultyString());
// Add info to social network map(s)
socialNetwork.getAttrMap().put(NodeAttribute.DEPARTMENT.toString(), getDepartmentName());
} catch (InvalidFormatException e) {
logger.log(Level.SEVERE, "Exception occurred", e);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception occurred", e);
}
} |
10514209_0 | public static boolean isOdd(int number) {
return number % 2 == 1;
} |
10522064_9 | @Override
public ServiceResponse[] getRaw(String attribute)
throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException {
if (!this.isConnected()) {
throw new ServiceNotAvailableException();
}
// Retrieve attribute from service
AttributeMap attributeMap = new AttributeMap();
String genericAttribute = attributeMap.getAttribute(attribute);
Map<String, String> ids = attributeMap.extractIds(genericAttribute,
attribute);
// Retrieve all users attending an event
// Attribute: /events/@me/{eid}/@all
if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) {
String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all";
ServiceResponse[] r = new ServiceResponse[1];
r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url));
return r;
}
// Retrieve event details
// Attribute: /events/@me/{eid}
else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) {
String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info";
ServiceResponse[] r = new ServiceResponse[1];
r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url));
return r;
}
// Retrieve event details
// Attribute: /events/@all
else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) {
String url = "/ameticevents/@all";
ServiceResponse[] r = new ServiceResponse[1];
r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url));
return r;
}
// No action found - throw an exception.
throw new AttributeNotSupportedException(attribute, this);
} |
10522120_5116 | @Override
public boolean accepts(final Diagram diagram) {
return this.definitionSetId.equals(diagram.getMetadata().getDefinitionSetId());
} |
10532531_3 | @Override
public GuacamoleInstruction readInstruction() throws GuacamoleException {
GuacamoleInstruction filteredInstruction;
// Read and filter instructions until no instructions are dropped
do {
// Read next instruction
GuacamoleInstruction unfilteredInstruction = reader.readInstruction();
if (unfilteredInstruction == null)
return null;
// Apply filter
filteredInstruction = filter.filter(unfilteredInstruction);
} while (filteredInstruction == null);
return filteredInstruction;
} |
10548179_61 | public double computeRangeResolution(double pixel) {
return ((rsr2x / 2.) / rangeBandwidth) * (computeDeltaRange(pixel) / mlRg);
} |
10550221_4 | @Override
public int value()
{
if (mFlag != Notification.DEFAULT_VIBRATE && mFlag != Notification.DEFAULT_SOUND && mFlag != Notification.DEFAULT_LIGHTS)
{
throw new IllegalArgumentException("Notification signal flag is not valid: " + mFlag);
}
return mEnable ? addFlag(mOriginal.value(), mFlag) : removeFlag(mOriginal.value(), mFlag);
} |
10553586_1 | public boolean isEmpty() {
return this.connection == null && this.developerConnection == null && this.tag == null && this.url == null;
} |
10564509_25 | } |
10597460_1979 | public static void registerMBeans(
net.sf.ehcache.CacheManager cacheManager,
MBeanServer mBeanServer,
boolean registerCacheManager,
boolean registerCaches,
boolean registerCacheConfigurations,
boolean registerCacheStatistics) throws CacheException {
ManagementService registry = new ManagementService(cacheManager,
mBeanServer,
registerCacheManager,
registerCaches,
registerCacheConfigurations,
registerCacheStatistics);
registry.init();
} |
10605000_6 | public T getContent() {
return content;
} |
10609316_42 | @Override
public String getResourceType() {
return "reportUnit";
} |
10609318_30 | @Override
public Map<String, String> getStreamMetadata() {
if(!closed) {
throw new IllegalStateException("Stream must be closed before getting metadata");
}
Map<String,String> metadata = new HashMap<String, String>();
long compSize = compressedSize.getByteCount();
long uncompSize = uncompressedSize.getByteCount();
String compRatioString = String.format("%.1f%%", 100.0 - (compSize*100.0/uncompSize));
metadata.put(TransformConstants.META_COMPRESSION_UNCOMP_SIZE, ""+uncompSize);
metadata.put(TransformConstants.META_COMPRESSION_COMP_SIZE, ""+compSize);
metadata.put(TransformConstants.META_COMPRESSION_COMP_RATIO, ""+compRatioString);
metadata.put(TransformConstants.META_COMPRESSION_UNCOMP_SHA1,
KeyUtils.toHexPadded(digest));
return metadata;
} |
10610797_3 | public static String getPrimitiveTypeNameFromWrapper(Class<?> type) {
return wrapperTypes.get(type);
} |
10617959_1 | static int positionToChapterIndex(int position) throws IllegalArgumentException {
if (position < 0) {
throw new IllegalArgumentException("Invalid position: " + position);
}
final int bookCount = Bible.getBookCount();
for (int bookIndex = 0; bookIndex < bookCount; ++bookIndex) {
final int chapterCount = Bible.getChapterCount(bookIndex);
if (position < chapterCount) {
return position;
}
position -= chapterCount;
}
throw new IllegalArgumentException("Invalid position: " + position);
} |
10624930_17 | public Criteria getCriteria() {
return criteria;
} |
10637895_21 | public static Builder newBuilder(String keyClassName, String valueClassName,
String partitionerClassName, Configuration partitionerConf) {
return new Builder(keyClassName, valueClassName, partitionerClassName, partitionerConf);
} |
10646587_49 | public void onOpen(final SockJsSessionContext session) {
setState(State.OPEN);
service.onOpen(session);
updateTimestamp();
} |
10663360_43 | public byte[] getAndClear() {
writeLock.lock();
try {
size = 0;
return poolDigest.digest();
} finally {
writeLock.unlock();
}
} |
10667695_14 | public static BuildFromFile file() {
return new DatasetBuilder().new BuildFromFile();
} |
10676833_32 | public XQDataSource getDataSource() throws Exception {
XQueryDataSourceType dataSourceType = config.getDataSourceType();
XQDataSource dataSource = getXQDataSource(dataSourceType, config);
if (dataSourceType.connectionPropertiesAreSupported()) {
if (config.getHost() != null && config.getHost().length() > 0) {
dataSource.setProperty(SERVER_NAME, config.getHost());
}
if (config.getPort() != null && config.getPort().length() > 0) {
dataSource.setProperty(PORT, config.getPort());
}
if (config.getDatabaseName() != null && config.getDatabaseName().length() > 0) {
dataSource.setProperty(DATABASE_NAME, config.getDatabaseName());
}
}
return dataSource;
} |
10692925_14 | public static String status() {
StringBuilder sb = new StringBuilder(512);
sb.append("\r\nreading_mcq(yangwm,true):\t");
sb.append(IS_ALL_READ.get());
return sb.toString();
} |
10711220_16 | public Request clearIndexAsync(@Nullable CompletionHandler completionHandler) {
return clearIndexAsync(/* requestOptions: */ null, completionHandler);
} |
10726093_2 | private String getRootProjectName(String name){
f(name.contains("--")){
String type = null;
if(name.endsWith("column"))
type = "column";
else if(name.endsWith("row"))
type = "row";
String subset = name.substring(name.indexOf("--"), name.length()-type.length());
name = name.replace(subset, "");
eturn name;
} |
10737956_21 | public void init() throws InternalServiceException {
sensorPluginLoader = ServiceLoader.load(SensorInstanceFactory.class);
if (isMissingRepository()) {
throw new IllegalStateException("SensorInstanceProvider misses a repository.");
}
Iterable<SensorConfiguration> configs = sensorConfigurationRepository.getSensorConfigurations();
for (SensorConfiguration sensorConfiguration : configs) {
sensorInstances.add(initSensorInstance(sensorConfiguration));
}
LOGGER.info("Initialised {} with #{} sensor configuration(s).", getClass().getSimpleName(), sensorInstances.size());
} |
10741477_39 | public final SortedSet<Long> getTimestamps() {
SortedSet<Long> result = new TreeSet<>(bucketList.keySet());
return result;
} |
10746583_101 | public static RoaringBitmap xor(RoaringBitmap... bitmaps) {
return groupByKey(bitmaps)
.entrySet()
.parallelStream()
.collect(XOR);
} |
10761704_2 | public static Matcher<DateTime> onDayOfMonth(Matcher<Integer> dayMatcher)
{
return new DayOfMonthMatcher(dayMatcher);
} |
10762348_1 | @NotNull
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet();
} |
10772221_0 | @Deprecated
public static void export(Module module, List<Class<?>> classesToConvert) {
new StaticFieldExporter(module, null).export(classesToConvert);
} |
10785687_16 | public boolean isSimpleNumber() {
return isSimpleNumber;
} |
10806441_91 | public boolean isHotReloadMode() {
return hotReloadMode;
} |
10820374_12 | public Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context)
{
return performAction(userId, mailboxAddress, context, mailbox -> {
final MailboxData mailboxData = new MailboxData(mailbox);
return ApiResults.ok().render(mailboxData);
});
} |
10828921_31 | @Override
public Optional<String> getRequestApiClientHostname() {
return Optional.ofNullable(this.requestApiClientHostname);
} |
10837431_9 | public int getPlace_id() {
return place_id;
} |
10856630_69 | public void addTemplateRootDir(File file) {
templateRootDirs.add(file);
} |
10866521_11 | public PropertyStore ff4jStore() {
if (ff4jStore == null) {
throw new IllegalStateException("Cannot load property from store as not initialized please set 'ff4jStore' property");
}
return getFf4jStore();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.