code
stringlengths
73
34.1k
label
stringclasses
1 value
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<AccountingDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<AccountingDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal); }
java
@Override public CopticDate date(int prolepticYear, int month, int dayOfMonth) { return CopticDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<CopticDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<CopticDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<CopticDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<CopticDate>) super.zonedDateTime(temporal); }
java
private YearQuarter with(int newYear, Quarter newQuarter) { if (year == newYear && quarter == newQuarter) { return this; } return new YearQuarter(newYear, newQuarter); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<BritishCutoverDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<BritishCutoverDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal); }
java
private static int weekRange(int weekBasedYear) { LocalDate date = LocalDate.of(weekBasedYear, 1, 1); // 53 weeks if year starts on Thursday, or Wed in a leap year if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) { return 53; } return 52; }
java
private YearWeek with(int newYear, int newWeek) { if (year == newYear && week == newWeek) { return this; } return of(newYear, newWeek); }
java
void register(long mjDay, int leapAdjustment) { if (leapAdjustment != -1 && leapAdjustment != 1) { throw new IllegalArgumentException("Leap adjustment must be -1 or 1"); } Data data = dataRef.get(); int pos = Arrays.binarySearch(data.dates, mjDay); int currentAdj = pos > 0 ? data.offsets[pos] - data.offsets[pos - 1] : 0; if (currentAdj == leapAdjustment) { return; // matches previous definition } if (mjDay <= data.dates[data.dates.length - 1]) { throw new IllegalArgumentException("Date must be after the last configured leap second date"); } long[] dates = Arrays.copyOf(data.dates, data.dates.length + 1); int[] offsets = Arrays.copyOf(data.offsets, data.offsets.length + 1); long[] taiSeconds = Arrays.copyOf(data.taiSeconds, data.taiSeconds.length + 1); int offset = offsets[offsets.length - 2] + leapAdjustment; dates[dates.length - 1] = mjDay; offsets[offsets.length - 1] = offset; taiSeconds[taiSeconds.length - 1] = tai(mjDay, offset); Data newData = new Data(dates, offsets, taiSeconds); if (dataRef.compareAndSet(data, newData) == false) { throw new ConcurrentModificationException("Unable to update leap second rules as they have already been updated"); } }
java
private static Data loadLeapSeconds() { Data bestData = null; URL url = null; try { // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/" + LEAP_SECONDS_TXT); while (en.hasMoreElements()) { url = en.nextElement(); Data candidate = loadLeapSeconds(url); if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) { bestData = candidate; } } // this location does not work on Java 9 module path because the resource is encapsulated en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT); while (en.hasMoreElements()) { url = en.nextElement(); Data candidate = loadLeapSeconds(url); if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) { bestData = candidate; } } // this location is the canonical one, and class-based loading works on Java 9 module path url = SystemUtcRules.class.getResource("/" + LEAP_SECONDS_TXT); if (url != null) { Data candidate = loadLeapSeconds(url); if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) { bestData = candidate; } } } catch (Exception ex) { throw new RuntimeException("Unable to load time-zone rule data: " + url, ex); } if (bestData == null) { // no data on classpath, but we allow manual registration of leap seconds // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10 bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)}); } return bestData; }
java
private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException { List<String> lines; try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { lines = reader.lines().collect(Collectors.toList()); } List<Long> dates = new ArrayList<>(); List<Integer> offsets = new ArrayList<>(); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) { continue; } Matcher matcher = LEAP_FILE_FORMAT.matcher(line); if (matcher.matches() == false) { throw new StreamCorruptedException("Invalid leap second file"); } dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY)); offsets.add(Integer.valueOf(matcher.group(2))); } long[] datesData = new long[dates.size()]; int[] offsetsData = new int[dates.size()]; long[] taiData = new long[dates.size()]; for (int i = 0; i < datesData.length; i++) { datesData[i] = dates.get(i); offsetsData[i] = offsets.get(i); taiData[i] = tai(datesData[i], offsetsData[i]); } return new Data(datesData, offsetsData, taiData); }
java
static InternationalFixedDate create(int prolepticYear, int month, int dayOfMonth) { YEAR_RANGE.checkValidValue(prolepticYear, ChronoField.YEAR_OF_ERA); MONTH_OF_YEAR_RANGE.checkValidValue(month, ChronoField.MONTH_OF_YEAR); DAY_OF_MONTH_RANGE.checkValidValue(dayOfMonth, ChronoField.DAY_OF_MONTH); if (dayOfMonth == DAYS_IN_LONG_MONTH && month != 6 && month != MONTHS_IN_YEAR) { throw new DateTimeException("Invalid date: " + prolepticYear + '/' + month + '/' + dayOfMonth); } if (month == 6 && dayOfMonth == DAYS_IN_LONG_MONTH && !INSTANCE.isLeapYear(prolepticYear)) { throw new DateTimeException("Invalid Leap Day as '" + prolepticYear + "' is not a leap year"); } return new InternationalFixedDate(prolepticYear, month, dayOfMonth); }
java
@Override public JulianDate date(int prolepticYear, int month, int dayOfMonth) { return JulianDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public JulianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<JulianDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<JulianDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<JulianDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<JulianDate>) super.zonedDateTime(temporal); }
java
@Override public Symmetry454Date date(int prolepticYear, int month, int dayOfMonth) { return Symmetry454Date.of(prolepticYear, month, dayOfMonth); }
java
@Override public Symmetry454Date dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<Symmetry454Date> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<Symmetry454Date>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<Symmetry454Date> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<Symmetry454Date>) super.zonedDateTime(temporal); }
java
@Override public Symmetry010Date date(int prolepticYear, int month, int dayOfMonth) { return Symmetry010Date.of(prolepticYear, month, dayOfMonth); }
java
@Override public Symmetry010Date dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<Symmetry010Date> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<Symmetry010Date>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal); }
java
@Override public PaxDate date(int prolepticYear, int month, int dayOfMonth) { return PaxDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public PaxDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<PaxDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<PaxDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<PaxDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<PaxDate>) super.zonedDateTime(temporal); }
java
@Override public EthiopicDate date(Era era, int yearOfEra, int month, int dayOfMonth) { return date(prolepticYear(era, yearOfEra), month, dayOfMonth); }
java
@Override public EthiopicDate date(int prolepticYear, int month, int dayOfMonth) { return EthiopicDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public EthiopicDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<EthiopicDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<EthiopicDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<EthiopicDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<EthiopicDate>) super.zonedDateTime(temporal); }
java
@Override public DiscordianDate date(int prolepticYear, int month, int dayOfMonth) { return DiscordianDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public DiscordianDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal); }
java
@Override public InternationalFixedDate date(int prolepticYear, int month, int dayOfMonth) { return InternationalFixedDate.of(prolepticYear, month, dayOfMonth); }
java
@Override public InternationalFixedDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java
@Override @SuppressWarnings("unchecked") public ChronoLocalDateTime<InternationalFixedDate> localDateTime(TemporalAccessor temporal) { return (ChronoLocalDateTime<InternationalFixedDate>) super.localDateTime(temporal); }
java
@Override @SuppressWarnings("unchecked") public ChronoZonedDateTime<InternationalFixedDate> zonedDateTime(TemporalAccessor temporal) { return (ChronoZonedDateTime<InternationalFixedDate>) super.zonedDateTime(temporal); }
java
public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() { if (bounds == null) { bounds = new ReadOnlyObjectWrapper<>(getBounds()); addStateEventHandler(MapStateEventType.idle, () -> { bounds.set(getBounds()); }); } return bounds.getReadOnlyProperty(); }
java
public void addMarker(Marker marker) { if (markers == null) { markers = new HashSet<>(); } markers.add(marker); marker.setMap(this); }
java
public void removeMarker(Marker marker) { if (markers != null && markers.contains(marker)) { markers.remove(marker); } marker.setMap(null); }
java
public void clearMarkers() { if (markers != null && !markers.isEmpty()) { markers.forEach((m) -> { m.setMap(null); }); markers.clear(); }
java
protected void setProperty(String propertyName, JavascriptObject propertyValue) { jsObject.setMember(propertyName, propertyValue.getJSObject()); }
java
protected void setProperty(String propertyName, JavascriptEnum propertyValue) { jsObject.setMember(propertyName, propertyValue.getEnumValue()); }
java
protected <T> T getProperty(String key, Class<T> type) { Object returnValue = getProperty(key); if (returnValue != null) { return (T) returnValue; } else { return null; } }
java
protected <T> T invokeJavascriptReturnValue(String function, Class<T> returnType) { Object returnObject = invokeJavascript(function); if (returnObject instanceof JSObject) { try { Constructor<T> constructor = returnType.getConstructor(JSObject.class); return constructor.newInstance((JSObject) returnObject); } catch (Exception ex) { throw new IllegalStateException(ex); } } else { return (T) returnObject; } }
java
protected Object checkUndefined(Object val) { if (val instanceof String && ((String) val).equals("undefined")) { return null; } return val; }
java
protected Boolean checkBoolean(Object val, Boolean def) { return (val == null) ? def : (Boolean) val; }
java
public String registerHandler(GFXEventHandler handler) { String uuid = UUID.randomUUID().toString(); handlers.put(uuid, handler); return uuid; }
java
public void handleStateEvent(String callbackKey) { if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) { ((StateEventHandler) handlers.get(callbackKey)).handle(); } else { System.err.println("Error in handle: " + callbackKey + " for state handler "); } }
java
public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) { MVCArray res = buildArcPoints(center, start, end); if (ArcType.ROUND.equals(arcType)) { res.push(center); } return new PolygonOptions().paths(res); }
java
public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) { MVCArray res = buildArcPoints(center, start, end); return new PolylineOptions().path(res); }
java
public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) { int points = DEFAULT_ARC_POINTS; MVCArray res = new MVCArray(); if (startBearing > endBearing) { endBearing += 360.0; } double deltaBearing = endBearing - startBearing; deltaBearing = deltaBearing / points; for (int i = 0; (i < points + 1); i++) { res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius)); } return res; }
java
public LatLong getLocation() { if (location == null) { location = new LatLong((JSObject) (getJSObject().getMember("location"))); } return location; }
java
protected String getArgString(Object arg) { //if (arg instanceof LatLong) { // return ((LatLong) arg).getVariableName(); //} else if (arg instanceof JavascriptObject) { return ((JavascriptObject) arg).getVariableName(); // return ((JavascriptObject) arg).getPropertiesAsString(); } else if( arg instanceof JavascriptEnum ) { return ((JavascriptEnum) arg).getEnumValue().toString(); } else { return arg.toString(); } }
java
private String registerEventHandler(GFXEventHandler h) { //checkInitialized(); if (!registeredOnJS) { JSObject doc = (JSObject) runtime.execute("document"); doc.setMember("jsHandlers", jsHandlers); registeredOnJS = true; } return jsHandlers.registerHandler(h); }
java
public void addUIEventHandler(JavascriptObject obj, UIEventType type, UIEventHandler h) { String key = registerEventHandler(h); String mcall = "google.maps.event.addListener(" + obj.getVariableName() + ", '" + type.name() + "', " + "function(event) {document.jsHandlers.handleUIEvent('" + key + "', event);});";//.latLng //System.out.println("addUIEventHandler mcall: " + mcall); runtime.execute(mcall); }
java
public double distanceFrom(LatLong end) { double dLat = (end.getLatitude() - getLatitude()) * Math.PI / 180; double dLon = (end.getLongitude() - getLongitude()) * Math.PI / 180; double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getLatitude() * Math.PI / 180) * Math.cos(end.getLatitude() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double d = EarthRadiusMeters * c; return d; }
java
public LatLong getDestinationPoint(double bearing, double distance) { double brng = Math.toRadians(bearing); double lat1 = latToRadians(); double lon1 = longToRadians(); double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance / EarthRadiusMeters) + Math.cos(lat1) * Math.sin(distance / EarthRadiusMeters) * Math.cos(brng)); double lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(distance / EarthRadiusMeters) * Math.cos(lat1), Math.cos(distance / EarthRadiusMeters) - Math.sin(lat1) * Math.sin(lat2)); return new LatLong(Math.toDegrees(lat2), Math.toDegrees(lon2)); }
java
public double getBearing(LatLong end) { if (this.equals(end)) { return 0; } double lat1 = latToRadians(); double lon1 = longToRadians(); double lat2 = end.latToRadians(); double lon2 = end.longToRadians(); double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)); if (angle < 0.0) { angle += Math.PI * 2.0; } if (angle > Math.PI) { angle -= Math.PI * 2.0; } return Math.toDegrees(angle); }
java
public void getElevationForLocations(LocationElevationRequest req, ElevationServiceCallback callback) { this.callback = callback; JSObject doc = (JSObject) getJSObject().eval("document"); doc.setMember(getVariableName(), this); StringBuilder r = new StringBuilder(getVariableName()) .append(".") .append("getElevationForLocations(") .append(req.getVariableName()) .append(", ") .append("function(results, status) {alert('rec:'+status);\ndocument.") .append(getVariableName()) .append(".processResponse(results, status);});"); LOG.trace("ElevationService direct call: " + r.toString()); getJSObject().eval(r.toString()); }
java
public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) { this.callback = callback; JSObject doc = (JSObject) getJSObject().eval("document"); doc.setMember(getVariableName(), this); StringBuilder r = new StringBuilder(getVariableName()) .append(".") .append("getElevationAlongPath(") .append(req.getVariableName()) .append(", ") .append("function(results, status) {document.") .append(getVariableName()) .append(".processResponse(results, status);});"); getJSObject().eval(r.toString()); }
java
public static double distance(double lat1, double lon1, double lat2, double lon2) { double dLat = Math.toRadians(lat2-lat1); double dLon = Math.toRadians(lon2-lon1); lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }
java
public static String soundex(String str) { if (str.length() < 1) return ""; // no soundex key for the empty string (could use 000) char[] key = new char[4]; key[0] = str.charAt(0); int pos = 1; char prev = '0'; for (int ix = 1; ix < str.length() && pos < 4; ix++) { char ch = str.charAt(ix); int charno; if (ch >= 'A' && ch <= 'Z') charno = ch - 'A'; else if (ch >= 'a' && ch <= 'z') charno = ch - 'a'; else continue; if (number[charno] != '0' && number[charno] != prev) key[pos++] = number[charno]; prev = number[charno]; } for ( ; pos < 4; pos++) key[pos] = '0'; return new String(key); }
java
private static char[] buildTable() { char[] table = new char[26]; for (int ix = 0; ix < table.length; ix++) table[ix] = '0'; table['B' - 'A'] = '1'; table['P' - 'A'] = '1'; table['F' - 'A'] = '1'; table['V' - 'A'] = '1'; table['C' - 'A'] = '2'; table['S' - 'A'] = '2'; table['K' - 'A'] = '2'; table['G' - 'A'] = '2'; table['J' - 'A'] = '2'; table['Q' - 'A'] = '2'; table['X' - 'A'] = '2'; table['Z' - 'A'] = '2'; table['D' - 'A'] = '3'; table['T' - 'A'] = '3'; table['L' - 'A'] = '4'; table['M' - 'A'] = '5'; table['N' - 'A'] = '5'; table['R' - 'A'] = '6'; return table; }
java
private void addStatement(RecordImpl record, String subject, String property, String object) { Collection<Column> cols = columns.get(property); if (cols == null) { if (property.equals(RDF_TYPE) && !types.isEmpty()) addValue(record, subject, property, object); return; } for (Column col : cols) { String cleaned = object; if (col.getCleaner() != null) cleaned = col.getCleaner().clean(object); if (cleaned != null && !cleaned.equals("")) addValue(record, subject, col.getProperty(), cleaned); } }
java
public Filter geoSearch(String value) { GeopositionComparator comp = (GeopositionComparator) prop.getComparator(); double dist = comp.getMaxDistance(); double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0); Shape circle = spatialctx.makeCircle(parsePoint(value), degrees); SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle); return strategy.makeFilter(args); }
java
private Point parsePoint(String point) { int comma = point.indexOf(','); if (comma == -1) return null; float lat = Float.valueOf(point.substring(0, comma)); float lng = Float.valueOf(point.substring(comma + 1)); return spatialctx.makePoint(lng, lat); }
java
public static Statement open(String jndiPath) { try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiPath); Connection conn = ds.getConnection(); return conn.createStatement(); } catch (NamingException e) { throw new DukeException("No database configuration found via JNDI at " + jndiPath, e); } catch (SQLException e) { throw new DukeException("Error connecting to database via " + jndiPath, e); } }
java
public static Statement open(String driverklass, String jdbcuri, Properties props) { try { Driver driver = (Driver) ObjectUtils.instantiate(driverklass); Connection conn = driver.connect(jdbcuri, props); if (conn == null) throw new DukeException("Couldn't connect to database at " + jdbcuri); return conn.createStatement(); } catch (SQLException e) { throw new DukeException(e); } }
java
public static void close(Statement stmt) { try { Connection conn = stmt.getConnection(); try { if (!stmt.isClosed()) stmt.close(); } catch (UnsupportedOperationException e) { // not all JDBC drivers implement the isClosed() method. // ugly, but probably the only way to get around this. // http://stackoverflow.com/questions/12845385/duke-fast-deduplication-java-lang-unsupportedoperationexception-operation-not stmt.close(); } if (conn != null && !conn.isClosed()) conn.close(); } catch (SQLException e) { throw new DukeException(e); } }
java
public static boolean validate(Statement stmt) { try { Connection conn = stmt.getConnection(); if (conn == null) return false; if (!conn.isClosed() && conn.isValid(10)) return true; stmt.close(); conn.close(); } catch (SQLException e) { // this may well fail. that doesn't matter. we're just making an // attempt to clean up, and if we can't, that's just too bad. } return false; }
java
public static int queryForInt(Statement stmt, String sql, int nullvalue) { try { ResultSet rs = stmt.executeQuery(sql); try { if (!rs.next()) return nullvalue; return rs.getInt(1); } finally { rs.close(); } } catch (SQLException e) { throw new DukeException(e); } }
java
public static boolean queryHasResult(Statement stmt, String sql) { try { ResultSet rs = stmt.executeQuery(sql); try { return rs.next(); } finally { rs.close(); } } catch (SQLException e) { throw new DukeException(e); } }
java
public static String replaceAnyOf(String value, String chars, char replacement) { char[] tmp = new char[value.length()]; int pos = 0; for (int ix = 0; ix < tmp.length; ix++) { char ch = value.charAt(ix); if (chars.indexOf(ch) != -1) tmp[pos++] = replacement; else tmp[pos++] = ch; } return new String(tmp, 0, tmp.length); }
java
public static String normalizeWS(String value) { char[] tmp = new char[value.length()]; int pos = 0; boolean prevws = false; for (int ix = 0; ix < tmp.length; ix++) { char ch = value.charAt(ix); if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') { if (prevws && pos != 0) tmp[pos++] = ' '; tmp[pos++] = ch; prevws = false; } else prevws = true; } return new String(tmp, 0, pos); }
java
public static String get(Properties props, String name, String defval) { String value = props.getProperty(name); if (value == null) value = defval; return value; }
java
public Collection<DataSource> getDataSources(int groupno) { if (groupno == 1) return group1; else if (groupno == 2) return group2; else throw new DukeConfigException("Invalid group number: " + groupno); }
java
public void addDataSource(int groupno, DataSource datasource) { // the loader takes care of validation if (groupno == 0) datasources.add(datasource); else if (groupno == 1) group1.add(datasource); else if (groupno == 2) group2.add(datasource); }
java
public double compare(String v1, String v2) { // FIXME: it should be possible here to say that, actually, we // didn't learn anything from comparing these two values, so that // probability is set to 0.5. if (comparator == null) return 0.5; // we ignore properties with no comparator // first, we call the comparator, to get a measure of how similar // these two values are. note that this is not the same as what we // are going to return, which is a probability. double sim = comparator.compare(v1, v2); // we have been configured with a high probability (for equal // values) and a low probability (for different values). given // sim, which is a measure of the similarity somewhere in between // equal and different, we now compute our estimate of the // probability. // if sim = 1.0, we return high. if sim = 0.0, we return low. for // values in between we need to compute a little. the obvious // formula to use would be (sim * (high - low)) + low, which // spreads the values out equally spaced between high and low. // however, if the similarity is higher than 0.5 we don't want to // consider this negative evidence, and so there's a threshold // there. also, users felt Duke was too eager to merge records, // and wanted probabilities to fall off faster with lower // probabilities, and so we square sim in order to achieve this. if (sim >= 0.5) return ((high - 0.5) * (sim * sim)) + 0.5; else return low; }
java
public SparqlResult runQuery(String endpoint, String query) { return SparqlClient.execute(endpoint, query, username, password); }
java
private void merge(Integer cid1, Integer cid2) { Collection<String> klass1 = classix.get(cid1); Collection<String> klass2 = classix.get(cid2); // if klass1 is the smaller, swap the two if (klass1.size() < klass2.size()) { Collection<String> tmp = klass2; klass2 = klass1; klass1 = tmp; Integer itmp = cid2; cid2 = cid1; cid1 = itmp; } // now perform the actual merge for (String id : klass2) { klass1.add(id); recordix.put(id, cid1); } // delete the smaller class, and we're done classix.remove(cid2); }
java
private void bumpScores(Map<Long, Score> candidates, List<Bucket> buckets, int ix) { for (; ix < buckets.size(); ix++) { Bucket b = buckets.get(ix); if (b.nextfree > CUTOFF_FACTOR_2 * candidates.size()) return; double score = b.getScore(); for (Score s : candidates.values()) if (b.contains(s.id)) s.score += score; } }
java
private int collectCandidates(Map<Long, Score> candidates, List<Bucket> buckets, int threshold) { int ix; for (ix = 0; ix < threshold && candidates.size() < (CUTOFF_FACTOR_1 * max_search_hits); ix++) { Bucket b = buckets.get(ix); long[] ids = b.records; double score = b.getScore(); for (int ix2 = 0; ix2 < b.nextfree; ix2++) { Score s = candidates.get(ids[ix2]); if (s == null) { s = new Score(ids[ix2]); candidates.put(ids[ix2], s); } s.score += score; } if (DEBUG) System.out.println("Bucket " + b.nextfree + " -> " + candidates.size()); } return ix; }
java
private List<Bucket> lookup(Record record) { List<Bucket> buckets = new ArrayList(); for (Property p : config.getLookupProperties()) { String propname = p.getName(); Collection<String> values = record.getValues(propname); if (values == null) continue; for (String value : values) { String[] tokens = StringUtils.split(value); for (int ix = 0; ix < tokens.length; ix++) { Bucket b = store.lookupToken(propname, tokens[ix]); if (b == null || b.records == null) continue; long[] ids = b.records; if (DEBUG) System.out.println(propname + ", " + tokens[ix] + ": " + b.nextfree + " (" + b.getScore() + ")"); buckets.add(b); } } } return buckets; }
java
public void spawnThread(DukeController controller, int check_interval) { this.controller = controller; timer = mgr.schedule(this, 0, check_interval * 1000); // convert to ms }
java
public String[] init(String[] argv, int min, int max, Collection<CommandLineParser.Option> options) throws IOException, SAXException { // parse command line parser = new CommandLineParser(); parser.setMinimumArguments(min); parser.setMaximumArguments(max); parser.registerOption(new CommandLineParser.BooleanOption("reindex", 'I')); if (options != null) for (CommandLineParser.Option option : options) parser.registerOption(option); try { argv = parser.parse(argv); } catch (CommandLineParser.CommandLineParserException e) { System.err.println("ERROR: " + e.getMessage()); usage(); System.exit(1); } // do we need to reindex? boolean reindex = parser.getOptionState("reindex"); // load configuration config = ConfigLoader.load(argv[0]); database = config.getDatabase(reindex); // overwrite iff reindex if (database.isInMemory()) reindex = true; // no other way to do it in this case // reindex, if requested if (reindex) reindex(config, database); return argv; }
java
public static File createTempDirectory(String prefix) { File temp = null; try { temp = File.createTempFile(prefix != null ? prefix : "temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } } catch (IOException e) { throw new DukeException("Unable to create temporary directory with prefix " + prefix, e); } return temp; }
java
public static Configuration loadFromString(String config) throws IOException, SAXException { ConfigurationImpl cfg = new ConfigurationImpl(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new ConfigHandler(cfg, null)); Reader reader = new StringReader(config); parser.parse(new InputSource(reader)); return cfg; }
java
public void endRecord_() { // this is where we actually update the link database. basically, // all we need to do is to retract those links which weren't seen // this time around, and that can be done via assertLink, since it // can override existing links. // get all the existing links Collection<Link> oldlinks = linkdb.getAllLinksFor(getIdentity(current)); // build a hashmap so we can look up corresponding old links from // new links if (oldlinks != null) { Map<String, Link> oldmap = new HashMap(oldlinks.size()); for (Link l : oldlinks) oldmap.put(makeKey(l), l); // removing all the links we found this time around from the set of // old links. any links remaining after this will be stale, and need // to be retracted for (Link newl : new ArrayList<Link>(curlinks)) { String key = makeKey(newl); Link oldl = oldmap.get(key); if (oldl == null) continue; if (oldl.overrides(newl)) // previous information overrides this link, so ignore curlinks.remove(newl); else if (sameAs(oldl, newl)) { // there's no new information here, so just ignore this curlinks.remove(newl); oldmap.remove(key); // we don't want to retract the old one } else // the link is out of date, but will be overwritten, so remove oldmap.remove(key); } // all the inferred links left in oldmap are now old links we // didn't find on this pass. there is no longer any evidence // supporting them, and so we can retract them. for (Link oldl : oldmap.values()) if (oldl.getStatus() == LinkStatus.INFERRED) { oldl.retract(); // changes to retracted, updates timestamp curlinks.add(oldl); } } // okay, now we write it all to the database for (Link l : curlinks) linkdb.assertLink(l); }
java
public void write(Configuration config) throws IOException { pp.startDocument(); pp.startElement("duke", null); // FIXME: here we should write the objects, but that's not // possible with the current API. we don't need that for the // genetic algorithm at the moment, but it would be useful. pp.startElement("schema", null); writeElement("threshold", "" + config.getThreshold()); if (config.getMaybeThreshold() != 0.0) writeElement("maybe-threshold", "" + config.getMaybeThreshold()); for (Property p : config.getProperties()) writeProperty(p); pp.endElement("schema"); String dbclass = config.getDatabase(false).getClass().getName(); AttributeListImpl atts = new AttributeListImpl(); atts.addAttribute("class", "CDATA", dbclass); pp.startElement("database", atts); pp.endElement("database"); if (config.isDeduplicationMode()) for (DataSource src : config.getDataSources()) writeDataSource(src); else { pp.startElement("group", null); for (DataSource src : config.getDataSources(1)) writeDataSource(src); pp.endElement("group"); pp.startElement("group", null); for (DataSource src : config.getDataSources(2)) writeDataSource(src); pp.endElement("group"); } pp.endElement("duke"); pp.endDocument(); }
java
public static void parse(Reader src, StatementHandler handler) throws IOException { new NTriplesParser(src, handler).parse(); }
java
public static int distance(String s1, String s2) { if (s1.length() == 0) return s2.length(); if (s2.length() == 0) return s1.length(); int s1len = s1.length(); // we use a flat array for better performance. we address it by // s1ix + s1len * s2ix. this modification improves performance // by about 30%, which is definitely worth the extra complexity. int[] matrix = new int[(s1len + 1) * (s2.length() + 1)]; for (int col = 0; col <= s2.length(); col++) matrix[col * s1len] = col; for (int row = 0; row <= s1len; row++) matrix[row] = row; for (int ix1 = 0; ix1 < s1len; ix1++) { char ch1 = s1.charAt(ix1); for (int ix2 = 0; ix2 < s2.length(); ix2++) { int cost; if (ch1 == s2.charAt(ix2)) cost = 0; else cost = 1; int left = matrix[ix1 + ((ix2 + 1) * s1len)] + 1; int above = matrix[ix1 + 1 + (ix2 * s1len)] + 1; int aboveleft = matrix[ix1 + (ix2 * s1len)] + cost; matrix[ix1 + 1 + ((ix2 + 1) * s1len)] = Math.min(left, Math.min(above, aboveleft)); } } // for (int ix1 = 0; ix1 <= s1len; ix1++) { // for (int ix2 = 0; ix2 <= s2.length(); ix2++) { // System.out.print(matrix[ix1 + (ix2 * s1len)] + " "); // } // System.out.println(); // } return matrix[s1len + (s2.length() * s1len)]; }
java
public static int compactDistance(String s1, String s2) { if (s1.length() == 0) return s2.length(); if (s2.length() == 0) return s1.length(); // the maximum edit distance there is any point in reporting. int maxdist = Math.min(s1.length(), s2.length()) / 2; // we allocate just one column instead of the entire matrix, in // order to save space. this also enables us to implement the // algorithm somewhat faster. the first cell is always the // virtual first row. int s1len = s1.length(); int[] column = new int[s1len + 1]; // first we need to fill in the initial column. we use a separate // loop for this, because in this case our basis for comparison is // not the previous column, but a virtual first column. int ix2 = 0; char ch2 = s2.charAt(ix2); column[0] = 1; // virtual first row for (int ix1 = 1; ix1 <= s1len; ix1++) { int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1; // Lowest of three: above (column[ix1 - 1]), aboveleft: ix1 - 1, // left: ix1. Latter cannot possibly be lowest, so is // ignored. column[ix1] = Math.min(column[ix1 - 1], ix1 - 1) + cost; } // okay, now we have an initialized first column, and we can // compute the rest of the matrix. int above = 0; for (ix2 = 1; ix2 < s2.length(); ix2++) { ch2 = s2.charAt(ix2); above = ix2 + 1; // virtual first row int smallest = s1len * 2; // used to implement cutoff for (int ix1 = 1; ix1 <= s1len; ix1++) { int cost = s1.charAt(ix1 - 1) == ch2 ? 0 : 1; // above: above // aboveleft: column[ix1 - 1] // left: column[ix1] int value = Math.min(Math.min(above, column[ix1 - 1]), column[ix1]) + cost; column[ix1 - 1] = above; // write previous above = value; // keep current smallest = Math.min(smallest, value); } column[s1len] = above; // check if we can stop because we'll be going over the max distance if (smallest > maxdist) return smallest; } // ok, we're done return above; }
java