code
stringlengths
73
34.1k
label
stringclasses
1 value
public Collection<SerialMessage> initialize() { ArrayList<SerialMessage> result = new ArrayList<SerialMessage>(); if (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) { logger.warn("Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET."); return result; } result.add(this.getSupportedMessage()); return result; }
java
public static java.util.Date newDateTime() { return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS); }
java
public static java.sql.Date newDate() { return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS); }
java
public static java.sql.Time newTime() { return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS); }
java
public static int secondsDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS)); }
java
public static int minutesDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS)); }
java
public static int hoursDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS)); }
java
public static int daysDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS)); }
java
public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(startDate); gc.add(period, amount); return new java.sql.Time(gc.getTime().getTime()); }
java
public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(startDate); gc.add(period, amount); return new java.util.Date(gc.getTime().getTime()); }
java
public static java.sql.Date rollYears(java.util.Date startDate, int years) { return rollDate(startDate, Calendar.YEAR, years); }
java
@SuppressWarnings("deprecation") public static boolean dateEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear(); }
java
@SuppressWarnings("deprecation") public static boolean timeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
java
@SuppressWarnings("deprecation") public static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear() && d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
java
public static Object toObject(Class<?> clazz, Object value) throws ParseException { if (value == null) { return null; } if (clazz == null) { return value; } if (java.sql.Date.class.isAssignableFrom(clazz)) { return toDate(value); } if (java.sql.Time.class.isAssignableFrom(clazz)) { return toTime(value); } if (java.sql.Timestamp.class.isAssignableFrom(clazz)) { return toTimestamp(value); } if (java.util.Date.class.isAssignableFrom(clazz)) { return toDateTime(value); } return value; }
java
public static java.util.Date getDateTime(Object value) { try { return toDateTime(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
java
public static java.util.Date toDateTime(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.util.Date) { return (java.util.Date) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return IN_DATETIME_FORMAT.parse((String) value); } return IN_DATETIME_FORMAT.parse(value.toString()); }
java
public static java.sql.Date getDate(Object value) { try { return toDate(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
java
public static java.sql.Date toDate(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Date) { return (java.sql.Date) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime()); } return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime()); }
java
public static java.sql.Time getTime(Object value) { try { return toTime(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
java
public static java.sql.Time toTime(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Time) { return (java.sql.Time) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime()); } return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime()); }
java
public static java.sql.Timestamp getTimestamp(Object value) { try { return toTimestamp(value); } catch (ParseException pe) { pe.printStackTrace(); return null; } }
java
public static java.sql.Timestamp toTimestamp(Object value) throws ParseException { if (value == null) { return null; } if (value instanceof java.sql.Timestamp) { return (java.sql.Timestamp) value; } if (value instanceof String) { if ("".equals((String) value)) { return null; } return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime()); } return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime()); }
java
@SuppressWarnings("deprecation") public static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) { d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds()); if (start == null || end == null) { return false; } if (start.before(end) && (!(d.after(start) && d.before(end)))) { return false; } if (end.before(start) && (!(d.after(end) || d.before(start)))) { return false; } return true; }
java
public static Trajectory combineTrajectory(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } if(a.size()!=b.size()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not " + "have the same number of steps a="+a.size() + " b="+b.size()); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x+b.get(i).x, a.get(i).y+b.get(i).y, a.get(i).z+b.get(i).z); c.add(pos); } return c; }
java
public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x, a.get(i).y, a.get(i).z); c.add(pos); } double dx = a.get(a.size()-1).x - b.get(0).x; double dy = a.get(a.size()-1).y - b.get(0).y; double dz = a.get(a.size()-1).z - b.get(0).z; for(int i = 1 ; i < b.size(); i++){ Point3d pos = new Point3d(b.get(i).x+dx, b.get(i).y+dy, b.get(i).z+dz); c.add(pos); } return c; }
java
public static Trajectory resample(Trajectory t, int n){ Trajectory t1 = new Trajectory(2); for(int i = 0; i < t.size(); i=i+n){ t1.add(t.get(i)); } return t1; }
java
public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){ Trajectory track = null; for(int i = 0; i < t.size() ; i++){ if(t.get(i).getID()==id){ track = t.get(i); break; } } return track; }
java
public void setPropertyDestinationType(Class<?> clazz, String propertyName, TypeReference<?> destinationType) { propertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType); }
java
public void addConverter(int index, IConverter converter) { converterList.add(index, converter); if (converter instanceof IContainerConverter) { IContainerConverter containerConverter = (IContainerConverter) converter; if (containerConverter.getElementConverter() == null) { containerConverter.setElementConverter(elementConverter); } } }
java
public static SPIProviderResolver getInstance(ClassLoader cl) { SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl); return resolver; }
java
static Parameter createParameter(final String name, final String value) { if (value != null && isQuoted(value)) { return new QuotedParameter(name, value); } return new Parameter(name, value); }
java
public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) { String value = null; Annotation annotation = classType.getAnnotation(annotationType); if (annotation != null) { try { value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation); } catch (Exception ex) {} } return value; }
java
private Long string2long(String text, DateTimeFormat fmt) { // null or "" returns null if (text == null) return null; text = text.trim(); if (text.length() == 0) return null; Date date = fmt.parse(text); return date != null ? UTCDateBox.date2utc(date) : null; }
java
private String long2string(Long value, DateTimeFormat fmt) { // for html5 inputs, use "" for no value if (value == null) return ""; Date date = UTCDateBox.utc2date(value); return date != null ? fmt.format(date) : null; }
java
public static RgbaColor from(String color) { if (color.startsWith("#")) { return fromHex(color); } else if (color.startsWith("rgba")) { return fromRgba(color); } else if (color.startsWith("rgb")) { return fromRgb(color); } else if (color.startsWith("hsla")) { return fromHsla(color); } else if (color.startsWith("hsl")) { return fromHsl(color); } else { return getDefaultColor(); } }
java
public static RgbaColor fromHex(String hex) { if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor(); // #rgb if (hex.length() == 4) { return new RgbaColor(parseHex(hex, 1, 2), parseHex(hex, 2, 3), parseHex(hex, 3, 4)); } // #rrggbb else if (hex.length() == 7) { return new RgbaColor(parseHex(hex, 1, 3), parseHex(hex, 3, 5), parseHex(hex, 5, 7)); } else { return getDefaultColor(); } }
java
public static RgbaColor fromRgb(String rgb) { if (rgb.length() == 0) return getDefaultColor(); String[] parts = getRgbParts(rgb).split(","); if (parts.length == 3) { return new RgbaColor(parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2])); } else { return getDefaultColor(); } }
java
public static RgbaColor fromRgba(String rgba) { if (rgba.length() == 0) return getDefaultColor(); String[] parts = getRgbaParts(rgba).split(","); if (parts.length == 4) { return new RgbaColor(parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]), parseFloat(parts[3])); } else { return getDefaultColor(); } }
java
private RgbaColor withHsl(int index, float value) { float[] HSL = convertToHsl(); HSL[index] = value; return RgbaColor.fromHsl(HSL); }
java
public RgbaColor adjustHue(float degrees) { float[] HSL = convertToHsl(); HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360) return RgbaColor.fromHsl(HSL); }
java
public RgbaColor opacify(float amount) { return new RgbaColor(r, g, b, alphaCheck(a + amount)); }
java
protected static final float[] getSpreadInRange(float member, int count, int max, int offset) { // to find the spread, we first find the min that is a // multiple of max/count away from the member int interval = max / count; float min = (member + offset) % interval; if (min == 0 && member == max) { min += interval; } float[] range = new float[count]; for (int i = 0; i < count; i++) { range[i] = min + interval * i + offset; } return range; }
java
public static RgbaColor fromHsl(float H, float S, float L) { // convert to [0-1] H /= 360f; S /= 100f; L /= 100f; float R, G, B; if (S == 0) { // grey R = G = B = L; } else { float m2 = L <= 0.5 ? L * (S + 1f) : L + S - L * S; float m1 = 2f * L - m2; R = hue2rgb(m1, m2, H + 1 / 3f); G = hue2rgb(m1, m2, H); B = hue2rgb(m1, m2, H - 1 / 3f); } // convert [0-1] to [0-255] int r = Math.round(R * 255f); int g = Math.round(G * 255f); int b = Math.round(B * 255f); return new RgbaColor(r, g, b, 1); }
java
private float max(float x, float y, float z) { if (x > y) { // not y if (x > z) { return x; } else { return z; } } else { // not x if (y > z) { return y; } else { return z; } } }
java
public Constructor<?> getCompatibleConstructor(Class<?> type, Class<?> argumentType) { try { return type.getConstructor(new Class[] { argumentType }); } catch (Exception e) { // get public classes and interfaces Class<?>[] types = type.getClasses(); for (int i = 0; i < types.length; i++) { try { return type.getConstructor(new Class[] { types[i] }); } catch (Exception e1) { } } } return null; }
java
public <T> T convert(Object source, TypeReference<T> typeReference) throws ConverterException { return (T) convert(new ConversionContext(), source, typeReference); }
java
public <T> T convert(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { try { return (T) multiConverter.convert(context, source, destinationType); } catch (ConverterException e) { throw e; } catch (Exception e) { // There is a problem with one converter. This should not happen. // Either there is a bug in this converter or it is not properly // configured throw new ConverterException( MessageFormat .format( "Could not convert given object with class ''{0}'' to object with type signature ''{1}''", source == null ? "null" : source.getClass() .getName(), destinationType), e); } }
java
public static int compare(double a, double b, double delta) { if (equals(a, b, delta)) { return 0; } return Double.compare(a, b); }
java
public double getValue(int[] batch) { double value = 0.0; for (int i=0; i<batch.length; i++) { value += getValue(i); } return value; }
java
public void getGradient(int[] batch, double[] gradient) { for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
java
public synchronized static SQLiteDatabase getConnection(Context context) { if (database == null) { // Construct the single helper and open the unique(!) db connection for the app database = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase(); } return database; }
java
@SuppressWarnings("unchecked") public static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } return ((ParameterizedType) superclass).getActualTypeArguments()[0]; }
java
@Override protected void onLoad() { super.onLoad(); // these styles need to be the same for the box and shadow so // that we can measure properly matchStyles("display"); matchStyles("fontSize"); matchStyles("fontFamily"); matchStyles("fontWeight"); matchStyles("lineHeight"); matchStyles("paddingTop"); matchStyles("paddingRight"); matchStyles("paddingBottom"); matchStyles("paddingLeft"); adjustSize(); }
java
@Override public void onKeyDown(KeyDownEvent event) { char c = MiscUtils.getCharCode(event.getNativeEvent()); onKeyCodeEvent(event, box.getValue()+c); }
java
public static void setEnabled(Element element, boolean enabled) { element.setPropertyBoolean("disabled", !enabled); setStyleName(element, "disabled", !enabled); }
java
private Method getPropertySourceMethod(Object sourceObject, Object destinationObject, String destinationProperty) { BeanToBeanMapping beanToBeanMapping = beanToBeanMappings.get(ClassPair .get(sourceObject.getClass(), destinationObject .getClass())); String sourceProperty = null; if (beanToBeanMapping != null) { sourceProperty = beanToBeanMapping .getSourceProperty(destinationProperty); } if (sourceProperty == null) { sourceProperty = destinationProperty; } return BeanUtils.getGetterPropertyMethod(sourceObject.getClass(), sourceProperty); }
java
protected TypeReference<?> getBeanPropertyType(Class<?> clazz, String propertyName, TypeReference<?> originalType) { TypeReference<?> propertyDestinationType = null; if (beanDestinationPropertyTypeProvider != null) { propertyDestinationType = beanDestinationPropertyTypeProvider .getPropertyType(clazz, propertyName, originalType); } if (propertyDestinationType == null) { propertyDestinationType = originalType; } return propertyDestinationType; }
java
public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) { beanToBeanMappings.put(ClassPair.get(beanToBeanMapping .getSourceClass(), beanToBeanMapping.getDestinationClass()), beanToBeanMapping); }
java
public static SPIProvider getInstance() { if (me == null) { final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader(); me = SPIProviderResolver.getInstance(cl).getProvider(); } return me; }
java
public <T> T getSPI(Class<T> spiType) { return getSPI(spiType, SecurityActions.getContextClassLoader()); }
java
public Optional<SoyMsgBundle> resolve(final Optional<Locale> locale) throws IOException { if (!locale.isPresent()) { return Optional.absent(); } synchronized (msgBundles) { SoyMsgBundle soyMsgBundle = null; if (isHotReloadModeOff()) { soyMsgBundle = msgBundles.get(locale.get()); } if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(locale.get()); if (soyMsgBundle == null) { soyMsgBundle = createSoyMsgBundle(new Locale(locale.get().getLanguage())); } if (soyMsgBundle == null && fallbackToEnglish) { soyMsgBundle = createSoyMsgBundle(Locale.ENGLISH); } if (soyMsgBundle == null) { return Optional.absent(); } if (isHotReloadModeOff()) { msgBundles.put(locale.get(), soyMsgBundle); } } return Optional.fromNullable(soyMsgBundle); } }
java
private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) { if (soyMsgBundles.isEmpty()) { return Optional.absent(); } final List<SoyMsg> msgs = Lists.newArrayList(); for (final SoyMsgBundle smb : soyMsgBundles) { for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) { msgs.add(it.next()); } } return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs)); }
java
@Override public Optional<String> hash(final Optional<URL> url) throws IOException { if (!url.isPresent()) { return Optional.absent(); } logger.debug("Calculating md5 hash, url:{}", url); if (isHotReloadModeOff()) { final String md5 = cache.getIfPresent(url.get()); logger.debug("md5 hash:{}", md5); if (md5 != null) { return Optional.of(md5); } } final InputStream is = url.get().openStream(); final String md5 = getMD5Checksum(is); if (isHotReloadModeOff()) { logger.debug("caching url:{} with hash:{}", url, md5); cache.put(url.get(), md5); } return Optional.fromNullable(md5); }
java
public static String[] allUpperCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toUpperCase(); } } return tmp; }
java
public static String[] allLowerCase(String... strings){ String[] tmp = new String[strings.length]; for(int idx=0;idx<strings.length;idx++){ if(strings[idx] != null){ tmp[idx] = strings[idx].toLowerCase(); } } return tmp; }
java
public FullTypeSignature getTypeErasureSignature() { if (typeErasureSignature == null) { typeErasureSignature = new ClassTypeSignature(binaryName, new TypeArgSignature[0], ownerTypeSignature == null ? null : (ClassTypeSignature) ownerTypeSignature .getTypeErasureSignature()); } return typeErasureSignature; }
java
public MIMEType addParameter(String name, String value) { Map<String, String> copy = new LinkedHashMap<>(this.parameters); copy.put(name, value); return new MIMEType(type, subType, copy); }
java
@Override public List<String> contentTypes() { List<String> contentTypes = null; final HttpServletRequest request = getHttpRequest(); if (favorParameterOverAcceptHeader) { contentTypes = getFavoredParameterValueAsList(request); } else { contentTypes = getAcceptHeaderValues(request); } if (isEmpty(contentTypes)) { logger.debug("Setting content types to default: {}.", DEFAULT_SUPPORTED_CONTENT_TYPES); contentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES; } return unmodifiableList(contentTypes); }
java
public Headers getAllHeaders() { Headers requestHeaders = getHeaders(); requestHeaders = hasPayload() ? requestHeaders.withContentType(getPayload().get().getMimeType()) : requestHeaders; //We don't want to add headers more than once. return requestHeaders; }
java
public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt, final double l1Lambda, final double l2Lambda) { if (l1Lambda == 0 && l2Lambda == 0) { return opt; } return new Optimizer<DifferentiableFunction>() { @Override public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) { DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda); return opt.minimize(fn, point); } }; }
java
public String toRomanNumeral() { if (this.romanString == null) { this.romanString = ""; int remainder = this.value; for (int i = 0; i < BASIC_VALUES.length; i++) { while (remainder >= BASIC_VALUES[i]) { this.romanString += BASIC_ROMAN_NUMERALS[i]; remainder -= BASIC_VALUES[i]; } } } return this.romanString; }
java
public void takeNoteOfGradient(IntDoubleVector gradient) { gradient.iterate(new FnIntDoubleToVoid() { @Override public void call(int index, double value) { gradSumSquares[index] += value * value; assert !Double.isNaN(gradSumSquares[index]); } }); }
java
private ArrayTypeSignature getArrayTypeSignature( GenericArrayType genericArrayType) { FullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType .getGenericComponentType()); ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature( componentTypeSignature); return arrayTypeSignature; }
java
private ClassTypeSignature getClassTypeSignature( ParameterizedType parameterizedType) { Class<?> rawType = (Class<?>) parameterizedType.getRawType(); Type[] typeArguments = parameterizedType.getActualTypeArguments(); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArguments.length]; for (int i = 0; i < typeArguments.length; i++) { typeArgSignatures[i] = getTypeArgSignature(typeArguments[i]); } String binaryName = rawType.isMemberClass() ? rawType.getSimpleName() : rawType.getName(); ClassTypeSignature ownerTypeSignature = parameterizedType .getOwnerType() == null ? null : (ClassTypeSignature) getFullTypeSignature(parameterizedType .getOwnerType()); ClassTypeSignature classTypeSignature = new ClassTypeSignature( binaryName, typeArgSignatures, ownerTypeSignature); return classTypeSignature; }
java
private FullTypeSignature getTypeSignature(Class<?> clazz) { StringBuilder sb = new StringBuilder(); if (clazz.isArray()) { sb.append(clazz.getName()); } else if (clazz.isPrimitive()) { sb.append(primitiveTypesMap.get(clazz).toString()); } else { sb.append('L').append(clazz.getName()).append(';'); } return TypeSignatureFactory.getTypeSignature(sb.toString(), false); }
java
private TypeArgSignature getTypeArgSignature(Type type) { if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type lowerBound = wildcardType.getLowerBounds().length == 0 ? null : wildcardType.getLowerBounds()[0]; Type upperBound = wildcardType.getUpperBounds().length == 0 ? null : wildcardType.getUpperBounds()[0]; if (lowerBound == null && Object.class.equals(upperBound)) { return new TypeArgSignature( TypeArgSignature.UNBOUNDED_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound == null && upperBound != null) { return new TypeArgSignature( TypeArgSignature.UPPERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(upperBound)); } else if (lowerBound != null) { return new TypeArgSignature( TypeArgSignature.LOWERBOUND_WILDCARD, (FieldTypeSignature) getFullTypeSignature(lowerBound)); } else { throw new RuntimeException("Invalid type"); } } else { return new TypeArgSignature(TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) getFullTypeSignature(type)); } }
java
public static boolean zipFolder(File folder, String fileName){ boolean success = false; if(!folder.isDirectory()){ return false; } if(fileName == null){ fileName = folder.getAbsolutePath()+ZIP_EXT; } ZipArchiveOutputStream zipOutput = null; try { zipOutput = new ZipArchiveOutputStream(new File(fileName)); success = addFolderContentToZip(folder,zipOutput,""); zipOutput.close(); } catch (IOException e) { e.printStackTrace(); return false; } finally{ try { if(zipOutput != null){ zipOutput.close(); } } catch (IOException e) {} } return success; }
java
public static boolean unzipFileOrFolder(File zipFile, String unzippedFolder){ InputStream is; ArchiveInputStream in = null; OutputStream out = null; if(!zipFile.isFile()){ return false; } if(unzippedFolder == null){ unzippedFolder = FilenameUtils.removeExtension(zipFile.getAbsolutePath()); } try { is = new FileInputStream(zipFile); new File(unzippedFolder).mkdir(); in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is); ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry(); while(entry != null){ if(entry.isDirectory()){ new File(unzippedFolder,entry.getName()).mkdir(); } else{ out = new FileOutputStream(new File(unzippedFolder, entry.getName())); IOUtils.copy(in, out); out.close(); out = null; } entry = (ZipArchiveEntry)in.getNextEntry(); } } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (ArchiveException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally{ if(out != null){ try { out.close(); } catch (IOException e) {} } if(in != null){ try { in.close(); } catch (IOException e) {} } } return true; }
java
protected static final String formatUsingFormat(Long value, DateTimeFormat fmt) { if (value == null) { return ""; } else { // midnight GMT Date date = new Date(0); // offset by timezone and value date.setTime(UTCDateBox.timezoneOffsetMillis(date) + value.longValue()); // format it return fmt.format(date); } }
java
protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) { if (text.indexOf(':') == -1) { text = text.replace(" ", ""); int numdigits = 0; int lastdigit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) { numdigits++; lastdigit = i; } } if (numdigits == 1 || numdigits == 2) { // insert :00 int colon = lastdigit + 1; text = text.substring(0, colon) + ":00" + text.substring(colon); } else if (numdigits > 2) { // insert : int colon = lastdigit - 1; text = text.substring(0, colon) + ":" + text.substring(colon); } return parseUsingFallbacks(text, timeFormat); } else { return null; } }
java
public static Class<?> getRawType(Type type) { if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType actualType = (ParameterizedType) type; return getRawType(actualType.getRawType()); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; Object rawArrayType = Array.newInstance(getRawType(genericArrayType .getGenericComponentType()), 0); return rawArrayType.getClass(); } else if (type instanceof WildcardType) { WildcardType castedType = (WildcardType) type; return getRawType(castedType.getUpperBounds()[0]); } else { throw new IllegalArgumentException( "Type \'" + type + "\' is not a Class, " + "ParameterizedType, or GenericArrayType. Can't extract class."); } }
java
public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) { if (from == null) { return false; } if (to.equals(from)) { return true; } if (to.getType() instanceof Class) { return to.getRawType().isAssignableFrom(from.getRawType()); } else if (to.getType() instanceof ParameterizedType) { return isAssignableFrom(from.getType(), (ParameterizedType) to .getType(), new HashMap<String, Type>()); } else if (to.getType() instanceof GenericArrayType) { return to.getRawType().isAssignableFrom(from.getRawType()) && isAssignableFrom(from.getType(), (GenericArrayType) to .getType()); } else { throw new AssertionError("Unexpected Type : " + to); } }
java
private static boolean isAssignableFrom(Type from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from == null) { return false; } if (to.equals(from)) { return true; } // First figure out the class and any type information. Class<?> clazz = getRawType(from); ParameterizedType ptype = null; if (from instanceof ParameterizedType) { ptype = (ParameterizedType) from; } // Load up parameterized variable info if it was parameterized. if (ptype != null) { Type[] tArgs = ptype.getActualTypeArguments(); TypeVariable<?>[] tParams = clazz.getTypeParameters(); for (int i = 0; i < tArgs.length; i++) { Type arg = tArgs[i]; TypeVariable<?> var = tParams[i]; while (arg instanceof TypeVariable) { TypeVariable<?> v = (TypeVariable<?>) arg; arg = typeVarMap.get(v.getName()); } typeVarMap.put(var.getName(), arg); } // check if they are equivalent under our current mapping. if (typeEquals(ptype, to, typeVarMap)) { return true; } } for (Type itype : clazz.getGenericInterfaces()) { if (isAssignableFrom(itype, to, new HashMap<String, Type>( typeVarMap))) { return true; } } // Interfaces didn't work, try the superclass. Type sType = clazz.getGenericSuperclass(); if (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) { return true; } return false; }
java
private static boolean typeEquals(ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap) { if (from.getRawType().equals(to.getRawType())) { Type[] fromArgs = from.getActualTypeArguments(); Type[] toArgs = to.getActualTypeArguments(); for (int i = 0; i < fromArgs.length; i++) { if (!matches(fromArgs[i], toArgs[i], typeVarMap)) { return false; } } return true; } return false; }
java
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) { if (to.equals(from)) return true; if (from instanceof TypeVariable) { return to.equals(typeMap.get(((TypeVariable<?>) from).getName())); } return false; }
java
private static boolean isAssignableFrom(Type from, GenericArrayType to) { Type toGenericComponentType = to.getGenericComponentType(); if (toGenericComponentType instanceof ParameterizedType) { Type t = from; if (from instanceof GenericArrayType) { t = ((GenericArrayType) from).getGenericComponentType(); } else if (from instanceof Class) { Class<?> classType = (Class<?>) from; while (classType.isArray()) { classType = classType.getComponentType(); } t = classType; } return isAssignableFrom(t, (ParameterizedType) toGenericComponentType, new HashMap<String, Type>()); } // No generic defined on "to"; therefore, return true and let other // checks determine assignability return true; }
java
@Override public void setValue(String value, boolean fireEvents) { boolean added = setSelectedValue(this, value, addMissingValue); if (added && fireEvents) { ValueChangeEvent.fire(this, getValue()); } }
java
public static final String getSelectedValue(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getValue(index) : null; }
java
public static final String getSelectedText(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getItemText(index) : null; }
java
public static final int findValueInListBox(ListBox list, String value) { for (int i=0; i<list.getItemCount(); i++) { if (value.equals(list.getValue(i))) { return i; } } return -1; }
java
public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) { if (value == null) { list.setSelectedIndex(0); return false; } else { int index = findValueInListBox(list, value); if (index >= 0) { list.setSelectedIndex(index); return true; } if (addMissingValues) { list.addItem(value, value); // now that it's there, search again index = findValueInListBox(list, value); list.setSelectedIndex(index); return true; } return false; } }
java
public static String capitalizePropertyName(String s) { if (s.length() == 0) { return s; } char[] chars = s.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return new String(chars); }
java
public static Method getGetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "get" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod == null) { sourceMethodName = "is" + BeanUtils.capitalizePropertyName(propertyName); sourceMethod = BeanUtils.getMethod(type, sourceMethodName); if (sourceMethod != null && sourceMethod.getReturnType() != Boolean.TYPE) { sourceMethod = null; } } return sourceMethod; }
java
public static Method getSetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "set" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); return sourceMethod; }
java
@Override public Optional<SoyMapData> toSoyMap(@Nullable final Object model) throws Exception { if (model instanceof SoyMapData) { return Optional.of((SoyMapData) model); } if (model instanceof Map) { return Optional.of(new SoyMapData(model)); } return Optional.of(new SoyMapData()); }
java
@Override public int getShadowSize() { Element shadowElement = shadow.getElement(); shadowElement.setScrollTop(10000); return shadowElement.getScrollTop(); }
java
public Object get(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { return convertedObjects.get(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
java
public void add(IConverter converter, Object sourceObject, TypeReference<?> destinationType, Object convertedObject) { convertedObjects.put(new ConvertedObjectsKey(converter, sourceObject, destinationType), convertedObject); }
java
public void remove(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { convertedObjects.remove(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
java