_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q8800
RgbaColor.fromHsl
train
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
{ "resource": "" }
q8801
RgbaColor.max
train
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
{ "resource": "" }
q8802
ObjectToObjectUsingConstructor.getCompatibleConstructor
train
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
{ "resource": "" }
q8803
Transmorph.convert
train
public <T> T convert(Object source, TypeReference<T> typeReference) throws ConverterException { return (T) convert(new ConversionContext(), source, typeReference); }
java
{ "resource": "" }
q8804
Transmorph.convert
train
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
{ "resource": "" }
q8805
Utilities.compare
train
public static int compare(double a, double b, double delta) { if (equals(a, b, delta)) { return 0; } return Double.compare(a, b); }
java
{ "resource": "" }
q8806
AbstractSumBatchFunction.getValue
train
public double getValue(int[] batch) { double value = 0.0; for (int i=0; i<batch.length; i++) { value += getValue(i); } return value; }
java
{ "resource": "" }
q8807
AbstractSumBatchFunction.getGradient
train
public void getGradient(int[] batch, double[] gradient) { for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
java
{ "resource": "" }
q8808
CupboardDbHelper.getConnection
train
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
{ "resource": "" }
q8809
TypeReference.getSuperclassTypeParameter
train
@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
{ "resource": "" }
q8810
AutoSizingBase.onLoad
train
@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
{ "resource": "" }
q8811
AutoSizingBase.onKeyDown
train
@Override public void onKeyDown(KeyDownEvent event) { char c = MiscUtils.getCharCode(event.getNativeEvent()); onKeyCodeEvent(event, box.getValue()+c); }
java
{ "resource": "" }
q8812
DomUtils.setEnabled
train
public static void setEnabled(Element element, boolean enabled) { element.setPropertyBoolean("disabled", !enabled); setStyleName(element, "disabled", !enabled); }
java
{ "resource": "" }
q8813
BeanToBean.getPropertySourceMethod
train
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
{ "resource": "" }
q8814
BeanToBean.getBeanPropertyType
train
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
{ "resource": "" }
q8815
BeanToBean.addBeanToBeanMapping
train
public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) { beanToBeanMappings.put(ClassPair.get(beanToBeanMapping .getSourceClass(), beanToBeanMapping.getDestinationClass()), beanToBeanMapping); }
java
{ "resource": "" }
q8816
SPIProvider.getInstance
train
public static SPIProvider getInstance() { if (me == null) { final ClassLoader cl = ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader(); me = SPIProviderResolver.getInstance(cl).getProvider(); } return me; }
java
{ "resource": "" }
q8817
SPIProvider.getSPI
train
public <T> T getSPI(Class<T> spiType) { return getSPI(spiType, SecurityActions.getContextClassLoader()); }
java
{ "resource": "" }
q8818
DefaultSoyMsgBundleResolver.resolve
train
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
{ "resource": "" }
q8819
DefaultSoyMsgBundleResolver.mergeMsgBundles
train
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
{ "resource": "" }
q8820
MD5HashFileGenerator.hash
train
@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
{ "resource": "" }
q8821
StringUtils.allUpperCase
train
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
{ "resource": "" }
q8822
StringUtils.allLowerCase
train
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
{ "resource": "" }
q8823
ClassTypeSignature.getTypeErasureSignature
train
public FullTypeSignature getTypeErasureSignature() { if (typeErasureSignature == null) { typeErasureSignature = new ClassTypeSignature(binaryName, new TypeArgSignature[0], ownerTypeSignature == null ? null : (ClassTypeSignature) ownerTypeSignature .getTypeErasureSignature()); } return typeErasureSignature; }
java
{ "resource": "" }
q8824
MIMEType.addParameter
train
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
{ "resource": "" }
q8825
DefaultContentNegotiator.contentTypes
train
@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
{ "resource": "" }
q8826
HTTPRequest.getAllHeaders
train
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
{ "resource": "" }
q8827
DifferentiableFunctionOpts.getRegularizedOptimizer
train
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
{ "resource": "" }
q8828
RomanNumeral.toRomanNumeral
train
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
{ "resource": "" }
q8829
AdaGradSchedule.takeNoteOfGradient
train
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
{ "resource": "" }
q8830
JavaTypeToTypeSignature.getArrayTypeSignature
train
private ArrayTypeSignature getArrayTypeSignature( GenericArrayType genericArrayType) { FullTypeSignature componentTypeSignature = getFullTypeSignature(genericArrayType .getGenericComponentType()); ArrayTypeSignature arrayTypeSignature = new ArrayTypeSignature( componentTypeSignature); return arrayTypeSignature; }
java
{ "resource": "" }
q8831
JavaTypeToTypeSignature.getClassTypeSignature
train
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
{ "resource": "" }
q8832
JavaTypeToTypeSignature.getTypeSignature
train
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
{ "resource": "" }
q8833
JavaTypeToTypeSignature.getTypeArgSignature
train
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
{ "resource": "" }
q8834
ZipUtils.zipFolder
train
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
{ "resource": "" }
q8835
ZipUtils.unzipFileOrFolder
train
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
{ "resource": "" }
q8836
UTCTimeBoxImplShared.formatUsingFormat
train
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
{ "resource": "" }
q8837
UTCTimeBoxImplShared.parseUsingFallbacksWithColon
train
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
{ "resource": "" }
q8838
TypeUtils.getRawType
train
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
{ "resource": "" }
q8839
TypeUtils.isAssignableFrom
train
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
{ "resource": "" }
q8840
TypeUtils.isAssignableFrom
train
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
{ "resource": "" }
q8841
TypeUtils.typeEquals
train
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
{ "resource": "" }
q8842
TypeUtils.matches
train
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
{ "resource": "" }
q8843
TypeUtils.isAssignableFrom
train
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
{ "resource": "" }
q8844
SingleListBox.setValue
train
@Override public void setValue(String value, boolean fireEvents) { boolean added = setSelectedValue(this, value, addMissingValue); if (added && fireEvents) { ValueChangeEvent.fire(this, getValue()); } }
java
{ "resource": "" }
q8845
SingleListBox.getSelectedValue
train
public static final String getSelectedValue(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getValue(index) : null; }
java
{ "resource": "" }
q8846
SingleListBox.getSelectedText
train
public static final String getSelectedText(ListBox list) { int index = list.getSelectedIndex(); return (index >= 0) ? list.getItemText(index) : null; }
java
{ "resource": "" }
q8847
SingleListBox.findValueInListBox
train
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
{ "resource": "" }
q8848
SingleListBox.setSelectedValue
train
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
{ "resource": "" }
q8849
BeanUtils.capitalizePropertyName
train
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
{ "resource": "" }
q8850
BeanUtils.getGetterPropertyMethod
train
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
{ "resource": "" }
q8851
BeanUtils.getSetterPropertyMethod
train
public static Method getSetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "set" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); return sourceMethod; }
java
{ "resource": "" }
q8852
NoConvertSoyDataConverter.toSoyMap
train
@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
{ "resource": "" }
q8853
AutoSizingTextArea.getShadowSize
train
@Override public int getShadowSize() { Element shadowElement = shadow.getElement(); shadowElement.setScrollTop(10000); return shadowElement.getScrollTop(); }
java
{ "resource": "" }
q8854
ConvertedObjectPool.get
train
public Object get(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { return convertedObjects.get(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
java
{ "resource": "" }
q8855
ConvertedObjectPool.add
train
public void add(IConverter converter, Object sourceObject, TypeReference<?> destinationType, Object convertedObject) { convertedObjects.put(new ConvertedObjectsKey(converter, sourceObject, destinationType), convertedObject); }
java
{ "resource": "" }
q8856
ConvertedObjectPool.remove
train
public void remove(IConverter converter, Object sourceObject, TypeReference<?> destinationType) { convertedObjects.remove(new ConvertedObjectsKey(converter, sourceObject, destinationType)); }
java
{ "resource": "" }
q8857
SampleFunction.convertBatch
train
private int[] convertBatch(int[] batch) { int[] conv = new int[batch.length]; for (int i=0; i<batch.length; i++) { conv[i] = sample[batch[i]]; } return conv; }
java
{ "resource": "" }
q8858
ListUtils.containsAtLeastOneNonBlank
train
public static boolean containsAtLeastOneNonBlank(List<String> list){ for(String str : list){ if(StringUtils.isNotBlank(str)){ return true; } } return false; }
java
{ "resource": "" }
q8859
ListUtils.toIntegerList
train
public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){ List<Integer> intList = new ArrayList<Integer>(); for(String str : strList){ try{ intList.add(Integer.parseInt(str)); } catch(NumberFormatException nfe){ if(failOnException){ return null; } else{ intList.add(null); } } } return intList; }
java
{ "resource": "" }
q8860
Vectors.add
train
public static void add(double[] array1, double[] array2) { assert (array1.length == array2.length); for (int i=0; i<array1.length; i++) { array1[i] += array2[i]; } }
java
{ "resource": "" }
q8861
ArrayUtils.containsOnlyNull
train
public static boolean containsOnlyNull(Object... values){ for(Object o : values){ if(o!= null){ return false; } } return true; }
java
{ "resource": "" }
q8862
ArrayUtils.containsOnlyNotNull
train
public static boolean containsOnlyNotNull(Object... values){ for(Object o : values){ if(o== null){ return false; } } return true; }
java
{ "resource": "" }
q8863
SoyAjaxController.compile
train
@RequestMapping(value="/soy/compileJs", method=GET) public ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash, @RequestParam(required = true, value = "file") final String[] templateFileNames, @RequestParam(required = false, value = "locale") String locale, @RequestParam(required = false, value = "disableProcessors", defaultValue = "false") String disableProcessors, final HttpServletRequest request) throws IOException { return compileJs(templateFileNames, hash, new Boolean(disableProcessors).booleanValue(), request, locale); }
java
{ "resource": "" }
q8864
BatchSampler.sampleBatchWithReplacement
train
public int[] sampleBatchWithReplacement() { // Sample the indices with replacement. int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { batch[i] = Prng.nextInt(numExamples); } return batch; }
java
{ "resource": "" }
q8865
BatchSampler.sampleBatchWithoutReplacement
train
public int[] sampleBatchWithoutReplacement() { int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { if (cur == indices.length) { cur = 0; } if (cur == 0) { IntArrays.shuffle(indices); } batch[i] = indices[cur++]; } return batch; }
java
{ "resource": "" }
q8866
TractionDialogBox.adjustGlassSize
train
public void adjustGlassSize() { if (isGlassEnabled()) { ResizeHandler handler = getGlassResizer(); if (handler != null) handler.onResize(null); } }
java
{ "resource": "" }
q8867
Bounds.getSymmetricBounds
train
public static Bounds getSymmetricBounds(int dim, double l, double u) { double [] L = new double[dim]; double [] U = new double[dim]; for(int i=0; i<dim; i++) { L[i] = l; U[i] = u; } return new Bounds(L, U); }
java
{ "resource": "" }
q8868
Tag.parse
train
public static Optional<Tag> parse(final String httpTag) { Tag result = null; boolean weak = false; String internal = httpTag; if (internal.startsWith("W/")) { weak = true; internal = internal.substring(2); } if (internal.startsWith("\"") && internal.endsWith("\"")) { result = new Tag( internal.substring(1, internal.length() - 1), weak); } else if (internal.equals("*")) { result = new Tag("*", weak); } return Optional.ofNullable(result); }
java
{ "resource": "" }
q8869
Tag.format
train
public String format() { if (getName().equals("*")) { return "*"; } else { StringBuilder sb = new StringBuilder(); if (isWeak()) { sb.append("W/"); } return sb.append('"').append(getName()).append('"').toString(); } }
java
{ "resource": "" }
q8870
UTF8PropertyResourceBundle.getBundle
train
public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{ InputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream("/"+baseName + "_"+locale.toString()+PROPERTIES_EXT); if(is != null){ return new PropertyResourceBundle(new InputStreamReader(is, "UTF-8")); } return null; }
java
{ "resource": "" }
q8871
SGD.minimize
train
@Override public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) { return minimize(function, point, null); }
java
{ "resource": "" }
q8872
AbstractSimpleBeanConverter.convertElement
train
@SuppressWarnings("unchecked") public <T> T convertElement(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { return (T) elementConverter.convert(context, source, destinationType); }
java
{ "resource": "" }
q8873
Conditionals.addIfMatch
train
public Conditionals addIfMatch(Tag tag) { Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE)); Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH)); List<Tag> match = new ArrayList<>(this.match); if (tag == null) { tag = Tag.ALL; } if (Tag.ALL.equals(tag)) { match.clear(); } if (!match.contains(Tag.ALL)) { if (!match.contains(tag)) { match.add(tag); } } else { throw new IllegalArgumentException("Tag ALL already in the list"); } return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince); }
java
{ "resource": "" }
q8874
Conditionals.ifModifiedSince
train
public Conditionals ifModifiedSince(LocalDateTime time) { Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH)); Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_UNMODIFIED_SINCE)); time = time.withNano(0); return new Conditionals(empty(), noneMatch, Optional.of(time), Optional.empty()); }
java
{ "resource": "" }
q8875
Conditionals.toHeaders
train
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get())); } if (unModifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get())); } return headers; }
java
{ "resource": "" }
q8876
WebserviceDescriptionMetaData.getPortComponentQNames
train
public Collection<QName> getPortComponentQNames() { //TODO:Check if there is just one QName that drives all portcomponents //or each port component can have a distinct QName (namespace/prefix) //Maintain uniqueness of the QName Map<String, QName> map = new HashMap<String, QName>(); for (PortComponentMetaData pcm : portComponents) { QName qname = pcm.getWsdlPort(); map.put(qname.getPrefix(), qname); } return map.values(); }
java
{ "resource": "" }
q8877
WebserviceDescriptionMetaData.getPortComponentByWsdlPort
train
public PortComponentMetaData getPortComponentByWsdlPort(String name) { ArrayList<String> pcNames = new ArrayList<String>(); for (PortComponentMetaData pc : portComponents) { String wsdlPortName = pc.getWsdlPort().getLocalPart(); if (wsdlPortName.equals(name)) return pc; pcNames.add(wsdlPortName); } Loggers.METADATA_LOGGER.cannotGetPortComponentName(name, pcNames); return null; }
java
{ "resource": "" }
q8878
Geometry.setBounds
train
public static final void setBounds(UIObject o, Rect bounds) { setPosition(o, bounds); setSize(o, bounds); }
java
{ "resource": "" }
q8879
Geometry.setPosition
train
public static final void setPosition(UIObject o, Rect pos) { Style style = o.getElement().getStyle(); style.setPropertyPx("left", pos.x); style.setPropertyPx("top", pos.y); }
java
{ "resource": "" }
q8880
Geometry.setSize
train
public static final void setSize(UIObject o, Rect size) { o.setPixelSize(size.w, size.h); }
java
{ "resource": "" }
q8881
Geometry.isInside
train
public static final boolean isInside(int x, int y, Rect box) { return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h); }
java
{ "resource": "" }
q8882
Geometry.isMouseInside
train
public static final boolean isMouseInside(NativeEvent event, Element element) { return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element)); }
java
{ "resource": "" }
q8883
Geometry.getViewportBounds
train
public static final Rect getViewportBounds() { return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight()); }
java
{ "resource": "" }
q8884
UTCDateBox.utc2date
train
public static final Date utc2date(Long time) { // don't accept negative values if (time == null || time < 0) return null; // add the timezone offset time += timezoneOffsetMillis(new Date(time)); return new Date(time); }
java
{ "resource": "" }
q8885
UTCDateBox.date2utc
train
public static final Long date2utc(Date date) { // use null for a null date if (date == null) return null; long time = date.getTime(); // remove the timezone offset time -= timezoneOffsetMillis(date); return time; }
java
{ "resource": "" }
q8886
TypeSignatureFactory.getTypeSignature
train
public static FullTypeSignature getTypeSignature(String typeSignatureString, boolean useInternalFormFullyQualifiedName) { String key; if (!useInternalFormFullyQualifiedName) { key = typeSignatureString.replace('.', '/') .replace('$', '.'); } else { key = typeSignatureString; } // we always use the internal form as a key for cache FullTypeSignature typeSignature = typeSignatureCache .get(key); if (typeSignature == null) { ClassFileTypeSignatureParser typeSignatureParser = new ClassFileTypeSignatureParser( typeSignatureString); typeSignatureParser.setUseInternalFormFullyQualifiedName(useInternalFormFullyQualifiedName); typeSignature = typeSignatureParser.parseTypeSignature(); typeSignatureCache.put(typeSignatureString, typeSignature); } return typeSignature; }
java
{ "resource": "" }
q8887
TypeSignatureFactory.getTypeSignature
train
public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) { ClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature .getTypeSignature(clazz); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length]; for (int i = 0; i < typeArgs.length; i++) { typeArgSignatures[i] = new TypeArgSignature( TypeArgSignature.NO_WILDCARD, (FieldTypeSignature) javaTypeToTypeSignature .getTypeSignature(typeArgs[i])); } ClassTypeSignature classTypeSignature = new ClassTypeSignature( rawClassTypeSignature.getBinaryName(), typeArgSignatures, rawClassTypeSignature.getOwnerTypeSignature()); return classTypeSignature; }
java
{ "resource": "" }
q8888
ResourceStrings.ofNullable
train
public static OptionalString ofNullable(ResourceKey key, String value) { return new GenericOptionalString(RUNTIME_SOURCE, key, value); }
java
{ "resource": "" }
q8889
AdlDeserializer.parse
train
public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } }
java
{ "resource": "" }
q8890
DaemonScanner.object2Array
train
@SuppressWarnings({"unchecked", "unused"}) public static <T> T[] object2Array(final Class<T> clazz, final Object obj) { return (T[]) obj; }
java
{ "resource": "" }
q8891
AsyncAssembly.pauseUpload
train
public void pauseUpload() throws LocalOperationException { if (state == State.UPLOADING) { setState(State.PAUSED); executor.hardStop(); } else { throw new LocalOperationException("Attempt to pause upload while assembly is not uploading"); } }
java
{ "resource": "" }
q8892
AsyncAssembly.watchStatus
train
protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException { AssemblyResponse response; do { response = getClient().getAssemblyByUrl(url); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new LocalOperationException(e); } } while (!response.isFinished()); setState(State.FINISHED); return response; }
java
{ "resource": "" }
q8893
AsyncAssembly.getTotalUploadSize
train
private long getTotalUploadSize() throws IOException { long size = 0; for (Map.Entry<String, File> entry : files.entrySet()) { size += entry.getValue().length(); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { size += entry.getValue().available(); } return size; }
java
{ "resource": "" }
q8894
InterconnectMapper.fromJson
train
public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException { return InterconnectMapper.mapper.readValue(data, clazz); }
java
{ "resource": "" }
q8895
Template.save
train
public Response save() throws RequestException, LocalOperationException { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("name", name); options.put("steps", steps.toMap()); templateData.put("template", options); Request request = new Request(transloadit); return new Response(request.post("/templates", templateData)); }
java
{ "resource": "" }
q8896
ServiceInfo.matches
train
public boolean matches(String resourcePath) { if (!valid) { return false; } if (resourcePath == null) { return acceptsContextPathEmpty; } if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) { return false; } if (contextPathBlacklistRegex != null && contextPathBlacklistRegex.matcher(resourcePath).matches()) { return false; } return true; }
java
{ "resource": "" }
q8897
JsonService.getClassLoader
train
private ClassLoaderInterface getClassLoader() { Map<String, Object> application = ActionContext.getContext().getApplication(); if (application != null) { return (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE); } return null; }
java
{ "resource": "" }
q8898
QueryStringBuilder.build
train
public @Nullable String build() { StringBuilder queryString = new StringBuilder(); for (NameValuePair param : params) { if (queryString.length() > 0) { queryString.append(PARAM_SEPARATOR); } queryString.append(Escape.urlEncode(param.getName())); queryString.append(VALUE_SEPARATOR); queryString.append(Escape.urlEncode(param.getValue())); } if (queryString.length() > 0) { return queryString.toString(); } else { return null; } }
java
{ "resource": "" }
q8899
Transloadit.cancelAssembly
train
public AssemblyResponse cancelAssembly(String url) throws RequestException, LocalOperationException { Request request = new Request(this); return new AssemblyResponse(request.delete(url, new HashMap<String, Object>())); }
java
{ "resource": "" }