code
stringlengths
73
34.1k
label
stringclasses
1 value
public static Date addHours(Date d, int hours) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.HOUR_OF_DAY, hours); return cal.getTime(); }
java
public static Date setHours(Date d, int hours) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.HOUR_OF_DAY, hours); return cal.getTime(); }
java
public static Date addDays(Date d, int days) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.DAY_OF_YEAR, days); return cal.getTime(); }
java
public static Date addWeeks(Date d, int weeks) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.WEEK_OF_YEAR, weeks); return cal.getTime(); }
java
public static Date addMonths(Date d, int months) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.MONTH, months); return cal.getTime(); }
java
public static int getLastDayOfMonth(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); return c.getActualMaximum(Calendar.DATE); }
java
public static Date getFromTimestamp(Timestamp timestamp) { if (timestamp == null) { return null; } return new Date(timestamp.getTime()); }
java
public static Date getFirstDayFromCurrentWeek(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.s...
java
public static Date getLastDayFromCurrentWeek(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); // depends on Locale (if a week starts on Monday or on Sunday) if (cal.getFirstDayOfWeek() == Calendar.SUNDAY) { cal.add(Calendar.WEEK_OF_YEAR, 1); } ...
java
public static Date getFirstDayFromLastMonth(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Cale...
java
public static Date getLastDayFromLastMonth(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.MONTH, -1); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE...
java
public static Date getFirstDayFromCurrentMonth(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); c...
java
public static Date getLastDayFromCurrentMonth(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Cal...
java
public static Date getFirstDayFromLastYear(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.YEAR, -1); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); ...
java
public static Date getFirstDayFromCurrentYear(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, ...
java
public static Date getLastDayFromCurrentYear(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); ...
java
public static Date getLastNDay(Date d, int n, int unitType) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(unitType, -n); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); ...
java
public void setTriggerContainer (JComponent comp, JPanel content, boolean collapsed) { // these are our only two components. add(comp); add(_content = content); // When the content is shown, make sure it's scrolled visible _content.addComponentListener(new ComponentAdapter()...
java
public void setTrigger (AbstractButton trigger, Icon collapsed, Icon uncollapsed) { _trigger = trigger; _trigger.setHorizontalAlignment(SwingConstants.LEFT); _trigger.setHorizontalTextPosition(SwingConstants.RIGHT); _downIcon = collapsed; _upIcon =...
java
public void setCollapsed (boolean collapse) { if (collapse) { _content.setVisible(false); _trigger.setIcon(_downIcon); } else { _content.setVisible(true); _trigger.setIcon(_upIcon); } SwingUtil.refresh(this); }
java
public static int[] add (int[] list, int value) { // make sure we've got a list to work with if (list == null) { return new int[] { value }; } // check to see if the element is in the list int llength = list.length; for (int i = 0; i < llength; i++) { ...
java
public static boolean contains (int[] list, int value) { int llength = list.length; // no optimizing bastards for (int i = 0; i < llength; i++) { if (list[i] == value) { return true; } } return false; }
java
public static int[] remove (int[] list, int value) { // nothing to remove from an empty list if (list == null) { return null; } // search for the index of the element to be removed int llength = list.length; // no optimizing bastards for (int i = 0; i < l...
java
public static int[] removeAt (int[] list, int index) { // this will NPE if the bastards passed a null list, which is how // we'll let them know not to do that int nlength = list.length-1; // create a new array minus the removed element int[] nlist = new int[nlength]; ...
java
public int incrementCount (K key, int amount) { int[] val = get(key); if (val == null) { put(key, val = new int[1]); } val[0] += amount; return val[0]; /* Alternate implementation, less hashing on the first increment but more garbage created * ev...
java
public int setCount (K key, int count) { int[] val = get(key); if (val == null) { put(key, new int[] { count }); return 0; // old value } int oldVal = val[0]; val[0] = count; return oldVal; }
java
public void compress () { for (Iterator<int[]> itr = values().iterator(); itr.hasNext(); ) { if (itr.next()[0] == 0) { itr.remove(); } } }
java
public static JInternalDialog createDialog (JFrame frame, JPanel content) { return createDialog(frame, null, content); }
java
public static JInternalDialog createDialog ( JFrame frame, String title, JPanel content) { JInternalDialog dialog = new JInternalDialog(frame); dialog.setOpaque(false); if (title != null) { dialog.setTitle(title); } setContent(dialog, content); Swi...
java
public static void setContent (JInternalDialog dialog, JPanel content) { Container holder = dialog.getContentPane(); holder.removeAll(); holder.add(content, BorderLayout.CENTER); dialog.pack(); }
java
public static JInternalDialog getInternalDialog (Component any) { Component parent = any; while (parent != null && !(parent instanceof JInternalDialog)) { parent = parent.getParent(); } return (JInternalDialog) parent; }
java
public static void invalidateDialog (Component any) { JInternalDialog dialog = getInternalDialog(any); if (dialog == null) { return; } SwingUtil.applyToHierarchy(dialog, new SwingUtil.ComponentOp() { public void apply (Component comp) { comp.i...
java
public int add (K key, int amount) { CountEntry<K> entry = _backing.get(key); if (entry == null) { _backing.put(key, new CountEntry<K>(key, amount)); return amount; } return (entry.count += amount); }
java
public int getCount (K key) { CountEntry<K> entry = _backing.get(key); return (entry == null) ? 0 : entry.count; }
java
public void compress () { for (Iterator<CountEntry<K>> it = _backing.values().iterator(); it.hasNext(); ) { if (it.next().count == 0) { it.remove(); } } }
java
protected <T> T pickPluck (Iterable<? extends T> iterable, T ifEmpty, boolean remove) { if (iterable instanceof Collection) { // optimized path for Collection @SuppressWarnings("unchecked") Collection<? extends T> coll = (Collection<? extends T>)iterable; int ...
java
public void postUnit (Unit unit) { if (shutdownRequested()) { throw new IllegalStateException("Cannot post units to shutdown invoker."); } // note the time unit.queueStamp = System.currentTimeMillis(); // and append it to the queue _queue.append(unit); ...
java
@Override public void shutdown () { _shutdownRequested = true; _queue.append(new Unit() { @Override public boolean invoke () { _running = false; return false; } }); }
java
protected void didInvokeUnit (Unit unit, long start) { // track some performance metrics if (PERF_TRACK) { long duration = System.currentTimeMillis() - start; Object key = unit.getClass(); recordMetrics(key, duration); // report long runners ...
java
public int compareTo (ComparableTuple<L, R> other) { int rv = ObjectUtil.compareTo(left, other.left); return (rv != 0) ? rv : ObjectUtil.compareTo(right, other.right); }
java
public void parseStream (InputStream stream) throws IOException { try { // read the XML input stream and construct the scene object _chars = new StringBuilder(); XMLUtil.parse(this, stream); } catch (ParserConfigurationException pce) { throw (...
java
protected InputStream getInputStream (String path) throws IOException { FileInputStream fis = new FileInputStream(path); return new BufferedInputStream(fis); }
java
protected int parseInt (String val) { try { return (val == null) ? -1 : Integer.parseInt(val); } catch (NumberFormatException nfe) { log.warning("Malformed integer value", "val", val); return -1; } }
java
public static String truncate (String s, int maxLength, String append) { if ((s == null) || (s.length() <= maxLength)) { return s; } else { return s.substring(0, maxLength - append.length()) + append; } }
java
public static String capitalize (String s) { if (isBlank(s)) { return s; } char c = s.charAt(0); if (Character.isUpperCase(c)) { return s; } else { return String.valueOf(Character.toUpperCase(c)) + s.substring(1); } }
java
public static String toUSLowerCase (String s) { return isBlank(s) ? s : s.toLowerCase(Locale.US); }
java
public static String toUSUpperCase (String s) { return isBlank(s) ? s : s.toUpperCase(Locale.US); }
java
public static String sanitize (String source, CharacterValidator validator) { if (source == null) { return null; } int nn = source.length(); StringBuilder buf = new StringBuilder(nn); for (int ii=0; ii < nn; ii++) { char c = source.charAt(ii); ...
java
public static String sanitize (String source, String charRegex) { final StringBuilder buf = new StringBuilder(" "); final Matcher matcher = Pattern.compile(charRegex).matcher(buf); return sanitize(source, new CharacterValidator() { public boolean isValid (char c) { ...
java
public static String pad (String value, int width, char c) { // sanity check if (width <= 0) { throw new IllegalArgumentException("Pad width must be greater than zero."); } int l = value.length(); return (l >= width) ? value : value + f...
java
public static String fill (char c, int count) { char[] sameChars = new char[count]; Arrays.fill(sameChars, c); return new String(sameChars); }
java
public static String[] split (String source, String sep) { // handle the special case of a zero-component source if (isBlank(source)) { return new String[0]; } int tcount = 0, tpos = -1, tstart = 0; // count up the number of tokens while ((tpos = source....
java
public static String wordWrap (String str, int width) { int size = str.length(); StringBuilder buf = new StringBuilder(size + size/width); int lastidx = 0; while (lastidx < size) { if (lastidx + width >= size) { buf.append(str.substring(lastidx)); ...
java
public List<String> getI18nkeys() { if (i18nkeys == null) { return new ArrayList<String>(); } Collections.sort(i18nkeys, new Comparator<String>() { @Override public int compare(String o1, String o2) { return Collator.getInstance().compare(o1, o2); } }); return i18nkeys; }
java
public String xlate (String key, Object arg) { return _msgmgr.getMessage(_req, key, new Object[] { arg }); }
java
public String xlate (String key, Object arg1, Object arg2) { return _msgmgr.getMessage(_req, key, new Object[] { arg1, arg2 }); }
java
protected String date (int style, Object arg) { Date when = massageDate(arg); if (when == null) { return "<!" + arg + ">"; } return DateFormat.getDateInstance(style, getLocale()).format(when); }
java
public boolean export() throws QueryException, NoDataFoundException { start = true; testForData(); if (needsFirstCrossing() && !(this instanceof FirstCrossingExporter)) { FirstCrossingExporter fe = new FirstCrossingExporter(bean); fe.export(); // get template values from Fir...
java
protected Set<CellElement> getIgnoredCellElements(Band band) { Set<CellElement> result = new HashSet<CellElement>(); int rows = band.getRowCount(); int cols = band.getColumnCount(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { BandElement ...
java
protected Set<CellElement> getIgnoredCellElementsForColSpan(Band band) { Set<CellElement> result = new HashSet<CellElement>(); int rows = band.getRowCount(); int cols = band.getColumnCount(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { Ba...
java
void fireExporterEvent(ExporterEvent evt) { Object[] listeners = listenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i...
java
private String getFunctionTemplate(GroupCache gc, FunctionBandElement fbe, boolean previous) throws QueryException { StringBuilder templateKey = new StringBuilder(); if (gc == null) { // function in Header templateKey.append("F_"). append(fbe.getFunction()).append("_"). append(fbe.getColumn());...
java
protected String getCurrentValueForGroup(String group) { Object obj = groupValues.get(group); if (obj == null) { return ""; } return obj.toString(); }
java
public static String getValueFromElement(Element element, String tagName) { NodeList elementNodeList = element.getElementsByTagName(tagName); if (elementNodeList == null) { return ""; } else { Element tagElement = (Element) elementNodeList.item(0); if (tagElem...
java
public static String convertDocToString(Document doc) throws TransformerException { //set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES); ...
java
public static boolean writeDocumentToFile(Document doc, String localFile) { try { TransformerFactory transfact = TransformerFactory.newInstance(); Transformer trans = transfact.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES); trans....
java
public static void appendChild(Document doc, Element parentElement, String elementName, String elementValue) { Element child = doc.createElement(elementName); Text text = doc.createTextNode(elementValue); child.appendChild(text); parentElement.appendChild(child); }
java
private static void waiting(int milliseconds) { long t0, t1; t0 = System.currentTimeMillis(); do { t1 = System.currentTimeMillis(); } while ((t1 - t0) < milliseconds); }
java
public Collection<CompilationUnit> execute() throws IOException { List<CompilationUnit> compiledUnits = new ArrayList<CompilationUnit>(); logger.debug("CompilationTask: execute"); long start = System.currentTimeMillis(); for (CompilationUnit unit : compilationUnits) { if (com...
java
public void startDaemon(final long interval) { if (daemon != null) { throw new RuntimeException("Trying to start daemon while it is still running"); } stopDaemon = false; daemon = new Thread(new Runnable() { @Override public void run() { ...
java
private boolean compileIfDirty(CompilationUnit unit) throws IOException { if (isDirty(unit)) { logger.debug("compiling less: {}", unit); long start = System.currentTimeMillis(); try { String sourceMapFileName = unit.getSourceMapFile() != null ? unit.getSource...
java
public Series getSeries(String id, String language) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(SERIES_URL) .append(id) .append("/"); if (StringU...
java
public Episode getEpisode(String seriesId, int seasonNbr, int episodeNbr, String language) throws TvDbException { return getTVEpisode(seriesId, seasonNbr, episodeNbr, language, "/default/"); }
java
private Episode getTVEpisode(String seriesId, int seasonNbr, int episodeNbr, String language, String episodeType) throws TvDbException { if (!isValidNumber(seriesId) || !isValidNumber(seasonNbr) || !isValidNumber(episodeNbr)) { // Invalid number passed return new Episode(); } ...
java
public List<Actor> getActors(String seriesId) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(SERIES_URL) .append(seriesId) .append("/actors.xml"); ...
java
public List<Series> searchSeries(String title, String language) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); try { urlBuilder.append(BASE_URL) .append("GetSeries.php?seriesname=") .append(URLEncoder.encode(title, "UTF-8")...
java
public Episode getEpisodeById(String episodeId, String language) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append("/episodes/") .append(episodeId) .append("/...
java
public TVDBUpdates getWeeklyUpdates(int seriesId) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(WEEKLY_UPDATES_URL); LOG.trace(URL, urlBuilder.toString()); return TvdbParser...
java
public static List<Actor> getActors(String urlString) throws TvDbException { List<Actor> results = new ArrayList<>(); Actor actor; Document doc; NodeList nlActor; Node nActor; Element eActor; try { doc = DOMHelper.getEventDocFromUrl(urlString); ...
java
public static List<Episode> getAllEpisodes(String urlString, int season) throws TvDbException { List<Episode> episodeList = new ArrayList<>(); Episode episode; NodeList nlEpisode; Node nEpisode; Element eEpisode; Document doc = DOMHelper.getEventDocFromUrl(urlString); ...
java
public static Banners getBanners(String urlString) throws TvDbException { Banners banners = new Banners(); Banner banner; NodeList nlBanners; Node nBanner; Element eBanner; Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { n...
java
public static Episode getEpisode(String urlString) throws TvDbException { Episode episode = new Episode(); NodeList nlEpisode; Node nEpisode; Element eEpisode; Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc == null) { return new Episode(); ...
java
public static List<Series> getSeriesList(String urlString) throws TvDbException { List<Series> seriesList = new ArrayList<>(); Series series; NodeList nlSeries; Node nSeries; Element eSeries; Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc...
java
public static TVDBUpdates getUpdates(String urlString, int seriesId) throws TvDbException { TVDBUpdates updates = new TVDBUpdates(); Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { Node root = doc.getChildNodes().item(0); List<SeriesUpdate> se...
java
public static String parseErrorMessage(String errorMessage) { StringBuilder response = new StringBuilder(); Pattern pattern = Pattern.compile(".*?/series/(\\d*?)/default/(\\d*?)/(\\d*?)/.*?"); Matcher matcher = pattern.matcher(errorMessage); // See if the error message matches the patt...
java
private static List<String> parseList(String input, String delim) { List<String> result = new ArrayList<>(); StringTokenizer st = new StringTokenizer(input, delim); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.length() > 0) { ...
java
private static Banner parseNextBanner(Element eBanner) { Banner banner = new Banner(); String artwork; artwork = DOMHelper.getValueFromElement(eBanner, BANNER_PATH); if (!artwork.isEmpty()) { banner.setUrl(URL_BANNER + artwork); } artwork = DOMHelper.getValu...
java
private static Episode parseNextEpisode(Element eEpisode) { Episode episode = new Episode(); episode.setId(DOMHelper.getValueFromElement(eEpisode, "id")); episode.setCombinedEpisodeNumber(DOMHelper.getValueFromElement(eEpisode, "Combined_episodenumber")); episode.setCombinedSeason(DOMHe...
java
private static int getEpisodeValue(Element eEpisode, String key) { int episodeValue; try { String value = DOMHelper.getValueFromElement(eEpisode, key); episodeValue = NumberUtils.toInt(value, 0); } catch (WebServiceException ex) { LOG.trace("Failed to read epi...
java
private static Series parseNextSeries(Element eSeries) { Series series = new Series(); series.setId(DOMHelper.getValueFromElement(eSeries, "id")); series.setActors(parseList(DOMHelper.getValueFromElement(eSeries, "Actors"), "|,")); series.setAirsDayOfWeek(DOMHelper.getValueFromElement(e...
java
private static SeriesUpdate parseNextSeriesUpdate(Element element) { SeriesUpdate seriesUpdate = new SeriesUpdate(); seriesUpdate.setSeriesId(DOMHelper.getValueFromElement(element, "id")); seriesUpdate.setTime(DOMHelper.getValueFromElement(element, TIME)); return seriesUpdate; }
java
private static EpisodeUpdate parseNextEpisodeUpdate(Element element) { EpisodeUpdate episodeUpdate = new EpisodeUpdate(); episodeUpdate.setSeriesId(DOMHelper.getValueFromElement(element, "id")); episodeUpdate.setEpisodeId(DOMHelper.getValueFromElement(element, SERIES)); episodeUpdate.se...
java
private static BannerUpdate parseNextBannerUpdate(Element element) { BannerUpdate bannerUpdate = new BannerUpdate(); bannerUpdate.setSeasonNum(DOMHelper.getValueFromElement(element, "SeasonNum")); bannerUpdate.setSeriesId(DOMHelper.getValueFromElement(element, SERIES)); bannerUpdate.set...
java
private static Language parseNextLanguage(Element element) { Language language = new Language(); language.setName(DOMHelper.getValueFromElement(element, "name")); language.setAbbreviation(DOMHelper.getValueFromElement(element, "abbreviation")); language.setId(DOMHelper.getValueFromEleme...
java
private void copyBaseDirs(File[] baseDirs) { this.baseDirs = new File[baseDirs.length]; for (int i = 0; i < baseDirs.length; i++) { this.baseDirs[i] = baseDirs[i].getAbsoluteFile(); } }
java
public Group<E> group(String name) { for (Group<E> group : this.groups()) { if (group.expr instanceof Expression.NamedGroup<?>) { Expression.NamedGroup<E> namedGroup = (Expression.NamedGroup<E>) group.expr; if (namedGroup.name.equals(name)) { retur...
java
public BindingAssert<T> hasSameValue(ObservableValue<T> expectedValue) { new ObservableValueAssertions<>(actual).hasSameValue(expectedValue); return this; }
java
public static LessCompilationEngine create(String type, String executable) { if (type == null || RHINO.equals(type)) { return create(); } if (COMMAND_LINE.equals(type)) { return new CommandLineLesscCompilationEngine(executable); } return new ScriptEngineL...
java
public static void configure(boolean verbose, boolean daemon) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>(); ca.setContext(lc); ca.setName("less console"); PatternLayoutEncoder pl =...
java
public static <E> Automaton<E> build(List<Expression<E>> exprs) { Expression.MatchingGroup<E> group = new Expression.MatchingGroup<E>(exprs); return group.build(); }
java