_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8700 | Check.matches | train | private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {
return pattern.matcher(chars).matches();
} | java | {
"resource": ""
} |
q8701 | ConditionalCheck.isNumber | train | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class })
public static void isNumber(final boolean condition, @Nonnull final String value) {
if (condition) {
Check.isNumber(value);
}
} | java | {
"resource": ""
} |
q8702 | Trajectory.subList | train | @Override
public Trajectory subList(int fromIndex, int toIndex) {
Trajectory t = new Trajectory(dimension);
for(int i = fromIndex; i < toIndex; i++){
t.add(this.get(i));
}
return t;
} | java | {
"resource": ""
} |
q8703 | Trajectory.getPositionsAsArray | train | public double[][] getPositionsAsArray(){
double[][] posAsArr = new double[size()][3];
for(int i = 0; i < size(); i++){
if(get(i)!=null){
posAsArr[i][0] = get(i).x;
posAsArr[i][1] = get(i).y;
posAsArr[i][2] = get(i).z;
}
else{
posAsArr[i] = null;
}
}
return posAsArr;
} | java | {
"resource": ""
} |
q8704 | Trajectory.scale | train | public void scale(double v){
for(int i = 0; i < this.size(); i++){
this.get(i).scale(v);;
}
} | java | {
"resource": ""
} |
q8705 | MyNumberUtils.randomIntBetween | train | public static int randomIntBetween(int min, int max) {
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
} | java | {
"resource": ""
} |
q8706 | MyNumberUtils.randomLongBetween | train | public static long randomLongBetween(long min, long max) {
Random rand = new Random();
return min + (long) (rand.nextDouble() * (max - min));
} | java | {
"resource": ""
} |
q8707 | MyImageUtils.getTrimmedXStart | train | private static int getTrimmedXStart(BufferedImage img) {
int height = img.getHeight();
int width = img.getWidth();
int xStart = width;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {
xStart = j;
break;
}
}
}
return xStart;
} | java | {
"resource": ""
} |
q8708 | MyImageUtils.getTrimmedWidth | train | private static int getTrimmedWidth(BufferedImage img) {
int height = img.getHeight();
int width = img.getWidth();
int trimmedWidth = 0;
for (int i = 0; i < height; i++) {
for (int j = width - 1; j >= 0; j--) {
if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {
trimmedWidth = j;
break;
}
}
}
return trimmedWidth;
} | java | {
"resource": ""
} |
q8709 | MyImageUtils.getTrimmedYStart | train | private static int getTrimmedYStart(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int yStart = height;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (img.getRGB(i, j) != Color.WHITE.getRGB() && j < yStart) {
yStart = j;
break;
}
}
}
return yStart;
} | java | {
"resource": ""
} |
q8710 | MyImageUtils.getTrimmedHeight | train | private static int getTrimmedHeight(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int trimmedHeight = 0;
for (int i = 0; i < width; i++) {
for (int j = height - 1; j >= 0; j--) {
if (img.getRGB(i, j) != Color.WHITE.getRGB() && j > trimmedHeight) {
trimmedHeight = j;
break;
}
}
}
return trimmedHeight;
} | java | {
"resource": ""
} |
q8711 | MyImageUtils.resizeToHeight | train | public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int heightPercent = (heightOut * 100) / height;
int newWidth = (width * heightPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);
g.dispose();
return resizedImage;
} | java | {
"resource": ""
} |
q8712 | MyImageUtils.resizeToWidth | train | public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int widthPercent = (widthOut * 100) / width;
int newHeight = (height * widthPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);
g.dispose();
return resizedImage;
} | java | {
"resource": ""
} |
q8713 | MyStringUtils.regexFindFirst | train | public static String regexFindFirst(String pattern, String str) {
return regexFindFirst(Pattern.compile(pattern), str, 1);
} | java | {
"resource": ""
} |
q8714 | MyStringUtils.asListLines | train | public static List<String> asListLines(String content) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
retorno.add(str);
}
return retorno;
} | java | {
"resource": ""
} |
q8715 | MyStringUtils.asListLinesIgnore | train | public static List<String> asListLinesIgnore(String content, Pattern ignorePattern) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
if (!ignorePattern.matcher(str).matches()) {
retorno.add(str);
}
}
return retorno;
} | java | {
"resource": ""
} |
q8716 | MyStringUtils.getContentMap | train | public static Map<String, String> getContentMap(File file, String separator) throws IOException {
List<String> content = getContentLines(file);
Map<String, String> map = new LinkedHashMap<String, String>();
for (String line : content) {
String[] spl = line.split(separator);
if (line.trim().length() > 0) {
map.put(spl[0], (spl.length > 1 ? spl[1] : ""));
}
}
return map;
} | java | {
"resource": ""
} |
q8717 | MyStringUtils.saveContentMap | train | public static void saveContentMap(Map<String, String> map, File file) throws IOException {
FileWriter out = new FileWriter(file);
for (String key : map.keySet()) {
if (map.get(key) != null) {
out.write(key.replace(":", "#escapedtwodots#") + ":"
+ map.get(key).replace(":", "#escapedtwodots#") + "\r\n");
}
}
out.close();
} | java | {
"resource": ""
} |
q8718 | MyStringUtils.getTabularData | train | public static String getTabularData(String[] labels, String[][] data, int padding) {
int[] size = new int[labels.length];
for (int i = 0; i < labels.length; i++) {
size[i] = labels[i].length() + padding;
}
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
if (row[i].length() >= size[i]) {
size[i] = row[i].length() + padding;
}
}
}
StringBuffer tabularData = new StringBuffer();
for (int i = 0; i < labels.length; i++) {
tabularData.append(labels[i]);
tabularData.append(fill(' ', size[i] - labels[i].length()));
}
tabularData.append("\n");
for (int i = 0; i < labels.length; i++) {
tabularData.append(fill('=', size[i] - 1)).append(" ");
}
tabularData.append("\n");
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
tabularData.append(row[i]);
tabularData.append(fill(' ', size[i] - row[i].length()));
}
tabularData.append("\n");
}
return tabularData.toString();
} | java | {
"resource": ""
} |
q8719 | MyStringUtils.replaceHtmlEntities | train | public static String replaceHtmlEntities(String content, Map<String, Character> map) {
for (Entry<String, Character> entry : escapeStrings.entrySet()) {
if (content.indexOf(entry.getKey()) != -1) {
content = content.replace(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return content;
} | java | {
"resource": ""
} |
q8720 | LinkerBinderManager.add | train | public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);
declarationBinders.put(declarationBinderRef, binderDescriptor);
} | java | {
"resource": ""
} |
q8721 | LinkerBinderManager.modified | train | public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
declarationBinders.get(declarationBinderRef).update(declarationBinderRef);
} | java | {
"resource": ""
} |
q8722 | LinkerBinderManager.createLinks | train | public void createLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {
linkerManagement.link(declaration, declarationBinderRef);
}
}
} | java | {
"resource": ""
} |
q8723 | LinkerBinderManager.updateLinks | train | public void updateLinks(ServiceReference<S> serviceReference) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);
boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);
if (isAlreadyLinked && !canBeLinked) {
linkerManagement.unlink(declaration, serviceReference);
} else if (!isAlreadyLinked && canBeLinked) {
linkerManagement.link(declaration, serviceReference);
}
}
} | java | {
"resource": ""
} |
q8724 | LinkerBinderManager.removeLinks | train | public void removeLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {
linkerManagement.unlink(declaration, declarationBinderRef);
}
}
} | java | {
"resource": ""
} |
q8725 | LinkerBinderManager.getMatchedDeclarationBinder | train | public Set<S> getMatchedDeclarationBinder() {
Set<S> bindedSet = new HashSet<S>();
for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {
if (e.getValue().match) {
bindedSet.add(getDeclarationBinder(e.getKey()));
}
}
return bindedSet;
} | java | {
"resource": ""
} |
q8726 | MyZipUtils.extract | train | public static List<File> extract(File zipFile, File outputFolder) throws IOException {
List<File> extracted = new ArrayList<File>();
byte[] buffer = new byte[2048];
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
String neFileNameName = zipEntry.getName();
File newFile = new File(outputFolder + File.separator + neFileNameName);
newFile.getParentFile().mkdirs();
if (!zipEntry.isDirectory()) {
FileOutputStream fos = new FileOutputStream(newFile);
int size;
while ((size = zipInput.read(buffer)) > 0) {
fos.write(buffer, 0, size);
}
fos.close();
extracted.add(newFile);
}
zipEntry = zipInput.getNextEntry();
}
zipInput.closeEntry();
zipInput.close();
return extracted;
} | java | {
"resource": ""
} |
q8727 | MyZipUtils.validateZip | train | public static void validateZip(File file) throws IOException {
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
zipEntry = zipInput.getNextEntry();
}
try {
if (zipInput != null) {
zipInput.close();
}
} catch (IOException e) {
}
} | java | {
"resource": ""
} |
q8728 | MyZipUtils.compress | train | public static void compress(File dir, File zipFile) throws IOException {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
recursiveAddZip(dir, zos, dir);
zos.finish();
zos.close();
} | java | {
"resource": ""
} |
q8729 | MyZipUtils.recursiveAddZip | train | public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)
throws IOException {
File[] files = fileSource.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recursiveAddZip(parent, zout, files[i]);
continue;
}
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
ZipEntry zipEntry =
new ZipEntry(files[i].getAbsolutePath()
.replace(parent.getAbsolutePath(), "").substring(1)); //$NON-NLS-1$
zout.putNextEntry(zipEntry);
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
} | java | {
"resource": ""
} |
q8730 | MyStreamUtils.readContent | train | public static String readContent(InputStream is) {
String ret = "";
try {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer out = new StringBuffer();
while ((line = in.readLine()) != null) {
out.append(line).append(CARRIAGE_RETURN);
}
ret = out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
} | java | {
"resource": ""
} |
q8731 | MyStreamUtils.streamHasText | train | public static boolean streamHasText(InputStream in, String text) {
final byte[] readBuffer = new byte[8192];
StringBuffer sb = new StringBuffer();
try {
if (in.available() > 0) {
int bytesRead = 0;
while ((bytesRead = in.read(readBuffer)) != -1) {
sb.append(new String(readBuffer, 0, bytesRead));
if (sb.toString().contains(text)) {
sb = null;
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} | java | {
"resource": ""
} |
q8732 | PhilipsPreference.tryWritePreferenceOnDisk | train | private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {
final String DUMMY_PROP="dummywrite";
instance.put(DUMMY_PROP,"test");
instance.flush();
instance.remove(DUMMY_PROP);
instance.flush();
} | java | {
"resource": ""
} |
q8733 | KNXNetworkLinkFT12.doSend | train | private void doSend(byte[] msg, boolean wait, KNXAddress dst)
throws KNXAckTimeoutException, KNXLinkClosedException
{
if (closed)
throw new KNXLinkClosedException("link closed");
try {
logger.info("send message to " + dst + (wait ? ", wait for ack" : ""));
logger.trace("EMI " + DataUnitBuilder.toHex(msg, " "));
conn.send(msg, wait);
logger.trace("send to " + dst + " succeeded");
}
catch (final KNXPortClosedException e) {
logger.error("send error, closing link", e);
close();
throw new KNXLinkClosedException("link closed, " + e.getMessage());
}
} | java | {
"resource": ""
} |
q8734 | SerialMessage.bb2hex | train | static public String bb2hex(byte[] bb) {
String result = "";
for (int i=0; i<bb.length; i++) {
result = result + String.format("%02X ", bb[i]);
}
return result;
} | java | {
"resource": ""
} |
q8735 | SerialMessage.calculateChecksum | train | private static byte calculateChecksum(byte[] buffer) {
byte checkSum = (byte)0xFF;
for (int i=1; i<buffer.length-1; i++) {
checkSum = (byte) (checkSum ^ buffer[i]);
}
logger.trace(String.format("Calculated checksum = 0x%02X", checkSum));
return checkSum;
} | java | {
"resource": ""
} |
q8736 | SerialMessage.getMessageBuffer | train | public byte[] getMessageBuffer() {
ByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();
byte[] result;
resultByteBuffer.write((byte)0x01);
int messageLength = messagePayload.length +
(this.messageClass == SerialMessageClass.SendData &&
this.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length
resultByteBuffer.write((byte) messageLength);
resultByteBuffer.write((byte) messageType.ordinal());
resultByteBuffer.write((byte) messageClass.getKey());
try {
resultByteBuffer.write(messagePayload);
} catch (IOException e) {
}
// callback ID and transmit options for a Send Data message.
if (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {
resultByteBuffer.write(transmitOptions);
resultByteBuffer.write(callbackId);
}
resultByteBuffer.write((byte) 0x00);
result = resultByteBuffer.toByteArray();
result[result.length - 1] = 0x01;
result[result.length - 1] = calculateChecksum(result);
logger.debug("Assembled message buffer = " + SerialMessage.bb2hex(result));
return result;
} | java | {
"resource": ""
} |
q8737 | Settings.getBundle | train | private static String getBundle(String friendlyName, String className, int truncate)
{
try {
cl.loadClass(className);
int start = className.length();
for (int i = 0; i < truncate; ++i)
start = className.lastIndexOf('.', start - 1);
final String bundle = className.substring(0, start);
return "+ " + friendlyName + align(friendlyName) + "- " + bundle;
}
catch (final ClassNotFoundException e) {}
catch (final NoClassDefFoundError e) {}
return "- " + friendlyName + align(friendlyName) + "- not available";
} | java | {
"resource": ""
} |
q8738 | JAXWSImporter.registerProxy | train | protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
ServiceRegistration registration;
registration = context.registerService(clazz, objectProxy, props);
return registration;
} | java | {
"resource": ""
} |
q8739 | JAXWSImporter.denyImportDeclaration | train | @Override
protected void denyImportDeclaration(ImportDeclaration importDeclaration) {
LOG.debug("CXFImporter destroy a proxy for " + importDeclaration);
ServiceRegistration serviceRegistration = map.get(importDeclaration);
serviceRegistration.unregister();
// set the importDeclaration has unhandled
super.unhandleImportDeclaration(importDeclaration);
map.remove(importDeclaration);
} | java | {
"resource": ""
} |
q8740 | ImmutableObjectGenerator.generate | train | public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {
Check.notNull(code, "code");
final ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, "settings"));
final InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);
final Clazz clazz = scaffoldClazz(analysis, settings);
// immutable settings
settingsBuilder.fields(clazz.getFields());
settingsBuilder.immutableName(clazz.getName());
settingsBuilder.imports(clazz.getImports());
final Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));
settingsBuilder.mainInterface(definition);
settingsBuilder.interfaces(clazz.getInterfaces());
settingsBuilder.packageDeclaration(clazz.getPackage());
final String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));
final String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));
return new Result(implementationCode, testCode);
} | java | {
"resource": ""
} |
q8741 | MyClasspathUtils.addJarToClasspath | train | public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException {
URLClassLoader sysloader = (URLClassLoader) loader;
Class<?> sysclass = URLClassLoader.class;
Method method =
sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});
method.setAccessible(true);
method.invoke(sysloader, new Object[] {url});
} | java | {
"resource": ""
} |
q8742 | ZWaveNode.resetResendCount | train | public void resetResendCount() {
this.resendCount = 0;
if (this.initializationComplete)
this.nodeStage = NodeStage.NODEBUILDINFO_DONE;
this.lastUpdated = Calendar.getInstance().getTime();
} | java | {
"resource": ""
} |
q8743 | ZWaveNode.addCommandClass | train | public void addCommandClass(ZWaveCommandClass commandClass)
{
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
if (commandClass instanceof ZWaveEventListener)
this.controller.addEventListener((ZWaveEventListener)commandClass);
this.lastUpdated = Calendar.getInstance().getTime();
}
} | java | {
"resource": ""
} |
q8744 | WebUtil.getPostString | train | public static String getPostString(InputStream is, String encoding) {
try {
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw, encoding);
return sw.toString();
} catch (IOException e) {
// no op
return null;
} finally {
IOUtils.closeQuietly(is);
}
} | java | {
"resource": ""
} |
q8745 | WebUtil.outputString | train | public static void outputString(final HttpServletResponse response, final Object obj) {
try {
response.setContentType("text/javascript");
response.setCharacterEncoding("utf-8");
disableCache(response);
response.getWriter().write(obj.toString());
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
}
} | java | {
"resource": ""
} |
q8746 | StokesEinsteinConverter.convert | train | public double convert(double value, double temperatur, double viscosity){
return temperatur*kB / (Math.PI*viscosity*value);
} | java | {
"resource": ""
} |
q8747 | MyReflectionUtils.buildInstanceForMap | train | public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());
} | java | {
"resource": ""
} |
q8748 | MyReflectionUtils.buildInstanceForMap | train | public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
log.debug("Building new instance of Class " + clazz.getName());
T instance = clazz.newInstance();
for (String key : values.keySet()) {
Object value = values.get(key);
if (value == null) {
log.debug("Value for field " + key + " is null, so ignoring it...");
continue;
}
log.debug(
"Invoke setter for " + key + " (" + value.getClass() + " / " + value.toString() + ")");
Method setter = null;
try {
setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();
} catch (Exception e) {
throw new IllegalArgumentException("Setter for field " + key + " was not found", e);
}
Class<?> argumentType = setter.getParameterTypes()[0];
if (argumentType.isAssignableFrom(value.getClass())) {
setter.invoke(instance, value);
} else {
Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);
setter.invoke(instance, newValue);
}
}
return instance;
} | java | {
"resource": ""
} |
q8749 | FuchsiaUtils.getExportedPackage | train | private static BundleCapability getExportedPackage(BundleContext context, String packageName) {
List<BundleCapability> packages = new ArrayList<BundleCapability>();
for (Bundle bundle : context.getBundles()) {
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {
String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
if (pName.equalsIgnoreCase(packageName)) {
packages.add(packageCapability);
}
}
}
Version max = Version.emptyVersion;
BundleCapability maxVersion = null;
for (BundleCapability aPackage : packages) {
Version version = (Version) aPackage.getAttributes().get("version");
if (max.compareTo(version) <= 0) {
max = version;
maxVersion = aPackage;
}
}
return maxVersion;
} | java | {
"resource": ""
} |
q8750 | DefaultEntityResolver.readXMLDeclaration | train | private String[] readXMLDeclaration(Reader r) throws KNXMLException
{
final StringBuffer buf = new StringBuffer(100);
try {
for (int c = 0; (c = r.read()) != -1 && c != '?';)
buf.append((char) c);
}
catch (final IOException e) {
throw new KNXMLException("reading XML declaration, " + e.getMessage(), buf
.toString(), 0);
}
String s = buf.toString().trim();
String version = null;
String encoding = null;
String standalone = null;
for (int state = 0; state < 3; ++state)
if (state == 0 && s.startsWith("version")) {
version = getAttValue(s = s.substring(7));
s = s.substring(s.indexOf(version) + version.length() + 1).trim();
}
else if (state == 1 && s.startsWith("encoding")) {
encoding = getAttValue(s = s.substring(8));
s = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();
}
else if (state == 1 || state == 2) {
if (s.startsWith("standalone")) {
standalone = getAttValue(s);
if (!standalone.equals("yes") && !standalone.equals("no"))
throw new KNXMLException("invalid standalone pseudo-attribute",
standalone, 0);
break;
}
}
else
throw new KNXMLException("unknown XML declaration pseudo-attribute", s, 0);
return new String[] { version, encoding, standalone };
} | java | {
"resource": ""
} |
q8751 | DeclarationImpl.fetchServiceId | train | private Long fetchServiceId(ServiceReference serviceReference) {
return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);
} | java | {
"resource": ""
} |
q8752 | ZWaveDeviceClass.setSpecificDeviceClass | train | public void setSpecificDeviceClass(Specific specificDeviceClass) throws IllegalArgumentException {
// The specific Device class does not match the generic device class.
if (specificDeviceClass.genericDeviceClass != Generic.NOT_KNOWN &&
specificDeviceClass.genericDeviceClass != this.genericDeviceClass)
throw new IllegalArgumentException("specificDeviceClass");
this.specificDeviceClass = specificDeviceClass;
} | java | {
"resource": ""
} |
q8753 | WeatherForeCastWSImpl.parseRssFeed | train | private String parseRssFeed(String feed) {
String[] result = feed.split("<br />");
String[] result2 = result[2].split("<BR />");
return result2[0];
} | java | {
"resource": ""
} |
q8754 | WeatherForeCastWSImpl.parseRssFeedForeCast | train | private List<String> parseRssFeedForeCast(String feed) {
String[] result = feed.split("<br />");
List<String> returnList = new ArrayList<String>();
String[] result2 = result[2].split("<BR />");
returnList.add(result2[3] + "\n");
returnList.add(result[3] + "\n");
returnList.add(result[4] + "\n");
returnList.add(result[5] + "\n");
returnList.add(result[6] + "\n");
return returnList;
} | java | {
"resource": ""
} |
q8755 | ZWaveAlarmSensorCommandClass.getMessage | train | public SerialMessage getMessage(AlarmType alarmType) {
logger.debug("Creating new message for application command SENSOR_ALARM_GET for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_GET,
(byte) alarmType.getKey() };
result.setMessagePayload(newPayload);
return result;
} | java | {
"resource": ""
} |
q8756 | ZWaveAlarmSensorCommandClass.getSupportedMessage | train | public SerialMessage getSupportedMessage() {
logger.debug("Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}", this.getNode().getNodeId());
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 null;
}
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
2,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_SUPPORTED_GET };
result.setMessagePayload(newPayload);
return result;
} | java | {
"resource": ""
} |
q8757 | ZWaveAlarmSensorCommandClass.initialize | train | 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 | {
"resource": ""
} |
q8758 | DateUtils.newDateTime | train | public static java.util.Date newDateTime() {
return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);
} | java | {
"resource": ""
} |
q8759 | DateUtils.newDate | train | public static java.sql.Date newDate() {
return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);
} | java | {
"resource": ""
} |
q8760 | DateUtils.newTime | train | public static java.sql.Time newTime() {
return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);
} | java | {
"resource": ""
} |
q8761 | DateUtils.secondsDiff | train | 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 | {
"resource": ""
} |
q8762 | DateUtils.minutesDiff | train | 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 | {
"resource": ""
} |
q8763 | DateUtils.hoursDiff | train | 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 | {
"resource": ""
} |
q8764 | DateUtils.daysDiff | train | 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 | {
"resource": ""
} |
q8765 | DateUtils.rollTime | train | 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 | {
"resource": ""
} |
q8766 | DateUtils.rollDateTime | train | 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 | {
"resource": ""
} |
q8767 | DateUtils.rollYears | train | public static java.sql.Date rollYears(java.util.Date startDate, int years) {
return rollDate(startDate, Calendar.YEAR, years);
} | java | {
"resource": ""
} |
q8768 | DateUtils.dateEquals | train | @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 | {
"resource": ""
} |
q8769 | DateUtils.timeEquals | train | @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 | {
"resource": ""
} |
q8770 | DateUtils.dateTimeEquals | train | @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 | {
"resource": ""
} |
q8771 | DateUtils.toObject | train | 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 | {
"resource": ""
} |
q8772 | DateUtils.getDateTime | train | public static java.util.Date getDateTime(Object value) {
try {
return toDateTime(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q8773 | DateUtils.toDateTime | train | 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 | {
"resource": ""
} |
q8774 | DateUtils.getDate | train | public static java.sql.Date getDate(Object value) {
try {
return toDate(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q8775 | DateUtils.toDate | train | 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 | {
"resource": ""
} |
q8776 | DateUtils.getTime | train | public static java.sql.Time getTime(Object value) {
try {
return toTime(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q8777 | DateUtils.toTime | train | 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 | {
"resource": ""
} |
q8778 | DateUtils.getTimestamp | train | public static java.sql.Timestamp getTimestamp(Object value) {
try {
return toTimestamp(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q8779 | DateUtils.toTimestamp | train | 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 | {
"resource": ""
} |
q8780 | DateUtils.isTimeInRange | train | @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 | {
"resource": ""
} |
q8781 | TrajectoryUtil.combineTrajectory | train | 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 | {
"resource": ""
} |
q8782 | TrajectoryUtil.concactTrajectorie | train | 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 | {
"resource": ""
} |
q8783 | TrajectoryUtil.resample | train | 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 | {
"resource": ""
} |
q8784 | TrajectoryUtil.getTrajectoryByID | train | 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 | {
"resource": ""
} |
q8785 | BeanPropertyTypeProvider.setPropertyDestinationType | train | public void setPropertyDestinationType(Class<?> clazz, String propertyName,
TypeReference<?> destinationType) {
propertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType);
} | java | {
"resource": ""
} |
q8786 | MultiConverter.addConverter | train | 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 | {
"resource": ""
} |
q8787 | SPIProviderResolver.getInstance | train | public static SPIProviderResolver getInstance(ClassLoader cl)
{
SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);
return resolver;
} | java | {
"resource": ""
} |
q8788 | DirectivesParser.createParameter | train | 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 | {
"resource": ""
} |
q8789 | LangUtils.getClassAnnotationValue | train | 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 | {
"resource": ""
} |
q8790 | UTCDateBoxImplHtml5.string2long | train | 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 | {
"resource": ""
} |
q8791 | UTCDateBoxImplHtml5.long2string | train | 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 | {
"resource": ""
} |
q8792 | RgbaColor.from | train | 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 | {
"resource": ""
} |
q8793 | RgbaColor.fromHex | train | 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 | {
"resource": ""
} |
q8794 | RgbaColor.fromRgb | train | 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 | {
"resource": ""
} |
q8795 | RgbaColor.fromRgba | train | 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 | {
"resource": ""
} |
q8796 | RgbaColor.withHsl | train | private RgbaColor withHsl(int index, float value) {
float[] HSL = convertToHsl();
HSL[index] = value;
return RgbaColor.fromHsl(HSL);
} | java | {
"resource": ""
} |
q8797 | RgbaColor.adjustHue | train | public RgbaColor adjustHue(float degrees) {
float[] HSL = convertToHsl();
HSL[0] = hueCheck(HSL[0] + degrees); // ensure [0-360)
return RgbaColor.fromHsl(HSL);
} | java | {
"resource": ""
} |
q8798 | RgbaColor.opacify | train | public RgbaColor opacify(float amount) {
return new RgbaColor(r, g, b, alphaCheck(a + amount));
} | java | {
"resource": ""
} |
q8799 | RgbaColor.getSpreadInRange | train | 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 | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.