code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
package org.maxgamer.rs.model.skill.prayer; import java.util.LinkedList; /** * @author netherfoam, alva */ public enum PrayerGroup { //Standard prayer book /** All prayers that boost defense */ DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY), /** All prayers that boost strength */ STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost attack */ ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost range */ RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR), /** All prayers that boost magic */ MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY), /** * most prayers that put a symbol above player head (Prot * (melee/magic/range), retribution, smite, redemption) */ STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE), /** Protect from melee/range/magic prayers */ PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC), //Curses prayer book /** Sap prayers (warrior, range, spirit) */ SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT), /** * leech prayers (attack, range, magic, defence, strength, energy, special * attack) */ LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.LEECH_SPECIAL_ATTACK), /** * similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles, * melee) */ CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE), /** All deflections (magic, missiles, melee) */ DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE); private PrayerType[] types; private PrayerGroup(PrayerType... types) { this.types = types; } public PrayerType[] getTypes() { return types; } /** * Returns true if this prayer group contains the given prayer. * @param type the prayer * @return true if it is contained, else false. */ public boolean contains(PrayerType type) { for (PrayerType p : this.types) { if (type == p) { return true; } } return false; } /** * Returns an array of groups that the given prayer is in. * @param type the prayer * @return an array of groups that the given prayer is in. */ public static LinkedList<PrayerGroup> getGroups(PrayerType type) { LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>(); for (PrayerGroup g : values()) { if (g.contains(type)) { groups.add(g); } } return groups; } }
tehnewb/Titan
src/org/maxgamer/rs/model/skill/prayer/PrayerGroup.java
Java
gpl-3.0
3,118
/* * ASpark * Copyright (C) 2015 Nikolay Platov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nikoladasm.aspark; import java.io.IOException; import java.io.InputStream; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.netty.buffer.ByteBuf; import static nikoladasm.aspark.HttpMethod.*; public final class ASparkUtil { private static final String PARAMETERS_PATTERN = "(?i)(:[A-Z_][A-Z_0-9]*)"; private static final Pattern PATTERN = Pattern.compile(PARAMETERS_PATTERN); private static final String DEFAULT_ACCEPT_TYPE = "*/*"; private static final String REGEXP_METACHARS = "<([{\\^-=$!|]})?*+.>"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final String FOLDER_SEPARATOR = "/"; private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final String QUERY_KEYS_PATTERN = "\\s*\\[?\\s*([^\\]\\[\\s]+)\\s*\\]?\\s*"; private static final Pattern QK_PATTERN = Pattern.compile(QUERY_KEYS_PATTERN); private ASparkUtil() {} private static String processRegexPath(String path, String asteriskReplacement, String slashAsteriskReplacement) { String pathToUse = sanitizePath(path); int length = pathToUse.length(); StringBuilder sb = new StringBuilder(); boolean startWithWildcard = false; for (int i = 0; i < length; i++) { char c = pathToUse.charAt(i); if (i == 0 && c == '*') { sb.append(asteriskReplacement); startWithWildcard = true; continue; } if (i == length-2 && c == '/' && pathToUse.charAt(i+1) == '*') { if (startWithWildcard) throw new IllegalArgumentException("Path can't contain first and last star wildcard"); sb.append(slashAsteriskReplacement); break; } if (i == length-1 && c == '*') { if (startWithWildcard) throw new IllegalArgumentException("Path can't contain first and last star wildcard"); sb.append(asteriskReplacement); continue; } if (REGEXP_METACHARS.contains(String.valueOf(c))) { sb.append('\\').append(c); continue; } sb.append(c); } return sb.toString(); } public static Pattern buildParameterizedPathPattern(String path, Map<String, Integer> parameterNamesMap, Boolean startWithWildcard) { String pathToUse = processRegexPath(path, "(.*)", "(?:/?|/(.+))"); Matcher parameterMatcher = PATTERN.matcher(pathToUse); int i = 1; while (parameterMatcher.find()) { String parameterName = parameterMatcher.group(1); if (parameterNamesMap.containsKey(parameterName)) throw new ASparkException("Duplicate parameter name."); parameterNamesMap.put(parameterName, i); i++; } return Pattern.compile("^"+parameterMatcher.replaceAll("([^/]+)")+"$"); } public static Pattern buildPathPattern(String path) { String pathToUse = processRegexPath(path, ".*", "(?:/?|/.+)"); return Pattern.compile("^"+pathToUse+"$"); } public static boolean isAcceptContentType(String requestAcceptTypes, String routeAcceptType) { if (requestAcceptTypes == null) return routeAcceptType.trim().equals(DEFAULT_ACCEPT_TYPE); String[] requestAcceptTypesArray = requestAcceptTypes.split(","); String[] rtat = routeAcceptType.trim().split("/"); for (int i=0; i<requestAcceptTypesArray.length; i++) { String requestAcceptType = requestAcceptTypesArray[i].split(";")[0]; String[] rqat = requestAcceptType.trim().split("/"); if (((rtat[0].equals("*")) ? true : rqat[0].trim().equals(rtat[0])) && ((rtat[1].equals("*")) ? true : rqat[1].equals(rtat[1]))) return true; } return false; } public static long copyStreamToByteBuf(InputStream input, ByteBuf buf) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while ((n = input.read(buffer)) != -1) { buf.writeBytes(buffer, 0, n); count += n; } return count; } public static String collapsePath(String path) { String pathToUse = path.trim(); if (pathToUse.isEmpty()) return pathToUse; String rpath = pathToUse.replace(WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); String[] directories = rpath.split(FOLDER_SEPARATOR); Deque<String> newDirectories = new LinkedList<>(); for (int i=0; i<directories.length; i++) { String directory = directories[i].trim(); if (directory.equals(TOP_PATH) && !newDirectories.isEmpty()) newDirectories.removeLast(); else if (!directory.equals(CURRENT_PATH) && !directory.isEmpty()) newDirectories.addLast(directory); } String result = FOLDER_SEPARATOR; for (String directory : newDirectories) result += directory + FOLDER_SEPARATOR; if (!path.startsWith(FOLDER_SEPARATOR)) result = result.substring(1); if (!path.endsWith(FOLDER_SEPARATOR) && result.equals(FOLDER_SEPARATOR)) result = result.substring(0, result.length()-1); return result; } public static boolean isEqualHttpMethod(HttpMethod requestHttpMethod, HttpMethod routeHttpMethod) { if (requestHttpMethod.equals(HEAD) && routeHttpMethod.equals(GET)) return true; return requestHttpMethod.equals(routeHttpMethod); } public static ParamsMap parseParams(Map<String, List<String>> params) { ParamsMap result = new ParamsMap(); params.forEach((keys, values) -> { ParamsMap root = result; Matcher keyMatcher = QK_PATTERN.matcher(keys); while (keyMatcher.find()) { String key = keyMatcher.group(1); root = root.createIfAbsentAndGet(key); } root.values(values.toArray(new String[values.size()])); }); return result; } public static ParamsMap parseUniqueParams(Map<String, String> params) { ParamsMap result = new ParamsMap(); params.forEach((key, value) -> { result.createIfAbsentAndGet(key).value(value); }); return result; } public static String sanitizePath(String path) { String pathToUse = collapsePath(path); if (pathToUse.isEmpty()) return pathToUse; if (pathToUse.endsWith("/")) pathToUse = pathToUse.substring(0, pathToUse.length()-1); return pathToUse; } public static String mimeType(String file, Properties mimeTypes) { int extIndex = file.lastIndexOf('.'); extIndex = (extIndex < 0 ) ? 0 : extIndex; String ext = file.substring(extIndex); return mimeTypes.getProperty(ext, "application/octet-stream"); } }
NikolaDasm/aspark
src/nikoladasm/aspark/ASparkUtil.java
Java
gpl-3.0
7,066
package controller; import java.io.IOException; import java.sql.Time; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import utils.Common; import utils.Constant; import utils.MessageProperties; import dao.HocKyDao; import dao.OnlDao; import dao.WeekDao; import dao.impl.HocKyDaoImpl; import dao.impl.OnlDaoImpl; import dao.impl.PositionDaoImpl; import dao.impl.WeekDaoImpl; import entity.HocKy; import entity.Onl; import entity.Position; import entity.User; import entity.Week; /** * Servlet implementation class OnlController */ @WebServlet("/jsp/onl.htm") public class OnlController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); // get list học kỳ HocKyDao hocKyDao = new HocKyDaoImpl(); List<HocKy> listHocKy = hocKyDao.getListHocKy(); request.setAttribute("listHocKy", listHocKy); // lấy học kỳ hiện tại String currentHocKy = hocKyDao.getHocKy(Common.getNow()); request.setAttribute("currentHocKy", currentHocKy); // lấy danh sách tuần theo học kỳ hiện tại WeekDao weekDao = new WeekDaoImpl(); List<Week> listWeek = weekDao.getListWeek(currentHocKy); request.setAttribute("listWeek", listWeek); // lấy tuần hiện tại Week currentWeek = weekDao.getCurrentWeek(Common.getNow()); request.setAttribute("currentWeek", currentWeek); // lấy lịch trực trong tuần List<Onl> listOnl = new OnlDaoImpl().getListOnl(null, currentWeek.getWeekId(), user.getUserId()); request.setAttribute(Constant.ACTION, "viewOnl"); request.setAttribute("listOnl", listOnl); request.getRequestDispatcher("view_onl_cal.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @SuppressWarnings({ "unchecked", "deprecation" }) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("position".equals(action)) { double latitude = Double.parseDouble(request .getParameter("latitude")); double longitude = Double.parseDouble(request .getParameter("longitude")); long onlId = Long.parseLong(request.getParameter("id")); // lấy tọa độ phòng B1-502 Position position = new PositionDaoImpl().getPositionById("B1-502"); JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); if (position == null) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR12")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // check vị trí if (!checkPosition(position, latitude, longitude)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR13")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // if (!(latitude >= 20 && latitude <= 22 && longitude >= 105 && // longitude <= 106)) { // String error = MessageProperties.getData("ERR09"); // jsonObject.put(Constant.STATUS, false); // jsonObject.put(Constant.DATA, error); // out.write(jsonObject.toJSONString().getBytes()); // out.flush(); // return; // } // check thời giạn click nhận giao ban Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh")); Time now = new Time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); // lấy lịch trực bởi id OnlDao onlDao = new OnlDaoImpl(); Onl onl = onlDao.getOnlById(onlId); if (now.after(onl.getTimeStart()) && now.before(onl.getTimeEnd())) { // tính thời gian muộn int lateMin = (int) Math.round((double) ((now.getTime() - onl .getTimeStart().getTime()) / 1000) / 60); // thay đổi trạng thái onl.setLate(true); onl.setLateMin(lateMin); } else if (now.after(onl.getTimeEnd())) { // nghỉ String error = MessageProperties.getData("ERR14"); jsonObject.put(Constant.STATUS, false); jsonObject.put("flagHol", true); jsonObject.put(Constant.DATA, error); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // cập nhật trạng thái nghỉ onl.setHol(false); // cập nhật if (!onlDao.update(onl, true)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG04")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } else if ("addReason".equals(action)) { JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); String reason = request.getParameter("reason"); long onlId = Long.parseLong(request.getParameter("id")); // update lý do if (!new OnlDaoImpl().setReason(reason, onlId)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG01")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } } /** * check vị trí khi nhận giao ban * * @param position * tọa độ vị trí phòng B1-502 * @param latitude * vĩ độ lấy được ở vị trí hiện tại * @param longitude * kinh độ ở vị trí hiện tại * @return true nếu vị trí hiện tại trùng với vị trí phòng B1-502. flase nếu * ngược lại không trùng */ public boolean checkPosition(Position position, double latitude, double longitude) { double latitudeMin = Math.floor(position.getLatitude() * 1000000) / 1000000; double latitudeMax = Math.ceil(position.getLatitude() * 1000000) / 1000000; double longitudeMin = Math.floor(position.getLongitude() * 10000000) / 10000000; double longitudeMax = Math.ceil((position.getLongitude()) * 10000000) / 10000000; System.out.println(latitudeMin + " <= " + latitude + " <= "+ latitudeMax); System.out.println(longitudeMin + " <= " + longitude + " <= "+ longitudeMax); return latitudeMin <= latitude && latitude <= latitudeMax && longitudeMin <= longitude && longitude <= longitudeMax; } }
phuong95st/project-LA16
qlhoatdong2/src/controller/OnlController.java
Java
gpl-3.0
7,370
/* ----------------------------------------------------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ package ppm_java._dev.concept.example.event; import ppm_java.backend.TController; import ppm_java.typelib.IControllable; import ppm_java.typelib.IEvented; import ppm_java.typelib.VBrowseable; /** * */ class TSink extends VBrowseable implements IEvented, IControllable { public TSink (String id) { super (id); } public void OnEvent (int e, String arg0) { String msg; msg = GetID () + ": " + "Received messaging event. Message: " + arg0; System.out.println (msg); } public void Start () {/* Do nothing */} public void Stop () {/* Do nothing */} public void OnEvent (int e) {/* Do nothing */} public void OnEvent (int e, int arg0) {/* Do nothing */} public void OnEvent (int e, long arg0) {/* Do nothing */} protected void _Register () { TController.Register (this); } }
ustegrew/ppm-java
src/ppm_java/_dev/concept/example/event/TSink.java
Java
gpl-3.0
1,733
package org.runnerup.notification; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import org.runnerup.R; import org.runnerup.common.util.Constants; import org.runnerup.view.MainLayout; @TargetApi(Build.VERSION_CODES.FROYO) public class GpsBoundState implements NotificationState { private final Notification notification; public GpsBoundState(Context context) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Intent i = new Intent(context, MainLayout.class); i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); i.putExtra(Constants.Intents.FROM_NOTIFICATION, true); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); builder.setContentIntent(pi); builder.setContentTitle(context.getString(R.string.activity_ready)); builder.setContentText(context.getString(R.string.ready_to_start_running)); builder.setSmallIcon(R.drawable.icon); builder.setOnlyAlertOnce(true); org.runnerup.util.NotificationCompat.setLocalOnly(builder); notification = builder.build(); } @Override public Notification createNotification() { return notification; } }
netmackan/runnerup
app/src/org/runnerup/notification/GpsBoundState.java
Java
gpl-3.0
1,443
package pl.idedyk.japanese.dictionary.web.html; import java.util.List; public class Ul extends HtmlElementCommon { public Ul() { super(); } public Ul(String clazz) { super(clazz); } public Ul(String clazz, String style) { super(clazz, style); } @Override protected String getTagName() { return "ul"; } @Override protected boolean isSupportHtmlElementList() { return true; } @Override protected List<String[]> getAdditionalTagAttributes() { return null; } }
dedyk/JapaneseDictionaryWeb
src/main/java/pl/idedyk/japanese/dictionary/web/html/Ul.java
Java
gpl-3.0
502
public class Main { public static void main(String[] args) { ProdutoContext manga = new ProdutoContext(); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); manga.reestocar(5); manga.fazerCompra(5); manga.reestocar(15); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); System.out.println("Quantia: " + manga.getQuantia()); } }
guilhermepo2/bcc
2015-2/POO2 - Praticas/Pratica08-1 - State/src/Main.java
Java
gpl-3.0
402
/** Copyright (C) 2012 Delcyon, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.delcyon.capo.protocol.server; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author jeremiah * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ClientRequestProcessorProvider { String name(); }
jahnje/delcyon-capo
java/com/delcyon/capo/protocol/server/ClientRequestProcessorProvider.java
Java
gpl-3.0
1,024
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * ClusterMembership.java * Copyright (C) 2004 Mark Hall * */ package weka.filters.unsupervised.attribute; import weka.filters.Filter; import weka.filters.UnsupervisedFilter; import weka.filters.unsupervised.attribute.Remove; import weka.clusterers.Clusterer; import weka.clusterers.DensityBasedClusterer; import weka.core.Attribute; import weka.core.Instances; import weka.core.Instance; import weka.core.OptionHandler; import weka.core.Range; import weka.core.FastVector; import weka.core.Option; import weka.core.Utils; import java.util.Enumeration; import java.util.Vector; /** * A filter that uses a clusterer to obtain cluster membership values * for each input instance and outputs them as new instances. The * clusterer needs to be a density-based clusterer. If * a (nominal) class is set, then the clusterer will be run individually * for each class.<p> * * Valid filter-specific options are: <p> * * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Eibe Frank * @version $Revision: 1.7 $ */ public class ClusterMembership extends Filter implements UnsupervisedFilter, OptionHandler { /** The clusterer */ protected DensityBasedClusterer m_clusterer = new weka.clusterers.EM(); /** Array for storing the clusterers */ protected DensityBasedClusterer[] m_clusterers; /** Range of attributes to ignore */ protected Range m_ignoreAttributesRange; /** Filter for removing attributes */ protected Filter m_removeAttributes; /** The prior probability for each class */ protected double[] m_priors; /** * Sets the format of the input instances. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - only the * structure is required). * @return true if the outputFormat may be collected immediately * @exception Exception if the inputFormat can't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { super.setInputFormat(instanceInfo); m_removeAttributes = null; m_priors = null; return false; } /** * Signify that this batch of input to the filter is finished. * * @return true if there are instances pending output * @exception IllegalStateException if no input structure has been defined */ public boolean batchFinished() throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (outputFormatPeek() == null) { Instances toFilter = getInputFormat(); Instances[] toFilterIgnoringAttributes; // Make subsets if class is nominal if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) { toFilterIgnoringAttributes = new Instances[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { toFilterIgnoringAttributes[i] = new Instances(toFilter, toFilter.numInstances()); } for (int i = 0; i < toFilter.numInstances(); i++) { toFilterIgnoringAttributes[(int)toFilter.instance(i).classValue()].add(toFilter.instance(i)); } m_priors = new double[toFilter.numClasses()]; for (int i = 0; i < toFilter.numClasses(); i++) { toFilterIgnoringAttributes[i].compactify(); m_priors[i] = toFilterIgnoringAttributes[i].sumOfWeights(); } Utils.normalize(m_priors); } else { toFilterIgnoringAttributes = new Instances[1]; toFilterIgnoringAttributes[0] = toFilter; m_priors = new double[1]; m_priors[0] = 1; } // filter out attributes if necessary if (m_ignoreAttributesRange != null || toFilter.classIndex() >= 0) { m_removeAttributes = new Remove(); String rangeString = ""; if (m_ignoreAttributesRange != null) { rangeString += m_ignoreAttributesRange.getRanges(); } if (toFilter.classIndex() >= 0) { if (rangeString.length() > 0) { rangeString += (","+(toFilter.classIndex()+1)); } else { rangeString = ""+(toFilter.classIndex()+1); } } ((Remove)m_removeAttributes).setAttributeIndices(rangeString); ((Remove)m_removeAttributes).setInvertSelection(false); ((Remove)m_removeAttributes).setInputFormat(toFilter); for (int i = 0; i < toFilterIgnoringAttributes.length; i++) { toFilterIgnoringAttributes[i] = Filter.useFilter(toFilterIgnoringAttributes[i], m_removeAttributes); } } // build the clusterers if ((toFilter.classIndex() <= 0) || !toFilter.classAttribute().isNominal()) { m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, 1); m_clusterers[0].buildClusterer(toFilterIgnoringAttributes[0]); } else { m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, toFilter.numClasses()); for (int i = 0; i < m_clusterers.length; i++) { if (toFilterIgnoringAttributes[i].numInstances() == 0) { m_clusterers[i] = null; } else { m_clusterers[i].buildClusterer(toFilterIgnoringAttributes[i]); } } } // create output dataset FastVector attInfo = new FastVector(); for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) { attInfo.addElement(new Attribute("pCluster_" + j + "_" + i)); } } } if (toFilter.classIndex() >= 0) { attInfo.addElement(toFilter.classAttribute().copy()); } attInfo.trimToSize(); Instances filtered = new Instances(toFilter.relationName()+"_clusterMembership", attInfo, 0); if (toFilter.classIndex() >= 0) { filtered.setClassIndex(filtered.numAttributes() - 1); } setOutputFormat(filtered); // build new dataset for (int i = 0; i < toFilter.numInstances(); i++) { convertInstance(toFilter.instance(i)); } } flushInput(); m_NewBatch = true; return (numPendingOutput() != 0); } /** * Input an instance for filtering. Ordinarily the instance is processed * and made available for output immediately. Some filters require all * instances be read before producing output. * * @param instance the input instance * @return true if the filtered instance may now be * collected with output(). * @exception IllegalStateException if no input format has been defined. */ public boolean input(Instance instance) throws Exception { if (getInputFormat() == null) { throw new IllegalStateException("No input instance format defined"); } if (m_NewBatch) { resetQueue(); m_NewBatch = false; } if (outputFormatPeek() != null) { convertInstance(instance); return true; } bufferInput(instance); return false; } /** * Converts logs back to density values. */ protected double[] logs2densities(int j, Instance in) throws Exception { double[] logs = m_clusterers[j].logJointDensitiesForInstance(in); for (int i = 0; i < logs.length; i++) { logs[i] += Math.log(m_priors[j]); } return logs; } /** * Convert a single instance over. The converted instance is added to * the end of the output queue. * * @param instance the instance to convert */ protected void convertInstance(Instance instance) throws Exception { // set up values double [] instanceVals = new double[outputFormatPeek().numAttributes()]; double [] tempvals; if (instance.classIndex() >= 0) { tempvals = new double[outputFormatPeek().numAttributes() - 1]; } else { tempvals = new double[outputFormatPeek().numAttributes()]; } int pos = 0; for (int j = 0; j < m_clusterers.length; j++) { if (m_clusterers[j] != null) { double [] probs; if (m_removeAttributes != null) { m_removeAttributes.input(instance); probs = logs2densities(j, m_removeAttributes.output()); } else { probs = logs2densities(j, instance); } System.arraycopy(probs, 0, tempvals, pos, probs.length); pos += probs.length; } } tempvals = Utils.logs2probs(tempvals); System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length); if (instance.classIndex() >= 0) { instanceVals[instanceVals.length - 1] = instance.classValue(); } push(new Instance(instance.weight(), instanceVals)); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(2); newVector. addElement(new Option("\tFull name of clusterer to use (required).\n" + "\teg: weka.clusterers.EM", "W", 1, "-W <clusterer name>")); newVector. addElement(new Option("\tThe range of attributes the clusterer should ignore." +"\n\t(the class attribute is automatically ignored)", "I", 1,"-I <att1,att2-att4,...>")); return newVector.elements(); } /** * Parses the options for this object. Valid options are: <p> * * -W clusterer string <br> * Full class name of clusterer to use. Clusterer options may be * specified at the end following a -- .(required)<p> * * -I range string <br> * The range of attributes the clusterer should ignore. Note: * the class attribute (if set) is automatically ignored during clustering.<p> * * @param options the list of options as an array of strings * @exception Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String clustererString = Utils.getOption('W', options); if (clustererString.length() == 0) { throw new Exception("A clusterer must be specified" + " with the -W option."); } setDensityBasedClusterer((DensityBasedClusterer)Utils. forName(DensityBasedClusterer.class, clustererString, Utils.partitionOptions(options))); setIgnoredAttributeIndices(Utils.getOption('I', options)); Utils.checkForRemainingOptions(options); } /** * Gets the current settings of the filter. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] clustererOptions = new String [0]; if ((m_clusterer != null) && (m_clusterer instanceof OptionHandler)) { clustererOptions = ((OptionHandler)m_clusterer).getOptions(); } String [] options = new String [clustererOptions.length + 5]; int current = 0; if (!getIgnoredAttributeIndices().equals("")) { options[current++] = "-I"; options[current++] = getIgnoredAttributeIndices(); } if (m_clusterer != null) { options[current++] = "-W"; options[current++] = getDensityBasedClusterer().getClass().getName(); } options[current++] = "--"; System.arraycopy(clustererOptions, 0, options, current, clustererOptions.length); current += clustererOptions.length; while (current < options.length) { options[current++] = ""; } return options; } /** * Returns a string describing this filter * * @return a description of the filter suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "A filter that uses a density-based clusterer to generate cluster " + "membership values; filtered instances are composed of these values " + "plus the class attribute (if set in the input data). If a (nominal) " + "class attribute is set, the clusterer is run separately for each " + "class. The class attribute (if set) and any user-specified " + "attributes are ignored during the clustering operation"; } /** * Returns a description of this option suitable for display * as a tip text in the gui. * * @return description of this option */ public String clustererTipText() { return "The clusterer that will generate membership values for the instances."; } /** * Set the clusterer for use in filtering * * @param newClusterer the clusterer to use */ public void setDensityBasedClusterer(DensityBasedClusterer newClusterer) { m_clusterer = newClusterer; } /** * Get the clusterer used by this filter * * @return the clusterer used */ public DensityBasedClusterer getDensityBasedClusterer() { return m_clusterer; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String ignoredAttributeIndicesTipText() { return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last"; } /** * Gets ranges of attributes to be ignored. * * @return a string containing a comma-separated list of ranges */ public String getIgnoredAttributeIndices() { if (m_ignoreAttributesRange == null) { return ""; } else { return m_ignoreAttributesRange.getRanges(); } } /** * Sets the ranges of attributes to be ignored. If provided string * is null, no attributes will be ignored. * * @param rangeList a string representing the list of attributes. * eg: first-3,5,6-last * @exception IllegalArgumentException if an invalid range list is supplied */ public void setIgnoredAttributeIndices(String rangeList) { if ((rangeList == null) || (rangeList.length() == 0)) { m_ignoreAttributesRange = null; } else { m_ignoreAttributesRange = new Range(); m_ignoreAttributesRange.setRanges(rangeList); } } /** * Main method for testing this class. * * @param argv should contain arguments to the filter: use -h for help */ public static void main(String [] argv) { try { if (Utils.getFlag('b', argv)) { Filter.batchFilterFile(new ClusterMembership(), argv); } else { Filter.filterFile(new ClusterMembership(), argv); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
paolopavan/cfr
src/weka/filters/unsupervised/attribute/ClusterMembership.java
Java
gpl-3.0
15,028
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.util.concurrent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; /** * A supplier with a priority. * * <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a> * * @author Matthias Eichner * * @param <T> the type of results supplied by this supplier */ public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable { private static AtomicLong CREATION_COUNTER = new AtomicLong(0); private Supplier<T> delegate; private int priority; private long created; public MCRPrioritySupplier(Supplier<T> delegate, int priority) { this.delegate = delegate; this.priority = priority; this.created = CREATION_COUNTER.incrementAndGet(); } @Override public T get() { return delegate.get(); } @Override public int getPriority() { return this.priority; } @Override public long getCreated() { return created; } /** * use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)} * * This method keep the priority * @param es * @return */ public CompletableFuture<T> runAsync(ExecutorService es) { CompletableFuture<T> result = new CompletableFuture<>(); MCRPrioritySupplier<T> supplier = this; class MCRAsyncPrioritySupplier implements Runnable, MCRPrioritizable, CompletableFuture.AsynchronousCompletionTask { @Override @SuppressWarnings("PMD.AvoidCatchingThrowable") public void run() { try { if (!result.isDone()) { result.complete(supplier.get()); } } catch (Throwable t) { result.completeExceptionally(t); } } @Override public int getPriority() { return supplier.getPriority(); } @Override public long getCreated() { return supplier.getCreated(); } } es.execute(new MCRAsyncPrioritySupplier()); return result; } }
MyCoRe-Org/mycore
mycore-base/src/main/java/org/mycore/util/concurrent/MCRPrioritySupplier.java
Java
gpl-3.0
3,156
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.power.text.Run; import static com.power.text.dialogs.WebSearch.squerry; import java.awt.Desktop; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.swing.JOptionPane; import static com.power.text.Main.searchbox; /** * * @author thecarisma */ public class WikiSearch { public static void wikisearch(){ String searchqueryw = searchbox.getText(); searchqueryw = searchqueryw.replace(' ', '-'); String squeryw = squerry.getText(); squeryw = squeryw.replace(' ', '-'); if ("".equals(searchqueryw)){ searchqueryw = squeryw ; } else {} String url = "https://www.wikipedia.org/wiki/" + searchqueryw ; try { URI uri = new URL(url).toURI(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) desktop.browse(uri); } catch (URISyntaxException | IOException e) { /* * I know this is bad practice * but we don't want to do anything clever for a specific error */ JOptionPane.showMessageDialog(null, e.getMessage()); // Copy URL to the clipboard so the user can paste it into their browser StringSelection stringSelection = new StringSelection(url); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); // Notify the user of the failure System.out.println("This program just tried to open a webpage." + "\n" + "The URL has been copied to your clipboard, simply paste into your browser to accessWebpage: " + url); } } }
Thecarisma/powertext
Power Text/src/com/power/text/Run/WikiSearch.java
Java
gpl-3.0
2,201
/** * */ package org.jbpt.pm.bpmn; import org.jbpt.pm.IDataNode; /** * Interface class for BPMN Document. * * @author Cindy F�hnrich */ public interface IDocument extends IDataNode { /** * Marks this Document as list. */ public void markAsList(); /** * Unmarks this Document as list. */ public void unmarkAsList(); /** * Checks whether the current Document is a list. * @return */ public boolean isList(); }
BPT-NH/jpbt
jbpt-bpm/src/main/java/org/jbpt/pm/bpmn/IDocument.java
Java
gpl-3.0
447
/* * Copyright 2008-2013, ETH Zürich, Samuel Welten, Michael Kuhn, Tobias Langner, * Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain, * Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter, * Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann, * Samuel Zweifel * * This file is part of Jukefox. * * Jukefox is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or any later version. Jukefox is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * Jukefox. If not, see <http://www.gnu.org/licenses/>. */ package ch.ethz.dcg.jukefox.model.collection; public class MapTag extends BaseTag { float[] coordsPca2D; private float varianceOverPCA; public MapTag(int id, String name, float[] coordsPca2D, float varianceOverPCA) { super(id, name); this.coordsPca2D = coordsPca2D; this.varianceOverPCA = varianceOverPCA; } public float[] getCoordsPca2D() { return coordsPca2D; } public float getVarianceOverPCA() { return varianceOverPCA; } }
kuhnmi/jukefox
JukefoxModel/src/ch/ethz/dcg/jukefox/model/collection/MapTag.java
Java
gpl-3.0
1,428
/* * Copyright (C) 2011 Klaus Reimer <k@ailis.de> * See LICENSE.md for licensing information. */ package de.ailis.microblinks.l.lctrl.shell; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.util.Arrays; import de.ailis.microblinks.l.lctrl.resources.Resources; /** * Base class for all CLI programs. * * @author Klaus Reimer (k@ailis.de) */ public abstract class CLI { /** The command-line program name. */ private final String name; /** The short options. */ private final String shortOpts; /** The long options. */ private final LongOpt[] longOpts; /** Debug mode. */ private boolean debug = false; /** * Constructor. * * @param name * The command-line program name. * @param shortOpts * The short options. * @param longOpts * The long options. */ protected CLI(final String name, final String shortOpts, final LongOpt[] longOpts) { this.name = name; this.shortOpts = shortOpts; this.longOpts = longOpts; } /** * Displays command-line help. */ private void showHelp() { System.out.println(Resources.getText("help.txt")); } /** * Displays version information. */ private void showVersion() { System.out.println(Resources.getText("version.txt")); } /** * Displays the help hint. */ protected void showHelpHint() { System.out.println("Use --help to show usage information."); } /** * Prints error message to stderr and then exits with error code 1. * * @param message * The error message. * @param args * The error message arguments. */ protected void error(final String message, final Object... args) { System.err.print(this.name); System.err.print(": "); System.err.format(message, args); System.err.println(); showHelpHint(); System.exit(1); } /** * Processes all command line options. * * @param args * The command line arguments. * @throws Exception * When error occurs. * @return The index of the first non option argument. */ private int processOptions(final String[] args) throws Exception { final Getopt opts = new Getopt(this.name, args, this.shortOpts, this.longOpts); int opt; while ((opt = opts.getopt()) >= 0) { switch (opt) { case 'h': showHelp(); System.exit(0); break; case 'V': showVersion(); System.exit(0); break; case 'D': this.debug = true; break; case '?': showHelpHint(); System.exit(111); break; default: processOption(opt, opts.getOptarg()); } } return opts.getOptind(); } /** * Processes a single option. * * @param option * The option to process * @param arg * The optional option argument * @throws Exception * When an error occurred. */ protected abstract void processOption(final int option, final String arg) throws Exception; /** * Executes the program with the specified arguments. This is called from the run() method after options has been * processed. The specified arguments array only contains the non-option arguments. * * @param args * The non-option command-line arguments. * @throws Exception * When something goes wrong. */ protected abstract void execute(String[] args) throws Exception; /** * Runs the program. * * @param args * The command line arguments. */ public void run(final String[] args) { try { final int commandStart = processOptions(args); execute(Arrays.copyOfRange(args, commandStart, args.length)); } catch (final Exception e) { if (this.debug) { e.printStackTrace(System.err); } error(e.getMessage()); System.exit(1); } } /** * Checks if program runs in debug mode. * * @return True if debug mode, false if not. */ public boolean isDebug() { return this.debug; } }
microblinks/lctrl
src/main/java/de/ailis/microblinks/l/lctrl/shell/CLI.java
Java
gpl-3.0
4,729
package example; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import com.piedra.excel.annotation.ExcelExport; import com.piedra.excel.util.ExcelExportor; /** * @Description: Excel导出工具 例子程序 * @Creator:linwb 2014-12-19 */ public class ExcelExportorExample { public static void main(String[] args) { new ExcelExportorExample().testSingleHeader(); new ExcelExportorExample().testMulHeaders(); } /** * @Description: 测试单表头 * @History * 1. 2014-12-19 linwb 创建方法 */ @Test public void testSingleHeader(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST.xls")); List<ExcelRow> stus = new ArrayList<ExcelRow>(); for(int i=0; i<11120; i++){ stus.add(new ExcelRow()); } new ExcelExportor<ExcelRow>().exportExcel("测试单表头", stus, out); System.out.println("excel导出成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } /** * @Description: 测试多表头 * @History * 1. 2014-12-19 linwb 创建方法 */ @Test public void testMulHeaders(){ OutputStream out = null; try { out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST-MULTIHEADER.xls")); List<ExcelRowForMultiHeaders> stus = new ArrayList<ExcelRowForMultiHeaders>(); for(int i=0; i<1120; i++){ stus.add(new ExcelRowForMultiHeaders()); } new ExcelExportor<ExcelRowForMultiHeaders>().exportExcel("测试多表头", stus, out); System.out.println("excel导出成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if(out!=null){ try { out.close(); } catch (IOException e) { //Ignore.. } finally{ out = null; } } } } } /** * @Description: Excel的一行对应的JavaBean类 * @Creator:linwb 2014-12-19 */ class ExcelRow { @ExcelExport(header="姓名",colWidth=50) private String name="AAAAAAAAAAASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"; @ExcelExport(header="年龄") private int age=80; /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String clazz="SSSSSSSSS"; @ExcelExport(header="国家") private String country="RRRRRRR"; @ExcelExport(header="城市") private String city="EEEEEEEEE"; @ExcelExport(header="城镇") private String town="WWWWWWW"; /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String common="DDDDDDDD"; /** 如果colWidth <= 0 那么取默认的 15 */ @ExcelExport(header="出生日期",colWidth=-1) private Date birth = new Date(); public ExcelRow(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } } /** * @Description: Excel的一行对应的JavaBean类 * @Creator:linwb 2014-12-19 */ class ExcelRowForMultiHeaders { @ExcelExport(header="姓名",colspan="1",rowspan="3") private String name="无名氏"; @ExcelExport(header="省份,国家",colspan="1,5",rowspan="1,2") private String province="福建省"; @ExcelExport(header="城市",colspan="1",rowspan="1") private String city="福建省"; @ExcelExport(header="城镇",colspan="1",rowspan="1") private String town="不知何处"; @ExcelExport(header="年龄,年龄和备注",colspan="1,2",rowspan="1,1") private int age=80; @ExcelExport(header="备注?",colspan="1",rowspan="1") private String common="我是备注,我是备注"; @ExcelExport(header="我的生日",colspan="1",rowspan="3",datePattern="yyyy-MM-dd HH:mm:ss") private Date birth = new Date(); /** 这个属性没别注解,那么将不会出现在导出的excel文件中*/ private String clazz="我不会出现的,除非你给我 @ExcelExport 注解标记"; public ExcelRowForMultiHeaders(){ } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } }
webinglin/excelExportor
src/test/java/example/ExcelExportorExample.java
Java
gpl-3.0
6,820
/*************************************************************************** * Project file: NPlugins - NCore - BasicHttpClient.java * * Full Class name: fr.ribesg.com.mojang.api.http.BasicHttpClient * * * * Copyright (c) 2012-2014 Ribesg - www.ribesg.fr * * This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt * * Please contact me at ribesg[at]yahoo.fr if you improve this file! * ***************************************************************************/ package fr.ribesg.com.mojang.api.http; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.util.List; public class BasicHttpClient implements HttpClient { private static BasicHttpClient instance; private BasicHttpClient() { } public static BasicHttpClient getInstance() { if (instance == null) { instance = new BasicHttpClient(); } return instance; } @Override public String post(final URL url, final HttpBody body, final List<HttpHeader> headers) throws IOException { return this.post(url, null, body, headers); } @Override public String post(final URL url, Proxy proxy, final HttpBody body, final List<HttpHeader> headers) throws IOException { if (proxy == null) { proxy = Proxy.NO_PROXY; } final HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy); connection.setRequestMethod("POST"); for (final HttpHeader header : headers) { connection.setRequestProperty(header.getName(), header.getValue()); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); final DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.write(body.getBytes()); writer.flush(); writer.close(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; final StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); response.append('\r'); } reader.close(); return response.toString(); } }
cnaude/NPlugins
NCore/src/main/java/fr/ribesg/com/mojang/api/http/BasicHttpClient.java
Java
gpl-3.0
2,563
package Eac.event; import Eac.Eac; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.ItemStack; public class EacOnItemPickup extends Eac { @SubscribeEvent public void EacOnItemPickup(PlayerEvent.ItemPickupEvent e) { if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreAir))) { e.player.addStat(airoremined, 1); } else if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreShadow))) { e.player.addStat(shadoworemined, 1); } } }
EacMods/Eac
src/main/java/Eac/event/EacOnItemPickup.java
Java
gpl-3.0
596
/** * Copyright (c) 2013 Jad * * This file is part of Jad. * Jad is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jad is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jad. If not, see <http://www.gnu.org/licenses/>. */ package de.fhffm.jad.demo.jad; import java.util.ArrayList; import de.fhffm.jad.data.DataWrapper; import de.fhffm.jad.data.EInputFields; import de.fhffm.jad.data.IDataFieldEnum; /** * This class synchronizes the access to our Data.Frame * Added Observations are stored in a local ArrayList. * Use 'write' to send everything to GNU R. * @author Denis Hock */ public class DataFrame { private static DataWrapper dw = null; private static ArrayList<String[]> rows = new ArrayList<>(); /** * @return Singleton Instance of the GNU R Data.Frame */ public static DataWrapper getDataFrame(){ if (dw == null){ //Create the data.frame for GNU R: dw = new DataWrapper("data"); clear(); } return dw; } /** * Delete the old observations and send all new observations to Gnu R * @return */ public synchronized static boolean write(){ if (rows.size() < 1){ return false; } //Clear the R-Data.Frame clear(); //Send all new Observations to Gnu R for(String[] row : rows) dw.addObservation(row); //Clear the local ArrayList rows.clear(); return true; } /** * These Observations are locally stored and wait for the write() command * @param row */ public synchronized static void add(String[] row){ //Store everything in an ArrayList rows.add(row); } /** * Clear local ArrayList and GNU R Data.Frame */ private static void clear(){ ArrayList<IDataFieldEnum> fields = new ArrayList<IDataFieldEnum>(); fields.add(EInputFields.ipsrc); fields.add(EInputFields.tcpdstport); fields.add(EInputFields.framelen); dw.createEmptyDataFrame(fields); } }
fg-netzwerksicherheit/jaddemo
src/de/fhffm/jad/demo/jad/DataFrame.java
Java
gpl-3.0
2,330
/* This file is part of F3TextViewerFX. * * F3TextViewerFX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * F3TextViewerFX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with F3TextViewerFX. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2015 by Dominic Scheurer <dscheurer@dominic-scheurer.de>. */ package de.dominicscheurer.quicktxtview.view; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javafx.collections.transformation.FilteredList; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFText2HTML; import de.dominicscheurer.quicktxtview.model.DirectoryTreeItem; import de.dominicscheurer.quicktxtview.model.FileSize; import de.dominicscheurer.quicktxtview.model.FileSize.FileSizeUnits; public class FileViewerController { public static final Comparator<File> FILE_ACCESS_CMP = (f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()); public static final Comparator<File> FILE_ACCESS_CMP_REVERSE = (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()); public static final Comparator<File> FILE_NAME_CMP = (f1, f2) -> f1.getName().compareTo(f2.getName()); public static final Comparator<File> FILE_NAME_CMP_REVERSE = (f1, f2) -> f2.getName().compareTo(f1.getName()); private static final String FILE_VIEWER_CSS_FILE = "FileViewer.css"; private static final String ERROR_TEXT_FIELD_CSS_CLASS = "errorTextField"; private FileSize fileSizeThreshold = new FileSize(1, FileSizeUnits.MB); private Charset charset = Charset.defaultCharset(); private Comparator<File> fileComparator = FILE_ACCESS_CMP; @FXML private TreeView<File> fileSystemView; @FXML private WebView directoryContentView; @FXML private TextField filePatternTextField; @FXML private Label fileSizeThresholdLabel; private boolean isInShowContentsMode = false; private String fileTreeViewerCSS; private Pattern filePattern; @FXML private void initialize() { filePattern = Pattern.compile(filePatternTextField.getText()); filePatternTextField.setOnKeyReleased(event -> { final String input = filePatternTextField.getText(); try { Pattern p = Pattern.compile(input); filePattern = p; filePatternTextField.getStyleClass().remove(ERROR_TEXT_FIELD_CSS_CLASS); if (!fileSystemView.getSelectionModel().isEmpty()) { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } } catch (PatternSyntaxException e) { filePatternTextField.getStyleClass().add(ERROR_TEXT_FIELD_CSS_CLASS); } filePatternTextField.applyCss(); }); fileSystemView.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> showDirectoryContents(newValue)); { Scanner s = new Scanner(getClass().getResourceAsStream(FILE_VIEWER_CSS_FILE)); s.useDelimiter("\\A"); fileTreeViewerCSS = s.hasNext() ? s.next() : ""; s.close(); } DirectoryTreeItem[] roots = DirectoryTreeItem.getFileSystemRoots(); if (roots.length > 1) { TreeItem<File> dummyRoot = new TreeItem<File>(); dummyRoot.getChildren().addAll(roots); fileSystemView.setShowRoot(false); fileSystemView.setRoot(dummyRoot); } else { fileSystemView.setRoot(roots[0]); } fileSystemView.getRoot().setExpanded(true); refreshFileSizeLabel(); } public void toggleInShowContentsMode() { isInShowContentsMode = !isInShowContentsMode; refreshFileSystemView(); } public void setFileSizeThreshold(FileSize fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; refreshFileSystemView(); refreshFileSizeLabel(); } public FileSize getFileSizeThreshold() { return fileSizeThreshold; } public void setCharset(Charset charset) { this.charset = charset; refreshFileContentsView(); } public Charset getCharset() { return charset; } public Comparator<File> getFileComparator() { return fileComparator; } public void setFileComparator(Comparator<File> fileComparator) { this.fileComparator = fileComparator; refreshFileContentsView(); } private void refreshFileSizeLabel() { fileSizeThresholdLabel.setText(fileSizeThreshold.getSize() + " " + fileSizeThreshold.getUnit().toString()); } private void refreshFileContentsView() { if (!fileSystemView.getSelectionModel().isEmpty()) { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } } public void expandToDirectory(File file) { Iterator<Path> it = file.toPath().iterator(); //FIXME: The below root directory selection *might* not work for Windows systems. // => Do something with `file.toPath().getRoot()`. TreeItem<File> currentDir = fileSystemView.getRoot(); while (it.hasNext()) { final String currDirName = it.next().toString(); FilteredList<TreeItem<File>> matchingChildren = currentDir.getChildren().filtered(elem -> elem.getValue().getName().equals(currDirName)); if (matchingChildren.size() == 1) { matchingChildren.get(0).setExpanded(true); currentDir = matchingChildren.get(0); } } fileSystemView.getSelectionModel().clearSelection(); fileSystemView.getSelectionModel().select(currentDir); fileSystemView.scrollTo(fileSystemView.getSelectionModel().getSelectedIndex()); } private void showDirectoryContents(TreeItem<File> selectedDirectory) { if (selectedDirectory == null) { return; } final WebEngine webEngine = directoryContentView.getEngine(); webEngine.loadContent(!isInShowContentsMode ? getFileNamesInDirectoryHTML(selectedDirectory.getValue()) : getFileContentsInDirectoryHTML(selectedDirectory.getValue())); } private void refreshFileSystemView() { showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem()); } private String getFileNamesInDirectoryHTML(File directory) { final StringBuilder sb = new StringBuilder(); final DecimalFormat df = new DecimalFormat("0.00"); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html><head>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>") .append("</head><body><div id=\"fileList\"><ul>"); boolean even = false; for (File file : files) { sb.append("<li class=\"") .append(even ? "even" : "odd") .append("\"><span class=\"fileName\">") .append(file.getName()) .append("</span> <span class=\"fileSize\">(") .append(df.format((float) file.length() / 1024)) .append("K)</span>") .append("</li>"); even = !even; } sb.append("</ul></div></body></html>"); return sb.toString(); } private String getFileContentsInDirectoryHTML(File directory) { final StringBuilder sb = new StringBuilder(); final File[] files = listFiles(directory); if (files == null) { return ""; } sb.append("<html>") .append("<body>") .append("<style type=\"text/css\">") .append(fileTreeViewerCSS) .append("</style>"); for (File file : files) { try { String contentsString; if (file.getName().endsWith(".pdf")) { final PDDocument doc = PDDocument.load(file); final StringWriter writer = new StringWriter(); new PDFText2HTML("UTF-8").writeText(doc, writer); contentsString = writer.toString(); writer.close(); doc.close(); } else { byte[] encoded = Files.readAllBytes(file.toPath()); contentsString = new String(encoded, charset); contentsString = contentsString.replace("<", "&lt;"); contentsString = contentsString.replace(">", "&gt;"); contentsString = contentsString.replace("\n", "<br/>"); } sb.append("<div class=\"entry\"><h3>") .append(file.getName()) .append("</h3>") .append("<div class=\"content\">") .append(contentsString) .append("</div>") .append("</div>"); } catch (IOException e) {} } sb.append("</body></html>"); return sb.toString(); } private File[] listFiles(File directory) { if (directory == null) { return new File[0]; } File[] files = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && filePattern.matcher(pathname.getName().toString()).matches() && pathname.length() <= fileSizeThreshold.toBytes(); } }); if (files == null) { return new File[0]; } Arrays.sort(files, fileComparator); return files; } }
rindPHI/F3TextViewerFX
src/de/dominicscheurer/quicktxtview/view/FileViewerController.java
Java
gpl-3.0
9,526
//: pony/PartyFavor.java package pokepon.pony; import pokepon.enums.*; /** Party Favor * Good def and spa, lacks Hp and Speed * * @author silverweed */ public class PartyFavor extends Pony { public PartyFavor(int _level) { super(_level); name = "Party Favor"; type[0] = Type.LAUGHTER; type[1] = Type.HONESTY; race = Race.UNICORN; sex = Sex.MALE; baseHp = 60; baseAtk = 80; baseDef = 100; baseSpatk = 100; baseSpdef = 80; baseSpeed = 60; /* Learnable Moves */ learnableMoves.put("Tackle",1); learnableMoves.put("Hidden Talent",1); learnableMoves.put("Mirror Pond",1); learnableMoves.put("Dodge",1); } }
silverweed/pokepon
pony/PartyFavor.java
Java
gpl-3.0
654
////////////////////////////////////////////////// // JIST (Java In Simulation Time) Project // Timestamp: <EntityRef.java Sun 2005/03/13 11:10:16 barr rimbase.rimonbarr.com> // // Copyright (C) 2004 by Cornell University // All rights reserved. // Refer to LICENSE for terms and conditions of use. package jist.runtime; import java.lang.reflect.Method; import java.lang.reflect.InvocationHandler; import java.rmi.RemoteException; /** * Stores a reference to a (possibly remote) Entity object. A reference * consists of a serialized reference to a Controller and an index within that * Controller. * * @author Rimon Barr &lt;barr+jist@cs.cornell.edu&gt; * @version $Id: EntityRef.java,v 1.1 2007/04/09 18:49:26 drchoffnes Exp $ * @since JIST1.0 */ public class EntityRef implements InvocationHandler { /** * NULL reference constant. */ public static final EntityRef NULL = new EntityRefDist(null, -1); /** * Entity index within Controller. */ private final int index; /** * Initialise a new entity reference with given * Controller and Entity IDs. * * @param index entity ID */ public EntityRef(int index) { this.index = index; } /** * Return entity reference hashcode. * * @return entity reference hashcode */ public int hashCode() { return index; } /** * Test object equality. * * @param o object to test equality * @return object equality */ public boolean equals(Object o) { if(o==null) return false; if(!(o instanceof EntityRef)) return false; EntityRef er = (EntityRef)o; if(index!=er.index) return false; return true; } /** * Return controller of referenced entity. * * @return controller of referenced entity */ public ControllerRemote getController() { if(Main.SINGLE_CONTROLLER) { return Controller.activeController; } else { throw new RuntimeException("multiple controllers"); } } /** * Return index of referenced entity. * * @return index of referenced entity */ public int getIndex() { return index; } /** * Return toString of referenced entity. * * @return toString of referenced entity */ public String toString() { try { return "EntityRef:"+getController().toStringEntity(getIndex()); } catch(java.rmi.RemoteException e) { throw new RuntimeException(e); } } /** * Return class of referenced entity. * * @return class of referenced entity */ public Class getClassRef() { try { return getController().getEntityClass(getIndex()); } catch(java.rmi.RemoteException e) { throw new RuntimeException(e); } } ////////////////////////////////////////////////// // proxy entities // /** boolean type for null return. */ private static final Boolean RET_BOOLEAN = new Boolean(false); /** byte type for null return. */ private static final Byte RET_BYTE = new Byte((byte)0); /** char type for null return. */ private static final Character RET_CHARACTER = new Character((char)0); /** double type for null return. */ private static final Double RET_DOUBLE = new Double((double)0); /** float type for null return. */ private static final Float RET_FLOAT = new Float((float)0); /** int type for null return. */ private static final Integer RET_INTEGER = new Integer(0); /** long type for null return. */ private static final Long RET_LONG = new Long(0); /** short type for null return. */ private static final Short RET_SHORT = new Short((short)0); /** * Called whenever a proxy entity reference is invoked. Schedules the call * at the appropriate Controller. * * @param proxy proxy entity reference object whose method was invoked * @param method method invoked on entity reference object * @param args arguments of the method invocation * @return result of blocking event; null return for non-blocking events * @throws Throwable whatever was thrown by blocking events; never for non-blocking events */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if(Rewriter.isBlockingRuntimeProxy(method)) // todo: make Object methods blocking //|| method.getDeclaringClass()==Object.class) { return blockingInvoke(proxy, method, args); } else { // schedule a simulation event if(Main.SINGLE_CONTROLLER) { Controller.activeController.addEvent(method, this, args); } else { getController().addEvent(method, this, args); } return null; } } catch(RemoteException e) { throw new JistException("distributed simulation failure", e); } } /** * Helper method: called whenever a BLOCKING method on proxy entity reference * is invoked. Schedules the call at the appropriate Controller. * * @param proxy proxy entity reference object whose method was invoked * @param method method invoked on entity reference object * @param args arguments of the method invocation * @return result of blocking event * @throws Throwable whatever was thrown by blocking events */ private Object blockingInvoke(Object proxy, Method method, Object[] args) throws Throwable { Controller c = Controller.getActiveController(); if(c.isModeRestoreInst()) { // restore complete if(Controller.log.isDebugEnabled()) { Controller.log.debug("restored event state!"); } // return callback result return c.clearRestoreState(); } else { // calling blocking method c.registerCallEvent(method, this, args); // todo: darn Java; this junk slows down proxies Class ret = method.getReturnType(); if(ret==Void.TYPE) { return null; } else if(ret.isPrimitive()) { String retName = ret.getName(); switch(retName.charAt(0)) { case 'b': switch(retName.charAt(1)) { case 'o': return RET_BOOLEAN; case 'y': return RET_BYTE; default: throw new RuntimeException("unknown return type"); } case 'c': return RET_CHARACTER; case 'd': return RET_DOUBLE; case 'f': return RET_FLOAT; case 'i': return RET_INTEGER; case 'l': return RET_LONG; case 's': return RET_SHORT; default: throw new RuntimeException("unknown return type"); } } else { return null; } } } } // class: EntityRef
jbgi/replics
swans/jist/runtime/EntityRef.java
Java
gpl-3.0
6,768
package se.sics.asdistances; import se.sics.asdistances.ASDistances; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.*; /** * * @author Niklas Wahlén <nwahlen@kth.se> */ public class ASDistancesTest { ASDistances distances = null; public ASDistancesTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { distances = ASDistances.getInstance(); } @After public void tearDown() { } @Test public void testGetDistance() { System.out.println("Distance: " + distances.getDistance("193.10.67.148", "85.226.78.233")); } }
jimdowling/gvod
bootstrap/ISPFriendliness-Distances/src/test/java/se/sics/asdistances/ASDistancesTest.java
Java
gpl-3.0
796
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.hyranasoftware.githubupdater.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Objects; import org.joda.time.DateTime; /** * * @author danny_000 */ @JsonIgnoreProperties(ignoreUnknown = true) public class Asset { String url; String browser_download_url; int id; String name; String label; String state; String content_type; long size; long download_count; DateTime created_at; DateTime updated_at; GithubUser uploader; public Asset() { } public Asset(String url, String browser_download_url, int id, String name, String label, String state, String content_type, long size, long download_count, DateTime created_at, DateTime updated_at, GithubUser uploader) { this.url = url; this.browser_download_url = browser_download_url; this.id = id; this.name = name; this.label = label; this.state = state; this.content_type = content_type; this.size = size; this.download_count = download_count; this.created_at = created_at; this.updated_at = updated_at; this.uploader = uploader; } public String getState() { return state; } public String getUrl() { return url; } public String getBrowser_download_url() { return browser_download_url; } public int getId() { return id; } public String getName() { return name; } public String getLabel() { return label; } public String getContent_type() { return content_type; } public long getSize() { return size; } public long getDownload_count() { return download_count; } public DateTime getCreated_at() { return created_at; } public DateTime getUpdated_at() { return updated_at; } public GithubUser getUploader() { return uploader; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.content_type); hash = 79 * hash + (int) (this.download_count ^ (this.download_count >>> 32)); hash = 79 * hash + Objects.hashCode(this.created_at); hash = 79 * hash + Objects.hashCode(this.updated_at); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Asset other = (Asset) obj; if (this.id != other.id) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.content_type, other.content_type)) { return false; } return true; } @Override public String toString(){ return this.name; } }
eternia16/javaGithubUpdater
src/main/java/nl/hyranasoftware/githubupdater/domain/Asset.java
Java
gpl-3.0
3,243
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.08.02 at 08:05:16 PM CEST // package net.ramso.dita.concept; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for synblk.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="synblk.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}synblk.content"/> * &lt;/sequence> * &lt;attGroup ref="{}synblk.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "synblk.class", propOrder = { "title", "groupseqOrGroupchoiceOrGroupcomp" }) @XmlSeeAlso({ Synblk.class }) public class SynblkClass { protected Title title; @XmlElements({ @XmlElement(name = "groupseq", type = Groupseq.class), @XmlElement(name = "groupchoice", type = Groupchoice.class), @XmlElement(name = "groupcomp", type = Groupcomp.class), @XmlElement(name = "fragref", type = Fragref.class), @XmlElement(name = "synnote", type = Synnote.class), @XmlElement(name = "synnoteref", type = Synnoteref.class), @XmlElement(name = "fragment", type = Fragment.class) }) protected List<java.lang.Object> groupseqOrGroupchoiceOrGroupcomp; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; /** * Gets the value of the title property. * * @return * possible object is * {@link Title } * */ public Title getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link Title } * */ public void setTitle(Title value) { this.title = value; } /** * Gets the value of the groupseqOrGroupchoiceOrGroupcomp property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the groupseqOrGroupchoiceOrGroupcomp property. * * <p> * For example, to add a new item, do as follows: * <pre> * getGroupseqOrGroupchoiceOrGroupcomp().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Groupseq } * {@link Groupchoice } * {@link Groupcomp } * {@link Fragref } * {@link Synnote } * {@link Synnoteref } * {@link Fragment } * * */ public List<java.lang.Object> getGroupseqOrGroupchoiceOrGroupcomp() { if (groupseqOrGroupchoiceOrGroupcomp == null) { groupseqOrGroupchoiceOrGroupcomp = new ArrayList<java.lang.Object>(); } return this.groupseqOrGroupchoiceOrGroupcomp; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } }
ramsodev/DitaManagement
dita/dita.concept/src/net/ramso/dita/concept/SynblkClass.java
Java
gpl-3.0
14,623
/* * Copyright (C) 2013-2017 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package org.n52.series.db.beans.parameter; import java.util.HashMap; import java.util.Map; public abstract class Parameter<T> { private long parameterId; private long fkId; private String name; private T value; public Map<String, Object> toValueMap() { Map<String, Object> valueMap = new HashMap<>(); valueMap.put("name", getName()); valueMap.put("value", getValue()); return valueMap; } public long getParameterId() { return parameterId; } public void setParameterId(long parameterId) { this.parameterId = parameterId; } public long getFkId() { return fkId; } public void setFkId(long fkId) { this.fkId = fkId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSetName() { return getName() != null; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } public boolean isSetValue() { return getValue() != null; } }
ridoo/dao-series-api
dao/src/main/java/org/n52/series/db/beans/parameter/Parameter.java
Java
gpl-3.0
2,458
package com.mortensickel.measemulator; // http://maps.google.com/maps?q=loc:59.948509,10.602627 import com.google.android.gms.common.api.*; import android.content.Context; import android.text.*; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.view.animation.*; import android.app.*; import android.os.*; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.*; import android.view.View.*; import android.location.Location; import android.util.Log; import com.google.android.gms.location.*; import com.google.android.gms.common.*; import android.preference.*; import android.view.*; import android.content.*; import android.net.Uri; // import org.apache.http.impl.execchain.*; // Todo over a certain treshold, change calibration factor // TODO settable calibration factor // TODO finish icons // DONE location // DONE input background and source. Calculate activity from distance // TODO Use distribution map // DONE add settings menu // TODO generic skin // TODO handle pause and shutdown public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener { /* AUTOMESS: 0.44 pps = 0.1uSv/h ca 16. pulser pr nSv */ boolean poweron=false; long shutdowntime=0; long meastime; TextView tvTime,tvPulsedata, tvPause,tvAct, tvDoserate; long starttime = 0; public long pulses=0; Integer mode=0; final Integer MAXMODE=3; final int MODE_OFF=0; final int MODE_MOMENTANDOSE=1; final int MODE_DOSERATE=2; final int MODE_DOSE=3; public final String TAG="measem"; double calibration=4.4; public Integer sourceact=1; protected long lastpulses=0; public boolean gpsenabled = true; public Context context; public Integer gpsinterval=2000; private GoogleApiClient gac; private Location here,there; protected LocationRequest loreq; private LinearLayout llDebuginfo; private Double background=0.0; private float sourcestrength=1000; private boolean showDebug=false; private final String PULSES="pulses"; @Override public void onConnectionFailed(ConnectionResult p1) { // TODO: Implement this method } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putLong(PULSES,pulses); //savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance pulses = savedInstanceState.getLong(PULSES); //mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL); } protected void createLocationRequest(){ loreq = new LocationRequest(); loreq.setInterval(gpsinterval); loreq.setFastestInterval(100); loreq.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates(){ if(loreq==null){ createLocationRequest(); } LocationServices.FusedLocationApi.requestLocationUpdates(gac,loreq,this); } public void ConnectionCallbacks(){ } @Override public void onLocationChanged(Location p1) { here=p1; double distance=here.distanceTo(there); sourceact=(int)Math.round(background+sourcestrength/(distance*distance)); tvAct.setText(String.valueOf(sourceact)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO: Implement this method MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.mnuSettings: Intent intent=new Intent(); intent.setClass(MainActivity.this,SetPreferenceActivity.class); startActivityForResult(intent,0); return true; case R.id.mnuSaveLoc: saveLocation(); return true; case R.id.mnuShowLoc: showLocation(); return true; } return super.onOptionsItemSelected(item); } protected void showLocation(){ String lat=String.valueOf(there.getLatitude()); String lon=String.valueOf(there.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); try { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:"+lat+","+lon)); startActivity(myIntent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "No application can handle this request.",Toast.LENGTH_LONG).show(); e.printStackTrace(); } } protected void saveLocation(){ Location LastLocation = LocationServices.FusedLocationApi.getLastLocation( gac); if (LastLocation != null) { String lat=String.valueOf(LastLocation.getLatitude()); String lon=String.valueOf(LastLocation.getLongitude()); Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show(); there=LastLocation; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); //SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor ed=sp.edit(); ed.putString("Latitude",lat); ed.putString("Longitude",lon); ed.apply(); ed.commit(); }else{ Toast.makeText(getApplicationContext(),getString(R.string.CouldNotGetLocation), Toast.LENGTH_LONG).show(); } } @Override public void onConnected(Bundle p1) { Location loc = LocationServices.FusedLocationApi.getLastLocation(gac); if(loc != null){ here=loc; } } @Override public void onConnectionSuspended(int p1) { // TODO: Implement this method } protected void onStart(){ gac.connect(); super.onStart(); } protected void onStop(){ gac.disconnect(); super.onStop(); } //this posts a message to the main thread from our timertask //and updates the textfield final Handler h = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { long millis = System.currentTimeMillis() - starttime; int seconds = (int) (millis / 1000); if(seconds>0){ double display=0; if( mode==MODE_MOMENTANDOSE){ if (lastpulses==0 || (lastpulses>pulses)){ display=0; }else{ display=((pulses-lastpulses)/calibration); } lastpulses=pulses; } if (mode==MODE_DOSERATE){ display=(double)pulses/(double)seconds/calibration; } if (mode==MODE_DOSE){ display=(double)pulses/calibration/3600; } tvDoserate.setText(String.format("%.2f",display)); } if(showDebug){ int minutes = seconds / 60; seconds = seconds % 60; tvTime.setText(String.format("%d:%02d", minutes, seconds)); } return false; } }); //runs without timer - reposting itself after a random interval Handler h2 = new Handler(); Runnable run = new Runnable() { @Override public void run() { int n=1; long pause=pause(getInterval()); h2.postDelayed(run,pause); if(showDebug){ tvPause.setText(String.format("%d",pause)); } receivepulse(n); } }; public Integer getInterval(){ Integer act=sourceact; if(act==0){ act=1; } Integer interval=5000/act; if (interval==0){ interval=1; } return(interval); } public long pause(Integer interval){ double pause=interval; if(interval > 5){ Random rng=new Random(); pause=rng.nextGaussian(); Integer sd=interval/4; pause=pause*sd+interval; if(pause<0){pause=0;} } return((long)pause); } public void receivepulse(int n){ LinearLayout myText = (LinearLayout) findViewById(R.id.llLed ); Animation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(20); //You can manage the time of the blink with this parameter anim.setStartOffset(20); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(0); myText.startAnimation(anim); pulses=pulses+1; Double sdev=Math.sqrt(pulses); if(showDebug){ tvPulsedata.setText(String.format("%d - %.1f - %.0f %%",pulses,sdev,sdev/pulses*100)); } } //tells handler to send a message class firstTask extends TimerTask { @Override public void run() { h.sendEmptyMessage(0); } } @Override protected void onResume() { // TODO: Implement this method super.onResume(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); // lowprobCutoff = (double)sharedPref.getFloat("pref_key_lowprobcutoff", 1)/100; readPrefs(); //XlowprobCutoff= } private void readPrefs(){ SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String ret=sharedPref.getString("Latitude", "10"); Double lat= Double.parseDouble(ret); ret=sharedPref.getString("Longitude", "60"); Double lon= Double.parseDouble(ret); there.setLatitude(lat); there.setLongitude(lon); ret=sharedPref.getString("backgroundValue", "1"); background= Double.parseDouble(ret)/200; showDebug=sharedPref.getBoolean("showDebug", false); debugVisible(showDebug); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); readPrefs(); } Timer timer = new Timer(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context=this; loadPref(context); /*SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); double lat = getResources().get; long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue); SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE); // getString(R.string.preference_file_key), Context.MODE_PRIVATE); */ there = new Location("dummyprovider"); there.setLatitude(59.948509); there.setLongitude(10.602627); llDebuginfo=(LinearLayout)findViewById(R.id.llDebuginfo); llDebuginfo.setVisibility(View.GONE); gac=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); tvTime = (TextView)findViewById(R.id.tvTime); tvPulsedata = (TextView)findViewById(R.id.tvPulsedata); tvPause = (TextView)findViewById(R.id.tvPause); tvDoserate = (TextView)findViewById(R.id.etDoserate); tvAct=(EditText)findViewById(R.id.activity); tvAct.addTextChangedListener(activityTW); switchMode(mode); Button b = (Button)findViewById(R.id.btPower); b.setOnClickListener(onOffClick); b=(Button)findViewById(R.id.btMode); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { modechange(v); } }); b=(Button)findViewById(R.id.btLight); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDebug=!showDebug; } }); } @Override public void onPause() { super.onPause(); timer.cancel(); timer.purge(); h2.removeCallbacks(run); } TextWatcher activityTW = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { String act=tvAct.getText().toString(); if(act.equals("")){act="1";} sourceact=Integer.parseInt(act); // TODO better errorchecking. // TODO disable if using geolocation }}; View.OnClickListener onOffClick = new View.OnClickListener() { @Override public void onClick(View v) { if(poweron){ long now=System.currentTimeMillis(); if(now> shutdowntime && now < shutdowntime+500){ timer.cancel(); timer.purge(); h2.removeCallbacks(run); pulses=0; poweron=false; mode=MODE_OFF; switchMode(mode); } shutdowntime = System.currentTimeMillis()+500; }else{ shutdowntime=0; starttime = System.currentTimeMillis(); timer = new Timer(); timer.schedule(new firstTask(), 0,500); startLocationUpdates(); h2.postDelayed(run, pause(getInterval())); mode=1; switchMode(mode); poweron=true; } } }; private void debugVisible(Boolean show){ View debug=findViewById(R.id.llDebuginfo); if(show){ debug.setVisibility(View.VISIBLE); }else{ debug.setVisibility(View.GONE); } } public void loadPref(Context ctx){ //SharedPreferences shpref=PreferenceManager.getDefaultSharedPreferences(ctx); PreferenceManager.setDefaultValues(ctx, R.xml.preferences, false); } public void modechange(View v){ if(mode > 0){ mode++; if (mode > MAXMODE){ mode=1; } switchMode(mode);} } public void switchMode(int mode){ int unit=0; switch(mode){ case MODE_MOMENTANDOSE: unit= R.string.ugyh; break; case MODE_DOSERATE: unit = R.string.ugyhint; break; case MODE_DOSE: unit = R.string.ugy; break; case MODE_OFF: unit= R.string.blank; tvDoserate.setText(""); break; } TextView tv=(TextView)findViewById(R.id.etUnit); tv.setText(unit); } }
sickel/measem
app/src/main/java/com/mortensickel/measemulator/MainActivity.java
Java
gpl-3.0
13,932
/** * */ package cz.geokuk.core.napoveda; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import cz.geokuk.core.program.FConst; import cz.geokuk.framework.Action0; import cz.geokuk.util.process.BrowserOpener; /** * @author Martin Veverka * */ public class ZadatProblemAction extends Action0 { private static final long serialVersionUID = -2882817111560336824L; /** * @param aBoard */ public ZadatProblemAction() { super("Zadat problém ..."); putValue(SHORT_DESCRIPTION, "Zobrazí stránku na code.google.com, která umožní zadat chybu v Geokuku nebo požadavek na novou funkcionalitu."); putValue(MNEMONIC_KEY, KeyEvent.VK_P); } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent aE) { try { BrowserOpener.displayURL(new URL(FConst.POST_PROBLEM_URL)); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } }
marvertin/geokuk
src/main/java/cz/geokuk/core/napoveda/ZadatProblemAction.java
Java
gpl-3.0
1,073
/** * Copyright 2013, 2014 Ioana Ileana @ Telecom ParisTech * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package instance; import java.util.ArrayList; public class Parser { private ArrayList<ArrayList<String>> m_relationals; private ArrayList<String[]> m_equalities; int m_pos; public Parser() { m_relationals = new ArrayList<ArrayList<String>>(); m_equalities = new ArrayList<String[]>(); m_pos=0; } public void flush() { m_pos = 0; m_relationals.clear(); m_equalities.clear(); } public boolean charIsValidForRelation(char c) { return ((c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_')); } public boolean charIsValidForTerm(char c) { return ((c>='a' && c<='z') || (c>='0' && c<='9') || (c=='_') || (c=='.') ); } public ArrayList<String> parseAtom(String line) { ArrayList<String> list = new ArrayList<String>(); String relation=""; while (m_pos<line.length()) { if (charIsValidForRelation(line.charAt(m_pos))) { relation+=line.charAt(m_pos); m_pos++; } else if (line.charAt(m_pos)=='(') { m_pos++; list.add(relation); parseTerms(line, list); return list; } else { m_pos++; } } return null; } public void parseTerms(String line, ArrayList<String> list) { while (m_pos<line.length()) { if (line.charAt(m_pos) == ')') { m_pos++; return; } else if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else { String term=parseSingleTerm(line); list.add(term); } } } public String parseSingleTerm(String line) { String term=""; while (m_pos<line.length() && charIsValidForTerm(line.charAt(m_pos))) { term+=line.charAt(m_pos); m_pos++; } return term; } public void parseRelationals(String line) { m_pos = 0; while (m_pos<line.length()) { if (line.charAt(m_pos)<'A' || line.charAt(m_pos)>'Z') m_pos++; else { ArrayList<String> relStr = parseAtom(line); m_relationals.add(relStr); } } } public void parseEqualities(String line) { m_pos = 0; while (m_pos<line.length()) { if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else parseEquality(line); } } public void parseEquality(String line) { String[] terms=new String[2]; terms[0] = parseSingleTerm(line); while (m_pos<line.length() && !charIsValidForTerm(line.charAt(m_pos))) m_pos++; terms[1] = parseSingleTerm(line); m_equalities.add(terms); } public ArrayList<String[]> getEqualities() { return m_equalities; } public ArrayList<ArrayList<String>> getRelationals() { return m_relationals; } public ArrayList<String> parseProvenance(String line) { ArrayList<String> provList = new ArrayList<String>(); while (m_pos < line.length()) { while (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; String term = parseSingleTerm(line); if (!(term.equals(""))) { provList.add(term); } } return provList; } }
IoanaIleana/ProvCB
src/instance/Parser.java
Java
gpl-3.0
3,628
package com.test.ipetrov.start; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @SpringBootApplication @EnableWebMvc @ComponentScan(basePackages = {"com.test.ipetrov.configuration", "com.test.ipetrov.portal"}) @EnableJpaRepositories(basePackages = "com.test.ipetrov") public class Application { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); } }
081krieger/rps
src/main/java/com/test/ipetrov/start/Application.java
Java
gpl-3.0
804
public class Rectangulo { public int Base; public int Altura; //Ejercicio realizado con ayuda de esta pagina:http://diagramas-de-flujo.blogspot.com/2013/02/calcular-perimetro-rectangulo-Java.html //aqui llamamos las dos variables que utilizaremos. Rectangulo(int Base, int Altura) { this.Base = Base; this.Altura = Altura; } //COmo pueden observar aqui se obtiene la base y se asigna el valor de la base. int getBase () { return Base; } //aqui devolvemos ese valor void setBase (int Base) { this.Base = Base; } //aqui de igual forma se obtiene la altura y se le asigna el valor int getAltura () { return Altura; } //aqui devuelve el valor de la altura void setAltura (int Altura) { this.Altura = Altura; } //aqui con una formula matematica se obtiene el perimetro hacemos una suma y una multiplicacion int getPerimetro() { return 2*(Base+Altura); } //aqui solo se hace un calculo matematico como la multiplicacion int getArea() { return Base*Altura; } }
IvethS/Tarea2
src/Rectangulo.java
Java
gpl-3.0
1,004
/* * This file is part of "U Turismu" project. * * U Turismu is an enterprise application in support of calabrian tour operators. * This system aims to promote tourist services provided by the operators * and to develop and improve tourism in Calabria. * * Copyright (C) 2012 "LagrecaSpaccarotella" team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uturismu.dao; import uturismu.dto.Booking; /** * @author "LagrecaSpaccarotella" team. * */ public interface BookingDao extends GenericDao<Booking> { }
spa-simone/u-turismu
src/main/java/uturismu/dao/BookingDao.java
Java
gpl-3.0
1,133
package it.ads.activitiesmanager.model.dao; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; //Segnala che si tratta di una classe DAO (o Repository) @Repository //Significa che tutti i metodi della classe sono definiti come @Transactional @Transactional public abstract class AbstractDao<T extends Serializable> { private Class<T> c; @PersistenceContext EntityManager em; public final void setClass(Class<T> c){ this.c = c; } public T find(Integer id) { return em.find(c,id); } public List<T> findAll(){ String SELECT = "SELECT * FROM " + c.getName(); Query query = em.createQuery(SELECT); return query.getResultList(); } public void save(T entity){ em.persist(entity); } public void update(T entity){ em.merge(entity); } public void delete(T entity){ em.remove(entity); } public void deleteById(Integer id){ T entity = find(id); delete(entity); } }
paoloap/activitiesmanager
activitiesmanager-model/src/main/java/it/ads/activitiesmanager/model/dao/AbstractDao.java
Java
gpl-3.0
1,147
package ca.six.tomato.util; import org.json.JSONArray; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowEnvironment; import java.io.File; import ca.six.tomato.BuildConfig; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; /** * Created by songzhw on 2016-10-03 */ @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class DataUtilsTest { @Test public void testFile() { File dstFile = ShadowEnvironment.getExternalStorageDirectory(); assertTrue(dstFile.exists()); System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true System.out.println("szw isExisting = " + dstFile.exists()); //=> true System.out.println("szw path = " + dstFile.getPath()); //=> C:\Users\***\AppData\Local\Temp\android-tmp-robolectric7195966122073188215 } @Test public void testWriteString(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; DataUtilKt.write("abc", path); String ret = DataUtilKt.read(path, false); assertEquals("abc", ret); } @Test public void testWriteJSON(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}"; DataUtilKt.write(content, path); JSONArray ret = DataUtilKt.read(path); System.out.println("szw, ret = "+ret.toString()); assertNotNull(ret); } }
SixCan/SixTomato
app/src/test/java/ca/six/tomato/util/DataUtilsTest.java
Java
gpl-3.0
2,002
package net.thevpc.upa.impl; import net.thevpc.upa.*; import net.thevpc.upa.impl.transform.IdentityDataTypeTransform; import net.thevpc.upa.impl.util.NamingStrategy; import net.thevpc.upa.impl.util.NamingStrategyHelper; import net.thevpc.upa.impl.util.PlatformUtils; import net.thevpc.upa.types.*; import net.thevpc.upa.exceptions.UPAException; import net.thevpc.upa.filters.FieldFilter; import net.thevpc.upa.types.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public abstract class AbstractField extends AbstractUPAObject implements Field, Comparable<Object> { protected Entity entity; protected EntityItem parent; protected DataType dataType; protected Formula persistFormula; protected int persistFormulaOrder; protected Formula updateFormula; protected int updateFormulaOrder; protected Formula queryFormula; protected Object defaultObject; protected SearchOperator searchOperator = SearchOperator.DEFAULT; protected DataTypeTransform typeTransform; protected HashMap<String, Object> properties; protected FlagSet<UserFieldModifier> userModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<UserFieldModifier> userExcludeModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<FieldModifier> effectiveModifiers = FlagSets.noneOf(FieldModifier.class); protected boolean closed; protected Object unspecifiedValue = UnspecifiedValue.DEFAULT; private AccessLevel persistAccessLevel = AccessLevel.READ_WRITE; private AccessLevel updateAccessLevel = AccessLevel.READ_WRITE; private AccessLevel readAccessLevel = AccessLevel.READ_WRITE; private ProtectionLevel persistProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel updateProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel readProtectionLevel = ProtectionLevel.PUBLIC; private FieldPersister fieldPersister; private PropertyAccessType accessType; private List<Relationship> manyToOneRelationships; private List<Relationship> oneToOneRelationships; private boolean _customDefaultObject = false; private Object _typeDefaultObject = false; protected AbstractField() { } @Override public String getAbsoluteName() { return (getEntity() == null ? "?" : getEntity().getName()) + "." + getName(); } public EntityItem getParent() { return parent; } public void setParent(EntityItem item) { EntityItem old = this.parent; EntityItem recent = item; beforePropertyChangeSupport.firePropertyChange("parent", old, recent); this.parent = item; afterPropertyChangeSupport.firePropertyChange("parent", old, recent); } @Override public void commitModelChanges() { manyToOneRelationships = getManyToOneRelationshipsImpl(); oneToOneRelationships = getOneToOneRelationshipsImpl(); } public boolean is(FieldFilter filter) throws UPAException { return filter.accept(this); } public boolean isId() throws UPAException { return getModifiers().contains(FieldModifier.ID); } @Override public boolean isGeneratedId() throws UPAException { if (!isId()) { return false; } Formula persistFormula = getPersistFormula(); return (persistFormula != null); } public boolean isMain() throws UPAException { return getModifiers().contains(FieldModifier.MAIN); } @Override public boolean isSystem() { return getModifiers().contains(FieldModifier.SYSTEM); } public boolean isSummary() throws UPAException { return getModifiers().contains(FieldModifier.SUMMARY); } public List<Relationship> getManyToOneRelationships() { return manyToOneRelationships; } public List<Relationship> getOneToOneRelationships() { return oneToOneRelationships; } protected List<Relationship> getManyToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } protected List<Relationship> getOneToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } public void setFormula(Formula formula) { setPersistFormula(formula); setUpdateFormula(formula); } @Override public void setFormula(String formula) { setFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setPersistFormula(Formula formula) { this.persistFormula = formula; } public void setUpdateFormula(Formula formula) { this.updateFormula = formula; } @Override public void setFormulaOrder(int order) { setPersistFormulaOrder(order); setUpdateFormulaOrder(order); } public int getUpdateFormulaOrder() { return updateFormulaOrder; } @Override public void setUpdateFormulaOrder(int order) { this.updateFormulaOrder = order; } public int getPersistFormulaOrder() { return persistFormulaOrder; } @Override public void setPersistFormulaOrder(int order) { this.persistFormulaOrder = order; } public Formula getUpdateFormula() { return updateFormula; } @Override public void setUpdateFormula(String formula) { setUpdateFormula(formula == null ? null : new ExpressionFormula(formula)); } public Formula getSelectFormula() { return queryFormula; } @Override public void setSelectFormula(String formula) { setSelectFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setSelectFormula(Formula queryFormula) { this.queryFormula = queryFormula; } // public boolean isRequired() throws UPAException { // return (!isReadOnlyOnPersist() || !isReadOnlyOnUpdate()) && !getDataType().isNullable(); // } public String getPath() { EntityItem parent = getParent(); return parent == null ? ("/" + getName()) : (parent.getPath() + "/" + getName()); } @Override public PersistenceUnit getPersistenceUnit() { return entity.getPersistenceUnit(); } public Formula getPersistFormula() { return persistFormula; } @Override public void setPersistFormula(String formula) { setPersistFormula(formula == null ? null : new ExpressionFormula(formula)); } public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public DataType getDataType() { return dataType; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param datatype datatype */ @Override public void setDataType(DataType datatype) { this.dataType = datatype; if (!getDataType().isNullable()) { _typeDefaultObject = getDataType().getDefaultValue(); } else { _typeDefaultObject = null; } } public Object getDefaultValue() { if (_customDefaultObject) { Object o = ((CustomDefaultObject) defaultObject).getObject(); if (o == null) { o = _typeDefaultObject; } return o; } else { Object o = defaultObject; if (o == null) { o = _typeDefaultObject; } return o; } } public Object getDefaultObject() { return defaultObject; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param o default value witch may be san ObjectHandler */ public void setDefaultObject(Object o) { defaultObject = o; if (o instanceof CustomDefaultObject) { _customDefaultObject = true; } } public FlagSet<FieldModifier> getModifiers() { return effectiveModifiers; } public void setEffectiveModifiers(FlagSet<FieldModifier> effectiveModifiers) { this.effectiveModifiers = effectiveModifiers; } // public void addModifiers(long modifiers) { // setModifiers(getModifiers() | modifiers); // } // // public void removeModifiers(long modifiers) { // setModifiers(getModifiers() & ~modifiers); // } // public Expression getExpression() { // return formula == null ? null : formula.getExpression(); // } @Override public boolean equals(Object other) { return !(other == null || !(other instanceof Field)) && compareTo(other) == 0; } public int compareTo(Object other) { if (other == this) { return 0; } if (other == null) { return 1; } Field f = (Field) other; NamingStrategy comp = NamingStrategyHelper.getNamingStrategy(getEntity().getPersistenceUnit().isCaseSensitiveIdentifiers()); String s1 = entity != null ? comp.getUniformValue(entity.getName()) : ""; String s2 = f.getName() != null ? comp.getUniformValue(f.getEntity().getName()) : ""; int i = s1.compareTo(s2); if (i != 0) { return i; } else { String s3 = getName() != null ? comp.getUniformValue(getName()) : ""; String s4 = f.getName() != null ? comp.getUniformValue(f.getName()) : ""; i = s3.compareTo(s4); return i; } } @Override public FlagSet<UserFieldModifier> getUserModifiers() { return userModifiers; } // public void resetModifiers() { // modifiers = 0; // } public void setUserModifiers(FlagSet<UserFieldModifier> modifiers) { this.userModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public FlagSet<UserFieldModifier> getUserExcludeModifiers() { return userExcludeModifiers; } public void setUserExcludeModifiers(FlagSet<UserFieldModifier> modifiers) { this.userExcludeModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public String toString() { return getAbsoluteName(); } @Override public void close() throws UPAException { this.closed = true; } public boolean isClosed() { return closed; } @Override public Object getUnspecifiedValue() { return unspecifiedValue; } @Override public void setUnspecifiedValue(Object o) { this.unspecifiedValue = o; } public Object getUnspecifiedValueDecoded() { final Object fuv = getUnspecifiedValue(); if (UnspecifiedValue.DEFAULT.equals(fuv)) { return getDataType().getDefaultUnspecifiedValue(); } else { return fuv; } } public boolean isUnspecifiedValue(Object value) { Object v = getUnspecifiedValueDecoded(); return (v == value || (v != null && v.equals(value))); } public AccessLevel getPersistAccessLevel() { return persistAccessLevel; } public void setPersistAccessLevel(AccessLevel persistAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, persistAccessLevel)) { persistAccessLevel = AccessLevel.READ_WRITE; } this.persistAccessLevel = persistAccessLevel; } public AccessLevel getUpdateAccessLevel() { return updateAccessLevel; } public void setUpdateAccessLevel(AccessLevel updateAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, updateAccessLevel)) { updateAccessLevel = AccessLevel.READ_WRITE; } this.updateAccessLevel = updateAccessLevel; } public AccessLevel getReadAccessLevel() { return readAccessLevel; } public void setReadAccessLevel(AccessLevel readAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, readAccessLevel)) { readAccessLevel = AccessLevel.READ_ONLY; } if (readAccessLevel == AccessLevel.READ_WRITE) { readAccessLevel = AccessLevel.READ_ONLY; } this.readAccessLevel = readAccessLevel; } public void setAccessLevel(AccessLevel accessLevel) { setPersistAccessLevel(accessLevel); setUpdateAccessLevel(accessLevel); setReadAccessLevel(accessLevel); } public ProtectionLevel getPersistProtectionLevel() { return persistProtectionLevel; } public void setPersistProtectionLevel(ProtectionLevel persistProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, persistProtectionLevel)) { persistProtectionLevel = ProtectionLevel.PUBLIC; } this.persistProtectionLevel = persistProtectionLevel; } public ProtectionLevel getUpdateProtectionLevel() { return updateProtectionLevel; } public void setUpdateProtectionLevel(ProtectionLevel updateProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, updateProtectionLevel)) { updateProtectionLevel = ProtectionLevel.PUBLIC; } this.updateProtectionLevel = updateProtectionLevel; } public ProtectionLevel getReadProtectionLevel() { return readProtectionLevel; } public void setReadProtectionLevel(ProtectionLevel readProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, readProtectionLevel)) { readProtectionLevel = ProtectionLevel.PUBLIC; } this.readProtectionLevel = readProtectionLevel; } public void setProtectionLevel(ProtectionLevel persistLevel) { setPersistProtectionLevel(persistLevel); setUpdateProtectionLevel(persistLevel); setReadProtectionLevel(persistLevel); } public SearchOperator getSearchOperator() { return searchOperator; } public void setSearchOperator(SearchOperator searchOperator) { this.searchOperator = searchOperator; } public FieldPersister getFieldPersister() { return fieldPersister; } public void setFieldPersister(FieldPersister fieldPersister) { this.fieldPersister = fieldPersister; } public DataTypeTransform getTypeTransform() { return typeTransform; } @Override public DataTypeTransform getEffectiveTypeTransform() { DataTypeTransform t = getTypeTransform(); if (t == null) { DataType d = getDataType(); if (d != null) { t = new IdentityDataTypeTransform(d); } } return t; } public void setTypeTransform(DataTypeTransform transform) { this.typeTransform = transform; } public PropertyAccessType getPropertyAccessType() { return accessType; } public void setPropertyAccessType(PropertyAccessType accessType) { this.accessType = accessType; } @Override public Object getMainValue(Object instance) { Object v = getValue(instance); if (v != null) { Relationship manyToOneRelationship = getManyToOneRelationship(); if (manyToOneRelationship != null) { v = manyToOneRelationship.getTargetEntity().getBuilder().getMainValue(v); } } return v; } @Override public Object getValue(Object instance) { if (instance instanceof Document) { return ((Document) instance).getObject(getName()); } return getEntity().getBuilder().getProperty(instance, getName()); } @Override public void setValue(Object instance, Object value) { getEntity().getBuilder().setProperty(instance, getName(), value); } @Override public void check(Object value) { getDataType().check(value, getName(), null); } @Override public boolean isManyToOne() { return getDataType() instanceof ManyToOneType; } @Override public boolean isOneToOne() { return getDataType() instanceof OneToOneType; } @Override public ManyToOneRelationship getManyToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof ManyToOneType) { return (ManyToOneRelationship) ((ManyToOneType) dataType).getRelationship(); } return null; } @Override public OneToOneRelationship getOneToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof OneToOneType) { return (OneToOneRelationship) ((OneToOneType) dataType).getRelationship(); } return null; } protected void fillFieldInfo(FieldInfo i) { Field f = this; fillObjectInfo(i); DataTypeInfo dataType = f.getDataType() == null ? null : f.getDataType().getInfo(); if (dataType != null) { UPAI18n d = getPersistenceGroup().getI18nOrDefault(); if (f.getDataType() instanceof EnumType) { List<Object> values = ((EnumType) f.getDataType()).getValues(); StringBuilder v = new StringBuilder(); for (Object o : values) { if (v.length() > 0) { v.append(","); } v.append(d.getEnum(o)); } dataType.getProperties().put("titles", String.valueOf(v)); } } i.setDataType(dataType); i.setId(f.isId()); i.setGeneratedId(f.isGeneratedId()); i.setModifiers(f.getModifiers().toArray()); i.setPersistAccessLevel(f.getPersistAccessLevel()); i.setUpdateAccessLevel(f.getUpdateAccessLevel()); i.setReadAccessLevel(f.getReadAccessLevel()); i.setPersistProtectionLevel(f.getPersistProtectionLevel()); i.setUpdateProtectionLevel(f.getUpdateProtectionLevel()); i.setReadProtectionLevel(f.getReadProtectionLevel()); i.setEffectivePersistAccessLevel(f.getEffectivePersistAccessLevel()); i.setEffectiveUpdateAccessLevel(f.getEffectiveUpdateAccessLevel()); i.setEffectiveReadAccessLevel(f.getEffectiveReadAccessLevel()); i.setMain(f.isMain()); i.setSystem(f.getModifiers().contains(FieldModifier.SYSTEM)); i.setSummary(f.isSummary()); i.setManyToOne(f.isManyToOne()); i.setPropertyAccessType(f.getPropertyAccessType()); Relationship r = f.getManyToOneRelationship(); i.setManyToOneRelationship(r == null ? null : r.getName()); } @Override public AccessLevel getEffectiveAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getEffectiveReadAccessLevel(); case PERSIST: return getEffectivePersistAccessLevel(); case UPDATE: return getEffectiveUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public AccessLevel getAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadAccessLevel(); case PERSIST: return getPersistAccessLevel(); case UPDATE: return getUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public ProtectionLevel getProtectionLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadProtectionLevel(); case PERSIST: return getPersistProtectionLevel(); case UPDATE: return getUpdateProtectionLevel(); } } return ProtectionLevel.PRIVATE; } public AccessLevel getEffectivePersistAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getPersistAccessLevel(); ProtectionLevel pl = getPersistProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getPersistFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } break; } case PUBLIC: { break; } } break; } } if (al != AccessLevel.INACCESSIBLE) { if (isGeneratedId()) { al = AccessLevel.INACCESSIBLE; } if (!getModifiers().contains(FieldModifier.PERSIST_DEFAULT)) { al = AccessLevel.INACCESSIBLE; } } return al; } public AccessLevel getEffectiveUpdateAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getUpdateAccessLevel(); ProtectionLevel pl = getUpdateProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getUpdateFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } if (isId() && al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (getModifiers().contains(FieldModifier.UPDATE_DEFAULT)) { // } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } return al; } public AccessLevel getEffectiveReadAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getReadAccessLevel(); ProtectionLevel pl = getReadProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (al == AccessLevel.READ_ONLY) { if (!getModifiers().contains(FieldModifier.SELECT)) { al = AccessLevel.INACCESSIBLE; } } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } return al; } }
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/AbstractField.java
Java
gpl-3.0
27,988
package com.dmtools.webapp.config; import com.dmtools.webapp.config.locale.AngularCookieLocaleResolver; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocaleConfiguration extends WebMvcConfigurerAdapter implements EnvironmentAware { @SuppressWarnings("unused") private RelaxedPropertyResolver propertyResolver; @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messages."); } @Bean(name = "localeResolver") public LocaleResolver localeResolver() { AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); } }
jero-rodriguez/dmtools
src/main/java/com/dmtools/webapp/config/LocaleConfiguration.java
Java
gpl-3.0
1,616
/** * This class is generated by jOOQ */ package com.aviafix.db.generated.tables.pojos; import java.io.Serializable; import java.time.LocalDate; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class PAYBYCREDITCARDPROJECTION implements Serializable { private static final long serialVersionUID = 1444342293; private Integer ETID; private Integer CREDITCARDNUM; private LocalDate EXPDATE; private Integer CODE; private String CARDHOLDERNAME; private Double AMOUNT; public PAYBYCREDITCARDPROJECTION() {} public PAYBYCREDITCARDPROJECTION(PAYBYCREDITCARDPROJECTION value) { this.ETID = value.ETID; this.CREDITCARDNUM = value.CREDITCARDNUM; this.EXPDATE = value.EXPDATE; this.CODE = value.CODE; this.CARDHOLDERNAME = value.CARDHOLDERNAME; this.AMOUNT = value.AMOUNT; } public PAYBYCREDITCARDPROJECTION( Integer ETID, Integer CREDITCARDNUM, LocalDate EXPDATE, Integer CODE, String CARDHOLDERNAME, Double AMOUNT ) { this.ETID = ETID; this.CREDITCARDNUM = CREDITCARDNUM; this.EXPDATE = EXPDATE; this.CODE = CODE; this.CARDHOLDERNAME = CARDHOLDERNAME; this.AMOUNT = AMOUNT; } public Integer ETID() { return this.ETID; } public void ETID(Integer ETID) { this.ETID = ETID; } public Integer CREDITCARDNUM() { return this.CREDITCARDNUM; } public void CREDITCARDNUM(Integer CREDITCARDNUM) { this.CREDITCARDNUM = CREDITCARDNUM; } public LocalDate EXPDATE() { return this.EXPDATE; } public void EXPDATE(LocalDate EXPDATE) { this.EXPDATE = EXPDATE; } public Integer CODE() { return this.CODE; } public void CODE(Integer CODE) { this.CODE = CODE; } public String CARDHOLDERNAME() { return this.CARDHOLDERNAME; } public void CARDHOLDERNAME(String CARDHOLDERNAME) { this.CARDHOLDERNAME = CARDHOLDERNAME; } public Double AMOUNT() { return this.AMOUNT; } public void AMOUNT(Double AMOUNT) { this.AMOUNT = AMOUNT; } @Override public String toString() { StringBuilder sb = new StringBuilder("PAYBYCREDITCARDPROJECTION ("); sb.append(ETID); sb.append(", ").append(CREDITCARDNUM); sb.append(", ").append(EXPDATE); sb.append(", ").append(CODE); sb.append(", ").append(CARDHOLDERNAME); sb.append(", ").append(AMOUNT); sb.append(")"); return sb.toString(); } }
purple-sky/avia-fixers
app/src/main/java/com/aviafix/db/generated/tables/pojos/PAYBYCREDITCARDPROJECTION.java
Java
gpl-3.0
2,891
/* ComJail - A jail plugin for Minecraft servers Copyright (C) 2015 comdude2 (Matt Armer) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: admin@mcviral.net */ package net.mcviral.dev.plugins.comjail.events; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; import net.mcviral.dev.plugins.comjail.main.JailController; public class TeleportEvent implements Listener{ @SuppressWarnings("unused") private Plugin plugin; private JailController jailcontroller; public TeleportEvent(Plugin mplugin, JailController mjailcontroller){ plugin = mplugin; jailcontroller = mjailcontroller; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerTeleport(PlayerTeleportEvent event){ if (jailcontroller.isJailed(event.getPlayer().getUniqueId())){ if (!event.getPlayer().hasPermission("jail.override")){ event.setCancelled(true); event.getPlayer().sendMessage("[" + ChatColor.BLUE + "GUARD" + ChatColor.WHITE + "] " + ChatColor.RED + "You are jailed, you may not teleport."); } } } }
comdude2/ComJail
src/net/mcviral/dev/plugins/comjail/events/TeleportEvent.java
Java
gpl-3.0
1,828
package se.solit.timeit.resources; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpSession; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class BaseResource { protected WebApplicationException redirect(String destination) throws URISyntaxException { URI uri = new URI(destination); Response response = Response.seeOther(uri).build(); return new WebApplicationException(response); } /** * Set message to show the message in the next shown View. * * @param session * @param message */ protected void setMessage(HttpSession session, String message) { session.setAttribute("message", message); } }
Hoglet/TimeIT-Server
src/main/java/se/solit/timeit/resources/BaseResource.java
Java
gpl-3.0
703
/* * This file is part of rasdaman community. * * Rasdaman community is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rasdaman community is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <baumann@rasdaman.com>. */ package petascope.wcs2.handlers; import static petascope.wcs2.extensions.FormatExtension.MIME_XML; /** * Bean holding the response from executing a request operation. * * @author <a href="mailto:d.misev@jacobs-university.de">Dimitar Misev</a> */ public class Response { private final byte[] data; private final String xml; private final String mimeType; private final int exit_code; private static final int DEFAULT_CODE = 200; // constructrs public Response(byte[] data) { this(data, null, null, DEFAULT_CODE); } public Response(byte[] data, int code) { this(data, null, null, code); } public Response(String xml) { this(null, xml, null); //FormatExtension.MIME_GML); } public Response(String xml, int code) { this(null, xml, MIME_XML, code); } public Response(byte[] data, String xml, String mimeType) { this(data, xml, mimeType, DEFAULT_CODE); } public Response(byte[] data, String xml, String mimeType, int code) { this.data = data; this.xml = xml; this.mimeType = mimeType; this.exit_code = code; } // interface public byte[] getData() { return data; } public String getMimeType() { return mimeType; } public String getXml() { return xml; } public int getExitCode() { return exit_code; } }
miracee/rasdaman
applications/petascope/src/main/java/petascope/wcs2/handlers/Response.java
Java
gpl-3.0
2,322
package com.hacks.collegebarter.fragments; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hacks.collegebarter.R; import com.hacks.collegebarter.navdrawer.MainAppActivity; public class TradeboardFragment extends Fragment{ public static final String ARG_SECTION_NUMBER = "section_number"; // Following constructor public TradeboardFragment() { Bundle bundle = new Bundle(); bundle.putInt(ARG_SECTION_NUMBER, 0); this.setArguments(bundle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tradeboard_fragment, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainAppActivity) activity).onSectionAttached(getArguments().getInt( ARG_SECTION_NUMBER)); } }
ReggieSackey/CollegeBarter
CollegeBarter/src/com/hacks/collegebarter/fragments/TradeboardFragment.java
Java
gpl-3.0
1,009
package visualk.gallery.db; import java.awt.Color; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import visualk.db.MysqlLayer; import visualk.gallery.objects.Artist; import visualk.gallery.objects.Work; public class DbGallery extends MysqlLayer{ public DbGallery(String user, String pass, String db) { super(user, pass, db); } public void addObra(Work obra, Artist author) { if (this != null) { try { /*mySQL.executeDB("insert into hrzns (" + "nameHrz," + "dt," + "topHrz," + "topHrzColor," + "bottomHrzColor," + "canvasWidth," + "canvasHeigth," + "authorHrz," + "xPal," + "yPal," + "hPalx," + "hPaly," + "alcada," + "colPal," + "horizontal," + "aureaProp," + "superX," + "superY," + "textura," + "version) values ('" + hrz.getNameHrz() + "', " + "NOW()" + ", '" + hrz.getTopHrz() + "', '" + hrz.getTopHrzColor().getRGB() + "', '" + hrz.getBottomHrzColor().getRGB() + "', '" + hrz.getCanvasWidth() + "', '" + hrz.getCanvasHeigth() + "', '" + authorName + "', '" + hrz.getxPal() + "', '" + hrz.getyPal() + "', '" + hrz.gethPalx() + "', '" + hrz.gethPaly() + "', '" + hrz.getAlçada() + "', '" + hrz.getColPal().getRGB() + "', '" + hrz.isHorizontal() + "', '" + hrz.isAureaProp() + "', '" + hrz.getSuperX() + "', '" + hrz.getSuperY() + "', '" + hrz.isTextura() + "', '" + hrz.getVersion() + "')");*/ } catch (Exception e) { } finally { disconnect(); } } } public ResultSet listHrzns() { ResultSet myResult = null; try { myResult = queryDB("SELECT * FROM hrzns WHERE namehrz<>'wellcome' order by dt desc;"); } catch (SQLException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } return (myResult); } /* public Horizon getHrznBD(String name) { Horizon temp = new Horizon(name); ResultSet myResult; myResult = mySQL.queryDB("SELECT * FROM hrzns where nameHrz='" + name + "'"); temp.makeRandom(100, 300); if (myResult != null) { try { while (myResult.next()) { String nameHrz = ""; String topHrz = ""; String topHrzColor = ""; String bottomHrzColor = ""; String canvasWidth = ""; String canvasHeigth = ""; String authorHrz = ""; String xPal = ""; String yPal = ""; String hPalx = ""; String hPaly = ""; String alcada = ""; String horizontal = ""; String aureaProp = ""; String colPal = ""; String superX = ""; String superY = ""; String textura = ""; String version = ""; try { nameHrz = myResult.getString("nameHrz"); topHrz = myResult.getString("topHrz"); topHrzColor = myResult.getString("topHrzColor"); bottomHrzColor = myResult.getString("bottomHrzColor"); canvasWidth = myResult.getString("canvasWidth"); canvasHeigth = myResult.getString("canvasHeigth"); authorHrz = myResult.getString("authorHrz"); xPal = myResult.getString("xPal"); yPal = myResult.getString("yPal"); hPalx = myResult.getString("hPalx"); hPaly = myResult.getString("hPaly"); alcada = myResult.getString("alcada"); colPal = myResult.getString("colPal"); horizontal = myResult.getString("horizontal"); aureaProp = myResult.getString("aureaProp"); superX = myResult.getString("superX"); superY = myResult.getString("superY"); textura = myResult.getString("textura"); version = myResult.getString("version"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp.setNameHrz(nameHrz); temp.setTopHrz(Integer.parseInt(topHrz)); temp.setTopHrzColor(new Color(Integer.parseInt(topHrzColor))); temp.setBottomHrzColor(new Color(Integer.parseInt(bottomHrzColor))); temp.setCanvasWidth(Integer.parseInt(canvasWidth)); temp.setCanvasHeigth(Integer.parseInt(canvasHeigth)); temp.setAuthorHrz(authorHrz); temp.setxPal(Integer.parseInt(xPal)); temp.setyPal(Integer.parseInt(yPal)); temp.sethPalx(Integer.parseInt(hPalx)); temp.sethPaly(Integer.parseInt(hPaly)); temp.setAlcada(Integer.parseInt(alcada)); temp.setColPal(new Color(Integer.parseInt(colPal))); temp.setHorizontal(horizontal.equals("true")); temp.setAureaProp(aureaProp.equals("true")); temp.setSuperX(Integer.parseInt(superX)); temp.setSuperY(Integer.parseInt(superY)); temp.setTextura(textura.equals("true")); temp.setVersion(version); } myResult.close(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return (temp); } */ }
lamaken/visualk
src/java/visualk/gallery/db/DbGallery.java
Java
gpl-3.0
7,208
/** * Java Settlers - An online multiplayer version of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas <thomas@infolab.northwestern.edu> * Portions of this file Copyright (C) 2014,2017,2020 Jeremy D Monin <jeremy@nand.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The maintainer of this program can be reached at jsettlers@nand.net **/ package soc.message; /** * This reply from server means this client currently isn't allowed to connect. * * @author Robert S Thomas */ public class SOCRejectConnection extends SOCMessage { private static final long serialVersionUID = 100L; // last structural change v1.0.0 or earlier /** * Text message */ private String text; /** * Create a RejectConnection message. * * @param message the text message */ public SOCRejectConnection(String message) { messageType = REJECTCONNECTION; text = message; } /** * @return the text message */ public String getText() { return text; } /** * REJECTCONNECTION sep text * * @return the command String */ public String toCmd() { return toCmd(text); } /** * REJECTCONNECTION sep text * * @param tm the text message * @return the command string */ public static String toCmd(String tm) { return REJECTCONNECTION + sep + tm; } /** * Parse the command String into a RejectConnection message * * @param s the String to parse; will be directly used as {@link #getText()} without any parsing * @return a RejectConnection message */ public static SOCRejectConnection parseDataStr(String s) { return new SOCRejectConnection(s); } /** * @return a human readable form of the message */ public String toString() { return "SOCRejectConnection:" + text; } }
jdmonin/JSettlers2
src/main/java/soc/message/SOCRejectConnection.java
Java
gpl-3.0
2,564
package org.codefx.jwos.file; import org.codefx.jwos.analysis.AnalysisPersistence; import org.codefx.jwos.artifact.AnalyzedArtifact; import org.codefx.jwos.artifact.CompletedArtifact; import org.codefx.jwos.artifact.DownloadedArtifact; import org.codefx.jwos.artifact.FailedArtifact; import org.codefx.jwos.artifact.FailedProject; import org.codefx.jwos.artifact.IdentifiesArtifact; import org.codefx.jwos.artifact.IdentifiesProject; import org.codefx.jwos.artifact.ProjectCoordinates; import org.codefx.jwos.artifact.ResolvedArtifact; import org.codefx.jwos.artifact.ResolvedProject; import org.codefx.jwos.file.persistence.PersistentAnalysis; import org.codefx.jwos.file.persistence.PersistentAnalyzedArtifact; import org.codefx.jwos.file.persistence.PersistentCompletedArtifact; import org.codefx.jwos.file.persistence.PersistentDownloadedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedProject; import org.codefx.jwos.file.persistence.PersistentProjectCoordinates; import org.codefx.jwos.file.persistence.PersistentResolvedArtifact; import org.codefx.jwos.file.persistence.PersistentResolvedProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Collection; import java.util.SortedSet; import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.Function; import static java.util.Collections.unmodifiableSet; import static org.codefx.jwos.Util.transformToList; /** * An {@link AnalysisPersistence} that uses YAML to store results. * <p> * This implementation is not thread-safe. */ public class YamlAnalysisPersistence implements AnalysisPersistence { private static final Logger LOGGER = LoggerFactory.getLogger("Persistence"); private static final YamlPersister PERSISTER = new YamlPersister(); private final SortedSet<ProjectCoordinates> projects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<ResolvedProject> resolvedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<FailedProject> resolutionFailedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<DownloadedArtifact> downloadedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> downloadFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<AnalyzedArtifact> analyzedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> analysisFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<ResolvedArtifact> resolvedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> resolutionFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<CompletedArtifact> completedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); // CREATION & PERSISTENCE private YamlAnalysisPersistence() { // private constructor to enforce use of static factory methods } public static YamlAnalysisPersistence empty() { return new YamlAnalysisPersistence(); } public static YamlAnalysisPersistence fromString(String yamlString) { if (yamlString.isEmpty()) return empty(); PersistentAnalysis persistent = PERSISTER.read(yamlString, PersistentAnalysis.class); return from(persistent); } public static YamlAnalysisPersistence fromStream(InputStream yamlStream) { LOGGER.debug("Parsing result file..."); PersistentAnalysis persistent = PERSISTER.read(yamlStream, PersistentAnalysis.class); if (persistent == null) return new YamlAnalysisPersistence(); else return from(persistent); } private static YamlAnalysisPersistence from(PersistentAnalysis persistent) { YamlAnalysisPersistence yaml = new YamlAnalysisPersistence(); addTo(persistent.step_1_projects, PersistentProjectCoordinates::toProject, yaml.projects); addTo(persistent.step_2_resolvedProjects, PersistentResolvedProject::toProject, yaml.resolvedProjects); addTo(persistent.step_2_resolutionFailedProjects, PersistentFailedProject::toProject, yaml.resolutionFailedProjects); addTo(persistent.step_3_downloadedArtifacts, PersistentDownloadedArtifact::toArtifact, yaml.downloadedArtifacts); addTo(persistent.step_3_downloadFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.downloadFailedArtifacts); addTo(persistent.step_4_analyzedArtifacts, PersistentAnalyzedArtifact::toArtifact, yaml.analyzedArtifacts); addTo(persistent.step_4_analysisFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.analysisFailedArtifacts); addTo(persistent.step_5_resolvedArtifacts, PersistentResolvedArtifact::toArtifact, yaml.resolvedArtifacts); addTo(persistent.step_5_resolutionFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.resolutionFailedArtifacts); PersistentCompletedArtifact .toArtifacts(persistent.step_6_completedArtifacts.stream()) .forEach(yaml.completedArtifacts::add); return yaml; } private static <P, T> void addTo(Collection<P> source, Function<P, T> transform, Collection<T> target) { source.stream() .map(transform) .forEach(target::add); } public String toYaml() { PersistentAnalysis persistent = toPersistentAnalysis(); return PERSISTER.write(persistent); } private PersistentAnalysis toPersistentAnalysis() { PersistentAnalysis persistent = new PersistentAnalysis(); persistent.step_1_projects = transformToList(projects, PersistentProjectCoordinates::from); persistent.step_2_resolvedProjects = transformToList(resolvedProjects, PersistentResolvedProject::from); persistent.step_2_resolutionFailedProjects = transformToList(resolutionFailedProjects, PersistentFailedProject::from); persistent.step_3_downloadedArtifacts = transformToList(downloadedArtifacts, PersistentDownloadedArtifact::from); persistent.step_3_downloadFailedArtifacts = transformToList(downloadFailedArtifacts, PersistentFailedArtifact::from); persistent.step_4_analyzedArtifacts = transformToList(analyzedArtifacts, PersistentAnalyzedArtifact::from); persistent.step_4_analysisFailedArtifacts = transformToList(analysisFailedArtifacts, PersistentFailedArtifact::from); persistent.step_5_resolvedArtifacts = transformToList(resolvedArtifacts, PersistentResolvedArtifact::from); persistent.step_5_resolutionFailedArtifacts = transformToList(resolutionFailedArtifacts, PersistentFailedArtifact::from); persistent.step_6_completedArtifacts = transformToList(completedArtifacts, PersistentCompletedArtifact::from); return persistent; } // IMPLEMENTATION OF 'AnalysisPersistence' @Override public Collection<ProjectCoordinates> projectsUnmodifiable() { return unmodifiableSet(projects); } @Override public Collection<ResolvedProject> resolvedProjectsUnmodifiable() { return unmodifiableSet(resolvedProjects); } @Override public Collection<FailedProject> projectResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedProjects); } @Override public Collection<DownloadedArtifact> downloadedArtifactsUnmodifiable() { return unmodifiableSet(downloadedArtifacts); } @Override public Collection<FailedArtifact> artifactDownloadErrorsUnmodifiable() { return unmodifiableSet(downloadFailedArtifacts); } @Override public Collection<AnalyzedArtifact> analyzedArtifactsUnmodifiable() { return unmodifiableSet(analyzedArtifacts); } @Override public Collection<FailedArtifact> artifactAnalysisErrorsUnmodifiable() { return unmodifiableSet(analysisFailedArtifacts); } @Override public Collection<ResolvedArtifact> resolvedArtifactsUnmodifiable() { return unmodifiableSet(resolvedArtifacts); } @Override public Collection<FailedArtifact> artifactResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedArtifacts); } @Override public void addProject(ProjectCoordinates project) { projects.add(project); } @Override public void addResolvedProject(ResolvedProject project) { resolvedProjects.add(project); } @Override public void addProjectResolutionError(FailedProject project) { resolutionFailedProjects.add(project); } @Override public void addDownloadedArtifact(DownloadedArtifact artifact) { downloadedArtifacts.add(artifact); } @Override public void addDownloadError(FailedArtifact artifact) { downloadFailedArtifacts.add(artifact); } @Override public void addAnalyzedArtifact(AnalyzedArtifact artifact) { analyzedArtifacts.add(artifact); } @Override public void addAnalysisError(FailedArtifact artifact) { analysisFailedArtifacts.add(artifact); } @Override public void addResolvedArtifact(ResolvedArtifact artifact) { resolvedArtifacts.add(artifact); } @Override public void addArtifactResolutionError(FailedArtifact artifact) { resolutionFailedArtifacts.add(artifact); } @Override public void addResult(CompletedArtifact artifact) { completedArtifacts.add(artifact); } }
CodeFX-org/jdeps-wall-of-shame
src/main/java/org/codefx/jwos/file/YamlAnalysisPersistence.java
Java
gpl-3.0
9,278
package Calibradores; import java.io.File; import Metricas.MultiescalaConBorde; import Modelo.UrbanizandoFrenos; public class TanteadorTopilejo extends Tanteador { UrbanizandoFrenos CA; public TanteadorTopilejo() { // int[] unConjuntoDeParametros = {1, 1, 1, 333, 333, 333, 1, 1, 444, 400, 400, 555}; // puntoDeTanteo = new PuntoDeBusqueda(unConjuntoDeParametros); // puntoDelRecuerdo = new PuntoDeBusqueda(unConjuntoDeParametros); CA = new UrbanizandoFrenos(72, 56, 11, 4); CA.setInitialGrid(new File ("Topilejo/topi1995.txt")); CA.setBosque(new File ("Topilejo/bosqueb.txt")); CA.setDistVias(new File ("Topilejo/distancia1.txt")); CA.setPendiente(new File ("Topilejo/pendiente.txt")); CA.setGoalGrid(new File ("Topilejo/topi1999.txt")); infoADN = CA.infoADN; MultiescalaConBorde metrica = new MultiescalaConBorde(CA.gridMeta, CA.numeroDeCeldasX, CA.numeroDeCeldasY ); metrica.normalizateConEste(new File ("Topilejo/topi1995.txt")); CA.setMetric(metrica); CA.setIteraciones(4); puntoDeTanteo = new PuntoDeBusqueda(infoADN.size); puntoDelRecuerdo = new PuntoDeBusqueda(infoADN.size); vuelo = new PuntoDeBusqueda(infoADN.size); bajando = new Ventana("Guardar Acercamiento", "Caminante Siego Estocastico"); bajando.setVisible(true); bajando.graf.setLocation(850, 715); bajando.setQueTantoLocation(865, 650); //solo para correr los 3 calibradores al mismo tiempo // ventana = new Ventana("Guardar Todo", "Todos"); // ventana.setVisible(true); pintaGrid1 = new PintaGrid(new File("Topilejo/topi1999.txt"), "Grrid Meta", 4); pintaGrid2 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Mejor Aproximacion", 5); pintaGrid3 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Grid de Salida", 4); pintaGrid2.setLocation(865, 370); } public double mide(int[] parametros) { return CA.mide(parametros, 100); } public static void main(String[] args) { TanteadorTopilejo topo = new TanteadorTopilejo(); topo.busca(); } @Override public int[][] unOutputPara(int[] parametros) { // TODO Auto-generated method stub return CA.unOutputPara(parametros); } }
sostenibilidad-unam/crecimiento-urbano
Calibradores/TanteadorTopilejo.java
Java
gpl-3.0
2,250
/* * Copyright (C) 2017 phantombot.tv * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.mast3rplan.phantombot.event.ytplayer; import me.mast3rplan.phantombot.twitchwsirc.Channel; import me.mast3rplan.phantombot.ytplayer.YTPlayerState; public class YTPlayerStateEvent extends YTPlayerEvent { private final YTPlayerState state; public YTPlayerStateEvent(YTPlayerState state) { this.state = state; } public YTPlayerStateEvent(YTPlayerState state, Channel channel) { super(channel); this.state = state; } public YTPlayerState getState() { return state; } public int getStateId() { return state.i; } }
MrAdder/PhantomBot
source/me/mast3rplan/phantombot/event/ytplayer/YTPlayerStateEvent.java
Java
gpl-3.0
1,295
package com.plasmablazer.tutorialmod.proxy; public interface IProxy { }
PlasmaBlazer/TutorialMod
src/main/java/com/plasmablazer/tutorialmod/proxy/IProxy.java
Java
gpl-3.0
74
package org.thoughtcrime.securesms.jobs; import androidx.annotation.NonNull; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.Data; import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil; import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.recipients.RecipientUtil; import org.thoughtcrime.securesms.util.Base64; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.InvalidKeyException; import org.whispersystems.signalservice.api.SignalServiceMessageSender; import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage; import org.whispersystems.signalservice.api.push.SignalServiceAddress; import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException; import java.io.IOException; import java.util.concurrent.TimeUnit; public class MultiDeviceVerifiedUpdateJob extends BaseJob { public static final String KEY = "MultiDeviceVerifiedUpdateJob"; private static final String TAG = MultiDeviceVerifiedUpdateJob.class.getSimpleName(); private static final String KEY_DESTINATION = "destination"; private static final String KEY_IDENTITY_KEY = "identity_key"; private static final String KEY_VERIFIED_STATUS = "verified_status"; private static final String KEY_TIMESTAMP = "timestamp"; private RecipientId destination; private byte[] identityKey; private VerifiedStatus verifiedStatus; private long timestamp; public MultiDeviceVerifiedUpdateJob(@NonNull RecipientId destination, IdentityKey identityKey, VerifiedStatus verifiedStatus) { this(new Job.Parameters.Builder() .addConstraint(NetworkConstraint.KEY) .setQueue("__MULTI_DEVICE_VERIFIED_UPDATE__") .setLifespan(TimeUnit.DAYS.toMillis(1)) .setMaxAttempts(Parameters.UNLIMITED) .build(), destination, identityKey.serialize(), verifiedStatus, System.currentTimeMillis()); } private MultiDeviceVerifiedUpdateJob(@NonNull Job.Parameters parameters, @NonNull RecipientId destination, @NonNull byte[] identityKey, @NonNull VerifiedStatus verifiedStatus, long timestamp) { super(parameters); this.destination = destination; this.identityKey = identityKey; this.verifiedStatus = verifiedStatus; this.timestamp = timestamp; } @Override public @NonNull Data serialize() { return new Data.Builder().putString(KEY_DESTINATION, destination.serialize()) .putString(KEY_IDENTITY_KEY, Base64.encodeBytes(identityKey)) .putInt(KEY_VERIFIED_STATUS, verifiedStatus.toInt()) .putLong(KEY_TIMESTAMP, timestamp) .build(); } @Override public @NonNull String getFactoryKey() { return KEY; } @Override public void onRun() throws IOException, UntrustedIdentityException { try { if (!TextSecurePreferences.isMultiDevice(context)) { Log.i(TAG, "Not multi device..."); return; } if (destination == null) { Log.w(TAG, "No destination..."); return; } SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender(); Recipient recipient = Recipient.resolved(destination); VerifiedMessage.VerifiedState verifiedState = getVerifiedState(verifiedStatus); SignalServiceAddress verifiedAddress = RecipientUtil.toSignalServiceAddress(context, recipient); VerifiedMessage verifiedMessage = new VerifiedMessage(verifiedAddress, new IdentityKey(identityKey, 0), verifiedState, timestamp); messageSender.sendMessage(SignalServiceSyncMessage.forVerified(verifiedMessage), UnidentifiedAccessUtil.getAccessFor(context, recipient)); } catch (InvalidKeyException e) { throw new IOException(e); } } private VerifiedMessage.VerifiedState getVerifiedState(VerifiedStatus status) { VerifiedMessage.VerifiedState verifiedState; switch (status) { case DEFAULT: verifiedState = VerifiedMessage.VerifiedState.DEFAULT; break; case VERIFIED: verifiedState = VerifiedMessage.VerifiedState.VERIFIED; break; case UNVERIFIED: verifiedState = VerifiedMessage.VerifiedState.UNVERIFIED; break; default: throw new AssertionError("Unknown status: " + verifiedStatus); } return verifiedState; } @Override public boolean onShouldRetry(@NonNull Exception exception) { return exception instanceof PushNetworkException; } @Override public void onFailure() { } public static final class Factory implements Job.Factory<MultiDeviceVerifiedUpdateJob> { @Override public @NonNull MultiDeviceVerifiedUpdateJob create(@NonNull Parameters parameters, @NonNull Data data) { try { RecipientId destination = RecipientId.from(data.getString(KEY_DESTINATION)); VerifiedStatus verifiedStatus = VerifiedStatus.forState(data.getInt(KEY_VERIFIED_STATUS)); long timestamp = data.getLong(KEY_TIMESTAMP); byte[] identityKey = Base64.decode(data.getString(KEY_IDENTITY_KEY)); return new MultiDeviceVerifiedUpdateJob(parameters, destination, identityKey, verifiedStatus, timestamp); } catch (IOException e) { throw new AssertionError(e); } } } }
WhisperSystems/TextSecure
app/src/main/java/org/thoughtcrime/securesms/jobs/MultiDeviceVerifiedUpdateJob.java
Java
gpl-3.0
6,361
package com.silvermatch.advancedMod.block; import com.silvermatch.advancedMod.init.ModBlocks; import com.silvermatch.advancedMod.reference.Reference; import com.silvermatch.advancedMod.utility.Names; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.world.World; public class BlockFrenchFlag extends BlockAdvancedMod{ public BlockFrenchFlag() { setBlockName(Names.Blocks.FRENCH_FLAG); setBlockTextureName(Reference.MOD_ID_LOWER + ":" + Names.Blocks.FRENCH_FLAG); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) { if (world.isAirBlock(x, y+1, z)){ world.setBlock(x, y+1, z, ModBlocks.frenchFlag); } return true; } }
SilverMatch/TutoMineMaarten
src/main/java/com/silvermatch/advancedMod/block/BlockFrenchFlag.java
Java
gpl-3.0
901
package pg.autyzm.friendly_plans.manager_app.view.task_create; import android.app.FragmentTransaction; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import database.repository.StepTemplateRepository; import javax.inject.Inject; import database.entities.Asset; import database.entities.TaskTemplate; import database.repository.TaskTemplateRepository; import pg.autyzm.friendly_plans.ActivityProperties; import pg.autyzm.friendly_plans.App; import pg.autyzm.friendly_plans.AppComponent; import pg.autyzm.friendly_plans.R; import pg.autyzm.friendly_plans.asset.AssetType; import pg.autyzm.friendly_plans.databinding.FragmentTaskCreateBinding; import pg.autyzm.friendly_plans.manager_app.validation.TaskValidation; import pg.autyzm.friendly_plans.manager_app.validation.Utils; import pg.autyzm.friendly_plans.manager_app.validation.ValidationResult; import pg.autyzm.friendly_plans.manager_app.view.components.SoundComponent; import pg.autyzm.friendly_plans.manager_app.view.main_screen.MainActivity; import pg.autyzm.friendly_plans.manager_app.view.step_list.StepListFragment; import pg.autyzm.friendly_plans.manager_app.view.task_type_enum.TaskType; import pg.autyzm.friendly_plans.manager_app.view.view_fragment.CreateFragment; public class TaskCreateFragment extends CreateFragment implements TaskCreateActivityEvents { private static final String REGEX_TRIM_NAME = "_([\\d]*)(?=\\.)"; @Inject TaskValidation taskValidation; @Inject TaskTemplateRepository taskTemplateRepository; @Inject StepTemplateRepository stepTemplateRepository; private TextView labelTaskName; private EditText taskName; private EditText taskDurationTime; private Long taskId; private Integer typeId; private Button steps; private RadioGroup types; private TaskType taskType = TaskType.TASK; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FragmentTaskCreateBinding binding = DataBindingUtil.inflate( inflater, R.layout.fragment_task_create, container, false); binding.setEvents(this); View view = binding.getRoot(); ImageButton playSoundIcon = (ImageButton) view.findViewById(R.id.id_btn_play_sound); AppComponent appComponent = ((App) getActivity().getApplication()).getAppComponent(); soundComponent = SoundComponent.getSoundComponent( soundId, playSoundIcon, getActivity().getApplicationContext(), appComponent); appComponent.inject(this); binding.setSoundComponent(soundComponent); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { registerViews(view); view.post(new Runnable() { // Set assets only when the layout is completely built @Override public void run() { Bundle arguments = getArguments(); if (arguments != null) { Long taskId = (Long) arguments.get(ActivityProperties.TASK_ID); if (taskId != null) { initTaskForm(taskId); } } } }); } private void registerViews(View view) { labelTaskName = (TextView) view.findViewById(R.id.id_tv_task_name_label); Utils.markFieldMandatory(labelTaskName); taskName = (EditText) view.findViewById(R.id.id_et_task_name); pictureFileName = (EditText) view.findViewById(R.id.id_et_task_picture); soundFileName = (EditText) view.findViewById(R.id.id_et_task_sound); taskDurationTime = (EditText) view.findViewById(R.id.id_et_task_duration_time); picturePreview = (ImageView) view.findViewById(R.id.iv_picture_preview); clearSound = (ImageButton) view.findViewById(R.id.id_ib_clear_sound_btn); clearPicture = (ImageButton) view.findViewById(R.id.id_ib_clear_img_btn); steps = (Button) view.findViewById(R.id.id_btn_steps); types = (RadioGroup) view.findViewById(R.id.id_rg_types); RadioButton typeTask = (RadioButton) view.findViewById(R.id.id_rb_type_task); typeTask.setChecked(true); taskType = TaskType.TASK; } private Long saveOrUpdate() { soundComponent.stopActions(); try { if (taskId != null) { if (validateName(taskId, taskName) && validateDuration(taskDurationTime)) { typeId = taskType.getId(); Integer duration = getDuration(); clearSteps(typeId, taskId); taskTemplateRepository.update(taskId, taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } else { if (validateName(taskName) && validateDuration(taskDurationTime)) { Integer duration = getDuration(); typeId = taskType.getId(); long taskId = taskTemplateRepository.create(taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } } catch (RuntimeException exception) { Log.e("Task Create View", "Error saving task", exception); showToastMessage(R.string.save_task_error_message); } return null; } private void clearSteps(Integer typeId, Long taskId) { if (typeId != 1) { stepTemplateRepository.deleteAllStepsForTask(taskId); } } private boolean validateName(Long taskId, EditText taskName) { ValidationResult validationResult = taskValidation .isUpdateNameValid(taskId, taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateName(EditText taskName) { ValidationResult validationResult = taskValidation .isNewNameValid(taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateDuration(EditText duration) { ValidationResult validationResult = taskValidation .isDurationValid(duration.getText().toString()); return handleInvalidResult(duration, validationResult); } private void initTaskForm(long taskId) { this.taskId = taskId; TaskTemplate task = taskTemplateRepository.get(taskId); taskName.setText(task.getName()); if (task.getDurationTime() != null) { taskDurationTime.setText(String.valueOf(task.getDurationTime())); } Asset picture = task.getPicture(); Asset sound = task.getSound(); if (picture != null) { setAssetValue(AssetType.PICTURE, picture.getFilename(), picture.getId()); } if (sound != null) { setAssetValue(AssetType.SOUND, sound.getFilename(), sound.getId()); } typeId = task.getTypeId(); ((RadioButton) types.getChildAt(typeId - 1)).setChecked(true); setVisibilityStepButton(Integer.valueOf(task.getTypeId().toString())); } private void setVisibilityStepButton(int typeIdValue) { if (typeIdValue == 1) { steps.setVisibility(View.VISIBLE); } else { steps.setVisibility(View.INVISIBLE); } } private void showStepsList(final long taskId) { StepListFragment fragment = new StepListFragment(); Bundle args = new Bundle(); args.putLong(ActivityProperties.TASK_ID, taskId); fragment.setArguments(args); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.replace(R.id.task_container, fragment); transaction.addToBackStack(null); transaction.commit(); } private void showMainMenu() { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } @Override protected void setAssetValue(AssetType assetType, String assetName, Long assetId) { String assetNameTrimmed = assetName.replaceAll(REGEX_TRIM_NAME, ""); if (assetType.equals(AssetType.PICTURE)) { pictureFileName.setText(assetNameTrimmed); clearPicture.setVisibility(View.VISIBLE); pictureId = assetId; showPreview(pictureId, picturePreview); } else { soundFileName.setText(assetNameTrimmed); clearSound.setVisibility(View.VISIBLE); soundId = assetId; soundComponent.setSoundId(soundId); } } private Integer getDuration() { if (!taskDurationTime.getText().toString().isEmpty() && !taskDurationTime.getText().toString().equals("0")) { return Integer.valueOf(taskDurationTime.getText().toString()); } return null; } @Override public void eventListStep(View view) { taskId = saveOrUpdate(); if (taskId != null) { showStepsList(taskId); } } @Override public void eventSelectPicture(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.PICTURE); } @Override public void eventSelectSound(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.SOUND); } @Override public void eventClearPicture(View view) { clearPicture(); } @Override public void eventClearSound(View view) { clearSound(); } @Override public void eventClickPreviewPicture(View view) { showPicture(pictureId); } @Override public void eventChangeButtonStepsVisibility(View view, int id) { if (id == R.id.id_rb_type_task) { steps.setVisibility(View.VISIBLE); taskType = TaskType.TASK; } else { steps.setVisibility(View.INVISIBLE); if (id == R.id.id_rb_type_interaction) { taskType = TaskType.INTERACTION; } else { taskType = TaskType.PRIZE; } } } @Override public void eventSaveAndFinish(View view) { Long taskId = saveOrUpdate(); if (taskId != null) { showMainMenu(); } } }
autyzm-pg/friendly-plans
Friendly-plans/app/src/main/java/pg/autyzm/friendly_plans/manager_app/view/task_create/TaskCreateFragment.java
Java
gpl-3.0
11,189
/** Copyright 2010 Christian Kästner This file is part of CIDE. CIDE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. CIDE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CIDE. If not, see <http://www.gnu.org/licenses/>. See http://www.fosd.de/cide/ for further information. */ package de.ovgu.cide.export.virtual.internal; import java.util.Set; import org.eclipse.jdt.core.dom.CompilationUnit; import de.ovgu.cide.export.CopiedNaiveASTFlattener; import de.ovgu.cide.export.useroptions.IUserOptionProvider; import de.ovgu.cide.features.IFeature; import de.ovgu.cide.features.source.ColoredSourceFile; /** * how to print annotations? note: we assume ifdef semantics, i.e. annotations * may be nested, but always close in the reverse order * * * @author ckaestne * */ public interface IPPExportOptions extends IUserOptionProvider { /** * should the start and end instructions be printed in a new line? (i.e. * should a line break be enforced before?) * * the instruction is responsible for the linebreak at the end itself * * @return */ boolean inNewLine(); /** * get the code statement(s) to begin an annotation block * * @param f * set of features annotated for the current element * @return */ String getStartInstruction(Set<IFeature> f); /** * get the code statement(s) to end an annotation block * * @param f * set of features annotated for the current element * @return */ String getEndInstruction(Set<IFeature> f); CopiedNaiveASTFlattener getPrettyPrinter(ColoredSourceFile sourceFile); /** * allows the developer to change the AST before printing it. can be used * for some refactorings. returns the modified AST * * @param root * @param sourceFile * @return */ CompilationUnit refactorAST(CompilationUnit root, ColoredSourceFile sourceFile); }
ckaestne/CIDE
CIDE_Export_Virtual/src/de/ovgu/cide/export/virtual/internal/IPPExportOptions.java
Java
gpl-3.0
2,375
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.14 at 05:14:09 PM CDT // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.opengis.net/kml/2.2", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package hortonworks.hdp.refapp.trucking.simulator.impl.domain.transport.route.jaxb;
abeym/incubator
Trials/hdp/reference-apps/iot-trucking-app/trucking-data-simulator/src/main/java/hortonworks/hdp/refapp/trucking/simulator/impl/domain/transport/route/jaxb/package-info.java
Java
gpl-3.0
584
package com.softech.ls360.lms.api.proxy.service; import com.softech.vu360.lms.webservice.message.lmsapi.serviceoperations.user.AddUserResponse; import com.softech.vu360.lms.webservice.message.lmsapi.serviceoperations.user.UpdateUserResponse; import com.softech.vu360.lms.webservice.message.lmsapi.types.user.UpdateableUser; import com.softech.vu360.lms.webservice.message.lmsapi.types.user.User; public interface LmsApiUserService { AddUserResponse createUser(User user, Long customerId, String customerCode, String apiKey) throws Exception; UpdateUserResponse updateUser(UpdateableUser updateableUser, Long customerId, String customerCode, String apiKey) throws Exception; }
haider78github/apiProxy
LmsApiProxy/src/main/java/com/softech/ls360/lms/api/proxy/service/LmsApiUserService.java
Java
gpl-3.0
685
package cz.cuni.lf1.lge.ThunderSTORM.estimators; import cz.cuni.lf1.lge.ThunderSTORM.detectors.CentroidOfConnectedComponentsDetector; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.EllipticGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.EllipticGaussianWAnglePSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.Molecule; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.SymmetricGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.filters.CompoundWaveletFilter; import cz.cuni.lf1.lge.ThunderSTORM.FormulaParser.FormulaParserException; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.IntegratedSymmetricGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.PSFModel.Params; import cz.cuni.lf1.lge.ThunderSTORM.util.CSV; import static cz.cuni.lf1.lge.ThunderSTORM.util.MathProxy.sqr; import cz.cuni.lf1.lge.ThunderSTORM.util.Point; import ij.IJ; import ij.process.FloatProcessor; import java.util.List; import java.util.Vector; import org.junit.Test; import static org.junit.Assert.*; public class EstimatorsTest { @Test public void testRadialSymmetry() { testEstimator(new MultipleLocationsImageFitting(5, new RadialSymmetryFitter())); } @Test public void testLSQSym() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new SymmetricGaussianPSF(1), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new SymmetricGaussianPSF(1), true, Params.BACKGROUND))); } @Test public void testLSQIntSym() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new IntegratedSymmetricGaussianPSF(1), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new IntegratedSymmetricGaussianPSF(1), true, Params.BACKGROUND))); } @Test public void testMLEIntSym() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new IntegratedSymmetricGaussianPSF(1), Params.BACKGROUND))); } @Test public void testMLESym() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new SymmetricGaussianPSF(1), Params.BACKGROUND))); } @Test public void testLSQEllipticAngle() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianWAnglePSF(1, 0), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianWAnglePSF(1, 0), true, Params.BACKGROUND))); } @Test public void testMLEEllipticAngle() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new EllipticGaussianWAnglePSF(1, 0), Params.BACKGROUND))); } @Test public void testLSQElliptic() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianPSF(1, 45), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianPSF(1, 45), true, Params.BACKGROUND))); } @Test public void testMLEElliptic() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new EllipticGaussianPSF(1, 45), Params.BACKGROUND))); } private void testEstimator(IEstimator estimator) throws FormulaParserException { String basePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); FloatProcessor image = (FloatProcessor) IJ.openImage(basePath + "tubulins1_00020.tif").getProcessor().convertToFloat(); FloatProcessor filtered = (new CompoundWaveletFilter()).filterImage(image); Vector<Point> detections = (new CentroidOfConnectedComponentsDetector("16", true)).detectMoleculeCandidates(filtered); List<Molecule> fits = estimator.estimateParameters(image, detections); for(Molecule fit : fits) { convertXYToNanoMeters(fit, 150.0); } Vector<Molecule> ground_truth = null; try { ground_truth = CSV.csv2psf(basePath + "tubulins1_00020.csv", 1, 2); } catch(Exception ex) { fail(ex.getMessage()); } Vector<Pair> pairs = pairFitsAndDetections2GroundTruths(detections, fits, ground_truth); for(Pair pair : pairs) { assertFalse("Result from the estimator should be better than guess from the detector.", dist2(pair.fit, pair.ground_truth) > dist2(pair.detection, pair.ground_truth)); } // // Note: better test would be to compare these results to the results from Matlab...but I don't have them at the moment // } static void convertXYToNanoMeters(Molecule fit, double px2nm) { fit.setX(fit.getX() * px2nm); fit.setY(fit.getY() * px2nm); } static class Pair { Point detection; Molecule fit; Molecule ground_truth; public Pair(Point detection, Molecule fit, Molecule ground_truth) { this.detection = detection; this.fit = fit; this.ground_truth = ground_truth; } } static Vector<Pair> pairFitsAndDetections2GroundTruths(Vector<Point> detections, List<Molecule> fits, Vector<Molecule> ground_truth) { assertNotNull(fits); assertNotNull(detections); assertNotNull(ground_truth); assertFalse(fits.isEmpty()); assertFalse(detections.isEmpty()); assertFalse(ground_truth.isEmpty()); assertEquals("Number of detections should be the same as number of fits!", detections.size(), fits.size()); Vector<Pair> pairs = new Vector<Pair>(); int best_fit; double best_dist2, dist2; for(int i = 0, im = fits.size(); i < im; i++) { best_fit = 0; best_dist2 = dist2(fits.get(i), ground_truth.elementAt(best_fit)); for(int j = 1, jm = ground_truth.size(); j < jm; j++) { dist2 = dist2(fits.get(i), ground_truth.elementAt(j)); if(dist2 < best_dist2) { best_dist2 = dist2; best_fit = j; } } pairs.add(new Pair(detections.elementAt(i), fits.get(i), ground_truth.elementAt(best_fit))); } return pairs; } static double dist2(Point detection, Molecule ground_truth) { return sqr(detection.x.doubleValue() - ground_truth.getX()) + sqr(detection.y.doubleValue() - ground_truth.getY()); } static double dist2(Molecule fit, Molecule ground_truth) { return sqr(fit.getX() - ground_truth.getY()) + sqr(fit.getX() - ground_truth.getY()); } }
imunro/thunderstorm
src/test/java/cz/cuni/lf1/lge/ThunderSTORM/estimators/EstimatorsTest.java
Java
gpl-3.0
6,620
package org.renjin.invoke.codegen; import com.google.common.collect.Lists; import com.sun.codemodel.*; import org.apache.commons.math.complex.Complex; import org.renjin.invoke.annotations.PreserveAttributeStyle; import org.renjin.invoke.model.JvmMethod; import org.renjin.invoke.model.PrimitiveModel; import org.renjin.primitives.vector.DeferredComputation; import org.renjin.sexp.*; import java.util.List; import static com.sun.codemodel.JExpr.lit; public class DeferredVectorBuilder { public static final int LENGTH_THRESHOLD = 100; private final JExpression contextArgument; private JCodeModel codeModel; private PrimitiveModel primitive; private JvmMethod overload; private int arity; private JDefinedClass vectorClass; private VectorType type; private List<DeferredArgument> arguments = Lists.newArrayList(); private JFieldVar lengthField; public DeferredVectorBuilder(JCodeModel codeModel, JExpression contextArgument, PrimitiveModel primitive, JvmMethod overload) { this.codeModel = codeModel; this.primitive = primitive; this.overload = overload; this.arity = overload.getPositionalFormals().size(); this.contextArgument = contextArgument; if(overload.getReturnType().equals(double.class)) { type = VectorType.DOUBLE; } else if(overload.getReturnType().equals(boolean.class)) { type = VectorType.LOGICAL; } else if(overload.getReturnType().equals(Logical.class)) { type = VectorType.LOGICAL; } else if(overload.getReturnType().equals(int.class)) { type = VectorType.INTEGER; } else if(overload.getReturnType().equals(Complex.class)) { type = VectorType.COMPLEX; } else if(overload.getReturnType().equals(byte.class)) { type = VectorType.RAW; } else { throw new UnsupportedOperationException(overload.getReturnType().toString()); } } public void buildClass() { try { vectorClass = codeModel._class( WrapperGenerator2.toFullJavaName(primitive.getName()) + "$deferred_" + typeSuffix() ); } catch (JClassAlreadyExistsException e) { throw new RuntimeException(e); } vectorClass._extends(type.baseClass); vectorClass._implements(DeferredComputation.class); for(int i=0;i!=arity;++i) { arguments.add(new DeferredArgument(overload.getPositionalFormals().get(i), i)); } this.lengthField = vectorClass.field(JMod.PRIVATE, codeModel._ref(int.class), "length"); writeConstructor(); implementAccessor(); implementLength(); implementAttributeSetter(); implementGetOperands(); implementGetComputationName(); implementStaticApply(); implementIsConstantAccess(); implementGetComputationDepth(); if(overload.isPassNA() && overload.getReturnType().equals(boolean.class)) { overrideIsNaWithConstantValue(); } } private void implementIsConstantAccess() { JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isConstantAccessTime"); JExpression condition = null; for(DeferredArgument arg : arguments) { JExpression operandIsConstant = arg.valueField.invoke("isConstantAccessTime"); if(condition == null) { condition = operandIsConstant; } else { condition = condition.cand(operandIsConstant); } } method.body()._return(condition); } private void implementGetComputationDepth() { JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "getComputationDepth"); JVar depth = method.body().decl(codeModel._ref(int.class), "depth", arguments.get(0).valueField.invoke("getComputationDepth")); for(int i=1;i<arguments.size();++i) { method.body().assign(depth, codeModel.ref(Math.class).staticInvoke("max") .arg(depth) .arg(arguments.get(1).valueField.invoke("getComputationDepth"))); } method.body()._return(depth.plus(JExpr.lit(1))); } private void implementGetOperands() { JMethod method = vectorClass.method(JMod.PUBLIC, Vector[].class, "getOperands"); JArray array = JExpr.newArray(codeModel.ref(Vector.class)); for(DeferredArgument arg : arguments) { array.add(arg.valueField); } method.body()._return(array); } private void implementGetComputationName() { JMethod method = vectorClass.method(JMod.PUBLIC, String.class, "getComputationName"); method.body()._return(lit(primitive.getName())); } private String typeSuffix() { StringBuilder suffix = new StringBuilder(); for(JvmMethod.Argument formal : overload.getPositionalFormals()) { suffix.append(abbrev(formal.getClazz())); } return suffix.toString(); } private String abbrev(Class clazz) { if(clazz.equals(double.class)) { return "d"; } else if(clazz.equals(boolean.class)) { return "b"; } else if(clazz.equals(String.class)) { return "s"; } else if(clazz.equals(int.class)) { return "i"; } else if(clazz.equals(Complex.class)) { return "z"; } else if(clazz.equals(byte.class)) { return "r"; } else { throw new UnsupportedOperationException(clazz.toString()); } } public void maybeReturn(JBlock parent, JExpression cycleCount, List<JExpression> arguments) { JExpression condition = cycleCount.gt(lit(LENGTH_THRESHOLD)); for(JExpression arg : arguments) { condition = condition.cor(arg._instanceof(codeModel.ref(DeferredComputation.class))); } JBlock ifBig = parent._if(condition)._then(); JExpression attributes = copyAttributes(arguments); JInvocation newInvocation = JExpr._new(vectorClass); for(JExpression arg : arguments) { newInvocation.arg(arg); } newInvocation.arg(attributes); ifBig._return(contextArgument.invoke("simplify").arg(newInvocation)); } private JExpression copyAttributes(List<JExpression> arguments) { if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.NONE) { return codeModel.ref(AttributeMap.class).staticRef("EMPTY"); } else { if(arity == 1) { return copyAttributes(arguments.get(0)); } else if(arity == 2) { return copyAttributes(arguments.get(0), arguments.get(1)); } else { throw new UnsupportedOperationException("arity = " + arity); } } } private JExpression copyAttributes(JExpression arg0, JExpression arg1) { String combineMethod; switch(overload.getPreserveAttributesStyle()) { case ALL: combineMethod = "combineAttributes"; break; case SPECIAL: combineMethod = "combineStructuralAttributes"; break; default: throw new UnsupportedOperationException(); } return codeModel.ref(AttributeMap.class).staticInvoke(combineMethod) .arg(arg0) .arg(arg1); } private JExpression copyAttributes(JExpression arg) { if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.ALL) { return arg.invoke("getAttributes"); } else if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.SPECIAL) { return arg.invoke("getAttributes").invoke("copyStructural"); } else { throw new UnsupportedOperationException(); } } private void writeConstructor() { // public DoubleBinaryFnVector(Vector arg0, Vector arg1, AttributeMap attributes) { // super(attributes); // this.x = x; // this.y = y; // this.fn = fn; // this.xLength = x.length(); // this.yLength = y.length(); // this.length = Math.max(xLength, yLength); // } JMethod ctor = vectorClass.constructor(JMod.PUBLIC); List<JVar> argParams = Lists.newArrayList(); for(int i=0;i!=arity;++i) { argParams.add(ctor.param(Vector.class, "arg" + i)); } ctor.param(AttributeMap.class, "attributes"); ctor.body().directStatement("super(attributes);"); ctor.body().assign(lengthField, lit(0)); for(int i=0;i!=arity;++i) { ctor.body().assign(JExpr._this().ref(arg(i).valueField), argParams.get(i)); ctor.body().assign(arg(i).lengthField, arg(i).valueField.invoke("length")); } if(arity == 1) { ctor.body().assign(lengthField, arg(0).lengthField); } else if(arity == 2) { ctor.body().assign(lengthField, codeModel.ref(Math.class).staticInvoke("max") .arg(arg(0).lengthField) .arg(arg(1).lengthField)); } } private DeferredArgument arg(int i) { return arguments.get(i); } private void implementLength() { JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "length"); method.body()._return(lengthField); } private void implementStaticApply() { JMethod method = vectorClass.method(JMod.PUBLIC | JMod.STATIC, type.accessorType, "compute"); List<JExpression> params = Lists.newArrayList(); for(DeferredArgument argument : arguments) { JVar param = method.param(argument.accessorType(), "p" + argument.index); params.add(argument.convert(param)); } returnValue(method.body(), buildInvocation(params)); } private void implementAccessor() { JMethod method = vectorClass.method(JMod.PUBLIC, type.accessorType, type.accessorName); JVar index = method.param(int.class, "index"); // extract the arguments to the function from the given vectors List<JExpression> argValues = Lists.newArrayList(); for(DeferredArgument arg : arguments) { JExpression elementIndex; if(arity == 1) { elementIndex = index; } else { // avoid using modulus if we can JVar indexVar = method.body().decl(codeModel._ref(int.class), "i" + arg.index); JConditional ifLessThan = method.body()._if(index.lt(arg.lengthField)); ifLessThan._then().assign(indexVar, index); ifLessThan._else().assign(indexVar, index.mod(arg.lengthField)); elementIndex = indexVar; } JVar argValue = method.body().decl(arg.accessorType(), "arg" + arg.index + "_i", arg.invokeAccessor(elementIndex)); argValues.add(arg.convert(argValue)); if(!overload.isPassNA() && arg.type != ArgumentType.BYTE) { method.body()._if(arg.isNA(argValue))._then()._return(na()); } } // invoke the underlying function returnValue(method.body(), buildInvocation(argValues)); } private JInvocation buildInvocation(List<JExpression> argValues) { JInvocation invocation = codeModel .ref(overload.getDeclaringClass()) .staticInvoke(overload.getName()); for(JExpression argValue : argValues) { invocation.arg(argValue); } return invocation; } private JExpression na() { switch (type) { case DOUBLE: return codeModel.ref(DoubleVector.class).staticRef("NA"); case LOGICAL: case INTEGER: return codeModel.ref(IntVector.class).staticRef("NA"); case COMPLEX: return codeModel.ref(ComplexArrayVector.class).staticRef("NA"); } throw new UnsupportedOperationException(type.toString()); } private void returnValue(JBlock parent, JExpression retVal) { if(overload.getReturnType().equals(boolean.class)) { JConditional ifTrue = parent._if(retVal); ifTrue._then()._return(lit(1)); ifTrue._else()._return(lit(0)); } else if(overload.getReturnType().equals(Logical.class)) { parent._return(retVal.invoke("getInternalValue")); } else { parent._return(retVal); } } public void overrideIsNaWithConstantValue() { JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isElementNA"); method.param(int.class, "index"); method.body()._return(JExpr.FALSE); } private void implementAttributeSetter() { // @Override // protected SEXP cloneWithNewAttributes(AttributeMap attributes) { // return new DoubleBinaryFnVector(fn, x, y, attributes); // } JMethod method = vectorClass.method(JMod.PUBLIC, SEXP.class, "cloneWithNewAttributes"); JVar attributes = method.param(AttributeMap.class, "attributes"); JInvocation newInvocation = JExpr._new(vectorClass); for(DeferredArgument arg : arguments) { newInvocation.arg(arg.valueField); } newInvocation.arg(attributes); method.body()._return(newInvocation); } private class DeferredArgument { private JvmMethod.Argument model; private int index; private JFieldVar valueField; private JFieldVar lengthField; private ArgumentType type; private DeferredArgument(JvmMethod.Argument model, int index) { this.model = model; this.index = index; this.valueField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, Vector.class, "arg" + index); this.lengthField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, int.class, "argLength" + index); if(model.getClazz().equals(double.class)) { this.type = ArgumentType.DOUBLE; } else if(model.getClazz().equals(boolean.class)) { this.type = ArgumentType.BOOLEAN; } else if(model.getClazz().equals(int.class)) { this.type = ArgumentType.INTEGER; } else if(model.getClazz().equals(String.class)) { this.type = ArgumentType.STRING; } else if(model.getClazz().equals(Complex.class)) { this.type = ArgumentType.COMPLEX; } else if(model.getClazz().equals(byte.class)) { this.type = ArgumentType.BYTE; } else { throw new UnsupportedOperationException(model.getClazz().toString()); } } public JType type() { return codeModel._ref(model.getClazz()); } public JExpression invokeAccessor(JExpression elementIndex) { return valueField.invoke(type.accessorName).arg(elementIndex); } public JType accessorType() { return codeModel._ref(type.accessorType()); } public JExpression isNA(JExpression expr) { return type.isNa(codeModel, expr); } public JExpression convert(JExpression argValue) { return type.convertToArg(argValue); } } private enum VectorType { DOUBLE(DoubleVector.class, "getElementAsDouble", double.class), LOGICAL(LogicalVector.class, "getElementAsRawLogical", int.class), INTEGER(IntVector.class, "getElementAsInt", int.class), COMPLEX(ComplexVector.class, "getElementAsComplex", Complex.class), RAW(RawVector.class, "getElementAsByte", byte.class); private Class baseClass; private String accessorName; private Class accessorType; private VectorType(Class baseClass, String accessorName, Class accessorType) { this.baseClass = baseClass; this.accessorName = accessorName; this.accessorType = accessorType; } } private enum ArgumentType { DOUBLE(double.class, "getElementAsDouble") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(DoubleVector.class).staticInvoke("isNA").arg(expr); } }, INTEGER(int.class, "getElementAsInt") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr); } }, BOOLEAN(boolean.class, "getElementAsRawLogical") { @Override public JExpression convertToArg(JExpression expr) { return expr.ne(lit(0)); } @Override public Class accessorType() { return int.class; } @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr); } }, STRING(String.class, "getElementAsString") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(StringVector.class).staticInvoke("isNA").arg(expr); } }, COMPLEX(Complex.class, "getElementAsComplex" ) { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(ComplexVector.class).staticInvoke("isNA").arg(expr); } }, BYTE(byte.class, "getElementAsByte" ) { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return JExpr.lit(false); } }; private Class clazz; private String accessorName; private ArgumentType(Class clazz, String accessorName) { this.clazz = clazz; this.accessorName = accessorName; } public JExpression convertToArg(JExpression expr) { return expr; } public Class accessorType() { return clazz; } public abstract JExpression isNa(JCodeModel codeModel, JExpression expr); } }
hlin09/renjin
core/src/main/java/org/renjin/invoke/codegen/DeferredVectorBuilder.java
Java
gpl-3.0
16,612
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.core.preferences; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import eu.geopaparazzi.core.R; import eu.geopaparazzi.library.locale.LocaleUtils; /** * A custom preference to force a particular locale, even if the OS is on another. * * @author Andrea Antonello (www.hydrologis.com) */ public class ForceLocalePreference extends DialogPreference { public static final String PREFS_KEY_FORCELOCALE = "PREFS_KEY_FORCELOCALE";//NON-NLS private Context context; private Spinner localesSpinner; /** * @param ctxt the context to use. * @param attrs attributes. */ public ForceLocalePreference(Context ctxt, AttributeSet attrs) { super(ctxt, attrs); this.context = ctxt; setPositiveButtonText(ctxt.getString(android.R.string.ok)); setNegativeButtonText(ctxt.getString(android.R.string.cancel)); } @Override protected View onCreateDialogView() { LinearLayout mainLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mainLayout.setLayoutParams(layoutParams); mainLayout.setOrientation(LinearLayout.VERTICAL); mainLayout.setPadding(25, 25, 25, 25); localesSpinner = new Spinner(context); localesSpinner.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); localesSpinner.setPadding(15, 5, 15, 5); final String[] localesArray = context.getResources().getStringArray(R.array.locales); ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, localesArray); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); localesSpinner.setAdapter(adapter); final String currentLocale = LocaleUtils.getCurrentLocale(context); if (currentLocale != null) { for (int i = 0; i < localesArray.length; i++) { if (localesArray[i].equals(currentLocale.trim())) { localesSpinner.setSelection(i); break; } } } mainLayout.addView(localesSpinner); return mainLayout; } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { String selectedLocale = localesSpinner.getSelectedItem().toString(); LocaleUtils.changeLang(context, selectedLocale); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { } }
geopaparazzi/geopaparazzi
geopaparazzi_core/src/main/java/eu/geopaparazzi/core/preferences/ForceLocalePreference.java
Java
gpl-3.0
4,020
/* * Author: patiphat mana-u-krid (dew) * E-Mail: dewtx29@gmail.com * facebook: https://www.facebook.com/dewddminecraft */ package dewddgetaway; import java.util.Random; import java.util.Stack; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.plugin.java.JavaPlugin; public class dewgetaway2 implements Listener { class chatx implements Runnable { Player p = null; String message = ""; public void run() { String m[] = message.split("\\s+"); if (m[0].equalsIgnoreCase("/dewgetawayrun")) { staticarea.dslb.loaddewsetlistblockfile(); isruntick = !isruntick; dprint.r.printAll("isruntick = " + Boolean.toString(isruntick)); getawayticktock time = new getawayticktock(); time.setName("getaway"); time.start(); return; } if (m[0].equalsIgnoreCase("/dewgetaway")) { if (m.length == 1) { // it's mean toggle your self if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } int getid = getfreeselect(p.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } else if (m.length == 2) { // it's mean have player name if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } else if (m.length == 3) { // it's mean player 0|1 if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[2].equalsIgnoreCase("0") == false && m[2].equalsIgnoreCase("1") == false) { p.sendMessage("argument 3 must be 0 or 1"); return; } boolean togglemode = false; if (m[2].equalsIgnoreCase("1") == true) togglemode = true; if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } return; } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } } } } class ddata { public String playername[]; public boolean isrun[]; } class getawaytick2 implements Runnable { public void run() { long starttime = System.currentTimeMillis(); long endtime = 0; // loop everyone // printAll("tick"); for (int i = 0; i < ddatamax; i++) { if (nn.isrun[i] == true) { // printAll("found nn = true at " + i); if (nn.playername[i].equalsIgnoreCase("") == false) { // printAll(" nn name empty == false at " + i); // search that player Player p2 = null; for (Player p3 : Bukkit.getOnlinePlayers()) { if (p3.getName().equalsIgnoreCase(nn.playername[i])) { p2 = p3; break; } } if (p2 == null) { // printAll("p2 = null " + i); continue; } // printAll("foundn p2"); double td = 0; Block b = null; Block b2 = null; for (int x = -ra; x <= ra; x++) { for (int y = -ra; y <= ra; y++) { for (int z = -ra; z <= ra; z++) { endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } b = p2.getLocation().getBlock() .getRelative(x, y, z); // b2 is looking td = distance3d(b.getX(), b.getY(), b.getZ(), p2.getLocation().getBlockX(), p2 .getLocation().getBlockY(), p2.getLocation().getBlockZ()); // printAll("radi td " + td); if (td > ra) { continue; } // check this block // b = // p2.getLocation().getBlock().getRelative(x,y,z); boolean bll = blockdewset(b.getTypeId()); if (bll == false) { continue; } // check sign for (int nx = -1; nx <= 1; nx++) { for (int ny = -1; ny <= 1; ny++) { for (int nz = -1; nz <= 1; nz++) { if (b.getRelative(nx, ny, nz) .getTypeId() == 0) { continue; } if (b.getRelative(nx, ny, nz) .getTypeId() == 63 || b.getRelative(nx, ny, nz) .getTypeId() == 68 || b.getRelative(nx, ny, nz) .getType() .isBlock() == false || blockdewset(b .getRelative( nx, ny, nz) .getTypeId()) == false) { bll = false; if (bll == false) { break; } } if (bll == false) { break; } } } if (bll == false) { break; } } if (bll == false) { continue; } // printAll("adding " + b.getX() + "," + // b.getY() + "," + b.getZ()); // move it b2 = getran(b, 1); saveb xx = new saveb(); xx.b1id = b.getTypeId(); xx.b1data = b.getData(); xx.b1x = b.getX(); xx.b1y = b.getY(); xx.b1z = b.getZ(); xx.b2id = b2.getTypeId(); xx.b2data = b2.getData(); xx.b2x = b2.getX(); xx.b2y = b2.getY(); xx.b2z = b2.getZ(); xx.w = b.getWorld().getName(); bd.push(xx); // added queue // switch that block b.setTypeId(xx.b2id); b.setData(xx.b2data); b2.setTypeId(xx.b1id); b2.setData(xx.b1data); } } } // if found player // search neary block at player it's sholud be move // or not // if yes add to queue // and loop again to should it's roll back or not // We should't use quere // We should use array } } } // after add quere dprint.r.printC("bd size = " + bd.size()); for (int gx = 0; gx <= 300; gx++) { // this is rollback block if (bd.size() == 0) { bd.trimToSize(); return; } endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } // printC("before peek " + bd.size()); saveb ttt = bd.peek(); // printC("after peek " + bd.size()); Block b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); Block b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); boolean isp = false; isp = isplayernearblock(b3, ra) || isplayernearblock(b4, ra); if (isp == true) { return; } ttt = bd.pop(); b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); b4.setTypeId(ttt.b2id); b4.setData(ttt.b2data); b3.setTypeId(ttt.b1id); b3.setData(ttt.b1data); } // if not player near rollback // check // is't there have player near that block ? } } class getawayticktock extends Thread { public void run() { while (isruntick == true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } getawaytick2 eee = new getawaytick2(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, eee); } } } class saveb { public int b1id = 0; public byte b1data = 0; public int b1x = 0; public int b1y = 0; public int b1z = 0; public int b2id = 0; public byte b2data = 0; public int b2x = 0; public int b2y = 0; public int b2z = 0; public String w = ""; } boolean isruntick = false; JavaPlugin ac = null; int ra = 5; int ddatamax = 29; ddata nn = new ddata(); String pgetaway = "dewdd.getaway.use"; String pgetawayother = "dewdd.getaway.use.other"; Stack<saveb> bd = new Stack<saveb>(); // Queue<saveb> bd= new LinkedList<saveb>(); Random rnd = new Random(); public dewgetaway2() { nn.playername = new String[ddatamax]; nn.isrun = new boolean[ddatamax]; for (int i = 0; i < ddatamax; i++) { nn.playername[i] = ""; nn.isrun[i] = false; } } public boolean blockdewset(int blockid) { return staticarea.dslb.isdewset(blockid) && staticarea.dslb.isdewinventoryblock(blockid) == false && blockid != 0 && blockid != 8 && blockid != 9 && blockid != 10 && blockid != 11; } public int distance2d(int x1, int z1, int x2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(t1 + t2, 0.5); int t4 = (int) t3; return t4; } public double distance3d(int x1, int y1, int z1, int x2, int y2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(y1 - y2, 2); double t5 = Math.pow(t1 + t2 + t3, 0.5); return t5; } @EventHandler public void eventja(PlayerCommandPreprocessEvent event) { chatx a = new chatx(); a.p = event.getPlayer(); a.message = event.getMessage(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, a); } public int getfreeselect(String sname) { // clean exited player boolean foundx = false; for (int i = 0; i < ddatamax; i++) { foundx = false; for (Player pr : Bukkit.getOnlinePlayers()) { if (nn.playername[i].equalsIgnoreCase(pr.getName())) { foundx = true; break; } } if (foundx == false) { nn.playername[i] = ""; nn.isrun[i] = false; } } // clean for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase(sname)) { return i; } } for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase("")) { nn.playername[i] = sname; return i; } } return -1; } public Block getran(Block b, int ra) { Block b2 = b; int tx = 0; int ty = 0; int tz = 0; int counttry = 0; do { counttry++; tx = rnd.nextInt(ra * 2) - (ra * 1); ty = rnd.nextInt(ra * 2) - (ra * 1); tz = rnd.nextInt(ra * 2) - (ra * 1); if (ty < 1) ty = 1; if (ty > 254) ty = 254; b2 = b.getRelative(tx, ty, tz); if (counttry >= 100) { counttry = 0; ra = ra + 1; } } while (b2.getLocation().distance(b.getLocation()) < ra || b2 == b || b2.getTypeId() != 0); return b2; } public boolean isplayernearblock(Block bh, int ra) { for (Player uu : bh.getWorld().getPlayers()) { if (nn.isrun[getfreeselect(uu.getName())] == false) continue; if (uu.getLocation().distance(bh.getLocation()) <= ra) { return true; } } return false; } } // class
dewtx29/dewdd_minecraft_plugins
old/dewdd_getaway/src/dewddgetaway/dewgetaway2.java
Java
gpl-3.0
13,351
package com.baeldung.collection.filtering; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; /** * Various filtering examples. * * @author Rodolfo Felipe */ public class CollectionFilteringUnitTest { private List<Employee> buildEmployeeList() { return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); } private List<String> employeeNameFilter() { return Arrays.asList("Alice", "Mike", "Bob"); } @Test public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { List<Employee> filteredList = new ArrayList<>(); List<Employee> originalList = buildEmployeeList(); List<String> nameFilter = employeeNameFilter(); for (Employee employee : originalList) { for (String name : nameFilter) { if (employee.getName() .equalsIgnoreCase(name)) { filteredList.add(employee); } } } Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); } @Test public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { List<Employee> filteredList; List<Employee> originalList = buildEmployeeList(); List<String> nameFilter = employeeNameFilter(); filteredList = originalList.stream() .filter(employee -> nameFilter.contains(employee.getName())) .collect(Collectors.toList()); Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); } @Test public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { List<Employee> filteredList; List<Employee> originalList = buildEmployeeList(); Set<String> nameFilterSet = employeeNameFilter().stream() .collect(Collectors.toSet()); filteredList = originalList.stream() .filter(employee -> nameFilterSet.contains(employee.getName())) .collect(Collectors.toList()); Assert.assertThat(filteredList.size(), Matchers.is(nameFilterSet.size())); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java
Java
gpl-3.0
2,531
/* * Copyright (C) 2017 GG-Net GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Contains the Ui and actions for the detailed document view and edit and all supplemental uis. */ package eu.ggnet.dwoss.redtapext.ui.cao.document;
gg-net/dwoss
ui/redtapext/src/main/java/eu/ggnet/dwoss/redtapext/ui/cao/document/package-info.java
Java
gpl-3.0
865
package net.minecraft.server; import java.io.IOException; public class PacketPlayOutEntityHeadRotation implements Packet<PacketListenerPlayOut> { private int a; private byte b; public PacketPlayOutEntityHeadRotation() {} public PacketPlayOutEntityHeadRotation(Entity entity, byte b0) { this.a = entity.getId(); this.b = b0; } public void a(PacketDataSerializer packetdataserializer) throws IOException { this.a = packetdataserializer.g(); this.b = packetdataserializer.readByte(); } public void b(PacketDataSerializer packetdataserializer) throws IOException { packetdataserializer.d(this.a); packetdataserializer.writeByte(this.b); } public void a(PacketListenerPlayOut packetlistenerplayout) { packetlistenerplayout.a(this); } }
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/PacketPlayOutEntityHeadRotation.java
Java
gpl-3.0
839
package cmake.icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * Created by alex on 12/21/14. */ public class CMakeIcons { public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); }
dubrousky/CMaker
src/cmake/icons/CMakeIcons.java
Java
gpl-3.0
462
package com.brejza.matt.habmodem; import group.pals.android.lib.ui.filechooser.FileChooserActivity; import group.pals.android.lib.ui.filechooser.io.localfile.LocalFile; import java.io.File; import java.util.List; import android.os.Bundle; import android.os.Environment; import android.os.Parcelable; import android.preference.PreferenceManager; import android.app.Activity; import android.app.DialogFragment; import android.app.FragmentManager; import android.content.Intent; import android.view.Menu; public class StartActivity extends Activity implements FirstRunMessage.NoticeDialogListener, MapFileMessage.NoticeDialogListener { private static final int _ReqChooseFile = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_start, menu); return true; } @Override public void onResume() { super.onResume(); boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("firstrun1", false); if (!firstrun){ FragmentManager fm = getFragmentManager(); FirstRunMessage di = new FirstRunMessage(); di.show(fm, "firstrun"); } else { String mapst = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString("pref_map_path", ""); File file = new File(mapst); if(file.exists()) { //start main activity Intent intent = new Intent(this, Map_Activity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP ); startActivity(intent); finish(); } else { FragmentManager fm = getFragmentManager(); MapFileMessage di = new MapFileMessage(); di.show(fm, "mapmessage"); } } } @Override public void onDialogPositiveClickFirstRun(DialogFragment dialog) { // TODO Auto-generated method stub getSharedPreferences("PREFERENCE", MODE_PRIVATE) .edit() .putBoolean("firstrun1", true) .commit(); FragmentManager fm = getFragmentManager(); MapFileMessage di = new MapFileMessage(); di.show(fm, "mapmessage"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case _ReqChooseFile: if (resultCode == RESULT_OK) { List<LocalFile> files = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity._Results); for (File f : files) { PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).edit().putString("pref_map_path", f.getPath()).commit(); System.out.println(f.toString()); } } break; } } private void showMapChooser() { Intent intent = new Intent(StartActivity.this, FileChooserActivity.class); intent.putExtra(FileChooserActivity._Rootpath, (Parcelable) new LocalFile(Environment.getExternalStorageDirectory().getPath() )); intent.putExtra(FileChooserActivity._RegexFilenameFilter, "(?si).*\\.(map)$"); intent.putExtra(FileChooserActivity._Theme, android.R.style.Theme_Dialog); startActivityForResult(intent, _ReqChooseFile); } @Override public void onDialogNegativeClickFirstRun(DialogFragment dialog) { // TODO Auto-generated method stub this.finish(); } @Override public void onDialogPositiveClickMapHelp(DialogFragment dialog) { // TODO Auto-generated method stub showMapChooser(); } @Override public void onDialogNegativeClickMapHelp(DialogFragment dialog) { // TODO Auto-generated method stub Intent intent = new Intent(this, StatusScreen.class); startActivity(intent); } }
mattbrejza/rtty_modem
habmodem/src/com/brejza/matt/habmodem/StartActivity.java
Java
gpl-3.0
4,104
package ai.hellbound; import l2s.commons.util.Rnd; import l2s.gameserver.ai.CtrlEvent; import l2s.gameserver.ai.Mystic; import l2s.gameserver.model.Creature; import l2s.gameserver.model.Playable; import l2s.gameserver.model.World; import l2s.gameserver.model.instances.NpcInstance; import bosses.BelethManager; /** * @author pchayka */ public class Beleth extends Mystic { private long _lastFactionNotifyTime = 0; private static final int CLONE = 29119; public Beleth(NpcInstance actor) { super(actor); } @Override protected void onEvtDead(Creature killer) { BelethManager.setBelethDead(); super.onEvtDead(killer); } @Override protected void onEvtAttacked(Creature attacker, int damage) { NpcInstance actor = getActor(); if(System.currentTimeMillis() - _lastFactionNotifyTime > _minFactionNotifyInterval) { _lastFactionNotifyTime = System.currentTimeMillis(); for(NpcInstance npc : World.getAroundNpc(actor)) if(npc.getNpcId() == CLONE) npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, attacker, Rnd.get(1, 100)); } super.onEvtAttacked(attacker, damage); } @Override protected boolean randomWalk() { return false; } @Override protected boolean randomAnimation() { return false; } @Override public boolean canSeeInSilentMove(Playable target) { return true; } @Override public boolean canSeeInHide(Playable target) { return true; } @Override public void addTaskAttack(Creature target) { return; } }
pantelis60/L2Scripts_Underground
dist/gameserver/data/scripts/ai/hellbound/Beleth.java
Java
gpl-3.0
1,491
package be.ipl.mobile.projet.historypub; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
Crapoo/HistoryPub
app/src/androidTest/java/be/ipl/mobile/projet/historypub/ApplicationTest.java
Java
gpl-3.0
362
/** */ package net.paissad.waqtsalat.core.impl; import java.util.Calendar; import net.paissad.waqtsalat.core.WaqtSalatPackage; import net.paissad.waqtsalat.core.api.Pray; import net.paissad.waqtsalat.core.api.PrayName; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> An implementation of the model object ' <em><b>Pray</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getName <em>Name</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getTime <em>Time</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#isPlayingAdhan <em>Playing Adhan</em>}</li> * <li>{@link net.paissad.waqtsalat.core.impl.PrayImpl#getAdhanPlayer <em>Adhan Player</em>}</li> * </ul> * </p> * * @generated */ public class PrayImpl extends MinimalEObjectImpl.Container implements Pray { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getName() * @generated * @ordered */ protected static final PrayName NAME_EDEFAULT = PrayName.FADJR; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getName() * @generated * @ordered */ protected PrayName name = NAME_EDEFAULT; /** * The default value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getTime() * @generated * @ordered */ protected static final Calendar TIME_EDEFAULT = null; /** * The cached value of the '{@link #getTime() <em>Time</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc * --> * * @see #getTime() * @generated * @ordered */ protected Calendar time = TIME_EDEFAULT; /** * The default value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPlayingAdhan() * @generated * @ordered */ protected static final boolean PLAYING_ADHAN_EDEFAULT = false; /** * The cached value of the '{@link #isPlayingAdhan() <em>Playing Adhan</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #isPlayingAdhan() * @generated * @ordered */ protected boolean playingAdhan = PLAYING_ADHAN_EDEFAULT; /** * The default value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getAdhanPlayer() * @generated * @ordered */ protected static final Object ADHAN_PLAYER_EDEFAULT = null; /** * The cached value of the '{@link #getAdhanPlayer() <em>Adhan Player</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getAdhanPlayer() * @generated * @ordered */ protected Object adhanPlayer = ADHAN_PLAYER_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected PrayImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return WaqtSalatPackage.Literals.PRAY; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public PrayName getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setName(PrayName newName) { PrayName oldName = name; name = newName == null ? NAME_EDEFAULT : newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__NAME, oldName, name)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Calendar getTime() { return time; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setTime(Calendar newTime) { Calendar oldTime = time; time = newTime; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__TIME, oldTime, time)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public boolean isPlayingAdhan() { return playingAdhan; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setPlayingAdhan(boolean newPlayingAdhan) { boolean oldPlayingAdhan = playingAdhan; playingAdhan = newPlayingAdhan; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__PLAYING_ADHAN, oldPlayingAdhan, playingAdhan)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public Object getAdhanPlayer() { return adhanPlayer; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setAdhanPlayer(Object newAdhanPlayer) { Object oldAdhanPlayer = adhanPlayer; adhanPlayer = newAdhanPlayer; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WaqtSalatPackage.PRAY__ADHAN_PLAYER, oldAdhanPlayer, adhanPlayer)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: return getName(); case WaqtSalatPackage.PRAY__TIME: return getTime(); case WaqtSalatPackage.PRAY__PLAYING_ADHAN: return isPlayingAdhan(); case WaqtSalatPackage.PRAY__ADHAN_PLAYER: return getAdhanPlayer(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: setName((PrayName) newValue); return; case WaqtSalatPackage.PRAY__TIME: setTime((Calendar) newValue); return; case WaqtSalatPackage.PRAY__PLAYING_ADHAN: setPlayingAdhan((Boolean) newValue); return; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: setAdhanPlayer(newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: setName(NAME_EDEFAULT); return; case WaqtSalatPackage.PRAY__TIME: setTime(TIME_EDEFAULT); return; case WaqtSalatPackage.PRAY__PLAYING_ADHAN: setPlayingAdhan(PLAYING_ADHAN_EDEFAULT); return; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: setAdhanPlayer(ADHAN_PLAYER_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case WaqtSalatPackage.PRAY__NAME: return name != NAME_EDEFAULT; case WaqtSalatPackage.PRAY__TIME: return TIME_EDEFAULT == null ? time != null : !TIME_EDEFAULT.equals(time); case WaqtSalatPackage.PRAY__PLAYING_ADHAN: return playingAdhan != PLAYING_ADHAN_EDEFAULT; case WaqtSalatPackage.PRAY__ADHAN_PLAYER: return ADHAN_PLAYER_EDEFAULT == null ? adhanPlayer != null : !ADHAN_PLAYER_EDEFAULT.equals(adhanPlayer); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); //$NON-NLS-1$ result.append(name); result.append(", time: "); //$NON-NLS-1$ result.append(time); result.append(", playingAdhan: "); //$NON-NLS-1$ result.append(playingAdhan); result.append(", adhanPlayer: "); //$NON-NLS-1$ result.append(adhanPlayer); result.append(')'); return result.toString(); } } // PrayImpl
paissad/waqtsalat-eclipse-plugin
plugins/net.paissad.waqtsalat.core/src/net/paissad/waqtsalat/core/impl/PrayImpl.java
Java
gpl-3.0
9,597
package xigua.battle.of.elements.model; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IntWithMaxTest { private IntWithMax intWithMax; @Before public void setUp() { intWithMax = new IntWithMax(42); } @Test public void getValue_WithCorrectValue() { assertThat(intWithMax.getValue()).isEqualTo(42); } @Test public void setWhenValueBiggerThanMax_CorrectValueSet() { intWithMax.setValue(100); assertThat(intWithMax.getValue()).isEqualTo(42); } @Test public void setWhenValueSmallerThanMax_CorrectValueSet() { intWithMax.setValue(1); assertThat(intWithMax.getValue()).isEqualTo(1); } @Test public void getMax_WithCorrectMax() { assertThat(intWithMax.getMaxValue()).isEqualTo(42); } }
YuKitAs/battle-of-elements
src/test/java/xigua/battle/of/elements/model/IntWithMaxTest.java
Java
gpl-3.0
879
package ninja.mbedded.ninjaterm.util.rxProcessing.timeStamp; import javafx.scene.paint.Color; import ninja.mbedded.ninjaterm.JavaFXThreadingRule; import ninja.mbedded.ninjaterm.util.rxProcessing.streamedData.StreamedData; import ninja.mbedded.ninjaterm.util.rxProcessing.streamingFilter.StreamingFilter; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.time.Instant; import java.time.ZoneId; import static org.junit.Assert.assertEquals; /** * Unit tests for the {@link TimeStampParser} class. * * @author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja) * @since 2016-11-23 * @last-modified 2016-11-23 */ public class TimeStampParserTests { /** * Including this variable in class allows JavaFX objects to be created in tests. */ @Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule(); private TimeStampParser timeStampParser; private StreamedData inputStreamedData; private StreamedData outputStreamedData; @Before public void setUp() throws Exception { timeStampParser = new TimeStampParser("EOL"); inputStreamedData = new StreamedData(); outputStreamedData = new StreamedData(); } @Test public void firstCharTest() throws Exception { inputStreamedData.append("abc"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abc", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); } @Test public void oneNewLineTest() throws Exception { inputStreamedData.append("abcEOLd"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOLd", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); } @Test public void temporalTest() throws Exception { inputStreamedData.append("abcEOL"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOL", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); // Sleep enough that the next TimeStamp is guaranteed to be greater than // the first (delay must be larger than the min. LocalDateTime resolution) Thread.sleep(10); //==============================================// //====================== RUN 2 =================// //==============================================// inputStreamedData.append("d"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("abcEOLd", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); // Check time Instant time0 = outputStreamedData.getTimeStampMarkers().get(0).localDateTime.atZone(ZoneId.systemDefault()).toInstant(); Instant time1 = outputStreamedData.getTimeStampMarkers().get(1).localDateTime.atZone(ZoneId.systemDefault()).toInstant(); assertEquals(true, time1.isAfter(time0)); } @Test public void partialLineTest() throws Exception { inputStreamedData.append("123EO"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("EO", inputStreamedData.getText()); // Check output assertEquals("123", outputStreamedData.getText()); assertEquals(1, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); inputStreamedData.append("L456"); timeStampParser.parse(inputStreamedData, outputStreamedData); // Check input assertEquals("", inputStreamedData.getText()); // Check output assertEquals("123EOL456", outputStreamedData.getText()); assertEquals(2, outputStreamedData.getTimeStampMarkers().size()); assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos); assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos); } // @Test // public void multipleLinesTest() throws Exception { // // inputStreamedData.append("abcEOLabcEOLdefEOL"); // inputStreamedData.addNewLineMarkerAt(6); // inputStreamedData.addNewLineMarkerAt(12); // inputStreamedData.addNewLineMarkerAt(18); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input. Since "defEOL" counts as a valid line, but has no match, // // it should be removed from the input // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getColourMarkers().size()); // // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // } // // @Test // public void MatchedLinesBetweenNonMatchTest() throws Exception { // // inputStreamedData.append("abcEOLdefEOLabcEOL"); // inputStreamedData.addNewLineMarkerAt(6); // inputStreamedData.addNewLineMarkerAt(12); // inputStreamedData.addNewLineMarkerAt(18); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input. Since "defEOL" counts as a valid line, but has no match, // // it should be removed from the input // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getColourMarkers().size()); // // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // } // // @Test // public void streamTest() throws Exception { // // inputStreamedData.append("ab"); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("", inputStreamedData.getText()); // assertEquals("ab", outputStreamedData.getText()); // // inputStreamedData.append("cEOL"); // inputStreamedData.addNewLineMarkerAt(4); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("", inputStreamedData.getText()); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // } // // @Test // public void streamWithNonMatchLineInMiddleTest() throws Exception { // // //==============================================// // //==================== PASS 1 ==================// // //==============================================// // // inputStreamedData.append("ab"); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input // assertEquals("", inputStreamedData.getText()); // // // Check output // assertEquals("ab", outputStreamedData.getText()); // // //==============================================// // //==================== PASS 2 ==================// // //==============================================// // // inputStreamedData.append("cEOLde"); // inputStreamedData.addNewLineMarkerAt(4); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input // assertEquals(inputStreamedData.getText(), "de"); // // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // // //==============================================// // //==================== PASS 3 ==================// // //==============================================// // // inputStreamedData.append("fEOLa"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length() - 1); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input // assertEquals(inputStreamedData.getText(), ""); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // // Check output // assertEquals("abcEOLa", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // // //==============================================// // //==================== PASS 4 ==================// // //==============================================// // // inputStreamedData.append("bcEOL"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check input // assertEquals(inputStreamedData.getText(), ""); // assertEquals(0, inputStreamedData.getNewLineMarkers().size()); // // // Check output // assertEquals("abcEOLabcEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue()); // // } // // @Test // public void coloursAndNewLinesTest() throws Exception { // // inputStreamedData.append("abcEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addNewLineMarkerAt(6); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Check output // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // } // // @Test // public void complexNodesTest() throws Exception { // // inputStreamedData.append("abcdefEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addColour(3, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(9); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("abcdefEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getColourMarkers().size()); // // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // // assertEquals(3, outputStreamedData.getColourMarkers().get(1).position); // assertEquals(Color.GREEN, outputStreamedData.getColourMarkers().get(1).color); // // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(9, outputStreamedData.getNewLineMarkers().get(0).intValue()); // } // // @Test // public void complexNodes2Test() throws Exception { // // //==============================================// // //==================== PASS 1 ==================// // //==============================================// // // inputStreamedData.append("abcEOL"); // inputStreamedData.addColour(2, Color.RED); // inputStreamedData.addNewLineMarkerAt(6); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // // //==============================================// // //==================== PASS 2 ==================// // //==============================================// // // inputStreamedData.append("defEOL"); // inputStreamedData.addColour(0, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("abcEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(2, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // assertEquals(1, outputStreamedData.getNewLineMarkers().size()); // assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue()); // } // // @Test // public void bigTest() throws Exception { // // streamingFilter.setFilterPattern("d"); // // inputStreamedData.append("re"); // inputStreamedData.addColour(0, Color.RED); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("", outputStreamedData.getText()); // assertEquals(0, outputStreamedData.getColourMarkers().size()); // // inputStreamedData.append("dEOL"); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("redEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // // Nothing should of changed // assertEquals("redEOL", outputStreamedData.getText()); // assertEquals(1, outputStreamedData.getColourMarkers().size()); // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // // inputStreamedData.append("greenEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // inputStreamedData.append("redEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 6, Color.RED); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // inputStreamedData.append("greenEOL"); // inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN); // inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length()); // // streamingFilter.parse(inputStreamedData, outputStreamedData); // // assertEquals("redEOLredEOL", outputStreamedData.getText()); // assertEquals(2, outputStreamedData.getColourMarkers().size()); // // assertEquals(0, outputStreamedData.getColourMarkers().get(0).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color); // // assertEquals(6, outputStreamedData.getColourMarkers().get(1).position); // assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(1).color); // } }
mbedded-ninja/NinjaTerm
src/test/java/ninja/mbedded/ninjaterm/util/rxProcessing/timeStamp/TimeStampParserTests.java
Java
gpl-3.0
17,393
/** * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.reminders; import android.app.Dialog; import android.content.Intent; import android.view.View; import android.widget.TextView; import com.todoroo.astrid.activity.AstridActivity; import com.todoroo.astrid.activity.TaskListFragment; import org.tasks.Broadcaster; import org.tasks.R; import org.tasks.reminders.SnoozeActivity; import javax.inject.Inject; /** * This activity is launched when a user opens up a notification from the * tray. It launches the appropriate activity based on the passed in parameters. * * @author timsu * */ public class NotificationFragment extends TaskListFragment { public static final String TOKEN_ID = "id"; //$NON-NLS-1$ @Inject Broadcaster broadcaster; @Override protected void initializeData() { displayNotificationPopup(); super.initializeData(); } private void displayNotificationPopup() { final String title = extras.getString(Notifications.EXTRAS_TITLE); final long taskId = extras.getLong(TOKEN_ID); final AstridActivity activity = (AstridActivity) getActivity(); new Dialog(activity, R.style.ReminderDialog) {{ setContentView(R.layout.astrid_reminder_view_portrait); findViewById(R.id.speech_bubble_container).setVisibility(View.GONE); // set up listeners findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { dismiss(); } }); findViewById(R.id.reminder_snooze).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { dismiss(); activity.startActivity(new Intent(activity, SnoozeActivity.class) {{ putExtra(SnoozeActivity.TASK_ID, taskId); }}); } }); findViewById(R.id.reminder_complete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { broadcaster.completeTask(taskId); dismiss(); } }); findViewById(R.id.reminder_edit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); activity.onTaskListItemClicked(taskId); } }); ((TextView) findViewById(R.id.reminder_title)).setText(activity.getString(R.string.rmd_NoA_dlg_title) + " " + title); setOwnerActivity(activity); }}.show(); } }
xVir/tasks
src/main/java/com/todoroo/astrid/reminders/NotificationFragment.java
Java
gpl-3.0
2,884
package com.simplecity.amp_library.model; import android.content.Context; import com.simplecity.amp_library.R; import java.io.File; public class ArtworkModel { private static final String TAG = "ArtworkModel"; @ArtworkProvider.Type public int type; public File file; public ArtworkModel(@ArtworkProvider.Type int type, File file) { this.type = type; this.file = file; } public static String getTypeString(Context context, @ArtworkProvider.Type int type) { switch (type) { case ArtworkProvider.Type.MEDIA_STORE: return context.getString(R.string.artwork_type_media_store); case ArtworkProvider.Type.TAG: return context.getString(R.string.artwork_type_tag); case ArtworkProvider.Type.FOLDER: return "Folder"; case ArtworkProvider.Type.REMOTE: return context.getString(R.string.artwork_type_internet); } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArtworkModel that = (ArtworkModel) o; if (type != that.type) return false; return file != null ? file.equals(that.file) : that.file == null; } @Override public int hashCode() { int result = type; result = 31 * result + (file != null ? file.hashCode() : 0); return result; } }
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/model/ArtworkModel.java
Java
gpl-3.0
1,505
package com.newppt.android.ui; import com.newppt.android.data.AnimUtils2; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class ScaleImage extends ImageView { final private int FLIP_DISTANCE = 30; public ScaleImage(Context context) { super(context); // TODO Auto-generated constructor stub } public ScaleImage(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public ScaleImage(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } private int count = 0; private long firClick; private long secClick; private boolean scaleTip = true; private float x; private float y; @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if (MotionEvent.ACTION_DOWN == event.getAction()) { count++; if (count == 1) { firClick = System.currentTimeMillis(); x = event.getX(); y = event.getY(); } else if (count == 2) { secClick = System.currentTimeMillis(); float mx = event.getX(); float my = event.getY(); if (secClick - firClick < 700 && Math.abs(mx - x) < FLIP_DISTANCE && Math.abs(my - y) < FLIP_DISTANCE) { // ˫���¼� if (scaleTip) { x = event.getX(); y = event.getY(); AnimUtils2 animUtils2 = new AnimUtils2(); animUtils2.imageZoomOut(this, 200, x, y); scaleTip = false; } else { AnimUtils2 animUtils2 = new AnimUtils2(); animUtils2.imageZoomIn(this, 200, x, y); scaleTip = true; } } count = 0; firClick = 0; secClick = 0; } } return true; // return super.onTouchEvent(event); } }
beyondckw/SynchronizeOfPPT
Android_v5/src/com/newppt/android/ui/ScaleImage.java
Java
gpl-3.0
1,835
/* Copyright 2011 Anton Kraievoy akraievoy@gmail.com This file is part of Holonet. Holonet is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Holonet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Holonet. If not, see <http://www.gnu.org/licenses/>. */ package algores.holonet.core.events; import algores.holonet.core.CommunicationException; import algores.holonet.core.Network; import algores.holonet.core.Node; import algores.holonet.core.RequestPair; import algores.holonet.core.api.Address; import algores.holonet.core.api.Key; import algores.holonet.core.api.tier1.delivery.LookupService; import com.google.common.base.Optional; import org.akraievoy.cnet.gen.vo.EntropySource; import java.util.Collection; /** * Lookup entry event. */ public class EventNetLookup extends Event<EventNetLookup> { protected int retries = 1; public Result executeInternal(final Network network, final EntropySource eSource) { Result aggregateResult = Result.PASSIVE; for (int sequentialIndex = 0; sequentialIndex < retries; sequentialIndex++) { Optional<RequestPair> optRequest = network.generateRequestPair(eSource); if (!optRequest.isPresent()) { if (sequentialIndex > 0) { throw new IllegalStateException( "request model became empty amid request generation streak?" ); } break; } RequestPair request = optRequest.get(); Collection<Key> serverKeys = request.server.getServices().getStorage().getKeys(); final Key mapping = serverKeys.isEmpty() ? // we may also pull other keys from the range, not only the greatest one request.server.getServices().getRouting().ownRoute().getRange().getRKey().prev() : eSource.randomElement(serverKeys); final LookupService lookupSvc = request.client.getServices().getLookup(); final Address address; try { address = lookupSvc.lookup( mapping.getKey(), true, LookupService.Mode.GET, Optional.of(request.server.getAddress()) ); } catch (CommunicationException e) { if (!aggregateResult.equals(Result.FAILURE)) { aggregateResult = handleEventFailure(e, null); } continue; } final Node lookupResult = network.getEnv().getNode(address); if ( !lookupResult.equals(request.server) ) { network.getInterceptor().reportInconsistentLookup(LookupService.Mode.GET); } aggregateResult = Result.SUCCESS; } return aggregateResult; } public void setRetries(int retryCount) { this.retries = retryCount; } public EventNetLookup withRetries(int retryCount) { setRetries(retryCount); return this; } }
akraievoy/holonet
src/main/java/algores/holonet/core/events/EventNetLookup.java
Java
gpl-3.0
3,225
package br.ifrn.meutcc.visao; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.ifrn.meutcc.modelo.Aluno; import br.ifrn.meutcc.modelo.Orientador; @WebServlet("/ViewAlunoCandidatou") public class ViewAlunoCandidatou extends HttpServlet { private static final long serialVersionUID = 1L; public ViewAlunoCandidatou() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); int idCandidato = 2; int idTema = -1; try { idTema = Integer.parseInt(id); } catch (NumberFormatException nfex) { nfex.printStackTrace(); } Orientador a = new Orientador(); Orientador orientador = a.getOrientadorPorTema(idTema); Aluno logic = new Aluno(); logic.registraObserver(orientador); boolean aluno = logic.addCandidato(idTema, idCandidato); request.setAttribute("candidatou", logic.getStatus()); request.setAttribute("aluno", aluno); request.getRequestDispatcher("viewAluno.jsp").forward(request, response); } }
hayssac/MeuTCC_Grupo1
MeuTCCApp/src/br/ifrn/meutcc/visao/ViewAlunoCandidatou.java
Java
gpl-3.0
1,286
package com.idega.development.presentation; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Layer; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.HorizontalRule; import com.idega.presentation.text.Text; import com.idega.presentation.ui.IFrame; import com.idega.repository.data.RefactorClassRegistry; /** * Title: idega Framework * Description: * Copyright: Copyright (c) 2001 * Company: idega * @author <a href=mailto:"tryggvi@idega.is">Tryggvi Larusson</a> * @version 1.0 */ public class IWDeveloper extends com.idega.presentation.app.IWApplication { private static final String localizerParameter = "iw_localizer"; private static final String localeswitcherParameter = "iw_localeswitcher"; private static final String bundleCreatorParameter = "iw_bundlecreator"; private static final String bundleComponentManagerParameter = "iw_bundlecompmanager"; private static final String applicationPropertiesParameter = "iw_application_properties_setter"; private static final String bundlesPropertiesParameter = "iw_bundle_properties_setter"; public static final String actionParameter = "iw_developer_action"; public static final String dbPoolStatusViewerParameter = "iw_poolstatus_viewer"; public static final String updateManagerParameter = "iw_update_manager"; public static final String frameName = "iwdv_rightFrame"; public static final String PARAMETER_CLASS_NAME = "iwdv_class_name"; public IWDeveloper() { super("idegaWeb Developer"); add(IWDeveloper.IWDevPage.class); super.setResizable(true); super.setScrollbar(true); super.setScrolling(1, true); super.setWidth(800); super.setHeight(600); //super.setOnLoad("moveTo(0,0);"); } public static class IWDevPage extends com.idega.presentation.ui.Window { public IWDevPage() { this.setStatus(true); } private Table mainTable; private Table objectTable; private IFrame rightFrame; private int count = 1; public void main(IWContext iwc) throws Exception { IWBundle iwbCore = getBundle(iwc); if (iwc.isIE()) { getParentPage().setBackgroundColor("#B0B29D"); } Layer topLayer = new Layer(Layer.DIV); topLayer.setZIndex(3); topLayer.setPositionType(Layer.FIXED); topLayer.setTopPosition(0); topLayer.setLeftPosition(0); topLayer.setBackgroundColor("#0E2456"); topLayer.setWidth(Table.HUNDRED_PERCENT); topLayer.setHeight(25); add(topLayer); Table headerTable = new Table(); headerTable.setCellpadding(0); headerTable.setCellspacing(0); headerTable.setWidth(Table.HUNDRED_PERCENT); headerTable.setAlignment(2,1,Table.HORIZONTAL_ALIGN_RIGHT); topLayer.add(headerTable); Image idegaweb = iwbCore.getImage("/editorwindow/idegaweb.gif","idegaWeb"); headerTable.add(idegaweb,1,1); Text adminTitle = new Text("idegaWeb Developer"); adminTitle.setStyleAttribute("color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;margin-right:5px;"); headerTable.add(adminTitle,2,1); Layer leftLayer = new Layer(Layer.DIV); leftLayer.setZIndex(2); leftLayer.setPositionType(Layer.FIXED); leftLayer.setTopPosition(25); leftLayer.setLeftPosition(0); leftLayer.setPadding(5); leftLayer.setBackgroundColor("#B0B29D"); leftLayer.setWidth(180); leftLayer.setHeight(Table.HUNDRED_PERCENT); add(leftLayer); DeveloperList list = new DeveloperList(); leftLayer.add(list); Layer rightLayer = new Layer(Layer.DIV); rightLayer.setZIndex(1); rightLayer.setPositionType(Layer.ABSOLUTE); rightLayer.setTopPosition(25); rightLayer.setPadding(5); if (iwc.isIE()) { rightLayer.setBackgroundColor("#FFFFFF"); rightLayer.setWidth(Table.HUNDRED_PERCENT); rightLayer.setHeight(Table.HUNDRED_PERCENT); rightLayer.setLeftPosition(180); } else { rightLayer.setLeftPosition(190); } add(rightLayer); if (iwc.isParameterSet(PARAMETER_CLASS_NAME)) { String className = IWMainApplication.decryptClassName(iwc.getParameter(PARAMETER_CLASS_NAME)); PresentationObject obj = (PresentationObject) RefactorClassRegistry.getInstance().newInstance(className, this.getClass()); rightLayer.add(obj); } else { rightLayer.add(new Localizer()); } } } public static Table getTitleTable(String displayString, Image image) { Table titleTable = new Table(1, 2); titleTable.setCellpadding(0); titleTable.setCellspacing(0); titleTable.setWidth("100%"); Text headline = getText(displayString); headline.setFontSize(Text.FONT_SIZE_14_HTML_4); headline.setFontColor("#0E2456"); if (image != null) { image.setHorizontalSpacing(5); titleTable.add(image, 1, 1); } titleTable.add(headline, 1, 1); titleTable.add(new HorizontalRule("100%", 2, "color: #FF9310", true), 1, 2); return titleTable; } public static Table getTitleTable(String displayString) { return getTitleTable(displayString, null); } public static Table getTitleTable(Class classToUse, Image image) { return getTitleTable(classToUse.getName().substring(classToUse.getName().lastIndexOf(".") + 1), image); } public static Table getTitleTable(Class classToUse) { return getTitleTable(classToUse, null); } public static Text getText(String text) { Text T = new Text(text); T.setBold(); T.setFontFace(Text.FONT_FACE_VERDANA); T.setFontSize(Text.FONT_SIZE_10_HTML_2); return T; } }
idega/platform2
src/com/idega/development/presentation/IWDeveloper.java
Java
gpl-3.0
5,611
package itaf.WsCartItemService; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>bzCollectionOrderDto complex typeµÄ Java Àà¡£ * * <p>ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£ * * <pre> * &lt;complexType name="bzCollectionOrderDto"> * &lt;complexContent> * &lt;extension base="{itaf.framework.ws.server.cart}operateDto"> * &lt;sequence> * &lt;element name="bzDistributionOrderDto" type="{itaf.framework.ws.server.cart}bzDistributionOrderDto" minOccurs="0"/> * &lt;element name="receivableAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/> * &lt;element name="actualAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/> * &lt;element name="distributionAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "bzCollectionOrderDto", propOrder = { "bzDistributionOrderDto", "receivableAmount", "actualAmount", "distributionAmount" }) public class BzCollectionOrderDto extends OperateDto { protected BzDistributionOrderDto bzDistributionOrderDto; protected BigDecimal receivableAmount; protected BigDecimal actualAmount; protected BigDecimal distributionAmount; /** * »ñÈ¡bzDistributionOrderDtoÊôÐÔµÄÖµ¡£ * * @return * possible object is * {@link BzDistributionOrderDto } * */ public BzDistributionOrderDto getBzDistributionOrderDto() { return bzDistributionOrderDto; } /** * ÉèÖÃbzDistributionOrderDtoÊôÐÔµÄÖµ¡£ * * @param value * allowed object is * {@link BzDistributionOrderDto } * */ public void setBzDistributionOrderDto(BzDistributionOrderDto value) { this.bzDistributionOrderDto = value; } /** * »ñÈ¡receivableAmountÊôÐÔµÄÖµ¡£ * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getReceivableAmount() { return receivableAmount; } /** * ÉèÖÃreceivableAmountÊôÐÔµÄÖµ¡£ * * @param value * allowed object is * {@link BigDecimal } * */ public void setReceivableAmount(BigDecimal value) { this.receivableAmount = value; } /** * »ñÈ¡actualAmountÊôÐÔµÄÖµ¡£ * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getActualAmount() { return actualAmount; } /** * ÉèÖÃactualAmountÊôÐÔµÄÖµ¡£ * * @param value * allowed object is * {@link BigDecimal } * */ public void setActualAmount(BigDecimal value) { this.actualAmount = value; } /** * »ñÈ¡distributionAmountÊôÐÔµÄÖµ¡£ * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getDistributionAmount() { return distributionAmount; } /** * ÉèÖÃdistributionAmountÊôÐÔµÄÖµ¡£ * * @param value * allowed object is * {@link BigDecimal } * */ public void setDistributionAmount(BigDecimal value) { this.distributionAmount = value; } }
zpxocivuby/freetong_mobile_server
itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsCartItemService/BzCollectionOrderDto.java
Java
gpl-3.0
3,557
/* * Copyright 2018 Mauricio Colli <mauriciocolli@outlook.com> * AnimationUtils.java is part of NewPipe * * License: GPL-3.0+ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.schabi.newpipe.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.content.res.ColorStateList; import android.util.Log; import android.view.View; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.core.view.ViewCompat; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import org.schabi.newpipe.MainActivity; public final class AnimationUtils { private static final String TAG = "AnimationUtils"; private static final boolean DEBUG = MainActivity.DEBUG; private AnimationUtils() { } public static void animateView(final View view, final boolean enterOrExit, final long duration) { animateView(view, Type.ALPHA, enterOrExit, duration, 0, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, null); } public static void animateView(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { animateView(view, Type.ALPHA, enterOrExit, duration, delay, execOnEnd); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration) { animateView(view, animationType, enterOrExit, duration, 0, null); } public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay) { animateView(view, animationType, enterOrExit, duration, delay, null); } /** * Animate the view. * * @param view view that will be animated * @param animationType {@link Type} of the animation * @param enterOrExit true to enter, false to exit * @param duration how long the animation will take, in milliseconds * @param delay how long the animation will wait to start, in milliseconds * @param execOnEnd runnable that will be executed when the animation ends */ public static void animateView(final View view, final Type animationType, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (DEBUG) { String id; try { id = view.getResources().getResourceEntryName(view.getId()); } catch (final Exception e) { id = view.getId() + ""; } final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit, view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd); Log.d(TAG, "animateView()" + msg); } if (view.getVisibility() == View.VISIBLE && enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already visible > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); view.setAlpha(1f); if (execOnEnd != null) { execOnEnd.run(); } return; } else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE) && !enterOrExit) { if (DEBUG) { Log.d(TAG, "animateView() view was already gone > view = [" + view + "]"); } view.animate().setListener(null).cancel(); view.setVisibility(View.GONE); view.setAlpha(0f); if (execOnEnd != null) { execOnEnd.run(); } return; } view.animate().setListener(null).cancel(); view.setVisibility(View.VISIBLE); switch (animationType) { case ALPHA: animateAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case SCALE_AND_ALPHA: animateScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case LIGHT_SCALE_AND_ALPHA: animateLightScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case SLIDE_AND_ALPHA: animateSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; case LIGHT_SLIDE_AND_ALPHA: animateLightSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd); break; } } /** * Animate the background color of a view. * * @param view the view to animate * @param duration the duration of the animation * @param colorStart the background color to start with * @param colorEnd the background color to end with */ public static void animateBackgroundColor(final View view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "animateBackgroundColor() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final int[][] empty = {new int[0]}; final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); viewPropertyAnimator.addUpdateListener(animation -> ViewCompat.setBackgroundTintList(view, new ColorStateList(empty, new int[]{(int) animation.getAnimatedValue()}))); viewPropertyAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { ViewCompat.setBackgroundTintList(view, new ColorStateList(empty, new int[]{colorEnd})); } @Override public void onAnimationCancel(final Animator animation) { onAnimationEnd(animation); } }); viewPropertyAnimator.start(); } /** * Animate the text color of any view that extends {@link TextView} (Buttons, EditText...). * * @param view the text view to animate * @param duration the duration of the animation * @param colorStart the text color to start with * @param colorEnd the text color to end with */ public static void animateTextColor(final TextView view, final long duration, @ColorInt final int colorStart, @ColorInt final int colorEnd) { if (DEBUG) { Log.d(TAG, "animateTextColor() called with: " + "view = [" + view + "], duration = [" + duration + "], " + "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]"); } final ValueAnimator viewPropertyAnimator = ValueAnimator .ofObject(new ArgbEvaluator(), colorStart, colorEnd); viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator()); viewPropertyAnimator.setDuration(duration); viewPropertyAnimator.addUpdateListener(animation -> view.setTextColor((int) animation.getAnimatedValue())); viewPropertyAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setTextColor(colorEnd); } @Override public void onAnimationCancel(final Animator animation) { view.setTextColor(colorEnd); } }); viewPropertyAnimator.start(); } public static ValueAnimator animateHeight(final View view, final long duration, final int targetHeight) { final int height = view.getHeight(); if (DEBUG) { Log.d(TAG, "animateHeight: duration = [" + duration + "], " + "from " + height + " to → " + targetHeight + " in: " + view); } final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight); animator.setInterpolator(new FastOutSlowInInterpolator()); animator.setDuration(duration); animator.addUpdateListener(animation -> { final float value = (float) animation.getAnimatedValue(); view.getLayoutParams().height = (int) value; view.requestLayout(); }); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } @Override public void onAnimationCancel(final Animator animation) { view.getLayoutParams().height = targetHeight; view.requestLayout(); } }); animator.start(); return animator; } public static void animateRotation(final View view, final long duration, final int targetRotation) { if (DEBUG) { Log.d(TAG, "animateRotation: duration = [" + duration + "], " + "from " + view.getRotation() + " to → " + targetRotation + " in: " + view); } view.animate().setListener(null).cancel(); view.animate() .rotation(targetRotation).setDuration(duration) .setInterpolator(new FastOutSlowInInterpolator()) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationCancel(final Animator animation) { view.setRotation(targetRotation); } @Override public void onAnimationEnd(final Animator animation) { view.setRotation(targetRotation); } }).start(); } private static void animateAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(0f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } /*////////////////////////////////////////////////////////////////////////// // Internals //////////////////////////////////////////////////////////////////////////*/ private static void animateScaleAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setScaleX(.8f); view.setScaleY(.8f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).scaleX(.8f).scaleY(.8f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateLightScaleAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setAlpha(.5f); view.setScaleX(.95f); view.setScaleY(.95f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(1f).scaleX(1f).scaleY(1f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.setAlpha(1f); view.setScaleX(1f); view.setScaleY(1f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).scaleX(.95f).scaleY(.95f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateSlideAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight()); view.setAlpha(0f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate() .setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).translationY(-view.getHeight()) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } private static void animateLightSlideAndAlpha(final View view, final boolean enterOrExit, final long duration, final long delay, final Runnable execOnEnd) { if (enterOrExit) { view.setTranslationY(-view.getHeight() / 2.0f); view.setAlpha(0f); view.animate() .setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } else { view.animate().setInterpolator(new FastOutSlowInInterpolator()) .alpha(0f).translationY(-view.getHeight() / 2.0f) .setDuration(duration).setStartDelay(delay) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(final Animator animation) { view.setVisibility(View.GONE); if (execOnEnd != null) { execOnEnd.run(); } } }).start(); } } public static void slideUp(final View view, final long duration, final long delay, @FloatRange(from = 0.0f, to = 1.0f) final float translationPercent) { final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels * (translationPercent)); view.animate().setListener(null).cancel(); view.setAlpha(0f); view.setTranslationY(translationY); view.setVisibility(View.VISIBLE); view.animate() .alpha(1f) .translationY(0) .setStartDelay(delay) .setDuration(duration) .setInterpolator(new FastOutSlowInInterpolator()) .start(); } public enum Type { ALPHA, SCALE_AND_ALPHA, LIGHT_SCALE_AND_ALPHA, SLIDE_AND_ALPHA, LIGHT_SLIDE_AND_ALPHA } }
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java
Java
gpl-3.0
20,120
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: FillGeneratorTool.java * * Copyright (c) 2006 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.generator.layout.fill; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.Tool; import com.sun.electric.tool.generator.layout.Gallery; import com.sun.electric.tool.generator.layout.LayoutLib; import com.sun.electric.tool.generator.layout.TechType; import java.lang.reflect.Constructor; import java.util.*; abstract class MetalFloorplanBase extends Floorplan { /** width Vdd wires */ public double vddWidth; /** width Gnd wires */ public double gndWidth; MetalFloorplanBase(double cellWidth, double cellHeight, boolean horiz) { super(cellWidth, cellHeight, horiz); vddWidth = gndWidth = 0; } } // ------------------------------ MetalFloorplanFlex ------------------------------ // Similar to Metalfloor but number of power/gnd lines is determined by cell size class MetalFloorplanFlex extends MetalFloorplanBase { public final double minWidth, space, vddReserve, gndReserve; MetalFloorplanFlex(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, double vddW, double gndW, boolean horiz) { super(cellWidth, cellHeight, horiz); this.vddWidth = vddW; //27; this.gndWidth = gndW; //20; this.space = space; this.vddReserve = vddReserve; this.gndReserve = gndReserve; minWidth = vddReserve + gndReserve + 2*space + 2*gndWidth + 2*vddWidth; } } // ------------------------------ MetalFloorplan ------------------------------ // Floor plan: // // half of Gnd reserved // gggggggggggggggggggg // wide space // vvvvvvvvvvvvvvvvvvvv // Vdd reserved // vvvvvvvvvvvvvvvvvvvv // wide space // gggggggggggggggggggg // half of Gnd reserved class MetalFloorplan extends MetalFloorplanBase { /** no gap between Vdd wires */ public final boolean mergedVdd; /** if horizontal then y coordinate of top Vdd wire * if vertical then x coordinate of right Vdd wire */ public final double vddCenter; /** if horizontal then y coordinate of top Gnd wire * if vertical then x coordinate of right Gnd wire */ public final double gndCenter; public final double coverage; private double roundDownOneLambda(double x) { return Math.floor(x); } // Round metal widths down to multiples of 1 lambda resolution. // Then metal center can be on 1/2 lambda grid without problems. MetalFloorplan(double cellWidth, double cellHeight, double vddReserve, double gndReserve, double space, boolean horiz) { super(cellWidth, cellHeight, horiz); mergedVdd = vddReserve==0; double cellSpace = horiz ? cellHeight : cellWidth; double metalSpace = cellSpace - 2*space - vddReserve - gndReserve; // gnd is always in two pieces gndWidth = roundDownOneLambda(metalSpace / 4); gndCenter = cellSpace/2 - gndReserve/2 - gndWidth/2; // vdd may be one or two pieces if (mergedVdd) { vddWidth = gndWidth*2; vddCenter = 0; } else { vddWidth = gndWidth; vddCenter = vddReserve/2 + vddWidth/2; } // compute coverage statistics double cellArea = cellWidth * cellHeight; double strapLength = horiz ? cellWidth : cellHeight; double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; double gndArea = 2 * gndWidth * strapLength; coverage = (vddArea + gndArea)/cellArea; } // Save this code in case I need to replicate LoCo FillCell exactly // MetalFloorplan(double cellWidth, double cellHeight, // double vddReserve, double gndReserve, // double space, boolean horiz) { // super(cellWidth, cellHeight, horiz); // mergedVdd = vddReserve==0; // double cellSpace = horiz ? cellHeight : cellWidth; // if (mergedVdd) { // double w = cellSpace/2 - space - vddReserve; // vddWidth = roundDownOneLambda(w); // vddCenter = 0; // } else { // double w = (cellSpace/2 - space - vddReserve) / 2; // vddWidth = roundDownOneLambda(w); // vddCenter = vddReserve/2 + vddWidth/2; // } // double vddEdge = vddCenter + vddWidth/2; // double w = cellSpace/2 - vddEdge - space - gndReserve/2; // gndWidth = roundDownOneLambda(w); // gndCenter = vddEdge + space + gndWidth/2; // // // compute coverage statistics // double cellArea = cellWidth * cellHeight; // double strapLength = horiz ? cellWidth : cellHeight; // double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength; // double gndArea = 2 * gndWidth * strapLength; // coverage = (vddArea + gndArea)/cellArea; // } } // ------------------------------- ExportBars --------------------------------- class ExportBar { PortInst[] ports = null; Double center = null; ExportBar(PortInst p1, PortInst p2, double c) { ports = new PortInst[2]; ports[0] = p1; ports[1] = p2; center = (c); // autoboxing } } class MetalLayer extends VddGndStraps { protected MetalFloorplanBase plan; protected int layerNum; protected PrimitiveNode pin; protected ArcProto metal; protected ArrayList<ExportBar> vddBars = new ArrayList<ExportBar>(); protected ArrayList<ExportBar> gndBars = new ArrayList<ExportBar>(); public boolean addExtraArc() { return true; } private void buildGnd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.gndWidth/2; pinY = plan.gndCenter; } else { pinX = plan.gndCenter; pinY = plan.cellHeight/2; // - plan.gndWidth/2; } PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.gndWidth, tl, tr); G.noExtendArc(metal, plan.gndWidth, bl, br); gndBars.add(new ExportBar(bl, br, -plan.gndCenter)); gndBars.add(new ExportBar(tl, tr, plan.gndCenter)); } else { G.noExtendArc(metal, plan.gndWidth, bl, tl); G.noExtendArc(metal, plan.gndWidth, br, tr); gndBars.add(new ExportBar(bl, tl, -plan.gndCenter)); gndBars.add(new ExportBar(br, tr, plan.gndCenter)); } } private void buildVdd(Cell cell) { double pinX, pinY; MetalFloorplan plan = (MetalFloorplan)this.plan; if (plan.horizontal) { pinX = plan.cellWidth/2; // - plan.vddWidth/2; pinY = plan.vddCenter; } else { pinX = plan.vddCenter; pinY = plan.cellHeight/2; // - plan.vddWidth/2; } if (plan.mergedVdd) { PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); G.noExtendArc(metal, plan.vddWidth, bl, tr); vddBars.add(new ExportBar(bl, tr, plan.vddCenter)); } else { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); if (plan.horizontal) { G.noExtendArc(metal, plan.vddWidth, tl, tr); G.noExtendArc(metal, plan.vddWidth, bl, br); vddBars.add(new ExportBar(bl, br, -plan.vddCenter)); vddBars.add(new ExportBar(tl, tr, plan.vddCenter)); } else { G.noExtendArc(metal, plan.vddWidth, bl, tl); G.noExtendArc(metal, plan.vddWidth, br, tr); vddBars.add(new ExportBar(bl, tl, -plan.vddCenter)); vddBars.add(new ExportBar(br, tr, plan.vddCenter)); } } } /** It has to be protected to be overwritten by sub classes */ protected void buildGndAndVdd(Cell cell) { buildGnd(cell); buildVdd(cell); } public MetalLayer(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t); this.plan = (MetalFloorplanBase)plan; this.layerNum = layerNum; metal = METALS[layerNum]; pin = PINS[layerNum]; buildGndAndVdd(cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return vddBars.size();} public double getVddCenter(int n) { return (vddBars.get(n).center); // autoboxing } public PortInst getVdd(int n, int pos) {return vddBars.get(n).ports[pos];} public double getVddWidth(int n) {return plan.vddWidth;} public int numGnd() {return gndBars.size();} public double getGndCenter(int n) { return (gndBars.get(n).center); // autoboxing } public PortInst getGnd(int n, int pos) {return gndBars.get(n).ports[pos];} public double getGndWidth(int n) {return (plan).gndWidth;} public PrimitiveNode getPinType() {return pin;} public ArcProto getMetalType() {return metal;} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return layerNum;} } // ------------------------------- MetalLayerFlex ----------------------------- class MetalLayerFlex extends MetalLayer { public MetalLayerFlex(TechType t, int layerNum, Floorplan plan, Cell cell) { super(t, layerNum, plan, cell); } public boolean addExtraArc() { return false; } // For automatic fill generator no extra arcs are wanted. protected void buildGndAndVdd(Cell cell) { double pinX, pinY; double limit = 0; MetalFloorplanFlex plan = (MetalFloorplanFlex)this.plan; if (plan.horizontal) { limit = plan.cellHeight/2; } else { limit = plan.cellWidth/2; } double position = 0; int i = 0; while (position < limit) { boolean even = (i%2==0); double maxDelta = 0, pos = 0; if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth; pos = plan.vddReserve/2 + plan.vddWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth; pos = plan.gndReserve/2 + plan.gndWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) { pinY = pos; pinX = plan.cellWidth/2; } else { pinX = pos; pinY = plan.cellHeight/2; } // Vdd if even, gnd if odd if (!even) addBars(cell, pinX, pinY, plan.gndWidth, gndBars); else addBars(cell, pinX, pinY, plan.vddWidth, vddBars); if (even) { maxDelta = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth; pos = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth/2 + position; } else { maxDelta = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth; pos = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth/2 + position; } if (position + maxDelta > limit) return; // border was reached if (plan.horizontal) pinY = pos; else pinX = pos; // Gnd if even, vdd if odd if (!even) { addBars(cell, pinX, pinY, plan.vddWidth, vddBars); position = ((plan.horizontal)?pinY:pinX) + plan.vddWidth/2 + plan.vddReserve/2; } else { addBars(cell, pinX, pinY, plan.gndWidth, gndBars); position = ((plan.horizontal)?pinY:pinX) + plan.gndWidth/2 + plan.gndReserve/2; } i++; } } private void addBars(Cell cell, double pinX, double pinY, double width, ArrayList<ExportBar> bars) { PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE, G.DEF_SIZE, 0, cell ).getOnlyPortInst(); double center = 0; if (plan.horizontal) { G.noExtendArc(metal, width, tl, tr); G.noExtendArc(metal, width, bl, br); center = pinY; bars.add(new ExportBar(bl, br, -center)); bars.add(new ExportBar(tl, tr, center)); } else { G.noExtendArc(metal, width, bl, tl); G.noExtendArc(metal, width, br, tr); center = pinX; bars.add(new ExportBar(bl, tl, -center)); bars.add(new ExportBar(br, tr, center)); } } } //---------------------------------- CapLayer --------------------------------- class CapLayer extends VddGndStraps { private CapCell capCell; private NodeInst capCellInst; private CapFloorplan plan; public boolean addExtraArc() { return true; } public CapLayer(TechType t, CapFloorplan plan, CapCell capCell, Cell cell) { super(t); this.plan = plan; this.capCell = capCell; double angle = plan.horizontal ? 0 : 90; if (capCell != null) capCellInst = LayoutLib.newNodeInst(capCell.getCell(), 0, 0, G.DEF_SIZE, G.DEF_SIZE, angle, cell); } public boolean isHorizontal() {return plan.horizontal;} public int numVdd() {return (capCell != null) ? capCell.numVdd() : 0;} public PortInst getVdd(int n, int pos) { return capCellInst.findPortInst(FillCell.VDD_NAME+"_"+n); } public double getVddCenter(int n) { EPoint center = getVdd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getVddWidth(int n) {return capCell.getVddWidth();} public int numGnd() {return (capCell != null) ? capCell.numGnd() : 0;} public PortInst getGnd(int n, int pos) { return capCellInst.findPortInst(FillCell.GND_NAME+"_"+n); } public double getGndCenter(int n) { EPoint center = getGnd(n, 0).getCenter(); return plan.horizontal ? center.getY() : center.getX(); } public double getGndWidth(int n) {return capCell.getGndWidth();} public PrimitiveNode getPinType() {return tech.m1pin();} public ArcProto getMetalType() {return tech.m1();} public double getCellWidth() {return plan.cellWidth;} public double getCellHeight() {return plan.cellHeight;} public int getLayerNumber() {return 1;} } class FillRouter { private HashMap<String,List<PortInst>> portMap = new HashMap<String,List<PortInst>>(); private TechType tech; private String makeKey(PortInst pi) { EPoint center = pi.getCenter(); String x = ""+center.getX(); // LayoutLib.roundCenterX(pi); String y = ""+center.getY(); // LayoutLib.roundCenterY(pi); return x+"x"+y; } // private boolean bothConnect(ArcProto a, PortProto pp1, PortProto pp2) { // return pp1.connectsTo(a) && pp2.connectsTo(a); // } private ArcProto findCommonArc(PortInst p1, PortInst p2) { ArcProto[] metals = {tech.m6(), tech.m5(), tech.m4(), tech.m3(), tech.m2(), tech.m1()}; PortProto pp1 = p1.getPortProto(); PortProto pp2 = p2.getPortProto(); for (int i=0; i<metals.length; i++) { if (pp1.connectsTo(metals[i]) && pp2.connectsTo(metals[i])) { return metals[i]; } } return null; } private void connectPorts(List<PortInst> ports) { for (Iterator<PortInst> it=ports.iterator(); it.hasNext(); ) { PortInst first = it.next(); double width = LayoutLib.widestWireWidth(first); it.remove(); for (PortInst pi : ports) { ArcProto a = findCommonArc(first, pi); if (a!=null) LayoutLib.newArcInst(a, width, first, pi); } } } private FillRouter(TechType t, ArrayList<PortInst> ports) { tech = t; for (PortInst pi : ports) { String key = makeKey(pi); List<PortInst> l = portMap.get(key); if (l==null) { l = new LinkedList<PortInst>(); portMap.put(key, l); } l.add(pi); } // to guarantee deterministic results List<String> keys = new ArrayList<String>(); keys.addAll(portMap.keySet()); Collections.sort(keys); for (String str : keys) { connectPorts(portMap.get(str)); } } public static void connectCoincident(TechType t, ArrayList<PortInst> ports) { new FillRouter(t, ports); } } /** * Object for building fill libraries */ public class FillGeneratorTool extends Tool { public FillGenConfig config; protected Library lib; private boolean libInitialized; public List<Cell> masters; protected CapCell capCell; protected Floorplan[] plans; /** the fill generator tool. */ private static FillGeneratorTool tool = getTool(); // Depending on generator plugin available public static FillGeneratorTool getTool() { if (tool != null) return tool; FillGeneratorTool tool; try { Class<?> extraClass = Class.forName("com.sun.electric.plugins.generator.FillCellTool"); Constructor instance = extraClass.getDeclaredConstructor(); // varags Object obj = instance.newInstance(); // varargs; tool = (FillGeneratorTool)obj; } catch (Exception e) { if (Job.getDebug()) System.out.println("GNU Release can't find Fill Cell Generator plugin"); tool = new FillGeneratorTool(); } return tool; } public FillGeneratorTool() { super("Fill Generator"); } public void setConfig(FillGenConfig config) { this.config = config; this.libInitialized = false; } public enum Units {NONE, LAMBDA, TRACKS} protected boolean getOrientation() {return plans[plans.length-1].horizontal;} /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param reserved space to reserve in the middle of the central * strap in case of Vdd. The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * Space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * */ private double reservedToLambda(int layer, double reserved, Units units) { if (units==LAMBDA) return reserved; double nbTracks = reserved; if (nbTracks==0) return 0; return config.getTechType().reservedToLambda(layer, nbTracks); } private Floorplan[] makeFloorplans(boolean metalFlex, boolean hierFlex) { Job.error(config.width==Double.NaN, "width hasn't been specified. use setWidth()"); Job.error(config.height==Double.NaN, "height hasn't been specified. use setHeight()"); double w = config.width; double h = config.height; int numLayers = config.getTechType().getNumMetals() + 1; // one extra for the cap double[] vddRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndRes = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] vddW = new double[numLayers]; //{0,0,0,0,0,0,0}; double[] gndW = new double[numLayers]; //{0,0,0,0,0,0,0}; // set given values for (FillGenConfig.ReserveConfig c : config.reserves) { vddRes[c.layer] = reservedToLambda(c.layer, c.vddReserved, c.vddUnits); gndRes[c.layer] = reservedToLambda(c.layer, c.gndReserved, c.gndUnits); if (c.vddWUnits != Units.NONE) vddW[c.layer] = reservedToLambda(c.layer, c.vddWidth, c.vddWUnits); if (c.gndWUnits != Units.NONE) gndW[c.layer] = reservedToLambda(c.layer, c.gndWidth, c.gndWUnits); } boolean evenHor = config.evenLayersHorizontal; boolean alignedMetals = true; double[] spacing = new double[numLayers]; for (int i = 0; i < numLayers; i++) spacing[i] = config.drcSpacingRule; // {config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule, // config.drcSpacingRule,config.drcSpacingRule,config.drcSpacingRule}; if (alignedMetals) { double maxVddRes = 0, maxGndRes = 0, maxSpacing = 0, maxVddW = 0, maxGndW = 0; for (int i = 0; i < vddRes.length; i++) { boolean vddOK = false, gndOK = false; if (vddRes[i] > 0) { vddOK = true; if (maxVddRes < vddRes[i]) maxVddRes = vddRes[i]; } if (gndRes[i] > 0) { gndOK = true; if (maxGndRes < gndRes[i]) maxGndRes = gndRes[i]; } if (gndOK || vddOK) // checking max spacing rule { if (maxSpacing < config.drcSpacingRule) maxSpacing = config.drcSpacingRule; //drcRules[i]; } if (maxVddW < vddW[i]) maxVddW = vddW[i]; if (maxGndW < gndW[i]) maxGndW = gndW[i]; } // correct the values for (int i = 0; i < vddRes.length; i++) { vddRes[i] = maxVddRes; gndRes[i] = maxGndRes; spacing[i] = maxSpacing; vddW[i] = maxVddW; gndW[i] = maxGndW; } } Floorplan[] thePlans = new Floorplan[numLayers]; // 0 is always null thePlans[1] = new CapFloorplan(w, h, !evenHor); if (metalFlex) { if (!hierFlex) { for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplanFlex(w, h, vddRes[i], gndRes[i], spacing[i], vddW[i], gndW[i], horiz); } return thePlans; } w = config.width = config.minTileSizeX; h = config.height = config.minTileSizeY; } for (int i = 2; i < numLayers; i++) { boolean horiz = (i%2==0); thePlans[i] = new MetalFloorplan(w, h, vddRes[i], gndRes[i], spacing[i], horiz); } return thePlans; } private void printCoverage(Floorplan[] plans) { for (int i=2; i<plans.length; i++) { System.out.println("metal-"+i+" coverage: "+ ((MetalFloorplan)plans[i]).coverage); } } private static CapCell getCMOS90CapCell(Library lib, CapFloorplan plan) { CapCell c = null; try { Class<?> cmos90Class = Class.forName("com.sun.electric.plugins.tsmc.fill90nm.CapCellCMOS90"); Constructor capCellC = cmos90Class.getDeclaredConstructor(Library.class, CapFloorplan.class); // varargs Object cell = capCellC.newInstance(lib, plan); c = (CapCell)cell; } catch (Exception e) { assert(false); // runtime error } return c; } protected void initFillParameters(boolean metalFlex, boolean hierFlex) { if (libInitialized) return; Job.error(config.fillLibName==null, "no library specified. Use setFillLibrary()"); Job.error((config.width==Double.NaN || config.width<=0), "no width specified. Use setFillCellWidth()"); Job.error((config.height==Double.NaN || config.height<=0), "no height specified. Use setFillCellHeight()"); plans = makeFloorplans(metalFlex, hierFlex); if (!metalFlex) printCoverage(plans); lib = LayoutLib.openLibForWrite(config.fillLibName); if (!metalFlex) // don't do transistors { if (config.is180Tech()) { capCell = new CapCellMosis(lib, (CapFloorplan) plans[1], config.getTechType()); } else { capCell = getCMOS90CapCell(lib, (CapFloorplan) plans[1]); } } libInitialized = true; } private void makeTiledCells(Cell cell, Floorplan[] plans, Library lib, int[] tiledSizes) { if (tiledSizes==null) return; for (int num : tiledSizes) { TiledCell.makeTiledCell(num, num, cell, plans, lib); } } public static Cell makeFillCell(Library lib, Floorplan[] plans, int botLayer, int topLayer, CapCell capCell, TechType tech, ExportConfig expCfg, boolean metalFlex, boolean hierFlex) { FillCell fc = new FillCell(tech); return fc.makeFillCell1(lib, plans, botLayer, topLayer, capCell, expCfg, metalFlex, hierFlex); } /** * Method to create standard set of tiled cells. */ private Cell standardMakeAndTileCell(Library lib, Floorplan[] plans, int lowLay, int hiLay, CapCell capCell, TechType tech, ExportConfig expCfg, int[] tiledSizes, boolean metalFlex) { Cell master = makeFillCell(lib, plans, lowLay, hiLay, capCell, tech, expCfg, metalFlex, false); masters = new ArrayList<Cell>(); masters.add(master); makeTiledCells(master, plans, lib, tiledSizes); return master; } public static final Units LAMBDA = Units.LAMBDA; public static final Units TRACKS = Units.TRACKS; //public static final PowerType POWER = PowerType.POWER; //public static final PowerType VDD = PowerType.VDD; public static final ExportConfig PERIMETER = ExportConfig.PERIMETER; public static final ExportConfig PERIMETER_AND_INTERNAL = ExportConfig.PERIMETER_AND_INTERNAL; /** Reserve space in the middle of the Vdd and ground straps for signals. * @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer * number 1 is reserved to mean "capacitor between Vdd and ground". * @param vddReserved space to reserve in the middle of the central Vdd * strap. * The value 0 makes the Vdd strap one large strap instead of two smaller * adjacent straps. * @param vddUnits LAMBDA or TRACKS * @param gndReserved space to reserve between the ground strap of this * cell and the ground strap of the adjacent fill cell. The value 0 means * that these two ground straps should abut to form a single large strap * instead of two smaller adjacent straps. * @param gndUnits LAMBDA or TRACKS * param tiledSizes an array of sizes. The default value is null. The * value null means don't generate anything. */ // public void reserveSpaceOnLayer(int layer, // double vddReserved, Units vddUnits, // double gndReserved, Units gndUnits) { // LayoutLib.error(layer<2 || layer>6, // "Bad layer. Layers must be between 2 and 6 inclusive: "+ // layer); // this.vddReserved[layer] = reservedToLambda(layer, vddReserved, vddUnits); // this.gndReserved[layer] = reservedToLambda(layer, gndReserved, gndUnits); // } /** Create a fill cell using the current library, fill cell width, fill cell * height, layer orientation, and reserved spaces for each layer. Then * generate larger fill cells by tiling that fill cell according to the * current tiled cell sizes. * @param loLayer the lower layer. This may be 1 through 6. Layer 1 means * build a capacitor using MOS transistors between Vdd and ground. * @param hiLayer the upper layer. This may be 2 through 6. Note that hiLayer * must be >= loLayer. * @param exportConfig may be PERIMETER in which case exports are * placed along the perimeter of the cell for the top two layers. Otherwise * exportConfig must be PERIMETER_AND_INTERNAL in which case exports are * placed inside the perimeter of the cell for the bottom layer. * @param tiledSizes Array specifying composite Cells we should build by * concatonating fill cells. For example int[] {2, 4, 7} means we should * */ public Cell standardMakeFillCell(int loLayer, int hiLayer, TechType tech, ExportConfig exportConfig, int[] tiledSizes, boolean metalFlex) { initFillParameters(metalFlex, false); Job.error(loLayer<1, "loLayer must be >=1"); int maxNumMetals = config.getTechType().getNumMetals(); Job.error(hiLayer>maxNumMetals, "hiLayer must be <=" + maxNumMetals); Job.error(loLayer>hiLayer, "loLayer must be <= hiLayer"); Cell cell = null; cell = standardMakeAndTileCell(lib, plans, loLayer, hiLayer, capCell, tech, exportConfig, tiledSizes, metalFlex); return cell; } public void makeGallery() { Gallery.makeGallery(lib); } public void writeLibrary(int backupScheme) throws JobException { LayoutLib.writeLibrary(lib, backupScheme); } public enum FillTypeEnum {INVALID,TEMPLATE,CELL} }
imr/Electric8
com/sun/electric/tool/generator/layout/fill/FillGeneratorTool.java
Java
gpl-3.0
32,233
package com.lizardtech.djvubean.outline; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; public class ImageListCellRenderer implements ListCellRenderer { /** * From <a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:" title="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:">http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:</a> * * Return a component that has been configured to display the specified value. * That component's paint method is then called to "render" the cell. * If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, * this method is called to generate a component on which getPreferredSize can be invoked. * * jlist - the jlist we're painting * value - the value returned by list.getModel().getElementAt(index). * cellIndex - the cell index * isSelected - true if the specified cell is currently selected * cellHasFocus - true if the cell has focus */ public Component getListCellRendererComponent(JList jlist, Object value, int cellIndex, boolean isSelected, boolean cellHasFocus) { if (value instanceof JPanel) { Component component = (Component) value; component.setForeground (Color.white); component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white); return component; } else { // TODO - I get one String here when the JList is first rendered; proper way to deal with this? //System.out.println("Got something besides a JPanel: " + value.getClass().getCanonicalName()); return new JLabel("???"); } }}
DJVUpp/Desktop
djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/com/lizardtech/djvubean/outline/ImageListCellRenderer.java
Java
gpl-3.0
2,058
/* * Copyright (c) by Michał Niedźwiecki 2016 * Contact: nkg753 on gmail or via GitHub profile: dzwiedziu-nkg * * This file is part of Bike Road Quality. * * Bike Road Quality is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Bike Road Quality is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package pl.nkg.brq.android.ui; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import pl.nkg.brq.android.R; import pl.nkg.brq.android.events.SensorsRecord; import pl.nkg.brq.android.events.SensorsServiceState; import pl.nkg.brq.android.services.SensorsService; public class MainActivity extends AppCompatActivity { private static final int MY_PERMISSION_RESPONSE = 29; @Bind(R.id.button_on) Button mButtonOn; @Bind(R.id.button_off) Button mButtonOff; @Bind(R.id.speedTextView) TextView mSpeedTextView; @Bind(R.id.altitudeTextView) TextView mAltitudeTextView; @Bind(R.id.shakeTextView) TextView mShakeTextView; @Bind(R.id.noiseTextView) TextView mNoiseTextView; @Bind(R.id.distanceTextView) TextView mDistanceTextView; @Bind(R.id.warningTextView) TextView mWarningTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Prompt for permissions if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Log.w("BleActivity", "Location access not granted!"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, MY_PERMISSION_RESPONSE); } } ButterKnife.bind(this); } @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @OnClick(R.id.button_on) public void onButtonOnClick() { startService(new Intent(MainActivity.this, SensorsService.class)); } @OnClick(R.id.button_off) public void onButtonOffClick() { stopService(new Intent(MainActivity.this, SensorsService.class)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsServiceState state) { } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(SensorsRecord record) { mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h"); mAltitudeTextView.setText((int) record.altitude + " m n.p.m."); mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²"); mNoiseTextView.setText((int) record.soundNoise + " db"); mDistanceTextView.setText((double) record.distance / 100.0 + " m"); if (record.distance < 120 && record.distance != 0) { mWarningTextView.setVisibility(View.VISIBLE); mWarningTextView.setText((double) record.distance / 100.0 + " m"); mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100)); } else { mWarningTextView.setVisibility(View.GONE); } } }
dzwiedziu-nkg/cyclo-bruxism
proof-of-concept/apk/app/src/main/java/pl/nkg/brq/android/ui/MainActivity.java
Java
gpl-3.0
5,333
package com.malak.yaim.model; import java.util.List; public class FlickrFeed { private String title; private String link; private String description; private String modified; private String generator; private List<Item> items = null; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public String getGenerator() { return generator; } public void setGenerator(String generator) { this.generator = generator; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } }
xavarius/FlickrFeed
app/src/main/java/com/malak/yaim/model/FlickrFeed.java
Java
gpl-3.0
1,050
package grid; import java.util.Comparator; import world.World; /* * AP(r) Computer Science GridWorld Case Study: * Copyright(c) 2002-2006 College Entrance Examination Board * (http://www.collegeboard.com). * * This code is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Alyce Brady * @author Chris Nevison * @author APCS Development Committee * @author Cay Horstmann */ /** * A <code>Location</code> object represents the row and column of a location * in a two-dimensional grid. <br /> * The API of this class is testable on the AP CS A and AB exams. */ public class Location implements Comparable { private int row; // row location in grid private int col; // column location in grid /** * The turn angle for turning 90 degrees to the left. */ public static final int LEFT = -90; /** * The turn angle for turning 90 degrees to the right. */ public static final int RIGHT = 90; /** * The turn angle for turning 45 degrees to the left. */ public static final int HALF_LEFT = -45; /** * The turn angle for turning 45 degrees to the right. */ public static final int HALF_RIGHT = 45; /** * The turn angle for turning a full circle. */ public static final int FULL_CIRCLE = 360; /** * The turn angle for turning a half circle. */ public static final int HALF_CIRCLE = 180; /** * The turn angle for making no turn. */ public static final int AHEAD = 0; /** * The compass direction for north. */ public static final int NORTH = 0; /** * The compass direction for northeast. */ public static final int NORTHEAST = 45; /** * The compass direction for east. */ public static final int EAST = 90; /** * The compass direction for southeast. */ public static final int SOUTHEAST = 135; /** * The compass direction for south. */ public static final int SOUTH = 180; /** * The compass direction for southwest. */ public static final int SOUTHWEST = 225; /** * The compass direction for west. */ public static final int WEST = 270; /** * The compass direction for northwest. */ public static final int NORTHWEST = 315; /** * Constructs a location with given row and column coordinates. * @param r the row * @param c the column */ public Location(int r, int c) { row = r; col = c; } /** * Gets the row coordinate. * @return the row of this location */ public int getRow() { return row; } /** * Gets the column coordinate. * @return the column of this location */ public int getCol() { return col; } /** * Gets the adjacent location in any one of the eight compass directions. * @param direction the direction in which to find a neighbor location * @return the adjacent location in the direction that is closest to * <tt>direction</tt> */ public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); } /** * Returns the direction from this location toward another location. The * direction is rounded to the nearest compass direction. * @param target a location that is different from this location * @return the closest compass direction from this location toward * <code>target</code> */ public int getDirectionToward(Location target) { int dx = target.getCol() - getCol(); int dy = target.getRow() - getRow(); // y axis points opposite to mathematical orientation int angle = (int) Math.toDegrees(Math.atan2(-dy, dx)); // mathematical angle is counterclockwise from x-axis, // compass angle is clockwise from y-axis int compassAngle = RIGHT - angle; // prepare for truncating division by 45 degrees compassAngle += HALF_RIGHT / 2; // wrap negative angles if (compassAngle < 0) compassAngle += FULL_CIRCLE; // round to nearest multiple of 45 return (compassAngle / HALF_RIGHT) * HALF_RIGHT; } /** * Indicates whether some other <code>Location</code> object is "equal to" * this one. * @param other the other location to test * @return <code>true</code> if <code>other</code> is a * <code>Location</code> with the same row and column as this location; * <code>false</code> otherwise */ public boolean equals(Object other) { if (!(other instanceof Location)) return false; Location otherLoc = (Location) other; return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol(); } /** * Generates a hash code. * @return a hash code for this location */ public int hashCode() { return getRow() * 3737 + getCol(); } /** * Compares this location to <code>other</code> for ordering. Returns a * negative integer, zero, or a positive integer as this location is less * than, equal to, or greater than <code>other</code>. Locations are * ordered in row-major order. <br /> * (Precondition: <code>other</code> is a <code>Location</code> object.) * @param other the other location to test * @return a negative integer if this location is less than * <code>other</code>, zero if the two locations are equal, or a positive * integer if this location is greater than <code>other</code> */ public int compareTo(Object other) { Location otherLoc = (Location) other; if (getRow() < otherLoc.getRow()) return -1; if (getRow() > otherLoc.getRow()) return 1; if (getCol() < otherLoc.getCol()) return -1; if (getCol() > otherLoc.getCol()) return 1; return 0; } /** * (Added for RatBots) Calculates the distance to another location. * The distance is reported as the sum of the x and y distances * and therefore doesn't consider diagonal movement. * @param other the location that the distance is calculated to * @return the distance */ public int distanceTo(Location other) { int dx = Math.abs(row - other.getRow()); int dy = Math.abs(col - other.getCol()); return dx+dy; } public boolean isValidLocation() { if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS) return false; if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS) return false; return true; } /** * Creates a string that describes this location. * @return a string with the row and column of this location, in the format * (row, col) */ public String toString() { return "(r:" + getRow() + ", c:" + getCol() + ")"; } }
fazerlicourice7/botWorld2017
src/grid/Location.java
Java
gpl-3.0
8,439
/* This file is part of LiveCG. * * Copyright (C) 2013 Sebastian Kuerten * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.topobyte.livecg.ui.geometryeditor.preferences; import java.awt.Component; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.plaf.basic.BasicComboBoxRenderer; import de.topobyte.livecg.preferences.Configuration; public class LAFSelector extends JComboBox { private static final long serialVersionUID = 6856865390726849784L; public LAFSelector(Configuration configuration) { super(buildValues()); setRenderer(new Renderer()); setEditable(false); String lookAndFeel = configuration.getSelectedLookAndFeel(); setSelectedIndex(-1); for (int i = 0; i < getModel().getSize(); i++) { LookAndFeelInfo info = (LookAndFeelInfo) getModel().getElementAt(i); if (info.getClassName().equals(lookAndFeel)) { setSelectedIndex(i); break; } } } private static LookAndFeelInfo[] buildValues() { LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); return lafs; } private class Renderer extends BasicComboBoxRenderer { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { LookAndFeelInfo item = (LookAndFeelInfo) value; setText(item.getName()); } else { setText("default"); } return this; } } }
sebkur/live-cg
project/src/main/java/de/topobyte/livecg/ui/geometryeditor/preferences/LAFSelector.java
Java
gpl-3.0
2,265
package com.yoavst.quickapps.calendar; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.CalendarContract; import android.provider.CalendarContract.Events; import com.yoavst.quickapps.Preferences_; import com.yoavst.quickapps.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.TimeZone; import static android.provider.CalendarContract.Events.ALL_DAY; import static android.provider.CalendarContract.Events.DISPLAY_COLOR; import static android.provider.CalendarContract.Events.DTEND; import static android.provider.CalendarContract.Events.DTSTART; import static android.provider.CalendarContract.Events.DURATION; import static android.provider.CalendarContract.Events.EVENT_LOCATION; import static android.provider.CalendarContract.Events.RRULE; import static android.provider.CalendarContract.Events.TITLE; import static android.provider.CalendarContract.Events._ID; /** * Created by Yoav. */ public class CalendarUtil { private CalendarUtil() { } private static final SimpleDateFormat dayFormatter = new SimpleDateFormat( "EEE, MMM d, yyyy"); private static final SimpleDateFormat dateFormatter = new SimpleDateFormat( "EEE, MMM d, HH:mm"); private static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH:mm"); private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("EEE, MMM d"); private static final SimpleDateFormat otherDayFormatter = new SimpleDateFormat("MMM d, HH:mm"); private static final TimeZone timezone = Calendar.getInstance().getTimeZone(); public static ArrayList<Event> getCalendarEvents(Context context) { CalendarResources.init(context); boolean showRepeating = new Preferences_(context).showRepeatingEvents().get(); ArrayList<Event> events = new ArrayList<>(); String selection = "((" + DTSTART + " >= ?) OR (" + DTEND + " >= ?))"; String milli = String.valueOf(System.currentTimeMillis()); String[] selectionArgs = new String[]{milli, milli}; Cursor cursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, DTEND, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, selection, selectionArgs, null ); cursor.moveToFirst(); int count = cursor.getCount(); if (count != 0) { //<editor-fold desc="Future Events"> for (int i = 0; i < count; i++) { int id = cursor.getInt(0); String title = cursor.getString(1); long startDate = Long.parseLong(cursor.getString(2)); String endDateString = cursor.getString(3); String location = cursor.getString(4); boolean isAllDay = cursor.getInt(5) != 0; int color = cursor.getInt(6); String rRule = cursor.getString(7); String duration = cursor.getString(8); if (!isAllDay) { // If the event not repeat itself - regular event if (rRule == null) { long endDate = endDateString == null || endDateString.equals("null") ? 0 : Long.parseLong(endDateString); if (endDate == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else events.add(new Event(id, title, startDate, endDate, location).setColor(color)); } else if (showRepeating) { // Event that repeat itself events = addEvents(events, getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false)); } } else { if (rRule == null) { // One day event probably if (endDateString == null || Long.parseLong(endDateString) == 0) events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color)); else if (showRepeating) { int offset = timezone.getOffset(startDate); long newTime = startDate - offset; long endTime = Long.parseLong(endDateString) - offset; events.add(new Event(id, title, newTime, endTime, location, true).setColor(color)); } } else if (showRepeating) { // Repeat all day event, god why?!? events = addEvents(events, getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true)); } } cursor.moveToNext(); } //</editor-fold> } cursor.close(); if (showRepeating) { String repeatingSections = "((" + DURATION + " IS NOT NULL) AND (" + RRULE + " IS NOT NULL) AND ((" + DTSTART + " < ?) OR (" + DTEND + " < ?)))"; Cursor repeatingCursor = context.getContentResolver() .query( Events.CONTENT_URI, new String[]{_ID, TITLE, DTSTART, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, repeatingSections, selectionArgs, null ); repeatingCursor.moveToFirst(); int repeatingCount = repeatingCursor.getCount(); if (repeatingCount != 0) { //<editor-fold desc="repeating past Events"> for (int i = 0; i < repeatingCount; i++) { int id = repeatingCursor.getInt(0); String title = repeatingCursor.getString(1); long startDate = Long.parseLong(repeatingCursor.getString(2)); String location = repeatingCursor.getString(3); boolean isAllDay = repeatingCursor.getInt(4) != 0; int color = repeatingCursor.getInt(5); String rRule = repeatingCursor.getString(6); String duration = repeatingCursor.getString(7); if (!isAllDay) { ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false); events = addEvents(events, repeatingEvents); } else { ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true); events = addEvents(events, repeatingEvents); } repeatingCursor.moveToNext(); } //</editor-fold> repeatingCursor.close(); } } Collections.sort(events, new Comparator<Event>() { @Override //an integer < 0 if lhs is less than rhs, 0 if they are equal, and > 0 if lhs is greater than rhs. public int compare(Event lhs, Event rhs) { int first = (lhs.getStartDate() - rhs.getStartDate()) < 0 ? -1 : lhs.getStartDate() == rhs.getStartDate() ? 0 : 1; int second = (lhs.getEndDate() - rhs.getEndDate()) < 0 ? -1 : lhs.getEndDate() == rhs.getEndDate() ? 0 : 1; return first != 0 ? first : second; } }); return events; } private static ArrayList<Event> addEvents(ArrayList<Event> list, ArrayList<Event> toAdd) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 6); long milli = DateUtils.clearTime(calendar).getTimeInMillis(); long now = System.currentTimeMillis(); for (Event event : toAdd) { if (event.getEndDate() <= milli && event.getEndDate() >= now) list.add(event); } return list; } private static ArrayList<Event> getEventFromRepeating(Context context, String rRule, long startDate, String duration, String location, int color, String title, int id, boolean isAllDay) { ArrayList<Event> events = new ArrayList<>(); final String[] INSTANCE_PROJECTION = new String[]{ CalendarContract.Instances.EVENT_ID, // 0 CalendarContract.Instances.BEGIN, // 1 CalendarContract.Instances.END // 2 }; Calendar endTime = Calendar.getInstance(); endTime.add(Calendar.MONTH, 6); String selection = CalendarContract.Instances.EVENT_ID + " = ?"; Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, System.currentTimeMillis()); ContentUris.appendId(builder, endTime.getTimeInMillis()); Cursor cursor = context.getContentResolver().query(builder.build(), INSTANCE_PROJECTION, selection, new String[]{Integer.toString(id)}, null); if (cursor.moveToFirst()) { do { events.add(new Event(id, title, cursor.getLong(1) - (isAllDay ? timezone.getOffset(startDate) : 0), cursor.getLong(2) - (isAllDay ? timezone.getOffset(startDate) : 0), location, isAllDay).setColor(color)); } while (cursor.moveToNext()); } return events; } public static String getDateFromEvent(Event event) { if (event.getDate() != null) return event.getDate(); else if (event.isAllDay()) { Calendar startPlusOneDay = Calendar.getInstance(); startPlusOneDay.setTimeInMillis(event.getStartDate()); startPlusOneDay.add(Calendar.DAY_OF_YEAR, 1); Calendar endTime = Calendar.getInstance(); endTime.setTimeInMillis(event.getEndDate()); if (DateUtils.isSameDay(startPlusOneDay, endTime)) { startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) return CalendarResources.today + " " + CalendarResources.allDay; else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " " + CalendarResources.allDay; return dayFormatter.format(new Date(event.getStartDate())); } else { endTime.add(Calendar.DAY_OF_YEAR, -1); startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1); if (DateUtils.isToday(startPlusOneDay)) { if (DateUtils.isTomorrow(endTime)) return CalendarResources.today + " - " + CalendarResources.tomorrow; else return CalendarResources.today + " " + CalendarResources.allDay + " - " + fullDateFormat.format(endTime.getTime()); } else if (DateUtils.isTomorrow(startPlusOneDay)) return CalendarResources.tomorrow + " - " + fullDateFormat.format(endTime.getTime()); return fullDateFormat.format(new Date(event.getStartDate())) + " - " + fullDateFormat.format(endTime.getTime()); } } else { String text; Date first = new Date(event.getStartDate()); Date end = new Date(event.getEndDate()); if (DateUtils.isSameDay(first, end)) { if (DateUtils.isToday(first)) text = CalendarResources.today + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else if (DateUtils.isWithinDaysFuture(first, 1)) text = CalendarResources.tomorrow + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end); else text = dateFormatter.format(first) + " - " + hourFormatter.format(end); } else if (DateUtils.isToday(first)) { text = CalendarResources.today + hourFormatter.format(first) + " - " + otherDayFormatter.format(end); } else { text = otherDayFormatter.format(first) + " - " + otherDayFormatter.format(end); } return text; } } public static Intent launchEventById(long id) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri.Builder uri = Events.CONTENT_URI.buildUpon(); uri.appendPath(Long.toString(id)); intent.setData(uri.build()); return intent; } public static String getTimeToEvent(Event event) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(event.getStartDate()); Calendar now = Calendar.getInstance(); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (calendar.getTimeInMillis() <= now.getTimeInMillis()) return CalendarResources.now; else { long secondsLeft = (calendar.getTimeInMillis() - now.getTimeInMillis()) / 1000; if (secondsLeft < 60) return CalendarResources.in + " 1 " + CalendarResources.minute; long minutesLeft = secondsLeft / 60; if (minutesLeft < 60) return CalendarResources.in + " " + minutesLeft + " " + (minutesLeft > 1 ? CalendarResources.minutes : CalendarResources.minute); long hoursLeft = minutesLeft / 50; if (hoursLeft < 24) return CalendarResources.in + " " + hoursLeft + " " + (hoursLeft > 1 ? CalendarResources.hours : CalendarResources.hour); int days = (int) (hoursLeft / 24); if (days < 30) return CalendarResources.in + " " + days + " " + (days > 1 ? CalendarResources.days : CalendarResources.day); int months = days / 30; if (months < 12) return CalendarResources.in + " " + months + " " + (months > 1 ? CalendarResources.months : CalendarResources.month); else return CalendarResources.moreThenAYearLeft; } } public static class CalendarResources { public static String today; public static String tomorrow; public static String allDay; public static String now; public static String in; public static String minute; public static String minutes; public static String hour; public static String hours; public static String day; public static String days; public static String week; public static String weeks; public static String month; public static String months; public static String moreThenAYearLeft; public static void init(Context context) { if (today == null || moreThenAYearLeft == null) { today = context.getString(R.string.today); tomorrow = context.getString(R.string.tomorrow); allDay = context.getString(R.string.all_day); now = context.getString(R.string.now); in = context.getString(R.string.in); String[] min = context.getString(R.string.minute_s).split("/"); minute = min[0]; minutes = min[1]; String[] hoursArray = context.getString(R.string.hour_s).split("/"); hour = hoursArray[0]; hours = hoursArray[1]; String[] dayArray = context.getString(R.string.day_s).split("/"); day = dayArray[0]; days = dayArray[1]; String[] weekArray = context.getString(R.string.week_s).split("/"); week = weekArray[0]; weeks = weekArray[1]; String[] monthArray = context.getString(R.string.month_s).split("/"); month = monthArray[0]; months = monthArray[1]; moreThenAYearLeft = context.getString(R.string.more_then_year); } } } }
gaich/quickapps
app/src/main/java/com/yoavst/quickapps/calendar/CalendarUtil.java
Java
gpl-3.0
13,741
package uk.tim740.skUtilities.util; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import uk.tim740.skUtilities.skUtilities; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; /** * Created by tim740 on 11/09/2016 */ public class ExprTimeInTimeZone extends SimpleExpression<String> { private Expression<String> str; @Override @Nullable protected String[] get(Event e) { String s = str.getSingle(e); String[] sl = new String[0]; try { BufferedReader br = new BufferedReader(new FileReader(new File("plugins/Skript/config.sk").getAbsoluteFile())); sl = br.lines().toArray(String[]::new); br.close(); } catch (Exception x) { skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x); } String sf = ""; for (String aSl : sl) { if (aSl.contains("date format: ")) { sf = aSl.replaceFirst("date format: ", ""); } } String ff; if (sf.equalsIgnoreCase("default")) { ff = new SimpleDateFormat().toPattern(); } else { ff = sf; } return new String[]{ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(s)).format(DateTimeFormatter.ofPattern(ff))}; } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) { str = (Expression<String>) e[0]; return true; } @Override public Class<? extends String> getReturnType() { return String.class; } @Override public boolean isSingle() { return true; } @Override public String toString(@Nullable Event e, boolean b) { return getClass().getName(); } }
tim740/skUtilities
src/uk/tim740/skUtilities/util/ExprTimeInTimeZone.java
Java
gpl-3.0
1,995
/* * Copyright (C) 2010 The UAPI Authors * You may not use this file except in compliance with the License. * You may obtain a copy of the License at the LICENSE file. * * You must gained the permission from the authors if you want to * use the project into a commercial product */ package uapi.service; import uapi.InvalidArgumentException; import uapi.helper.ArgumentChecker; import java.util.HashMap; import java.util.Map; /** * Define response code */ public abstract class ResponseCode { private final Map<String, String> _codeMsgKeyMapping = new HashMap<>(); private final MessageExtractor _msgExtractor = new MessageExtractor(this.getClass().getClassLoader()); public void init() { getMessageLoader().registerExtractor(this._msgExtractor); } protected abstract MessageLoader getMessageLoader(); public String getMessageKey(final String code) { ArgumentChecker.required(code, "code"); return this._codeMsgKeyMapping.get("code"); } protected void addCodeMessageKeyMapping(String code, String messageKey) { ArgumentChecker.required(code, "code"); ArgumentChecker.required(messageKey, "messageKey"); if (this._codeMsgKeyMapping.containsKey(code)) { throw new InvalidArgumentException("Overwrite existing code message key is not allowed - {}", code); } this._codeMsgKeyMapping.put(code, messageKey); this._msgExtractor.addDefinedKeys(messageKey); } }
minjing/uapi
uapi.service/src/main/java/uapi/service/ResponseCode.java
Java
gpl-3.0
1,491
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.smssecure.smssecure.recipients; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import org.smssecure.smssecure.contacts.avatars.ContactPhotoFactory; import org.smssecure.smssecure.database.CanonicalAddressDatabase; import org.smssecure.smssecure.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; public class RecipientFactory { private static final RecipientProvider provider = new RecipientProvider(); public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) { if (TextUtils.isEmpty(recipientIds)) return new Recipients(); return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous); } public static Recipients getRecipientsFor(Context context, List<Recipient> recipients, boolean asynchronous) { long[] ids = new long[recipients.size()]; int i = 0; for (Recipient recipient : recipients) { ids[i++] = recipient.getRecipientId(); } return provider.getRecipients(context, ids, asynchronous); } public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) { long[] ids = new long[1]; ids[0] = recipient.getRecipientId(); return provider.getRecipients(context, ids, asynchronous); } public static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) { return provider.getRecipient(context, recipientId, asynchronous); } public static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) { return provider.getRecipients(context, recipientIds, asynchronous); } public static Recipients getRecipientsFromString(Context context, @NonNull String rawText, boolean asynchronous) { StringTokenizer tokenizer = new StringTokenizer(rawText, ","); List<String> ids = new LinkedList<>(); while (tokenizer.hasMoreTokens()) { Optional<Long> id = getRecipientIdFromNumber(context, tokenizer.nextToken()); if (id.isPresent()) { ids.add(String.valueOf(id.get())); } } return getRecipientsForIds(context, ids, asynchronous); } private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) { long[] ids = new long[idStrings.size()]; int i = 0; for (String id : idStrings) { ids[i++] = Long.parseLong(id); } return provider.getRecipients(context, ids, asynchronous); } private static Optional<Long> getRecipientIdFromNumber(Context context, String number) { number = number.trim(); if (number.isEmpty()) return Optional.absent(); if (hasBracketedNumber(number)) { number = parseBracketedNumber(number); } return Optional.of(CanonicalAddressDatabase.getInstance(context).getCanonicalAddressId(number)); } private static boolean hasBracketedNumber(String recipient) { int openBracketIndex = recipient.indexOf('<'); return (openBracketIndex != -1) && (recipient.indexOf('>', openBracketIndex) != -1); } private static String parseBracketedNumber(String recipient) { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>', begin); String value = recipient.substring(begin + 1, end); return value; } public static void clearCache() { provider.clearCache(); } }
matlink/SMSSecure
src/org/smssecure/smssecure/recipients/RecipientFactory.java
Java
gpl-3.0
4,267
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.graql.admin.RelationPlayer; import ai.grakn.graql.admin.VarPatternAdmin; import static ai.grakn.graql.Graql.var; /** * @author Felix Chapman */ public class RelationPlayers extends AbstractGenerator<RelationPlayer> { public RelationPlayers() { super(RelationPlayer.class); } @Override public RelationPlayer generate() { if (random.nextBoolean()) { return RelationPlayer.of(gen(VarPatternAdmin.class)); } else { VarPatternAdmin varPattern; if (random.nextBoolean()) { varPattern = var().label(gen(Label.class)).admin(); } else { varPattern = gen(VarPatternAdmin.class); } return RelationPlayer.of(varPattern, gen(VarPatternAdmin.class)); } } }
burukuru/grakn
grakn-test/test-integration/src/test/java/ai/grakn/generator/RelationPlayers.java
Java
gpl-3.0
1,612
package org.janus.miniforth; import org.janus.data.DataContext; public class Compare extends WordImpl { public enum Comp { EQ, NEQ, LT, GT, LEQ, GEQ } Comp comp; public Compare(Comp comp) { super(-1); this.comp = comp; } @Override public void perform(DataContext context) { super.perform(context); MiniForthContext withStack = (MiniForthContext) context; Comparable a = (Comparable) withStack.pop(); Comparable b = (Comparable) withStack.pop(); boolean result = false; if (a.getClass().equals(b.getClass())) { result = compare(a, b); } else { throw new IllegalArgumentException("Vergleich nicht möglich"); } withStack.pushBoolean(result); } private boolean compare(Comparable a, Comparable b) { int c = a.compareTo(b); if (c == 0) { if (comp.equals(Comp.NEQ)) { return false; } else { return comp.equals(Comp.EQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.GEQ); } } else { if (c > 0) { return comp.equals(Comp.NEQ) || comp.equals(Comp.LEQ) || comp.equals(Comp.LT); } else { return comp.equals(Comp.NEQ) || comp.equals(Comp.GEQ) || comp.equals(Comp.GT); } } } }
ThoNill/JanusMiniForth
JanusMiniForth/src/org/janus/miniforth/Compare.java
Java
gpl-3.0
1,226
/* * This file is part of Track It!. * Copyright (C) 2013 Henrique Malheiro * Copyright (C) 2015 Pedro Gomes * * TrackIt! is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Track It! is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Track It!. If not, see <http://www.gnu.org/licenses/>. * */ package com.trackit.business.domain; import java.util.ArrayList; import java.util.List; import com.trackit.business.exception.TrackItException; import com.trackit.presentation.event.Event; import com.trackit.presentation.event.EventManager; import com.trackit.presentation.event.EventPublisher; public class Folder extends TrackItBaseType implements DocumentItem { private String name; private List<GPSDocument> documents; public Folder(String name) { super(); this.name = name; documents = new ArrayList<GPSDocument>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<GPSDocument> getDocuments() { return documents; } public void add(GPSDocument document) { documents.add(document); } public void remove(GPSDocument document) { documents.remove(document); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Folder other = (Folder) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return String.format("Folder [name=%s]", name); } @Override public void publishSelectionEvent(EventPublisher publisher) { EventManager.getInstance().publish(publisher, Event.FOLDER_SELECTED, this); } @Override public void accept(Visitor visitor) throws TrackItException { visitor.visit(this); } }
Spaner/TrackIt
src/main/java/com/trackit/business/domain/Folder.java
Java
gpl-3.0
2,498
package com.snail.webgame.game.protocal.relation.getRequest; import org.epilot.ccf.config.Resource; import org.epilot.ccf.core.processor.ProtocolProcessor; import org.epilot.ccf.core.processor.Request; import org.epilot.ccf.core.processor.Response; import org.epilot.ccf.core.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.snail.webgame.game.common.GameMessageHead; import com.snail.webgame.game.common.util.Command; import com.snail.webgame.game.protocal.relation.service.RoleRelationMgtService; public class GetAddRequestProcessor extends ProtocolProcessor{ private static Logger logger = LoggerFactory.getLogger("logs"); private RoleRelationMgtService roleRelationMgtService; public void setRoleRelationMgtService(RoleRelationMgtService roleRelationMgtService) { this.roleRelationMgtService = roleRelationMgtService; } @Override public void execute(Request request, Response response) { Message msg = request.getMessage(); GameMessageHead header = (GameMessageHead) msg.getHeader(); header.setMsgType(Command.GET_ADD_REQUEST_RESP); int roleId = header.getUserID0(); GetAddRequestReq req = (GetAddRequestReq) msg.getBody(); GetAddRequestResp resp = roleRelationMgtService.getAddFriendRequestList(roleId, req); msg.setHeader(header); msg.setBody(resp); response.write(msg); if(logger.isInfoEnabled()){ logger.info(Resource.getMessage("game", "GAME_ROLE_RELATION_INFO_4") + ": result=" + resp.getResult() + ",roleId=" + roleId); } } }
bozhbo12/demo-spring-server
spring-game/src/main/java/com/spring/game/game/protocal/relation/getRequest/GetAddRequestProcessor.java
Java
gpl-3.0
1,541
/******************************************************************************* * Copyright (c) 2000, 2013 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core; import java.util.ArrayList; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IModuleDescription; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; /** * @see IJavaElementRequestor */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class JavaElementRequestor implements IJavaElementRequestor { /** * True if this requestor no longer wants to receive * results from its <code>IRequestorNameLookup</code>. */ protected boolean canceled= false; /** * A collection of the resulting fields, or <code>null</code> * if no field results have been received. */ protected ArrayList fields= null; /** * A collection of the resulting initializers, or <code>null</code> * if no initializer results have been received. */ protected ArrayList initializers= null; /** * A collection of the resulting member types, or <code>null</code> * if no member type results have been received. */ protected ArrayList memberTypes= null; /** * A collection of the resulting methods, or <code>null</code> * if no method results have been received. */ protected ArrayList methods= null; /** * A collection of the resulting package fragments, or <code>null</code> * if no package fragment results have been received. */ protected ArrayList packageFragments= null; /** * A collection of the resulting types, or <code>null</code> * if no type results have been received. */ protected ArrayList types= null; /** * A collection of the resulting modules, or <code>null</code> * if no module results have been received */ protected ArrayList<IModuleDescription> modules = null; /** * Empty arrays used for efficiency */ protected static final IField[] EMPTY_FIELD_ARRAY= new IField[0]; protected static final IInitializer[] EMPTY_INITIALIZER_ARRAY= new IInitializer[0]; protected static final IType[] EMPTY_TYPE_ARRAY= new IType[0]; protected static final IPackageFragment[] EMPTY_PACKAGE_FRAGMENT_ARRAY= new IPackageFragment[0]; protected static final IMethod[] EMPTY_METHOD_ARRAY= new IMethod[0]; protected static final IModuleDescription[] EMPTY_MODULE_ARRAY= new IModuleDescription[0]; /** * @see IJavaElementRequestor */ @Override public void acceptField(IField field) { if (this.fields == null) { this.fields= new ArrayList(); } this.fields.add(field); } /** * @see IJavaElementRequestor */ @Override public void acceptInitializer(IInitializer initializer) { if (this.initializers == null) { this.initializers= new ArrayList(); } this.initializers.add(initializer); } /** * @see IJavaElementRequestor */ @Override public void acceptMemberType(IType type) { if (this.memberTypes == null) { this.memberTypes= new ArrayList(); } this.memberTypes.add(type); } /** * @see IJavaElementRequestor */ @Override public void acceptMethod(IMethod method) { if (this.methods == null) { this.methods = new ArrayList(); } this.methods.add(method); } /** * @see IJavaElementRequestor */ @Override public void acceptPackageFragment(IPackageFragment packageFragment) { if (this.packageFragments== null) { this.packageFragments= new ArrayList(); } this.packageFragments.add(packageFragment); } /** * @see IJavaElementRequestor */ @Override public void acceptType(IType type) { if (this.types == null) { this.types= new ArrayList(); } this.types.add(type); } /** * @see IJavaElementRequestor */ @Override public void acceptModule(IModuleDescription module) { if (this.modules == null) { this.modules= new ArrayList(); } this.modules.add(module); } /** * @see IJavaElementRequestor */ public IField[] getFields() { if (this.fields == null) { return EMPTY_FIELD_ARRAY; } int size = this.fields.size(); IField[] results = new IField[size]; this.fields.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IInitializer[] getInitializers() { if (this.initializers == null) { return EMPTY_INITIALIZER_ARRAY; } int size = this.initializers.size(); IInitializer[] results = new IInitializer[size]; this.initializers.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IType[] getMemberTypes() { if (this.memberTypes == null) { return EMPTY_TYPE_ARRAY; } int size = this.memberTypes.size(); IType[] results = new IType[size]; this.memberTypes.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IMethod[] getMethods() { if (this.methods == null) { return EMPTY_METHOD_ARRAY; } int size = this.methods.size(); IMethod[] results = new IMethod[size]; this.methods.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IPackageFragment[] getPackageFragments() { if (this.packageFragments== null) { return EMPTY_PACKAGE_FRAGMENT_ARRAY; } int size = this.packageFragments.size(); IPackageFragment[] results = new IPackageFragment[size]; this.packageFragments.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IType[] getTypes() { if (this.types== null) { return EMPTY_TYPE_ARRAY; } int size = this.types.size(); IType[] results = new IType[size]; this.types.toArray(results); return results; } /** * @see IJavaElementRequestor */ public IModuleDescription[] getModules() { if (this.modules == null) { return EMPTY_MODULE_ARRAY; } int size = this.modules.size(); IModuleDescription[] results = new IModuleDescription[size]; this.modules.toArray(results); return results; } /** * @see IJavaElementRequestor */ @Override public boolean isCanceled() { return this.canceled; } /** * Reset the state of this requestor. */ public void reset() { this.canceled = false; this.fields = null; this.initializers = null; this.memberTypes = null; this.methods = null; this.packageFragments = null; this.types = null; } /** * Sets the #isCanceled state of this requestor to true or false. */ public void setCanceled(boolean b) { this.canceled= b; } }
Niky4000/UsefulUtils
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java
Java
gpl-3.0
6,654
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2015> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. */ package org.egov.search.service; import org.egov.search.domain.entities.Address; import org.egov.search.domain.entities.Person; import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static com.jayway.jsonassert.JsonAssert.with; public class SimpleFieldsResourceGeneratorTest { private String json; @Before public void before() { Person person = Person.newInstance(); ResourceGenerator<Person> resourceGenerator = new ResourceGenerator<>(Person.class, person); JSONObject resource = resourceGenerator.generate(); json = resource.toJSONString(); } @Test public void withMultipleFields() { with(json).assertEquals("$.searchable.citizen", true); with(json).assertEquals("$.searchable.age", 37); with(json).assertEquals("$.clauses.status", "ACTIVE"); with(json).assertNotDefined("$.searchable.role"); } @Test public void withMultipleFields_WithGivenName() { with(json).assertEquals("$.searchable.citizen_name", "Elzan"); } @Test public void withAListField() { with(json).assertEquals("$.searchable.jobs", Arrays.asList("Job One", "Job Two")); } @Test public void withAMapField() { with(json).assertEquals("$.searchable.serviceHistory.company1", "Job One"); with(json).assertEquals("$.searchable.serviceHistory.company2", "Job Two"); } @Test public void shouldGroupFields() { Address address = new Address("street1", "560001"); ResourceGenerator<Address> resourceGenerator = new ResourceGenerator<>(Address.class, address); JSONObject resource = resourceGenerator.generate(); String json = resource.toJSONString(); with(json).assertEquals("$.searchable.street", "street1"); with(json).assertEquals("$.searchable.pincode", "560001"); with(json).assertNotDefined("$.clauses"); with(json).assertNotDefined("$.common"); } }
egovernments/eGov-Search
src/test/java/org/egov/search/service/SimpleFieldsResourceGeneratorTest.java
Java
gpl-3.0
3,937
package com.mx.fic.inventory.business.builder; import com.mx.fic.inventory.business.builder.config.AbstractDTOBuilder; import com.mx.fic.inventory.business.builder.config.BuilderConfiguration; import com.mx.fic.inventory.dto.BaseDTO; import com.mx.fic.inventory.dto.UserDetailDTO; import com.mx.fic.inventory.persistent.BaseEntity; import com.mx.fic.inventory.persistent.UserDetail; @BuilderConfiguration (dtoClass = UserDetailDTO.class, entityClass= UserDetail.class) public class UserDetailBuilder extends AbstractDTOBuilder { public BaseDTO createDTO(BaseEntity entity) { UserDetailDTO userDetailDTO = new UserDetailDTO(); UserDetail userDetail = (UserDetail) entity; userDetailDTO.setAddress(userDetail.getAddress()); userDetailDTO.setCurp(userDetail.getCurp()); userDetailDTO.setEmail(userDetail.getEmail()); userDetailDTO.setId(userDetail.getId()); userDetailDTO.setLastAccess(userDetail.getLastAccess()); userDetailDTO.setLastName(userDetail.getLastName()); userDetailDTO.setName(userDetail.getName()); userDetailDTO.setRfc(userDetail.getRfc()); userDetailDTO.setShortName(userDetail.getShortName()); userDetailDTO.setSurName(userDetail.getSurName()); return userDetailDTO; } }
modemm3/fic
fic-inventory/fic-inventory-business/src/main/java/com/mx/fic/inventory/business/builder/UserDetailBuilder.java
Java
gpl-3.0
1,223
package com.programandoapasitos.facturador.gui; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import com.programandoapasitos.facturador.gui.superclases.FramePadre; import com.programandoapasitos.facturador.utiles.ManejadorProperties; @SuppressWarnings("serial") public class MenuPrincipal extends FramePadre { // Propiedades private JLabel lblIcono; private JMenuBar menuBar; private JMenu mnClientes; private JMenu mnFacturas; private JMenuItem mntmNuevaFactura; private JMenuItem mntmNuevoCliente; private JMenuItem mntmBuscarFactura; private JMenuItem mntmBuscarCliente; // Constructor public MenuPrincipal(int ancho, int alto, String titulo) { super(ancho, alto, titulo); this.inicializar(); } // Métodos public void inicializar() { this.inicializarMenuBar(); this.iniciarLabels(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sobrescribe setDefaultCloseOperation de FramePadre setVisible(true); } public void inicializarMenuBar() { menuBar = new JMenuBar(); menuBar.setBounds(0, 0, 900, 21); this.panel.add(menuBar); this.inicializarMenuFacturas(); this.inicializarMenuClientes(); } /** * Initialize submenu Bills */ public void inicializarMenuFacturas() { mnFacturas = new JMenu(ManejadorProperties.verLiteral("MENU_FACTURAS")); menuBar.add(mnFacturas); mntmNuevaFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL")); mntmNuevaFactura.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { new FrameNuevaFactura(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL")); } }); mnFacturas.add(mntmNuevaFactura); mntmBuscarFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL")); mntmBuscarFactura.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new FrameBuscarFacturas(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL")); } }); mnFacturas.add(mntmBuscarFactura); } public void inicializarMenuClientes() { mnClientes = new JMenu(ManejadorProperties.verLiteral("MENU_CLIENTES")); menuBar.add(mnClientes); mntmNuevoCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT")); mntmNuevoCliente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new FrameNuevoCliente(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT")); } }); mnClientes.add(mntmNuevoCliente); mntmBuscarCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT")); mntmBuscarCliente.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { new FrameBuscarClientes(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT")); } }); mnClientes.add(mntmBuscarCliente); } /** * Initialize icon label */ public void iniciarLabels() { lblIcono = new JLabel(""); lblIcono.setIcon(new ImageIcon(ManejadorProperties.verRuta("MENU_ITEM_SEARCH_CLIENT"))); lblIcono.setBounds(342, 240, 210, 124); this.panel.add(lblIcono); } }
inazense/java-generate-bills
src/main/java/com/programandoapasitos/facturador/gui/MenuPrincipal.java
Java
gpl-3.0
3,783
package com.diggime.modules.email.model.impl; import com.diggime.modules.email.model.EMail; import com.diggime.modules.email.model.MailContact; import org.json.JSONObject; import java.time.LocalDateTime; import java.util.List; import static org.foilage.utils.checkers.NullChecker.notNull; public class PostmarkEMail implements EMail { private final int id; private final String messageId; private final LocalDateTime sentDate; private final MailContact sender; private final List<MailContact> receivers; private final List<MailContact> carbonCopies; private final List<MailContact> blindCarbonCopies; private final String subject; private final String tag; private final String htmlBody; private final String textBody; public PostmarkEMail(LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = 0; this.messageId = ""; this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } public PostmarkEMail(String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = 0; this.messageId = notNull(messageId); this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } public PostmarkEMail(EMail mail, String messageId) { this.id = mail.getId(); this.messageId = notNull(messageId); this.sentDate = mail.getSentDate(); this.sender = mail.getSender(); this.receivers = mail.getReceivers(); this.carbonCopies = mail.getCarbonCopies(); this.blindCarbonCopies = mail.getBlindCarbonCopies(); this.subject = mail.getSubject(); this.tag = mail.getTag(); this.htmlBody = mail.getHtmlBody(); this.textBody = mail.getTextBody(); } public PostmarkEMail(int id, String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) { this.id = id; this.messageId = notNull(messageId); this.sentDate = notNull(sentDate); this.sender = notNull(sender); this.receivers = notNull(receivers); this.carbonCopies = notNull(carbonCopies); this.blindCarbonCopies = notNull(blindCarbonCopies); this.subject = notNull(subject); this.tag = notNull(tag); this.htmlBody = notNull(htmlBody); this.textBody = notNull(textBody); } @Override public int getId() { return id; } @Override public String getMessageId() { return messageId; } @Override public LocalDateTime getSentDate() { return sentDate; } @Override public MailContact getSender() { return sender; } @Override public List<MailContact> getReceivers() { return receivers; } @Override public List<MailContact> getCarbonCopies() { return carbonCopies; } @Override public List<MailContact> getBlindCarbonCopies() { return blindCarbonCopies; } @Override public String getSubject() { return subject; } @Override public String getTag() { return tag; } @Override public String getHtmlBody() { return htmlBody; } @Override public String getTextBody() { return textBody; } @Override public JSONObject getJSONObject() { JSONObject obj = new JSONObject(); obj.put("From", sender.getName()+" <"+sender.getAddress()+">"); addReceivers(obj, receivers, "To"); addReceivers(obj, carbonCopies, "Cc"); addReceivers(obj, blindCarbonCopies, "Bcc"); obj.put("Subject", subject); if(tag.length()>0) { obj.put("Tag", tag); } if(htmlBody.length()>0) { obj.put("HtmlBody", htmlBody); } else { obj.put("HtmlBody", textBody); } if(textBody.length()>0) { obj.put("TextBody", textBody); } return obj; } private void addReceivers(JSONObject obj, List<MailContact> sendList, String jsonType) { boolean first = true; StringBuilder sb = new StringBuilder(); for(MailContact contact: sendList) { if(first) { first = false; } else { sb.append(", "); } sb.append(contact.getName()); sb.append(" <"); sb.append(contact.getAddress()); sb.append(">"); } if(sendList.size()>0) { obj.put(jsonType, sb.toString()); } } }
drbizzaro/diggime
base/main/src/com/diggime/modules/email/model/impl/PostmarkEMail.java
Java
gpl-3.0
5,687
/* * Copyright (C) 2014 Hector Espert Pardo * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.blackleg.libdam.geometry; import es.blackleg.libdam.utilities.Calculadora; /** * * @author Hector Espert Pardo */ public class Circulo extends Figura { private double radio; public Circulo() { } public Circulo(double radio) { this.radio = radio; } public void setRadio(double radio) { this.radio = radio; } public double getRadio() { return radio; } public double getDiametro() { return 2 * radio; } @Override public double calculaArea() { return Calculadora.areaCirculo(radio); } @Override public double calculaPerimetro() { return Calculadora.perimetroCirculo(radio); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Circulo other = (Circulo) obj; return Double.doubleToLongBits(this.radio) == Double.doubleToLongBits(other.radio); } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (int) (Double.doubleToLongBits(this.radio) ^ (Double.doubleToLongBits(this.radio) >>> 32)); return hash; } @Override public String toString() { return String.format("Circulo: x=%d, y=%d, R=%.2f.", super.getCentro().getX(), super.getCentro().getY(), radio); } }
blackleg/libdam
src/main/java/es/blackleg/libdam/geometry/Circulo.java
Java
gpl-3.0
2,177
/** * Cerberus Copyright (C) 2013 - 2017 cerberustesting * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of Cerberus. * * Cerberus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cerberus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cerberus. If not, see <http://www.gnu.org/licenses/>. */ package org.cerberus.service.groovy.impl; import groovy.lang.GroovyShell; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.cerberus.service.groovy.IGroovyService; import org.codehaus.groovy.control.CompilerConfiguration; import org.kohsuke.groovy.sandbox.SandboxTransformer; import org.springframework.stereotype.Service; /** * {@link IGroovyService} default implementation * * @author Aurelien Bourdon */ @Service public class GroovyService implements IGroovyService { /** * Groovy specific compilation customizer in order to avoid code injection */ private static final CompilerConfiguration GROOVY_COMPILER_CONFIGURATION = new CompilerConfiguration().addCompilationCustomizers(new SandboxTransformer()); /** * Each Groovy execution is ran inside a dedicated {@link Thread}, * especially to register our Groovy interceptor */ private ExecutorService executorService; @PostConstruct private void init() { executorService = Executors.newCachedThreadPool(); } @PreDestroy private void shutdown() { if (executorService != null && !executorService.isShutdown()) { executorService.shutdownNow(); } } @Override public String eval(final String script) throws IGroovyServiceException { try { Future<String> expression = executorService.submit(() -> { RestrictiveGroovyInterceptor interceptor = new RestrictiveGroovyInterceptor( Collections.<Class<?>>emptySet(), Collections.<Class<?>>emptySet(), Collections.<RestrictiveGroovyInterceptor.AllowedPrefix>emptyList() ); try { interceptor.register(); GroovyShell shell = new GroovyShell(GROOVY_COMPILER_CONFIGURATION); return shell.evaluate(script).toString(); } finally { interceptor.unregister(); } }); String eval = expression.get(); if (eval == null) { throw new IGroovyServiceException("Groovy evaluation returns null result"); } return eval; } catch (Exception e) { throw new IGroovyServiceException(e); } } }
cerberustesting/cerberus-source
source/src/main/java/org/cerberus/service/groovy/impl/GroovyService.java
Java
gpl-3.0
3,363
/* * Symphony - A modern community (forum/SNS/blog) platform written in Java. * Copyright (C) 2012-2017, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.b3log.symphony.processor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.Pagination; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.After; import org.b3log.latke.servlet.annotation.Before; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer; import org.b3log.latke.util.Locales; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Article; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.UserExt; import org.b3log.symphony.processor.advice.AnonymousViewCheck; import org.b3log.symphony.processor.advice.PermissionGrant; import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice; import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice; import org.b3log.symphony.service.*; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Markdowns; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.util.*; /** * Index processor. * <p> * <ul> * <li>Shows index (/), GET</li> * <li>Shows recent articles (/recent), GET</li> * <li>Shows hot articles (/hot), GET</li> * <li>Shows perfect articles (/perfect), GET</li> * <li>Shows about (/about), GET</li> * <li>Shows b3log (/b3log), GET</li> * <li>Shows SymHub (/symhub), GET</li> * <li>Shows kill browser (/kill-browser), GET</li> * </ul> * </p> * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://vanessa.b3log.org">Liyuan Li</a> * @version 1.12.3.24, Dec 26, 2016 * @since 0.2.0 */ @RequestProcessor public class IndexProcessor { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName()); /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Timeline management service. */ @Inject private TimelineMgmtService timelineMgmtService; /** * Shows md guide. * * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/guide/markdown", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showMDGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/md-guide.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); InputStream inputStream = null; try { inputStream = IndexProcessor.class.getResourceAsStream("/md_guide.md"); final String md = IOUtils.toString(inputStream, "UTF-8"); String html = Emotions.convert(md); html = Markdowns.toHTML(html); dataModel.put("md", md); dataModel.put("html", html); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads markdown guide failed", e); } finally { IOUtils.closeQuietly(inputStream); } dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Shows index. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = {"", "/"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("index.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> recentArticles = articleQueryService.getIndexRecentArticles(avatarViewMode); dataModel.put(Common.RECENT_ARTICLES, recentArticles); JSONObject currentUser = userQueryService.getCurrentUser(request); if (null == currentUser) { userMgmtService.tryLogInWithCookie(request, context.getResponse()); } currentUser = userQueryService.getCurrentUser(request); if (null != currentUser) { if (!UserExt.finshedGuide(currentUser)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } final String userId = currentUser.optString(Keys.OBJECT_ID); final int pageSize = Symphonys.getInt("indexArticlesCnt"); final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles( avatarViewMode, userId, 1, pageSize); dataModel.put(Common.FOLLOWING_TAG_ARTICLES, followingTagArticles); final List<JSONObject> followingUserArticles = articleQueryService.getFollowingUserArticles( avatarViewMode, userId, 1, pageSize); dataModel.put(Common.FOLLOWING_USER_ARTICLES, followingUserArticles); } else { dataModel.put(Common.FOLLOWING_TAG_ARTICLES, Collections.emptyList()); dataModel.put(Common.FOLLOWING_USER_ARTICLES, Collections.emptyList()); } final List<JSONObject> perfectArticles = articleQueryService.getIndexPerfectArticles(avatarViewMode); dataModel.put(Common.PERFECT_ARTICLES, perfectArticles); final List<JSONObject> timelines = timelineMgmtService.getTimelines(); dataModel.put(Common.TIMELINES, timelines); dataModel.put(Common.SELECTED, Common.INDEX); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillIndexTags(dataModel); } /** * Shows recent articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = {"/recent", "/recent/hot", "/recent/good", "/recent/reply"}, method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showRecent(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("recent.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); if (!UserExt.finshedGuide(user)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/recent"); int sortMode; switch (sortModeStr) { case "": sortMode = 0; break; case "/hot": sortMode = 1; break; case "/good": sortMode = 2; break; case "/reply": sortMode = 3; break; default: sortMode = 0; } final JSONObject result = articleQueryService.getRecentArticles(avatarViewMode, sortMode, pageNum, pageSize); final List<JSONObject> allArticles = (List<JSONObject>) result.get(Article.ARTICLES); dataModel.put(Common.SELECTED, Common.RECENT); final List<JSONObject> stickArticles = new ArrayList<>(); final Iterator<JSONObject> iterator = allArticles.iterator(); while (iterator.hasNext()) { final JSONObject article = iterator.next(); final boolean stick = article.optInt(Article.ARTICLE_T_STICK_REMAINS) > 0; article.put(Article.ARTICLE_T_IS_STICK, stick); if (stick) { stickArticles.add(article); iterator.remove(); } } dataModel.put(Common.STICK_ARTICLES, stickArticles); dataModel.put(Common.LATEST_ARTICLES, allArticles); final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); dataModel.put(Common.CURRENT, StringUtils.substringAfter(request.getRequestURI(), "/recent")); } /** * Shows hot articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/hot", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showHotArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("hot.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final List<JSONObject> indexArticles = articleQueryService.getHotArticles(avatarViewMode, pageSize); dataModel.put(Common.INDEX_ARTICLES, indexArticles); dataModel.put(Common.SELECTED, Common.HOT); Stopwatchs.start("Fills"); try { dataModelService.fillHeaderAndFooter(request, response, dataModel); if (!(Boolean) dataModel.get(Common.IS_MOBILE)) { dataModelService.fillRandomArticles(avatarViewMode, dataModel); } dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } finally { Stopwatchs.end(); } } /** * Shows SymHub page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/symhub", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showSymHub(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/symhub.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> syms = Symphonys.getSyms(); dataModel.put("syms", (Object) syms); Stopwatchs.start("Fills"); try { final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); dataModelService.fillHeaderAndFooter(request, response, dataModel); if (!(Boolean) dataModel.get(Common.IS_MOBILE)) { dataModelService.fillRandomArticles(avatarViewMode, dataModel); } dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } finally { Stopwatchs.end(); } } /** * Shows perfect articles. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/perfect", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class}) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showPerfectArticles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("perfect.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); String pageNumStr = request.getParameter("p"); if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) { pageNumStr = "1"; } final int pageNum = Integer.valueOf(pageNumStr); int pageSize = Symphonys.getInt("indexArticlesCnt"); final JSONObject user = userQueryService.getCurrentUser(request); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); if (!UserExt.finshedGuide(user)) { response.sendRedirect(Latkes.getServePath() + "/guide"); return; } } final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); final JSONObject result = articleQueryService.getPerfectArticles(avatarViewMode, pageNum, pageSize); final List<JSONObject> perfectArticles = (List<JSONObject>) result.get(Article.ARTICLES); dataModel.put(Common.PERFECT_ARTICLES, perfectArticles); dataModel.put(Common.SELECTED, Common.PERFECT); final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(request, response, dataModel); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows about. * * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/about", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void showAbout(final HttpServletResponse response) throws Exception { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", "https://hacpai.com/article/1440573175609"); response.flushBuffer(); } /** * Shows b3log. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/b3log", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showB3log(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("other/b3log.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModelService.fillHeaderAndFooter(request, response, dataModel); final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE); dataModelService.fillRandomArticles(avatarViewMode, dataModel); dataModelService.fillSideHotArticles(avatarViewMode, dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows kill browser page with the specified context. * * @param context the specified context * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response */ @RequestProcessing(value = "/kill-browser", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); renderer.setTemplateName("other/kill-browser.ftl"); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, String> langs = langPropsService.getAll(Locales.getLocale()); dataModel.putAll(langs); Keys.fillRuntime(dataModel); dataModelService.fillMinified(dataModel); } }
BrickCat/symphony
src/main/java/org/b3log/symphony/processor/IndexProcessor.java
Java
gpl-3.0
21,728
package telinc.telicraft.util; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.ChatMessageComponent; import net.minecraft.util.StatCollector; public class PetrifyDamageSource extends TelicraftDamageSource { protected EntityLivingBase entity; protected PetrifyDamageSource(EntityLivingBase par1EntityLivingBase) { super("petrify"); this.setDamageAllowedInCreativeMode(); this.setDamageBypassesArmor(); this.entity = par1EntityLivingBase; } @Override public Entity getEntity() { return this.entity; } @Override public ChatMessageComponent getDeathMessage(EntityLivingBase par1EntityLivingBase) { EntityLivingBase attacker = par1EntityLivingBase.func_94060_bK(); String deathSelf = this.getRawDeathMessage(); String deathPlayer = deathSelf + ".player"; return attacker != null && StatCollector.func_94522_b(deathPlayer) ? ChatMessageComponent.func_111082_b(deathPlayer, new Object[]{par1EntityLivingBase.getTranslatedEntityName(), attacker.getTranslatedEntityName()}) : ChatMessageComponent.func_111082_b(deathSelf, new Object[]{par1EntityLivingBase.getTranslatedEntityName()}); } }
telinc1/Telicraft
telicraft_common/telinc/telicraft/util/PetrifyDamageSource.java
Java
gpl-3.0
1,253
package com.github.dozzatq.phoenix.advertising; /** * Created by Rodion Bartoshik on 04.07.2017. */ interface Reflector { FactoryAd reflection(); int state(); }
dozzatq/Phoenix
mylibrary/src/main/java/com/github/dozzatq/phoenix/advertising/Reflector.java
Java
gpl-3.0
173
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.web.commands; import net.sf.jasperreports.engine.JRConstants; import net.sf.jasperreports.web.JRInteractiveException; /** * @author Narcis Marcu (narcism@users.sourceforge.net) */ public class CommandException extends JRInteractiveException { private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; public CommandException(String message) { super(message); } public CommandException(Throwable t) { super(t); } public CommandException(String message, Throwable t) { super(message, t); } public CommandException(String messageKey, Object[] args, Throwable t) { super(messageKey, args, t); } public CommandException(String messageKey, Object[] args) { super(messageKey, args); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/web/commands/CommandException.java
Java
gpl-3.0
1,750
import java.util.*; public class Pali { public static void main(String args[]) { Scanner sc=new Scanner(System.in); String str=sc.next(); StringBuffer buff=new StringBuffer(str).reverse(); String str1=buff.toString(); if(str.isequals(str1)) { System.out.println("Palindrome"); } else { System.out.println("Not a Palindrome"); } }
RaviVengatesh/Guvi_codes
Pali.java
Java
gpl-3.0
449