repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
combogenomics/medusa | src/weightComparator.java | 360 |
import graphs.MyEdge;
import java.util.Comparator;
public class weightComparator implements Comparator<MyEdge> {
@Override
public int compare(MyEdge o1, MyEdge o2) {
int i = 0;
if(o1.getWeight()==o2.getWeight()){
i= 0;
} else if(o1.getWeight()<o2.getWeight()){
i=-1;
} else if (o1.getWeight()>o2.getWeight()){
i=1;
}
return i;
}
}
| gpl-3.0 |
BeMacized/Grimoire | src/main/java/net/bemacized/grimoire/commands/all/RandomCommand.java | 6172 | package net.bemacized.grimoire.commands.all;
import net.bemacized.grimoire.Grimoire;
import net.bemacized.grimoire.commands.BaseCommand;
import net.bemacized.grimoire.data.models.card.MtgCard;
import net.bemacized.grimoire.data.models.mtgjson.MtgJsonCard;
import net.bemacized.grimoire.data.models.preferences.GuildPreferences;
import net.bemacized.grimoire.data.models.scryfall.ScryfallCard;
import net.bemacized.grimoire.data.models.scryfall.ScryfallSet;
import net.bemacized.grimoire.data.retrievers.ScryfallRetriever;
import net.bemacized.grimoire.utils.LoadMessage;
import net.bemacized.grimoire.utils.MTGUtils;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class RandomCommand extends BaseCommand {
@Override
public String name() {
return "random";
}
@Override
public String[] aliases() {
return new String[]{"rand", "rng"};
}
@Override
public String description() {
return "Show a random card of a certain type.";
}
@Override
public String[] usages() {
return new String[]{"[supertype] [type] [subtype] [rarity] [set] [setcode]"};
}
@Override
public String[] examples() {
return new String[]{
"",
"legendary creature",
"C17 mythic",
"rare artifact"
};
}
@Override
public void exec(String[] args, String rawArgs, MessageReceivedEvent e, GuildPreferences guildPreferences) {
List<String> supertypes = new ArrayList<>();
List<String> types = new ArrayList<>();
List<String> subtypes = new ArrayList<>();
ScryfallCard.Rarity rarity = null;
ScryfallSet set = null;
// Send load message
LoadMessage loadMsg = new LoadMessage(e.getChannel(), "Drawing random card...", true, guildPreferences.disableLoadingMessages());
// Retrieve all types
List<String> allSupertypes = Grimoire.getInstance().getCardProvider().getMtgJsonProvider().getAllSupertypes();
List<String> allTypes = Grimoire.getInstance().getCardProvider().getMtgJsonProvider().getAllTypes();
List<String> allSubtypes = Grimoire.getInstance().getCardProvider().getMtgJsonProvider().getAllSubtypes();
// Extract filters
for (String arg : args) {
if (allSupertypes.parallelStream().anyMatch(t -> t.equalsIgnoreCase(arg))) {
if (!supertypes.contains(arg.toLowerCase())) supertypes.add(arg.toLowerCase());
} else if (allTypes.parallelStream().anyMatch(t -> t.equalsIgnoreCase(arg))) {
if (!types.contains(arg.toLowerCase())) types.add(arg.toLowerCase());
} else if (allSubtypes.parallelStream().anyMatch(t -> t.equalsIgnoreCase(arg))) {
if (!subtypes.contains(arg.toLowerCase())) subtypes.add(arg.toLowerCase());
} else if (Arrays.stream(ScryfallCard.Rarity.values()).parallel().anyMatch(r -> r.toString().equalsIgnoreCase(arg))) {
if (rarity != null) {
sendErrorEmbed(loadMsg, "Please do not specify more than one rarity.");
return;
}
rarity = Arrays.stream(ScryfallCard.Rarity.values()).parallel().filter(r -> r.toString().equalsIgnoreCase(arg)).findFirst().orElse(null);
} else {
ScryfallSet tmpSet = Grimoire.getInstance().getCardProvider().getSetByNameOrCode(arg);
if (tmpSet != null) {
if (set != null) {
sendErrorEmbed(loadMsg, "Please do not specify more than one set.");
return;
}
set = tmpSet;
} else {
sendErrorEmbedFormat(loadMsg, "**'%s'** is neither a rarity, set, setcode, type, supertype or subtype. Please only specify valid properties.", arg);
return;
}
}
}
// Edit load message to reflect chosen types
String joinedType = String.join(" ", new ArrayList<String>() {{
addAll(supertypes);
addAll(types);
addAll(subtypes);
}}.parallelStream().filter(Objects::nonNull).map(t -> t.substring(0, 1).toUpperCase() + t.substring(1, t.length())).collect(Collectors.toList()));
List<String> properties = new ArrayList<>();
if (rarity != null) properties.add(rarity.toString());
if (joinedType != null && !joinedType.isEmpty()) properties.add(joinedType);
if (set != null) properties.add(String.format("from set '%s (%s)'", set.getName(), set.getCode()));
loadMsg.setLineFormat(
"Drawing random **%s**...",
properties.isEmpty() ? "card" : String.join(" ", properties)
);
//Find cards
List<String> query = new ArrayList<>();
supertypes.forEach(t -> query.add("t:" + t));
types.forEach(t -> query.add("t:" + t));
subtypes.forEach(t -> query.add("t:" + t));
if (rarity != null) query.add("r:" + rarity.name().toLowerCase());
if (set != null) query.add("s:" + set.getCode());
MtgCard card;
try {
card = Grimoire.getInstance().getCardProvider().getRandomCardByScryfallQuery("++" + String.join(" ", query));
} catch (ScryfallRetriever.ScryfallRequest.ScryfallErrorException ex) {
LOG.log(Level.WARNING, "Scryfall gave an error when trying to get a random card.", ex);
sendErrorEmbed(loadMsg, "Could not get random card: " + ex.getError().getDetails());
return;
} catch (ScryfallRetriever.ScryfallRequest.UnknownResponseException ex) {
LOG.log(Level.WARNING, "Scryfall gave an unknown response when trying to get a random card.", ex);
sendErrorEmbed(loadMsg, "An unknown error occurred when trying to get a random card.");
return;
} catch (ScryfallRetriever.ScryfallRequest.NoResultException e1) {
sendErrorEmbed(loadMsg, "No cards have been found with the properties you've supplied.");
return;
}
// Build the embed
EmbedBuilder eb = new EmbedBuilder();
if (("Random " + String.join(" ", properties)).length() <= 128)
eb.setAuthor("Random " + String.join(" ", properties), null, null);
else eb.appendDescription("Random " + String.join(" ", properties) + "\n");
eb.setTitle(card.getName(), guildPreferences.getCardUrl(card));
eb.setDescription(String.format("%s (%s)", card.getSet().getName(), card.getSet().getCode()));
eb.setImage(card.getImageUrl(guildPreferences));
eb.setColor(MTGUtils.colorIdentitiesToColor(card.getColorIdentity()));
loadMsg.complete(eb.build());
}
}
| gpl-3.0 |
khaosdoctor/my-notes | Redis/Exercises/redisscard/src/main/java/com/lucaslocal/redisscard/Redis.java | 757 | /*
* 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.lucaslocal.redisscard;
import java.util.Set;
import redis.clients.jedis.Jedis;
/**
*
* @author Lucas
*/
public class Redis {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
Set<String> grupos = jedis.keys("grupos:*");
for (String grupo : grupos) {
long res = jedis.scard(grupo);
Set<String> membros = jedis.smembers(grupo);
System.out.println(String.format("O grupo %s tem %d membros: %s", grupo.split(":")[1], res, membros.toString()));
}
}
}
| gpl-3.0 |
OpenSHAPA/openshapa | src/main/java/org/openshapa/views/discrete/datavalues/vocabelements/VocabElementEditorFactory.java | 3666 | /**
* 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.openshapa.views.discrete.datavalues.vocabelements;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.JTextComponent;
import org.openshapa.models.db.Argument;
import org.openshapa.models.db.Variable;
import org.openshapa.views.discrete.EditorComponent;
import org.openshapa.views.discrete.datavalues.FixedText;
/**
* A Factory for creating data value editors.
*/
public class VocabElementEditorFactory {
/**
* Constructor.
*/
private VocabElementEditorFactory() {
}
/**
* Creates a vector of editor components that represent the matrix in a
* data cell.
*
* @param ta The parent JTextComponent the editor is in.
* @param ve The parent VocabElement the editor is in.
* @param pv The parent VocabElementV the editor is in.
*
* @return A vector of editor components to represent the element.
*/
public static List<EditorComponent> buildVocabElement(final JTextComponent ta,
final Variable var,
final Argument ve,
final VocabElementV pv) {
List<EditorComponent> eds = new ArrayList<EditorComponent>();
if (ve != null) {
eds.add(new VENameEditor(ta, ve, var, pv));
eds.add(new FixedText(ta, "("));
int numArgs = ve.childArguments.size();
// For each of the arguments, build a view representation
for (int i = 0; i < numArgs; i++) {
eds.addAll(buildFormalArg(ta, ve, var, i, pv));
if (numArgs > 1 && i < (numArgs - 1)) {
eds.add(new FixedText(ta, ","));
}
}
eds.add(new FixedText(ta, ")"));
}
return eds;
}
/**
* Creates a vector of editor components to represent an argument of a
* data cell's matrix.
*
* @param ta The parent JTextComponent the editor is in.
* @param ve The parent VocabElement the editor is in.
* @param i The index of the argument within the element.
* @param pv The parent VocabElementV the editor is in.
*
* @return A vector of editor components to represent the argument.
*/
public static List<EditorComponent> buildFormalArg(JTextComponent ta,
Argument ve,
Variable var,
int i,
VocabElementV pv) {
List<EditorComponent> eds = new ArrayList<EditorComponent>();
eds.add(new FixedText(ta, "<"));
eds.add(new FormalArgEditor(ta, var, i, pv));
eds.add(new FixedText(ta, ":"));
eds.add(new FormalArgTypeEditor(ta, ve, i, pv));
eds.add(new FixedText(ta, ">"));
return eds;
}
} | gpl-3.0 |
p3et/dmgm | src/test/java/org/biiig/dmgm/impl/operators/patternmining/SubgraphMiningThresholdTestBase.java | 2306 | /*
* This file is part of Directed Multigraph Miner (DMGM).
*
* DMGM 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.
*
* DMGM 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 DMGM. If not, see <http://www.gnu.org/licenses/>.
*/
package org.biiig.dmgm.impl.operators.patternmining;
import org.biiig.dmgm.DmgmTestBase;
import org.biiig.dmgm.api.db.PropertyGraphDb;
import org.biiig.dmgm.api.operators.CollectionToCollectionOperator;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public abstract class SubgraphMiningThresholdTestBase extends DmgmTestBase {
protected abstract CollectionToCollectionOperator getOperator(
PropertyGraphDb db, boolean b, float minSupportRel, int maxEdgeCount);
@Test
public void mine10() {
mine(1.0f, 702);
}
@Test
public void mine08() {
mine(0.8f, 2106);
}
private void mine(float minSupportThreshold, int expectedResultSize) {
PropertyGraphDb db = getPredictableDatabase();
CollectionToCollectionOperator fsm =
getOperator(db, false, minSupportThreshold, 20);
long inId = db.createCollection(0, db.getGraphIds());
Long outId = fsm.apply(inId);
long[] graphIds = db.getGraphIdsOfCollection(outId);
assertEquals(
"sequential @ " + minSupportThreshold,expectedResultSize, graphIds.length);
fsm = getOperator(db, true, minSupportThreshold, 20);
outId = fsm.apply(inId);
graphIds = db.getGraphIdsOfCollection(outId);
assertEquals(
"parallel @ " + minSupportThreshold, expectedResultSize, graphIds.length);
}
protected CollectionFrequentSubgraphsMinerBuilder getBuilder(PropertyGraphDb db, boolean b, float minSupportRel, int maxEdgeCount) {
return new PatternMiningBuilder(db, b)
.fromCollection()
.extractFrequentSubgraphs(minSupportRel, maxEdgeCount);
}
} | gpl-3.0 |
huangshucheng/WXHBTools2.0 | app/src/main/java/com/junyou/hbks/apppayutils/WXPayUtil.java | 8079 | package com.junyou.hbks.apppayutils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.junyou.hbks.config.Constants;
import com.junyou.hbks.R;
import com.junyou.hbks.utils.LogUtil;
import com.junyou.hbks.utils.SaveMoneyUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
public class WXPayUtil {
public static WXPayUtil mInstance = null;
private static Context mContext = null;
private static final String TAG = "TAG";
private static IWXAPI api = null;
public static void init(Context context){
mContext = context;
api = WXAPIFactory.createWXAPI(mContext, Constants.APP_ID,true);
api.registerApp(Constants.APP_ID); //注册到微
}
public static WXPayUtil getInitialize(){
if (null == mInstance){
mInstance = new WXPayUtil();
}
return mInstance;
}
public class GetPrepayIdTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
if (null != mContext){
dialog = ProgressDialog.show(mContext,
mContext.getResources().getString(R.string.app_tip),
mContext.getResources().getString(R.string.getting_prepayid));
}
}
@Override
protected String doInBackground(String... params) {
// 网络请求获取预付Id
// Log.i(TAG, "后台费时操作");
String url = String.format(Constants.ORDER_URL);
//Log.i(TAG, "url: " + url);
String entity = genEntity();
// Log.i(TAG, "entity: " + entity);
if ("".equals(entity)){
return null;
}
byte[] buf = WeChatHttpClient.httpPost(url, entity);
if (buf != null && buf.length > 0) {
try {
// Log.i(TAG, "http request seccess");
Map<String, String> map = XmlUtil.doXMLParse(new String(buf));
// Log.i(TAG, "buff: " + new String(buf));
//Log.i(TAG, "pre_id: "+ (String) map.get("prepay_id"));
return (String) map.get("prepay_id");
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Log.i(TAG,"后台操作结束");
if (dialog != null) {
dialog.dismiss();
}
if (s == null){
//Log.i(TAG, "支付失败111");
if (mContext != null){
Toast.makeText(mContext, mContext.getResources().getString(R.string.get_prepayid_fail), Toast.LENGTH_SHORT).show();
}
}else {
try {
//Log.i(TAG,"发送支付订单!");
//Toast.makeText(WXPayUtil.activity, WXPayUtil.activity.getResources().getString(R.string.send_payorder), Toast.LENGTH_SHORT).show();
sendPayReq((String)s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
protected void onCancelled() {
super.onCancelled();
}
//调起支付
private void sendPayReq(String prepayId) {
PayReq req = new PayReq();
req.appId = Constants.APP_ID;
req.partnerId = Constants.PARTNER_ID;
req.prepayId = prepayId;
req.nonceStr = ComFunction.genNonceStr();
req.timeStamp = String.valueOf(ComFunction.genTimeStamp());
req.packageValue = "Sign=WXPay";
List signParams = new LinkedList<NameValuePair>();
signParams.add(new BasicNameValuePair("appid", req.appId));
signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
signParams.add(new BasicNameValuePair("package", req.packageValue));
signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//再次签名
req.sign = ComFunction.genPackageSign(signParams);
api.sendReq(req);
}
//下单参数
public String genEntity(){
if (mContext == null){
return null;
}
SharedPreferences sharedP= mContext.getSharedPreferences("config",mContext.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedP.edit();
String nonceStr = ComFunction.genNonceStr();
List<NameValuePair> packageParams = new ArrayList<NameValuePair>();
// APPID
packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
// 商品描述
//packageParams.add(new BasicNameValuePair("body", WXPayUtil.activity.getResources().getString(R.string.wx_pay)));
packageParams.add(new BasicNameValuePair("body", "微信支付"));
// 商户ID
packageParams.add(new BasicNameValuePair("mch_id",Constants.PARTNER_ID));
// 随机字符�?
packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
// 回调接口地址
packageParams.add(new BasicNameValuePair("notify_url",Constants.NOTIFY_URL));
// 我们的订单号 todo
String orderNo = ComFunction.genOutTradNo();
// Log.i(TAG, "orderNo: "+ orderNo);
//保存订单号
editor.putString(Constants.ORDER_NUM,orderNo);
editor.apply();
// Log.i(TAG, "保存订单号:" + sharedP.getString(Constants.ORDER_NUM, "null"));
packageParams.add(new BasicNameValuePair("out_trade_no", orderNo));
// 提交用户端ip
packageParams.add(new BasicNameValuePair("spbill_create_ip",ComFunction.getIPAddress()));
// String moneyNum = sharedP.getString(Constants.MONEY_NUM,"null");
// Log.i(TAG,"钱:" + moneyNum);
// BigDecimal totalFeeBig = new BigDecimal(moneyNum);
// int totalFee = totalFeeBig.multiply(new BigDecimal(1)).intValue();
// 总金额,单位分!
String moneyNum = SaveMoneyUtil.getInitialize(mContext).getMoneyCount();
packageParams.add(new BasicNameValuePair("total_fee", "" + moneyNum));
// 支付类型
packageParams.add(new BasicNameValuePair("trade_type", "APP"));
// 生成签名
String sign = ComFunction.genPackageSign(packageParams);
// Log.i(TAG, "签名: " + sign);
packageParams.add(new BasicNameValuePair("sign", sign));
String xmlstring = XmlUtil.toXml(packageParams);
try {
// Log.i(TAG, "xmlstring: " + xmlstring);
//避免商品描述中文字符编码格式造成支付失败
return new String(xmlstring.toString().getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
LogUtil.i(TAG, "genProductArgs fail, ex = " + e.getMessage());
}
return null;
}
}
}
| gpl-3.0 |
Axe2760/Coffee-Revamped | src/us/axe2760/coffee/IconMenu.java | 4297 | package us.axe2760.coffee;
/*Thanks nisovin! http://forums.bukkit.org/threads/icon-menu.108342/ */
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
public class IconMenu implements Listener {
private String name;
private int size;
private OptionClickEventHandler handler;
private Plugin plugin;
private String[] optionNames;
private ItemStack[] optionIcons;
public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) {
this.name = name;
this.size = size;
this.handler = handler;
this.plugin = plugin;
this.optionNames = new String[size];
this.optionIcons = new ItemStack[size];
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public IconMenu setOption(int position, ItemStack icon, String name, String... info) {
optionNames[position] = name;
optionIcons[position] = setItemNameAndLore(icon, name, info);
return this;
}
public void open(Player player) {
Inventory inventory = Bukkit.createInventory(player, size, name);
for (int i = 0; i < optionIcons.length; i++) {
if (optionIcons[i] != null) {
inventory.setItem(i, optionIcons[i]);
}
}
player.openInventory(inventory);
}
public void destroy() {
HandlerList.unregisterAll(this);
handler = null;
plugin = null;
optionNames = null;
optionIcons = null;
}
@EventHandler(priority= EventPriority.MONITOR)
void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().getTitle().equals(name)) {
event.setCancelled(true);
int slot = event.getRawSlot();
if (slot >= 0 && slot < size && optionNames[slot] != null) {
Plugin plugin = this.plugin;
OptionClickEvent e = new OptionClickEvent((Player)event.getWhoClicked(), slot, optionNames[slot]);
handler.onOptionClick(e);
if (e.willClose()) {
final Player p = (Player)event.getWhoClicked();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
p.closeInventory();
}
}, 1);
}
if (e.willDestroy()) {
destroy();
}
}
}
}
public interface OptionClickEventHandler {
public void onOptionClick(OptionClickEvent event);
}
public class OptionClickEvent {
private Player player;
private int position;
private String name;
private boolean close;
private boolean destroy;
public OptionClickEvent(Player player, int position, String name) {
this.player = player;
this.position = position;
this.name = name;
this.close = true;
this.destroy = false;
}
public Player getPlayer() {
return player;
}
public int getPosition() {
return position;
}
public String getName() {
return name;
}
public boolean willClose() {
return close;
}
public boolean willDestroy() {
return destroy;
}
public void setWillClose(boolean close) {
this.close = close;
}
public void setWillDestroy(boolean destroy) {
this.destroy = destroy;
}
}
private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) {
ItemMeta im = item.getItemMeta();
im.setDisplayName(name);
im.setLore(Arrays.asList(lore));
item.setItemMeta(im);
return item;
}
}
| gpl-3.0 |
ankit4u3/jtracert | src/com/google/code/jtracert/classFilter/ClassFilterProcessor.java | 2837 | package com.google.code.jtracert.classFilter;
import static com.google.code.jtracert.classFilter.FilterAction.ALLOW;
import static com.google.code.jtracert.classFilter.FilterAction.DENY;
import com.google.code.jtracert.classFilter.impl.AllowClassFilter;
import com.google.code.jtracert.classFilter.impl.DenyBootstrapAndExtensionsClassLoaders;
import com.google.code.jtracert.classFilter.impl.DenyClassByPackageNameFilter;
import com.google.code.jtracert.classFilter.impl.DenyJTracertClassesFilter;
import com.google.code.jtracert.agent.JTracertAgent;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
/**
* Distributed under GNU GENERAL PUBLIC LICENSE Version 3
*
* @author Dmitry.Bedrin@gmail.com
*/
public class ClassFilterProcessor {
private Collection<ClassFilter> classFilters = new LinkedList<ClassFilter>();
/**
*
*/
public ClassFilterProcessor() {
addFilter(new AllowClassFilter());
addFilter(new DenyJTracertClassesFilter());
if (!JTracertAgent.isRetransformSystemClasses()) {
addFilter(new DenyBootstrapAndExtensionsClassLoaders());
}
addFilter(new DenyClassByPackageNameFilter("sun.reflect")); // todo investigate why this filter is necessary
//addFilter(new DenyClassByPackageNameFilter("org.apache.log4j"));
}
/**
* @param classFilters
*/
public ClassFilterProcessor(Collection<ClassFilter> classFilters) {
this.classFilters = classFilters;
}
/**
* @param classFilter
* @return
*/
public synchronized boolean addFilter(ClassFilter classFilter) {
return classFilters.add(classFilter);
}
/**
* @param classFilter
* @return
*/
public synchronized boolean removeClassFilter(ClassFilter classFilter) {
return classFilters.remove(classFilter);
}
/**
* @return
*/
public Collection<ClassFilter> getClassFilters() {
return Collections.unmodifiableCollection(classFilters);
}
/**
* @param className
* @param classLoader
* @return
*/
public synchronized boolean processClass(String className, ClassLoader classLoader) {
FilterAction classNameFilterAction = ALLOW;
FilterAction classLoaderFilterAction = ALLOW;
for (ClassFilter classFilter : classFilters) {
classNameFilterAction =
classNameFilterAction.apply(classFilter.filterClassName(className));
classLoaderFilterAction =
classLoaderFilterAction.apply(classFilter.filterClassLoader(classLoader));
}
return !((DENY == classNameFilterAction) || (DENY == classLoaderFilterAction));
}
}
| gpl-3.0 |
dstmath/VirtualApp | VirtualApp/lib/src/main/java/com/lody/virtual/helper/utils/FileUtils.java | 12671 | package com.lody.virtual.helper.utils;
import android.os.Build;
import android.os.Parcel;
import android.system.Os;
import android.text.TextUtils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Lody
*/
public class FileUtils {
/**
* @param path
* @param mode {@link FileMode}
* @throws Exception
*/
public static void chmod(String path, int mode) throws Exception {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Os.chmod(path, mode);
return;
} catch (Exception e) {
// ignore
}
}
File file = new File(path);
String cmd = "chmod ";
if (file.isDirectory()) {
cmd += " -R ";
}
String cmode = String.format("%o", mode);
Runtime.getRuntime().exec(cmd + cmode + " " + path).waitFor();
}
public static void createSymlink(String oldPath, String newPath) throws Exception {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Os.symlink(oldPath, newPath);
} else {
Runtime.getRuntime().exec("ln -s " + oldPath + " " + newPath).waitFor();
}
}
public static boolean isSymlink(File file) throws IOException {
if (file == null)
throw new NullPointerException("File must not be null");
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
public static void writeParcelToFile(Parcel p, File file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
fos.write(p.marshall());
fos.close();
}
public static byte[] toByteArray(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (String file : children) {
boolean success = deleteDir(new File(dir, file));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static boolean deleteDir(File dir, Set<File> ignores) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (String file : children) {
boolean success = deleteDir(new File(dir, file), ignores);
if (!success) {
return false;
}
}
}
return ignores != null && ignores.contains(dir) || dir.delete();
}
public static boolean deleteDir(String dir) {
return deleteDir(new File(dir));
}
public static void writeToFile(InputStream dataIns, File target) throws IOException {
final int BUFFER = 1024;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
int count;
byte data[] = new byte[BUFFER];
while ((count = dataIns.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.close();
}
public static void writeToFile(byte[] data, File target) throws IOException {
FileOutputStream fo = null;
ReadableByteChannel src = null;
FileChannel out = null;
try {
src = Channels.newChannel(new ByteArrayInputStream(data));
fo = new FileOutputStream(target);
out = fo.getChannel();
out.transferFrom(src, 0, data.length);
} finally {
if (fo != null) {
fo.close();
}
if (src != null) {
src.close();
}
if (out != null) {
out.close();
}
}
}
public static void copyFile(File source, File target) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
FileChannel iChannel = inputStream.getChannel();
FileChannel oChannel = outputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = iChannel.read(buffer);
if (r == -1)
break;
buffer.limit(buffer.position());
buffer.position(0);
oChannel.write(buffer);
}
} finally {
closeQuietly(inputStream);
closeQuietly(outputStream);
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception ignored) {
}
}
}
public static int peekInt(byte[] bytes, int value, ByteOrder endian) {
int v2;
int v0;
if (endian == ByteOrder.BIG_ENDIAN) {
v0 = value + 1;
v2 = v0 + 1;
v0 = (bytes[v0] & 255) << 16 | (bytes[value] & 255) << 24 | (bytes[v2] & 255) << 8 | bytes[v2 + 1] & 255;
} else {
v0 = value + 1;
v2 = v0 + 1;
v0 = (bytes[v0] & 255) << 8 | bytes[value] & 255 | (bytes[v2] & 255) << 16 | (bytes[v2 + 1] & 255) << 24;
}
return v0;
}
private static boolean isValidExtFilenameChar(char c) {
switch (c) {
case '\0':
case '/':
return false;
default:
return true;
}
}
/**
* Check if given filename is valid for an ext4 filesystem.
*/
public static boolean isValidExtFilename(String name) {
return (name != null) && name.equals(buildValidExtFilename(name));
}
/**
* Mutate the given filename to make it valid for an ext4 filesystem,
* replacing any invalid characters with "_".
*/
public static String buildValidExtFilename(String name) {
if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) {
return "(invalid)";
}
final StringBuilder res = new StringBuilder(name.length());
for (int i = 0; i < name.length(); i++) {
final char c = name.charAt(i);
if (isValidExtFilenameChar(c)) {
res.append(c);
} else {
res.append('_');
}
}
return res.toString();
}
public interface FileMode {
int MODE_ISUID = 04000;
int MODE_ISGID = 02000;
int MODE_ISVTX = 01000;
int MODE_IRUSR = 00400;
int MODE_IWUSR = 00200;
int MODE_IXUSR = 00100;
int MODE_IRGRP = 00040;
int MODE_IWGRP = 00020;
int MODE_IXGRP = 00010;
int MODE_IROTH = 00004;
int MODE_IWOTH = 00002;
int MODE_IXOTH = 00001;
int MODE_755 = MODE_IRUSR | MODE_IWUSR | MODE_IXUSR
| MODE_IRGRP | MODE_IXGRP
| MODE_IROTH | MODE_IXOTH;
}
/**
* Lock the specified fle
*/
public static class FileLock {
private static FileLock singleton;
private Map<String, FileLockCount> mRefCountMap = new ConcurrentHashMap<String, FileLockCount>();
public static FileLock getInstance() {
if (singleton == null) {
singleton = new FileLock();
}
return singleton;
}
private int RefCntInc(String filePath, java.nio.channels.FileLock fileLock, RandomAccessFile randomAccessFile,
FileChannel fileChannel) {
int refCount;
if (this.mRefCountMap.containsKey(filePath)) {
FileLockCount fileLockCount = this.mRefCountMap.get(filePath);
int i = fileLockCount.mRefCount;
fileLockCount.mRefCount = i + 1;
refCount = i;
} else {
refCount = 1;
this.mRefCountMap.put(filePath, new FileLockCount(fileLock, refCount, randomAccessFile, fileChannel));
}
return refCount;
}
private int RefCntDec(String filePath) {
int refCount = 0;
if (this.mRefCountMap.containsKey(filePath)) {
FileLockCount fileLockCount = this.mRefCountMap.get(filePath);
int i = fileLockCount.mRefCount - 1;
fileLockCount.mRefCount = i;
refCount = i;
if (refCount <= 0) {
this.mRefCountMap.remove(filePath);
}
}
return refCount;
}
public boolean LockExclusive(File targetFile) {
if (targetFile == null) {
return false;
}
try {
File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
if (!lockFile.exists()) {
lockFile.createNewFile();
}
RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
FileChannel channel = randomAccessFile.getChannel();
java.nio.channels.FileLock lock = channel.lock();
if (!lock.isValid()) {
return false;
}
RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
return true;
} catch (Exception e) {
return false;
}
}
/**
* unlock odex file
**/
public void unLock(File targetFile) {
File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
if (!lockFile.exists()) {
return;
}
if (this.mRefCountMap.containsKey(lockFile.getAbsolutePath())) {
FileLockCount fileLockCount = this.mRefCountMap.get(lockFile.getAbsolutePath());
if (fileLockCount != null) {
java.nio.channels.FileLock fileLock = fileLockCount.mFileLock;
RandomAccessFile randomAccessFile = fileLockCount.fOs;
FileChannel fileChannel = fileLockCount.fChannel;
try {
if (RefCntDec(lockFile.getAbsolutePath()) <= 0) {
if (fileLock != null && fileLock.isValid()) {
fileLock.release();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
if (fileChannel != null) {
fileChannel.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private class FileLockCount {
FileChannel fChannel;
RandomAccessFile fOs;
java.nio.channels.FileLock mFileLock;
int mRefCount;
FileLockCount(java.nio.channels.FileLock fileLock, int mRefCount, RandomAccessFile fOs,
FileChannel fChannel) {
this.mFileLock = fileLock;
this.mRefCount = mRefCount;
this.fOs = fOs;
this.fChannel = fChannel;
}
}
}
}
| gpl-3.0 |
timcoffman/java-m-engine | EpicAnnotationJdkProcessing/src/test/java/edu/vanderbilt/clinicalsystems/epic/annotation/RoutineTestUtils.java | 6930 | package edu.vanderbilt.clinicalsystems.epic.annotation;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.regex.Pattern;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class RoutineTestUtils {
private final Class<?> m_resourceBase;
public RoutineTestUtils( Class<?> resourceBase ) {
m_resourceBase = resourceBase ;
}
private static final Pattern IGNORE_LINES_M_LANGUAGE = Pattern.compile("Generated-On|^\\s*;|^\\s*$") ;
private static final Pattern IGNORE_LINES_TREE = Pattern.compile("^###|^\\s*$") ;
private File findOutputFolder( File dir, String pkgName ) {
if ( null == pkgName || pkgName.isEmpty() )
return dir ;
String[] s = pkgName.split("\\.",2) ;
File pkgDir = new File( dir, s[0] ) ;
if ( s.length < 2 )
return pkgDir ;
return findOutputFolder( pkgDir, s[1] );
}
public void canProcessRoutineAnnotations(String name) throws URISyntaxException, IOException {
File destinationDir = File.createTempFile("generated-sources-", null ) ;
destinationDir.delete() ;
destinationDir.mkdir() ;
File packageDir = findOutputFolder( destinationDir, m_resourceBase.getPackage().getName() );
try {
URL sourceResource = m_resourceBase.getResource( name + ".java" );
if ( null == sourceResource )
throw new IOException("source resource (" + name + ".java) is not available for testing" ) ;
process( sourceResource, destinationDir ) ;
URL actualResourceMLanguage = new File( packageDir, name + ".m" ).toURI().toURL();
URL actualResourceTree = new File( packageDir, name + ".tree" ).toURI().toURL();
URL actualMetaTree = new File( packageDir, name + ".xml" ).toURI().toURL();
assertThat( actualResourceMLanguage, notNullValue() ) ;
assertThat( actualResourceTree, notNullValue() ) ;
assertThat( actualMetaTree, notNullValue() ) ;
try ( java.util.Scanner s = new java.util.Scanner( actualMetaTree.openStream() ) ) {
System.out.println( s.useDelimiter("\\A").next() ) ;
}
URL expectedResourceMLanguage = m_resourceBase.getResource( name + "Expected.m");
URL expectedResourceTree = m_resourceBase.getResource( name + "Expected.tree");
if ( null == expectedResourceMLanguage && null == expectedResourceTree )
throw new IOException("neither an M-Language resource (" + name + "Expected.m) nor a Tree expected resource (" + name + "Expected.tree) was available for testing") ;
if ( null != expectedResourceMLanguage ) {
assertThatResourceContentsEqual( actualResourceMLanguage, expectedResourceMLanguage, IGNORE_LINES_M_LANGUAGE ) ;
}
if ( null != expectedResourceTree ) {
assertThatResourceContentsEqual( actualResourceTree, expectedResourceTree, IGNORE_LINES_TREE ) ;
}
} finally {
File[] files = destinationDir.listFiles();
if ( null != files )
for ( File file : files )
file.delete() ;
destinationDir.delete() ;
}
}
private void process( URL resourceFile, File destinationDir ) throws URISyntaxException, IOException { process( new File( resourceFile.toURI() ), destinationDir ) ; }
private void process( File resourceFile, File destinationDir ) throws IOException { process( getSourceFileResources(resourceFile), destinationDir ) ; }
private void process( Iterable<? extends JavaFileObject> files, File destinationDir ) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null) ;
standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton( destinationDir ) );
CompilationTask task = compiler.getTask(new PrintWriter(System.out), standardFileManager, null, null, null, files);
task.setProcessors(Arrays.asList(new Processor()));
task.call();
}
private Iterable<? extends JavaFileObject> getSourceFileResources(File resourceFile) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager files = compiler.getStandardFileManager(null, null, null);
return files.getJavaFileObjects(resourceFile) ;
}
private String finalPathComponent( URL resource ) {
return resource.getPath().replaceAll("^.*/","") ;
}
private static final int CONTEXT_LINES = 5 ;
private void assertThatResourceContentsEqual( URL actualResource, URL expectedResource, Pattern ignoreLines ) throws FileNotFoundException, IOException, URISyntaxException {
int actualLineNumber = 0 ;
int expectedLineNumber = 0 ;
Deque<String> actualQueue = new ArrayDeque<String>() ;
boolean passed = false ;
try ( BufferedReader actualReader = new BufferedReader( new FileReader( new File(actualResource.toURI()) ) ) ) {
try ( BufferedReader expectedReader = new BufferedReader( new FileReader( new File(expectedResource.toURI()) ) ) ) {
try {
String actualLine ;
String expectedLine ;
do {
do {
++expectedLineNumber ;
expectedLine = expectedReader.readLine() ;
} while ( null != expectedLine && null != ignoreLines && ignoreLines.matcher(expectedLine).find() ) ;
do {
++actualLineNumber ;
actualLine = actualReader.readLine() ;
} while ( null != actualLine && null != ignoreLines && ignoreLines.matcher(actualLine).find() ) ;
if ( null != actualLine ) {
actualQueue.offer(actualLine) ;
while ( actualQueue.size() > CONTEXT_LINES ) actualQueue.remove() ;
}
assertThat( finalPathComponent(actualResource) + "#" + actualLineNumber + " is equal to " + finalPathComponent(expectedResource) + "#" + expectedLineNumber, actualLine, equalTo(expectedLine) ) ;
} while ( null != expectedLine ) ;
assertThat( "line #" + actualLineNumber + " is the end of file", actualLine, nullValue() ) ;
passed = true ;
} finally {
if ( !passed ) {
String line ;
while ( actualQueue.size() > 1 )
System.out.println( " > " + actualQueue.remove() ) ;
if ( !actualQueue.isEmpty() )
System.out.println( "!!! " + actualQueue.remove() ) ;
for ( int i = 0 ; i < CONTEXT_LINES ; ++i ) {
line = actualReader.readLine() ;
if ( null != line )
System.out.println( " > " + line ) ;
}
}
}
}
}
}
}
| gpl-3.0 |
boost-starai/BoostSRL | code/src/edu/wisc/cs/will/MLN_Task/MLN_Task.java | 84265 | /**
*
*/
package edu.wisc.cs.will.MLN_Task;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.wisc.cs.will.FOPC.BindingList;
import edu.wisc.cs.will.FOPC.Clause;
import edu.wisc.cs.will.FOPC.Constant;
import edu.wisc.cs.will.FOPC.Function;
import edu.wisc.cs.will.FOPC.FunctionName;
import edu.wisc.cs.will.FOPC.HandleFOPCstrings;
import edu.wisc.cs.will.FOPC.Literal;
import edu.wisc.cs.will.FOPC.PredicateName;
import edu.wisc.cs.will.FOPC.PredicateSpec;
import edu.wisc.cs.will.FOPC.Sentence;
import edu.wisc.cs.will.FOPC.Term;
import edu.wisc.cs.will.FOPC.Type;
import edu.wisc.cs.will.FOPC.TypeSpec;
import edu.wisc.cs.will.FOPC.Unifier;
import edu.wisc.cs.will.FOPC.Variable;
import edu.wisc.cs.will.ResThmProver.HornClauseProver;
import edu.wisc.cs.will.Utils.Utils;
/**
* Richardson, M. and Domingos, P.,
* Markov logic networks,
* Machine Learning, 62, pp. 107-136, 2006.
* http://alchemy.cs.washington.edu/papers/richardson06/
*
* Note: literals in clauses will be processed faster if any constant arguments are the FIRST argument (of course might not always be possible).
* Could index on ALL positions (or the first K), but might not be worth the increase in space.
*
* @author shavlik
*
*/
public class MLN_Task {
private static final int debugLevel = 2; //Integer.MIN_VALUE;
public boolean useAllClauses = false; // JWSJWSJWS If false, only use those that unify with a query or hidden literal. (Might want all for some sorts of experiments.)
protected final static int maxWarnings = 100;
protected int warningCount = 0; // Count how many warnings provided to user; stop when some maximum number reached.
public double maxNumberOfQueryLiterals = 1e8;
public double maxNumberOfHiddenLiterals = 1e8;
private boolean checkForNewConstants = true; // Turn off when done to save time, plus once starting grounding a network, new constants would mess up things.
public boolean haveEliminatedNegativeWeightClauses = false; // Record this in case other (non-MCSAT) inference methods want to complain.
public double minWgtToBeHardClause = 0.75 * Sentence.maxWeight; // Used by some algorithms (e.g., MCSAT) to see if 'hard' clauses are satisfied.
public HandleFOPCstrings stringHandler;
public Unifier unifier;
public HornClauseProver prover;
public int maxConstantsOfGivenType = 1000000; // When more than this many constants of a given type, discard randomly until this many.
public int maxGroundingsOfLiteral = 1000000000; // When finding the groundings of a LITERAL, limit to this many. This is also the max size of JOINED argument lists.
public int maxGroundingsOfClause = 1000000000; // When finding the groundings of a CLAUSE, limit to this many.
protected String workingDirectory;
protected Collection<Clause> allClauses; // Not many of these, so no need to hash.
private Set<GroundLiteral> queryLiterals; // Make these sets since we don't want any duplicates.
private Set<GroundLiteral> hiddenLiterals; // Do NOT apply the closed-world assumption to these.
private Set<GroundLiteral> posQueryLiteralsForTraining;
private Set<GroundLiteral> negQueryLiteralsForTraining;
private Set<GroundLiteral> posEvidenceLiterals; // No need to allow this to be given as PredName as well, since presumably we do not want to say ALL are positive (or negative).
private Set<GroundLiteral> negEvidenceLiterals;
public Set<GroundLiteral> posEvidenceInQueryLiterals;// These are the query literals that were present in the positive evidence. They must be returned with probability 1.
public Set<GroundLiteral> negEvidenceInQueryLiterals;// These are the query literals that were present in the negative evidence. They must be returned with probability 0.
private boolean closedWorldAssumption = true; // Assume a literal is false if its truth value is not known.
// All literals that meet one of these spec's is a literal of the associated type.
// More compact that creating all such literals, but might be expanded later in any case (also, one might not want ALL groundings to be in the given class, and in that case explicit lits of grounded literals should be used).
// Also, can add something like 'p(x,y)' to a literal collection, which is the same (???) as putting 'p/2' in a Collection<PredNameArityPair>.
private Set<PredNameArityPair> queryPredNames; // TODO - if these are used with GroundThisMarkovNetwork, then need to ground before inference?
private Set<PredNameArityPair> hiddenPredNames; // These need to be SETs (at least in the creators) so that duplicates are not added.
private Set<PredNameArityPair> posEvidencePredNames; // Probably rarely used, since can then remove from clauses, but allow them anyway.
private Set<PredNameArityPair> negEvidencePredNames; // Ditto.
private Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> knownQueriesThisPnameArity;
private Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> knownHiddensThisPnameArity;
private Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> knownPosEvidenceThisPnameArity;
private Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> knownNegEvidenceThisPnameArity;
private boolean knownQueriesThisPnameArityHasVariables = false;
private boolean knownHiddensThisPnameArityHasVariables = false;
private boolean knownPosEvidenceThisPnameArityHasVariables = false;
private boolean knownNegEvidenceThisPnameArityHasVariables = false;
// Can override the default value for closed-world assumption.
private Map<PredicateName,Set<Integer>> neverCWAonThisPredNameArity;
private Map<PredicateName,Set<Integer>> alwaysCWAonThisPredNameArity;
private Literal trueLiteral, falseLiteral;
protected Set<FunctionName> skolemFunctions = null; // Record which functions are Skolems (Skolems need to be created by the stringHandler, not based on strings entered by the user).
protected Map<PredicateName,Set<Integer>> skolemsPresent = null; // Record which literals are associated with Skolem functions.
private Variable skolemMarker1 = null; // Skolem arguments are replaced with this marker, so it can be used to match any fact (no logical inference is done, so this works, but be careful of 'unit propagation' or the like is used).
private Variable skolemMarker2 = null; // A given literal can have more than one skolem variable,
private Variable skolemMarker3 = null; // so allow up to five in a clause (if more throw error, suggesting code be extended).
private Variable skolemMarker4 = null;
private Variable skolemMarker5 = null;
private Variable[] allSkolemMarkers = new Variable[5];
protected Set<Variable> setOfSkolemMarkers; // Duplicate for fast lookup.
protected Map<Literal,Set<Term>> skolemsPerLiteral; // Be sure to not COPY literals or this will be screwed up!
private Map<Type,Set<Term>> hashOfTypeToConstants; // Record all the constants of a given type. Use Term here so can become argument lists without copying.
private Map<Type,Set<Term>> hashOfTypeToReducedConstants; // A subset of the above, used for reducing the size of the ground Markov network via sampling.
// TODO is the following still used?
private Map<PredicateName,Map<Integer,Set<Clause>>> predNameToClauseList; // A hash table which gives all the clauses a literal (specified by predicateName/arity) appears in.
private Map<Integer,List<GroundLiteral>> hashOfGroundLiterals;
// private Map<PredicateName,Map<Integer,Map<Constant,Map<Constant,List<GroundLiteral>>>>> hashOfGroundLiterals2; // A hash table for quickly finding literals given a predicateName/arity pair.
// The next two are used after reductions to answer queries.
private Map<PredicateName,Map<Integer,Set<Literal>>> pNameArityToLiteralMap; // Record for each predicateName/arity, the literals in which it appears. NOTE: each literal is assumed to be UNIQUE (and not further copying can be done). MLN_Task does create copies of each literal in pre-processing, so that should suffice.
protected Map<Literal,Clause> literalToClauseMap; // Map literals to the clauses in which they appear. NOTE: this assumes that literals are NOT canonically represented.
private Map<Type,Set<Constant>> constantTypePairsHandled = new HashMap<Type,Set<Constant>>(4); // Used to prevent unnecessary calls to the stringHandler. TODO - move this to the string handler, as a space-time tradeoff.
private TimeStamp timeStamp;
/**
* Instances of this class hold all the common information in an MNL task.
*/
public MLN_Task(HandleFOPCstrings stringHandler) {
this(stringHandler, new Unifier(), new HornClauseProver(stringHandler));
}
// The next variant is called by the others to set up various things.
public MLN_Task(HandleFOPCstrings stringHandler, Unifier unifier, HornClauseProver prover) {
this.stringHandler = stringHandler;
this.unifier = unifier;
this.prover = prover;
stringHandler.setUseStrictEqualsForLiterals(false); // The MLN code does a lot of indexing on literals, and sometimes on clauses, and we don't want spurious matches (even though due to variables being separately named per literal, this probably isn't necessary).
stringHandler.setUseStrictEqualsForClauses( true);
//Utils.println("% The procedurallyDefinedPredicates = " + prover.getProcedurallyDefinedPredicates()); Utils.waitHere();
hashOfTypeToConstants = new HashMap<Type,Set<Term>>(4);
hashOfTypeToReducedConstants = new HashMap<Type,Set<Term>>(4);
hashOfGroundLiterals = new HashMap<Integer,List<GroundLiteral>>(4);
// hashOfGroundLiterals2 = new HashMap<PredicateName,Map<Integer,Map<Constant,Map<Constant,List<GroundLiteral>>>>>(4);
knownQueriesThisPnameArity = new HashMap<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>>(4);
knownHiddensThisPnameArity = new HashMap<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>>(4);
knownPosEvidenceThisPnameArity = new HashMap<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>>(4);
knownNegEvidenceThisPnameArity = new HashMap<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>>(4);
}
// Can only pass in predicateName/arity information.
public MLN_Task(HandleFOPCstrings stringHandler, Unifier unifier, HornClauseProver prover,
Collection<Clause> allClauses,
Set<PredNameArityPair> queryPredNames,
Set<PredNameArityPair> posEvidencePredNames,
Set<PredNameArityPair> negEvidencePredNames,
Set<PredNameArityPair> hiddenPredNames,
boolean closedWorldAssumption) {
this(stringHandler, unifier, prover);
if (allClauses != null) { setAllClauses(allClauses); }
if (queryPredNames != null) { setQueryPredNames(queryPredNames); }
if (hiddenPredNames != null) { setHiddenPredNames(hiddenPredNames); }
if (posEvidencePredNames != null) { setPosEvidencePredNames(posEvidencePredNames); }
if (negEvidencePredNames != null) { setNegEvidencePredNames(negEvidencePredNames); }
setClosedWorldAssumption(closedWorldAssumption);
}
// Or can pass in collections of groundings. NOTE: closedWorldAssumption is in a different position here so that this doesn't match the above (since the types of the Collections don't matter to this aspect of the compiler).
public MLN_Task(HandleFOPCstrings stringHandler, Unifier unifier, HornClauseProver prover, boolean closedWorldAssumption,
Collection<Clause> allClauses,
Collection<Literal> queryLiterals,
Collection<Literal> posEvidenceLiterals,
Collection<Literal> negEvidenceLiterals,
Collection<Literal> hiddenLiterals) {
this(stringHandler, unifier, prover);
if (allClauses != null) { setAllClauses(allClauses); }
if (queryLiterals != null) { setQueryLiterals(queryLiterals); }
if (hiddenLiterals != null) { setHiddenLiterals(hiddenLiterals); }
if (posEvidenceLiterals != null) { setPosEvidenceLiterals(posEvidenceLiterals); }
if (negEvidenceLiterals != null) { setNegEvidenceLiterals(negEvidenceLiterals); }
setClosedWorldAssumption(closedWorldAssumption);
}
// Or can mix-and-match (but cannot include both PredNameArityPair's and Literal's for the same category.)
public MLN_Task(HandleFOPCstrings stringHandler, Unifier unifier, HornClauseProver prover,
Collection<Clause> allClauses,
Collection<Literal> queryLiterals, // Can directly provide the literals of a given category.
Set<PredNameArityPair> queryPredNames, // Or can give their predicateName/arity pairs (but not both).
Collection<Literal> posEvidenceLiterals,
Set<PredNameArityPair> posEvidencePredNames,
Collection<Literal> negEvidenceLiterals,
Set<PredNameArityPair> negEvidencePredNames,
Collection<Literal> hiddenLiterals,
Set<PredNameArityPair> hiddenPredNames,
boolean closedWorldAssumption) {
this(stringHandler, unifier, prover);
if (allClauses != null) { setAllClauses(allClauses); }
if (queryLiterals != null) { setQueryLiterals(queryLiterals); }
if (hiddenLiterals != null) { setHiddenLiterals(hiddenLiterals); }
if (posEvidenceLiterals != null) { setPosEvidenceLiterals(posEvidenceLiterals); }
if (negEvidenceLiterals != null) { setNegEvidenceLiterals(negEvidenceLiterals); }
if (queryPredNames != null) { setQueryPredNames(queryPredNames); }
if (hiddenPredNames != null) { setHiddenPredNames(hiddenPredNames); }
if (posEvidencePredNames != null) { setPosEvidencePredNames(posEvidencePredNames); }
if (negEvidencePredNames != null) { setNegEvidencePredNames(negEvidencePredNames); }
setClosedWorldAssumption(closedWorldAssumption);
}
public void setPosQueryLiteralsForTraining(Set<GroundLiteral> lits) {
if (lits != null) { setQueryLiteralsForTraining(lits, true); }
}
public void setNegQueryLiteralsForTraining(Set<GroundLiteral> lits) {
if (lits != null) { setQueryLiteralsForTraining(lits, false); }
}
private void createTrueLiteralAndClause() {
if (trueLiteral == null) { trueLiteral = stringHandler.trueLiteral; }
if (falseLiteral == null) {falseLiteral = stringHandler.falseLiteral; }
}
public Literal getTrueLiteral() { return trueLiteral; }
public Literal getFalseLiteral() { return falseLiteral; }
private Set<Type> warningNoConstantsThisType;
public Set<Term> getReducedConstantsOfThisType(Type type) {
if (!hashOfTypeToConstants.containsKey(type)) {
Set<Term> allConstantsOfThisType = stringHandler.isaHandler.getAllInstances(type);
if (allConstantsOfThisType == null) {
if (warningNoConstantsThisType == null || !warningNoConstantsThisType.contains(type)) {
if (warningNoConstantsThisType == null) { warningNoConstantsThisType = new HashSet<Type>(4); }
warningNoConstantsThisType.add(type);
Utils.warning("Have no constants of type '" + type + "'.");
}
return null;
}
hashOfTypeToConstants.put(type, allConstantsOfThisType);
if (allConstantsOfThisType.size() > maxConstantsOfGivenType) {
Set<Term> reducedSet = new HashSet<Term>(4);
reducedSet.addAll(allConstantsOfThisType); // A bit inefficient to copy (especially if lots discarded), but this way we get exactly the desired number.
hashOfTypeToReducedConstants.put(type, Utils.reduceToThisSizeByRandomlyDiscardingItemsInPlace(reducedSet, maxConstantsOfGivenType));
} else { hashOfTypeToReducedConstants.put(type, allConstantsOfThisType); }
if (debugLevel > -10) {
Utils.println("% Have " + Utils.padLeft(allConstantsOfThisType.size(), 7) + " constants of type = '" + type + "'"
+ (allConstantsOfThisType.size() > maxConstantsOfGivenType ? ", reduced to " + Utils.comma(hashOfTypeToReducedConstants.get(type).size()) : "")
+ ".");
}
}
return hashOfTypeToReducedConstants.get(type);
}
public void setQueryPredNames(Set<PredNameArityPair> queryPredNames) {
if (this.queryPredNames == null) { this.queryPredNames = queryPredNames; }
else { Utils.error("Already have some query predicateNames/arities: " + Utils.limitLengthOfPrintedList(this.queryPredNames, 25)); }
}
private boolean calledCreateAllQueryLiterals = false;
protected void createAllQueryLiterals() {
if (calledCreateAllQueryLiterals) { return; }
calledCreateAllQueryLiterals = true;
if (queryPredNames == null) { return; }
if (queryLiterals != null) { Utils.error("Already have some query literals: " + Utils.limitLengthOfPrintedList(queryLiterals, 25)); }
queryLiterals = new HashSet<GroundLiteral>(4);
if (debugLevel > -10) { Utils.println("% queryPredNames = " + Utils.limitLengthOfPrintedList(queryPredNames, 25)); }
for (PredNameArityPair predNameArityPair : queryPredNames) {
Set<GroundLiteral> groundings = groundThisLiteral(predNameArityPair);
if (true) { Utils.println("% Have " + Utils.comma(groundings) + " groundings for query " + predNameArityPair+ "."); }
if (groundings != null) { queryLiterals.addAll(groundings); }
else { Utils.error("Have no groundings for query: " + predNameArityPair); }
}
int numbQueries = Utils.getSizeSafely(queryLiterals);
if (debugLevel > 0) { Utils.println("% Number of query literals generated from queryPredNames: " + Utils.comma(numbQueries)); }
if (numbQueries > maxNumberOfQueryLiterals) { Utils.error("Too many query literals. Note that the current code requires they all be explicitly grounded, even with lazy inference, since statistics need to be collected for each."); }
}
public void setHiddenPredNames(Set<PredNameArityPair> hiddenPredNames) {
if (this.hiddenPredNames == null) { this.hiddenPredNames = hiddenPredNames; }
else { Utils.error("Already have some hidden predicateNames/arities: " + Utils.limitLengthOfPrintedList(this.hiddenPredNames, 25)); }
}
private boolean calledCreateAllHiddenLiterals = false;
protected void createAllHiddenLiterals() {
if (calledCreateAllHiddenLiterals) { return; }
calledCreateAllHiddenLiterals = true;
if (hiddenPredNames == null) { return; }
if (hiddenLiterals != null) { Utils.error("Already have some hidden literals: " + Utils.limitLengthOfPrintedList(hiddenLiterals, 25)); }
hiddenLiterals = new HashSet<GroundLiteral>(4);
if (debugLevel > 0) { Utils.println("% hiddenPredNames = " + hiddenPredNames); }
for (PredNameArityPair predNameArityPair : hiddenPredNames) {
Set<GroundLiteral> groundings = groundThisLiteral(predNameArityPair);
if (true) { Utils.println("% Have " + Utils.comma(groundings) + " groundings for hidden " + predNameArityPair+ "."); }
if (groundings != null) { hiddenLiterals.addAll(groundings); }
else { Utils.error("Have no groundings for hidden: " + predNameArityPair); }
}
int numbQueries = Utils.getSizeSafely(hiddenLiterals);
if (debugLevel > 0) { Utils.println("% Size of hidden literals generated from hiddenPredNames: " + Utils.getSizeSafely(hiddenLiterals)); }
if (numbQueries > maxNumberOfHiddenLiterals) { Utils.error("Too many hidden literals. Note that the current code requires they all be explicitly grounded, even with lazy inference, since statistics need to be collected for each."); }
}
public void setPosEvidencePredNames(Set<PredNameArityPair> posEvidencePredNames) {
if (this.posEvidencePredNames == null) { this.posEvidencePredNames = posEvidencePredNames; }
else { Utils.error("Already have some positive-evidence predicateNames/arities: " + Utils.limitLengthOfPrintedList(this.posEvidencePredNames, 25)); }
}
private boolean calledCreateAllPositiveEvidence = false;
public void createAllPositiveEvidence() {
if (calledCreateAllPositiveEvidence) { return; }
calledCreateAllPositiveEvidence = true;
if (posEvidenceLiterals != null) { Utils.error("Already have some positive-evidence literals: " + Utils.limitLengthOfPrintedList(posEvidenceLiterals, 25)); }
posEvidenceLiterals = new HashSet<GroundLiteral>(4);
for (PredNameArityPair predNameArityPair : posEvidencePredNames) {
Set<GroundLiteral> groundings = groundThisLiteral(predNameArityPair);
if (true) { Utils.println("% Have " + Utils.comma(groundings) + " groundings for positive evidence " + predNameArityPair+ "."); }
if (groundings != null) { posEvidenceLiterals.addAll(groundings); }
else { Utils.error("Have no groundings for positive evidence: " + predNameArityPair); }
}
if (debugLevel > 0) { Utils.println("% Size of positive-evidence literals generated from evidencePredNames: " + Utils.getSizeSafely(posEvidenceLiterals)); }
}
public void setNegEvidencePredNames(Set<PredNameArityPair> negEvidencePredNames) {
if (this.negEvidencePredNames == null) { this.negEvidencePredNames = negEvidencePredNames; }
else { Utils.error("Already have some negative-evidence predicateNames/arities: " + Utils.limitLengthOfPrintedList(this.negEvidencePredNames, 25)); }
}
private boolean calledCreateAllNegativeEvidence = false;
public void createAllNegativeEvidence() {
if (calledCreateAllNegativeEvidence) { return; }
calledCreateAllNegativeEvidence = true;
if (negEvidenceLiterals != null) { Utils.error("Already have some negative-evidence literals: " + Utils.limitLengthOfPrintedList(negEvidenceLiterals, 25)); }
negEvidenceLiterals = new HashSet<GroundLiteral>(4);
for (PredNameArityPair predNameArityPair : negEvidencePredNames) {
Set<GroundLiteral> groundings = groundThisLiteral(predNameArityPair);
if (true) { Utils.println("% Have " + Utils.comma(groundings) + " groundings for negative evidence " + predNameArityPair+ "."); }
if (groundings != null) { negEvidenceLiterals.addAll(groundings); }
else { Utils.error("Have no groundings for negative evidence: " + predNameArityPair); }
}
if (debugLevel > 0) { Utils.println("% Size of negative-evidence literals generated from evidencePredNames: " + Utils.getSizeSafely(negEvidenceLiterals)); }
}
private boolean conflictingData = false;
private void checkForConflictsInPredNames() {
if (initialized) { Utils.error("Should not call after initialization."); }
conflictingData = false;
checkForIntersectingPredNames("query literals", queryPredNames, "hidden literals", hiddenPredNames);
checkForIntersectingPredNames("query literals", queryPredNames, "pos-evidence literals", posEvidencePredNames);
checkForIntersectingPredNames("query literals", queryPredNames, "neg-evidence literals", negEvidencePredNames);
checkForIntersectingPredNames("hidden literals", hiddenPredNames, "pos-evidence literals", posEvidencePredNames);
checkForIntersectingPredNames("hidden literals", hiddenPredNames, "neg-evidence literals", negEvidencePredNames);
checkForIntersectingPredNames("pos-evidence literals", posEvidencePredNames, "neg-evidence literals", negEvidencePredNames);
comparePredNamesAndLiterals( "query literals", queryPredNames);
comparePredNamesAndLiterals( "hidden literals", hiddenPredNames);
comparePredNamesAndLiterals( "pos-evidence literals", posEvidencePredNames);
comparePredNamesAndLiterals( "neg-evidence literals", negEvidencePredNames);
if (conflictingData) { Utils.error("Due to conflicting data, aborting."); }
}
// See if any of these pairs are in specific evidence.
private void comparePredNamesAndLiterals(String name, Collection<PredNameArityPair> pairs) {
comparePredNamesAndLiteralsThisMap(name, pairs, "query literals", knownQueriesThisPnameArity);
comparePredNamesAndLiteralsThisMap(name, pairs, "hidden literals", knownHiddensThisPnameArity);
comparePredNamesAndLiteralsThisMap(name, pairs, "pos-evidence literals", knownPosEvidenceThisPnameArity);
comparePredNamesAndLiteralsThisMap(name, pairs, "neg-evidence literals", knownNegEvidenceThisPnameArity);
}
private void checkForIntersectingPredNames(String name1, Collection<PredNameArityPair> pairs1, String name2, Collection<PredNameArityPair> pairs2) {
if (pairs1 == null || pairs2 == null) { return; }
for (PredNameArityPair pair1 : pairs1) if (pairs2.contains(pair1)) {
conflictingData = true;
Utils.println("% Conflicting data! PredName/arity specification for the " + name1 + " of '" + pair1 + "' is also in predName/arity specification for " + name2 + ".");
}
}
private void comparePredNamesAndLiteralsThisMap(String name, Collection<PredNameArityPair> pairs, String mapName, Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> map) {
if (pairs == null || map == null) { return; }
for (PredNameArityPair pair : pairs) {
Map<Integer,Map<Term,Collection<GroundLiteral>>> lookup1 = map.get(pair.pName);
if (lookup1 == null) { continue; }
Map<Term,Collection<GroundLiteral>> lookup2 = lookup1.get(pair.arity);
if (lookup2 == null) { continue; }
Collection<GroundLiteral> lookup3 = lookup2.get(null); // Get the 'all first arguments' list.
if (Utils.getSizeSafely(lookup3) > 0) {
conflictingData = true;
Utils.println("% Conflicting data! PredName/arity specification for the " + name + " of '" + pair + "' conflicts with the set of specific " + mapName + ", which contains: " + Utils.limitLengthOfPrintedList(lookup3, 25));
}
}
}
// This function checks and removes any evidence literals from the query literals.
private void removeAnyEvidenceFromQuery(){
if (Utils.getSizeSafely(queryLiterals) < 1) { return; }
Iterator<GroundLiteral> it = queryLiterals.iterator();
while(it.hasNext()){
GroundLiteral currLiteral = it.next();
if (posEvidenceLiterals!=null && posEvidenceLiterals.contains(currLiteral)) {
if (posEvidenceInQueryLiterals == null) { posEvidenceInQueryLiterals = new HashSet<GroundLiteral>(); }
posEvidenceInQueryLiterals.add(currLiteral);
it.remove();
}
else if (negEvidenceLiterals != null && negEvidenceLiterals.contains(currLiteral)) {
if (negEvidenceInQueryLiterals == null) { negEvidenceInQueryLiterals = new HashSet<GroundLiteral>(); }
negEvidenceInQueryLiterals.add(currLiteral);
it.remove();
}
}
}
/**
* Populate the predNameToClauseList data structure.
*/
private void populateLiteralToClauseList() {
predNameToClauseList = new HashMap<PredicateName,Map<Integer,Set<Clause>>>(4);
if (allClauses == null) { Utils.error("Should not have allClauses = null."); }
for (Clause currClause : allClauses) { // Walk through the structure (i.e., the set of clauses).
for (int i = 0; i < 2; i++) {
Iterator<Literal> iter = null;
if (i == 0 && currClause.posLiterals != null) {
iter = currClause.posLiterals.iterator();
} else if (currClause.negLiterals != null) {
iter = currClause.negLiterals.iterator();
}
if (iter == null) { continue; }
while (iter.hasNext()) {
Literal literal = iter.next();
PredicateName predName = literal.predicateName;
int arity = literal.numberArgs();
Map<Integer,Set<Clause>> lookup1 = predNameToClauseList.get(predName); // Get the clause list for this predicate name.
Set<Clause> lookup2 = null;
if (lookup1 == null) {
lookup1 = new HashMap<Integer,Set<Clause>>(4);
predNameToClauseList.put(predName, lookup1);
lookup2 = new HashSet<Clause>(4);
lookup1.put(arity, lookup2);
} else {
lookup2 = lookup1.get(arity); // Get the clause list for this predicateName/arity pair.
if (lookup2 == null) {
lookup2 = new HashSet<Clause>(4);
lookup1.put(arity, lookup2);
}
}
lookup2.add(currClause);
}
}
}
}
Set<Variable> varsInLiterals; // The next two methods use this to save some argument passing.
Map<FunctionName,Variable> skolemsInClauseMapToReplacement; // Ditto.
int locationInSkolemMarkerArray = 0; // Ditto.
private Collection<Clause> preprocessForSkolems(Collection<Clause> rawClauses) {
if (rawClauses == null) { return null; }
Collection<Clause> results = new ArrayList<Clause>(rawClauses.size());
int numbOfSkolemMarkers = 5;
skolemMarker1 = stringHandler.getExternalVariable("SkolemForMLNs");
skolemMarker2 = stringHandler.getExternalVariable("SkolemForMLNs");
skolemMarker3 = stringHandler.getExternalVariable("SkolemForMLNs");
skolemMarker4 = stringHandler.getExternalVariable("SkolemForMLNs");
skolemMarker5 = stringHandler.getExternalVariable("SkolemForMLNs");
allSkolemMarkers[0] = skolemMarker1;
allSkolemMarkers[1] = skolemMarker2;
allSkolemMarkers[2] = skolemMarker3;
allSkolemMarkers[3] = skolemMarker4;
allSkolemMarkers[4] = skolemMarker5;
setOfSkolemMarkers = new HashSet<Variable>(8);
skolemsPerLiteral = new HashMap<Literal,Set<Term>>(4);
for (int i = 0; i < numbOfSkolemMarkers; i++) { setOfSkolemMarkers.add(allSkolemMarkers[i]); }
skolemsInClauseMapToReplacement = new HashMap<FunctionName,Variable>(4);
boolean warning = false;
for (Clause clause : rawClauses) {
varsInLiterals = new HashSet<Variable>(4);
skolemsInClauseMapToReplacement.clear(); // In case clauses are ever used for resolution, consistently deal with Skolems across an entire clause.
locationInSkolemMarkerArray = 0; // Reset count for each CLAUSE (NOT for each literal).
List<Literal> newPos = processSkolemInLiterals(clause.posLiterals, true);
Set<Variable> varsInLiteralsPOS = new HashSet<Variable>(4);
varsInLiteralsPOS.addAll(varsInLiterals);
varsInLiterals = new HashSet<Variable>(4);
List<Literal> newNeg = processSkolemInLiterals(clause.negLiterals, false);
if (Utils.getSizeSafely(clause.negLiterals) > 0) for (Variable var : varsInLiteralsPOS) if (!varsInLiterals.contains(var)) { // Don't report singletons since their use is recommended by Pedro for MLNs. Actually, don't report unless any implication.
Utils.println("\n% WARNING: Should this be an existential variable '" + var + "'?\n% " + clause.toString(Integer.MAX_VALUE) + "?");
warning = true;
}
Clause newClause = stringHandler.getClause(newPos, newNeg);
newClause.setWeightOnSentence(clause.getWeightOnSentence());
newClause.setBodyContainsCut(clause.getBodyContainsCut());
results.add(newClause);
}
if (skolemFunctions != null) {
Utils.println("% Skolems in use: " + skolemFunctions);
Utils.println("% Literals with these Skolems: " + skolemsPresent);
}
if (debugLevel > 0 && warning) { Utils.waitHere(); }
return results;
}
// If there are any Skolem functions in these literals, replace the Skolem argument with a skolemMarker.
// If there are any other functions, look up their values (TODO - actually, these will need to be done at time of GROUNDING!).
private List<Literal> processSkolemInLiterals(List<Literal> literals, boolean pos) {
if (literals == null) { return null; }
List<Literal> results = new ArrayList<Literal>(literals.size());
Set<Term> skolemMarkersThisLiteral = new HashSet<Term>(4);
for (Literal lit : literals) {
if (lit.numberArgs() < 1) { results.add(lit); continue; }
PredicateName pName = lit.predicateName;
Literal newLit = lit.copy(false); // This will insure all the properties of the literal are properly assigned, even of a small waste in copying the list holding the arguments.
List<Term> arguments2 = new ArrayList<Term>(lit.numberArgs());
skolemMarkersThisLiteral.clear();
for (Term term : lit.getArguments()) if (term instanceof Function) {
if (((Function) term).functionName.isaSkolem) {
if (!pos) { Utils.println("Note: a Skolem in a NEGATED literal found: " + term + " in " + lit); Utils.waitHere("bug somewhere?"); }
FunctionName fName = ((Function) term).functionName;
if (skolemFunctions == null) { skolemFunctions = new HashSet<FunctionName>(4); }
skolemFunctions.add(fName);
Variable markerToUse = skolemsInClauseMapToReplacement.get(fName);
if (debugLevel > 1) { Utils.println("% Marker to use for Skolem '" + fName + "' is '" + markerToUse + "'."); }
if (skolemsPresent == null) { skolemsPresent = new HashMap<PredicateName,Set<Integer>>(4); }
Set<Integer> lookup = skolemsPresent.get(pName); // skolemsPresent not used currently, but seems worth keeping this information.
if (lookup == null) {
lookup = new HashSet<Integer>(4);
skolemsPresent.put(pName, lookup);
}
lookup.add(lit.numberArgs()); // Since a Set, deals with duplicates.
if (markerToUse == null) { // Not yet encountered in this clause.
if (locationInSkolemMarkerArray >= 5) { Utils.error("Have too many Skolems (max = 5) in one clause. Processing: " + lit); }
markerToUse = allSkolemMarkers[locationInSkolemMarkerArray++]; // Get next free one.
if (debugLevel > 1) { Utils.println("% Need a NEW marker: " + markerToUse); }
if (skolemsInClauseMapToReplacement == null) { skolemsInClauseMapToReplacement = new HashMap<FunctionName,Variable>(4); }
skolemsInClauseMapToReplacement.put(fName, markerToUse);
}
skolemMarkersThisLiteral.add(markerToUse); // A Set, so will handle duplicates properly.
arguments2.add(markerToUse);
} else {
Utils.error("Need to write code that looks up values of non-Skolem functions: " + term);
}
} else {
if (term instanceof Variable) { varsInLiterals.add((Variable) term); }
arguments2.add(term);
}
newLit.setArguments(arguments2);
results.add(newLit);
if (!skolemMarkersThisLiteral.isEmpty()) { skolemsPerLiteral.put(newLit, skolemMarkersThisLiteral); }
}
return results;
}
// Ground the network with respect to the clauses containing (i.e., unify with) query or hidden literals.
public GroundedMarkovNetwork createReducedNetwork() {
if (!initialized) { initialize(); }
Collection<Clause> clausesContainingQueryOrHiddenLiterals;
if (useAllClauses) {
clausesContainingQueryOrHiddenLiterals = allClauses;
} else {
if (debugLevel > 0) { Utils.println("\n% Creating a grounded network. First indexing all clauses in which query or hidden literals appear."); }
clausesContainingQueryOrHiddenLiterals = new HashSet<Clause>(4); // Use a set so duplicates removed.
Utils.println("% queryPredNames=" + Utils.limitLengthOfPrintedList(queryPredNames));
if (queryPredNames != null) for (PredNameArityPair pair : queryPredNames) {
Collection<Clause> matchingClauses = getClausesContainingThisPredNameAndArity(pair.pName, pair.arity);
if (debugLevel > 0) { Utils.println("% For query '" + pair + "' have collected: " + Utils.limitLengthOfPrintedList(matchingClauses, 25)); }
if (matchingClauses != null) { clausesContainingQueryOrHiddenLiterals.addAll(matchingClauses); }
else if (warningCount < maxWarnings) { Utils.println("% MLN WARNING #" + Utils.comma(++warningCount) + ": no clauses match " + pair + "."); }
}
if (debugLevel > 0 && queryPredNames != null) { Utils.println("% Done with the " + Utils.comma(Utils.getSizeSafely(queryPredNames)) + " query predicate/arity names: " + Utils.limitLengthOfPrintedList(queryPredNames, 25)); }
Utils.println("% hiddenPredNames=" + Utils.limitLengthOfPrintedList(hiddenPredNames));
if (hiddenPredNames != null) for (PredNameArityPair pair : hiddenPredNames) {
Collection<Clause> matchingClauses = getClausesContainingThisPredNameAndArity(pair.pName, pair.arity);
if (debugLevel > 0) { Utils.println("% For hidden '" + pair + "' have collected: " + Utils.limitLengthOfPrintedList(matchingClauses, 25)); }
if (matchingClauses != null) { clausesContainingQueryOrHiddenLiterals.addAll(matchingClauses); }
else if (warningCount < maxWarnings) { Utils.println("% MLN WARNING #" + Utils.comma(++warningCount) + ": no clauses match " + pair); }
}
if (debugLevel > 0 && hiddenPredNames != null) { Utils.println("% Done with the " + Utils.comma(Utils.getSizeSafely(hiddenPredNames)) + " hidden predicate/arity names: " + Utils.limitLengthOfPrintedList(hiddenPredNames, 25)); }
Utils.println("% queryLiterals=" + Utils.limitLengthOfPrintedList(queryLiterals));
if (queryLiterals != null) for (Literal lit : queryLiterals) {
Collection<Clause> unifyingClauses = getClausesThatUnifyWithThisLiteral(lit, false);
if (debugLevel > 0) { Utils.println("% For query '" + lit + "' have collected: " + Utils.limitLengthOfPrintedList(unifyingClauses, 25)); }
if (unifyingClauses != null) { clausesContainingQueryOrHiddenLiterals.addAll(unifyingClauses); } // Do NOT apply bindings.
}
if (debugLevel > 0 && queryLiterals != null) { Utils.println("% Done with the " + Utils.comma(queryLiterals) + " query literals: " + Utils.limitLengthOfPrintedList(queryLiterals, 25)); }
Utils.println("% hiddenLiterals=" + Utils.limitLengthOfPrintedList(hiddenLiterals));
if (hiddenLiterals != null) for (Literal lit : hiddenLiterals) {
Collection<Clause> unifyingClauses = getClausesThatUnifyWithThisLiteral(lit, false);
if (debugLevel > 0) { Utils.println("% For hidden '" + lit + "' have collected: " + Utils.limitLengthOfPrintedList(unifyingClauses, 25)); }
if (unifyingClauses != null) { clausesContainingQueryOrHiddenLiterals.addAll(unifyingClauses); } // Do NOT apply bindings.
}
if (debugLevel > 0 && hiddenLiterals != null) { Utils.println("% Done with the " + Utils.comma(hiddenLiterals) + " hidden literals: " + Utils.limitLengthOfPrintedList(hiddenLiterals, 25)); }
}
if (debugLevel > 0) {
Utils.println("% Have collected " + Utils.comma(clausesContainingQueryOrHiddenLiterals) + " clauses: " + Utils.limitLengthOfPrintedList(clausesContainingQueryOrHiddenLiterals, 25));
}
GroundedMarkovNetwork grounder = new GroundedMarkovNetwork(this, clausesContainingQueryOrHiddenLiterals);
grounder.analyzeClauses();
return grounder;
}
@SuppressWarnings("unused")
private GroundedMarkovNetwork createAllClausesGroundedNetwork() {
GroundedMarkovNetwork grounder = new GroundedMarkovNetwork(this, allClauses);
grounder.analyzeClauses();
return grounder;
}
// TODO - make this generic and put in some utilities class.
// If this literal is not in this 'database' (db), add it and return true. Otherwise return false.
@SuppressWarnings("unused")
private boolean addIfNotPresent(GroundLiteral gLit, Map<PredicateName,Map<Integer,List<GroundLiteral>>> db) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
Map<Integer,List<GroundLiteral>> lookup1 = db.get(pName);
if (lookup1 == null) {
lookup1 = new HashMap<Integer,List<GroundLiteral>>(4);
db.put(pName, lookup1); // Add to DB.
}
List<GroundLiteral> lookup2 = lookup1.get(arity);
if (lookup2 == null) {
lookup2 = new ArrayList<GroundLiteral>(1);
lookup1.put(arity, lookup2); // A new arity, so add to DB.
if (arity == 0) { // If got here with a zero-argument literal, then it is not yet present.
return lookup2.add(gLit);
}
}
if (arity == 0) { return false; } // This zero-argument literal is already present. (Code below would still work, but leave this hear anyway.)
List<Term> args = gLit.getArguments();
boolean foundMatch = false;
for (GroundLiteral inDB : lookup2) {
boolean matches = true;
for (int i = 0; i < arity; i++) if (!args.get(i).equals(inDB.getArgument(i))) {
matches = false;
break;
}
if (matches) {
foundMatch = true;
break;
}
}
if (!foundMatch) { return lookup2.add(gLit); }
return false;
}
/**
* Get all groundings of the literal whose predicate name and arity are passed as an argument.
* Postcondition: Be wary that at the end of this method, gndClauseList in the resulting ground literals in not initialized.
*
* @param predName
* We want to get all groundings of this predicate name and arity.
* @return Return all the groundings of predName/arity.
*/
private Set<GroundLiteral> groundThisLiteral(PredNameArityPair predNameArity) {
if (predNameArity == null) { Utils.error("Should not have predNameArity=null."); }
//Literal literal = convertPredNameArityPairToLiteral(predNameArity);
Set<GroundLiteral> results = new HashSet<GroundLiteral>(4);
if (predNameArity.arity < 1) { // Handle case of a literal with NO arguments.
Literal lit = stringHandler.getLiteral(predNameArity.pName);
GroundLiteral gndLiteral = getCanonicalRepresentative(lit);
results.add(gndLiteral);
return results;
}
// Collect all the types in the literal.
Collection<TypeSpec> typeSpecs = collectLiteralArgumentTypes(predNameArity.pName, predNameArity.arity);
if (debugLevel > -10) { Utils.println("% In groundThisLiteral(" + predNameArity + ") with typeSpecs = " + typeSpecs); }
List<Set<Term>> allArgPossibilities = new ArrayList<Set<Term>>(typeSpecs.size());
for (TypeSpec typeSpec : typeSpecs) { // Need to convert from lists of constants to lists of terms at some point. Might as well do it here (seems work the same regardless).
Set<Term> constants = getReducedConstantsOfThisType(typeSpec.isaType);
if (constants != null) {
Set<Term> convertConstantsToTerms = new HashSet<Term>(4);
convertConstantsToTerms.addAll(constants);
allArgPossibilities.add(convertConstantsToTerms);
} else {
//allArgPossibilities.add(null);
return null; // There are no groundings.
}
}
if (debugLevel > -10) {
int size = 1;
if (debugLevel > 3) { Utils.println(" allArgPossibilities = " + allArgPossibilities); }
for (Set<Term> possibilities : allArgPossibilities) { size *= Utils.getSizeSafely(possibilities); }
Utils.print("% Will produce " + Utils.comma(size) + " groundings. [1"); // TODO - filter if too many?
for (Set<Term> possibilities : allArgPossibilities) { Utils.print(" x " + possibilities.size()); }
Utils.println("]");
}
List<List<Term>> crossProduct = Utils.computeCrossProduct(allArgPossibilities, maxGroundingsOfLiteral);
int counter = 0;
for (List<Term> argList : crossProduct) {
if (debugLevel > -10 && ++counter % 100000 == 0) { Utils.println("% counter = " + Utils.comma(counter)); }
Literal lit = stringHandler.getLiteral(predNameArity.pName, argList);
GroundLiteral gndLiteral = getCanonicalRepresentative(lit);
results.add(gndLiteral);
}
if (debugLevel > 2) { Utils.println("% Returning " + Utils.comma(Utils.getSizeSafely(results)) + " results\n"); }
return results;
}
// Find the canonical (and grounded) representation of this literal, which should contain only constants as arguments.
// Hash on predicate name, arity, and the first two arguments (after which, do a linear lookup).
// Add this Literal to hashOfGroundLiterals if it isn't already there, unless requested not do so.
// Return the entry in hashOfGroundLiterals for the (grounded version of this) literal (or null if not there and not requested to add it).
// NOTE: literal signs are IGNORED in this method, so users of these GroundLiteral's need to maintain sign elsewhere (other p(1) and ~p(1) will not match).
// also, weights are ignored, so if they differ, a new design is needed here.
private int countOfCanonicalGroundLiterals = 0;
public int getCountOfCanonicalGroundLiterals() {
int counter = 0;
int counter2 = 0;
int max = 0;
Integer indexOfMax = 0;
for (Integer index : hashOfGroundLiterals.keySet()) {
int size = hashOfGroundLiterals.get(index).size();
//Utils.println(" " + Utils.limitLengthOfPrintedList(hashOfGroundLiterals.get(index), 25));
counter += size;
if (size > max) { max = size; indexOfMax = index; }
if (size > 1) { counter2++; }
}
Utils.println("\n% There are " + Utils.comma(countOfCanonicalGroundLiterals) + " unique ground literals.");
Utils.println("% |canonical ground-literal hash codes| = " + Utils.comma(hashOfGroundLiterals.keySet().size()) +
", |hash of ground literals| = " + Utils.comma(counter) +
", |with collisions| = " + Utils.comma(counter2) +
", max # of collisions = " + Utils.comma(max));
Utils.println("% max collisions: " + Utils.limitLengthOfPrintedList(hashOfGroundLiterals.get(indexOfMax), 25));
//Utils.waitHere();
return countOfCanonicalGroundLiterals;
}
private GroundLiteral newGlit_hold;
private Integer hashcode_hold;
public void storeGroundLiteralBeingHeld() {
if (hashcode_hold != null) {
List<GroundLiteral> lookup = hashOfGroundLiterals.get(hashcode_hold);
if (lookup == null) {
lookup = new ArrayList<GroundLiteral>(1);
hashOfGroundLiterals.put(hashcode_hold, lookup);
}
lookup.add(newGlit_hold);
countOfCanonicalGroundLiterals++;
if (checkForNewConstants) { collectTypedConstants(newGlit_hold.predicateName, newGlit_hold.getArguments()); } // Check for new constants when first stored.
if (debugLevel > 2) { Utils.println("% new ground literal: " + newGlit_hold); }
}
}
public GroundLiteral getCanonicalRepresentative(Literal lit) {
return getCanonicalRepresentative(lit, true, false);
}
public GroundLiteral getCanonicalRepresentative(Literal lit, boolean storeIfNotThere, boolean postponeAddition) {
boolean hold = stringHandler.useFastHashCodeForLiterals;
stringHandler.useFastHashCodeForLiterals = false; // Need this setting in order to get proper matching of equivalent literals.
int hash = lit.hashCode();
stringHandler.useFastHashCodeForLiterals = hold;
List<GroundLiteral> lookup = hashOfGroundLiterals.get(hash);
if (lookup == null) {
if (!storeIfNotThere) { return null; } // Return an indicator that this literal is not in the hash table.
} else {
for (GroundLiteral gLit : lookup) if (gLit.matchesThisGroundLiteral(lit)) { // Check the literals that hashed here.
newGlit_hold = null;
hashcode_hold = null;
return gLit; // Have found the canonical representative. No need to store anything later.
}
if (!storeIfNotThere) { return null; } // Return an indicator that this literal is not in the hash table.
}
// This literal is new. Convert to a GroundLiteral (if not already), add to hash table, and return it.
GroundLiteral newGlit = (lit instanceof GroundLiteral ? (GroundLiteral) lit : new GroundLiteral(lit));
newGlit_hold = newGlit; /// If postponeAddition = true, then we'll add these later (e.g., after calling code decides if these should be stored).
hashcode_hold = hash;
if (!postponeAddition) { storeGroundLiteralBeingHeld(); }
return newGlit;
}
/* TODO delete after 2/15/09
public GroundLiteral getCanonicalRepresentative2(Literal lit, boolean storeIfNotThere, boolean postponeAddition) {
PredicateName pName = lit.predicateName;
int arity = lit.numberArgs();
Constant arg0 = (arity == 0 ? null : (Constant) lit.getArgument(0)); // For 0-arity literals, use 'null' as the first argument.
Constant arg1 = (arity <= 1 ? null : (Constant) lit.getArgument(1)); // For 0- and 1-arity literals, use 'null' as the second argument.
boolean pavedNewGround = false; // Indicate if NEW memory created (if so, this literal has not been seen before).
Map<Integer,Map<Constant,Map<Constant,List<GroundLiteral>>>> lookup1 = hashOfGroundLiterals2.get(pName);
if (lookup1 == null) {
if (!storeIfNotThere) { return null; }
lookup1 = new HashMap<Integer,Map<Constant,Map<Constant,List<GroundLiteral>>>>(4);
hashOfGroundLiterals2.put(pName, lookup1);
pavedNewGround = true;
}
Map<Constant,Map<Constant,List<GroundLiteral>>> lookup2 = lookup1.get(arity);
if (lookup2 == null) {
if (!storeIfNotThere) { return null; }
lookup2 = new HashMap<Constant,Map<Constant,List<GroundLiteral>>>(4);
lookup1.put(arity, lookup2);
pavedNewGround = true;
}
Map<Constant,List<GroundLiteral>> lookup3 = lookup2.get(arg0);
if (lookup3 == null) {
if (!storeIfNotThere) { return null; }
lookup3 = new HashMap<Constant,List<GroundLiteral>>(4);
lookup2.put(arg0, lookup3);
pavedNewGround = true;
}
List<GroundLiteral> lookup4 = lookup3.get(arg1);
if (lookup4 == null) {
if (!storeIfNotThere) { return null; }
lookup4 = new ArrayList<GroundLiteral>(1);
lookup3.put(arg1, lookup4);
pavedNewGround = true;
}
if (!pavedNewGround && lookup4.size() > 0) { // Note that the lookup4 space might have been created yet nothing stored, due to postponeAddition=true.
// Now need to walk through lookup4 to see if literal's representative is in there.
if (arity <= 2) { return lookup4.get(0); } // Only one ground literal can reach these.
List<Term> litArgs = lit.getArguments();
for (GroundLiteral gLit : lookup4) { // Still need to check the rest of the literals.
boolean haveFoundIt = true;
List<Term> gLitArgs = gLit.getArguments();
for (int i = 2; i < arity; i++) if (gLitArgs.get(i) != litArgs) { haveFoundIt = false; continue; }
if (haveFoundIt) { return gLit; } // Have found the canonical representative.
}
}
if (!storeIfNotThere) { return null; } // Return an indicator that this literal is not in the hash table.
// This literal is new. Convert to a GroundLiteral (if not already), add to hash table, and return it.
GroundLiteral newGlit = (lit instanceof GroundLiteral ? (GroundLiteral) lit : new GroundLiteral(lit));
lookup4_hold = lookup4;
newGlit_hold = newGlit;
if (!postponeAddition) { storeGroundLiteralBeingHeld(); }
return newGlit;
}
*/
public Set<Clause> getClauseListFromPredNameAndArity(Literal lit) {
return getClauseListFromPredNameAndArity(lit.predicateName, lit.numberArgs());
}
public Set<Clause> getClauseListFromPredNameAndArity(PredicateName pName, int arity) {
Map<Integer,Set<Clause>> lookup1 = predNameToClauseList.get(pName);
if (lookup1 == null) { Utils.error("Cannot find " + pName + "/" + arity + " in " + Utils.limitLengthOfPrintedList(predNameToClauseList, 25)); }
Set<Clause> lookup2 = lookup1.get(arity);
if (lookup2 == null) { Utils.error("Cannot find " + pName + "/" + arity + " in " + lookup1); }
return lookup2;
}
// Return a list of types for the arguments in this literal.
public List<TypeSpec> collectLiteralArgumentTypes(Literal literal) {
return collectLiteralArgumentTypes(literal.predicateName, literal.numberArgs());
}
public List<TypeSpec> collectLiteralArgumentTypes(PredicateName pName, int arity) {
if (arity < 1) { return null; }
List<PredicateSpec> typeList = pName.getTypeOnlyList(arity);
// Currently ASSUME each literal has only one typeList. TODO - relax assumption
if (Utils.getSizeSafely(typeList) < 1) { Utils.error("Could not find the argument types for: '" + pName + "/" + arity + "'."); }
if (typeList.size() > 1) {
if (warningCount < maxWarnings) { Utils.println("% MLN WARNING #" + Utils.comma(++warningCount) + ": There is more than one mode for: '" + pName + "/" + arity + "'. " + typeList + " Will only use first one."); }
}
return typeList.get(0).getTypeSpecList();
}
public boolean isaQueryLiteral(Literal lit) {
if (queryLiterals != null) { return queryLiterals.contains(lit); }
return false;
}
public boolean isaPositiveEvidenceLiteral(GroundLiteral lit) {
if (debugLevel > 2) { Utils.print("*** Is '" + lit + "' in positive evidence " + Utils.limitLengthOfPrintedList(posEvidenceLiterals, 25)); }
boolean foundInPos = false;
if (posEvidenceLiterals != null) { foundInPos = posEvidenceLiterals.contains(lit); }
if (posEvidencePredNames != null) { Utils.error("Need to look here as well - TODO."); }
if (debugLevel > 2) { Utils.println((foundInPos ? " YES" : " NO")); }
return foundInPos;
}
public boolean isaNegativeEvidenceLiteral(GroundLiteral lit) {
if (debugLevel > 2) { Utils.print("*** Is '" + lit + "' in negative evidence " + Utils.limitLengthOfPrintedList(negEvidenceLiterals, 25)); }
boolean foundInNeg = false;
if (negEvidenceLiterals != null) { foundInNeg = negEvidenceLiterals.contains(lit); }
if (negEvidencePredNames != null) { Utils.error("Need to look here as well - TODO."); }
if (debugLevel > 2) { Utils.println((foundInNeg ? " YES" : " NO")); }
return foundInNeg;
}
public boolean isaEvidenceLiteral(GroundLiteral lit) {
return (isaNegativeEvidenceLiteral(lit) || isaPositiveEvidenceLiteral(lit));
}
// Don't use this, since we really care about those clauses that were grounded, which can be a subset of this.
//private Collection<Clause> getAllClauses() {
// return allClauses;
//}
public int getTotalNumberOfClauses() {
return Utils.getSizeSafely(allClauses);
}
public void setAllClauses(Collection<Clause> allClauses) {
if (allClauses == null) { Utils.error("Should not call with allClauses = null."); }
this.allClauses = preprocessForSkolems(allClauses);
populateLiteralToClauseList();
}
public void setAllClauses(Clause clause) {
if (clause == null) { Utils.error("Should not call with clause = null."); }
Collection<Clause> clauseList = new ArrayList<Clause>(1);
clauseList.add(clause);
setAllClauses(clauseList);
}
public void setNoCWApredNames(Collection<PredNameArityPair> noCWApredNames) {
if (noCWApredNames == null) { return; }
if (neverCWAonThisPredNameArity == null) { neverCWAonThisPredNameArity = new HashMap<PredicateName,Set<Integer>>(4); }
for (PredNameArityPair pair : noCWApredNames) {
addAlwaysCWAonThisPredNameArity(pair.pName, pair.arity);
}
}
public void setYesCWApredNames(Collection<PredNameArityPair> yesCWApredNames) {
if (yesCWApredNames == null) { return; }
if (alwaysCWAonThisPredNameArity == null) { alwaysCWAonThisPredNameArity = new HashMap<PredicateName,Set<Integer>>(4); }
for (PredNameArityPair pair : yesCWApredNames) {
addAlwaysCWAonThisPredNameArity(pair.pName, pair.arity);
}
}
public void addNeverCWAonThisPredNameArity(PredicateName pName, int arity) {
if (neverCWAonThisPredNameArity == null) { neverCWAonThisPredNameArity = new HashMap<PredicateName,Set<Integer>>(4); }
addToCWAoverrides(pName, arity, neverCWAonThisPredNameArity);
}
public void addAlwaysCWAonThisPredNameArity(PredicateName pName, int arity) {
if (alwaysCWAonThisPredNameArity == null) { alwaysCWAonThisPredNameArity = new HashMap<PredicateName,Set<Integer>>(4); }
addToCWAoverrides(pName, arity, alwaysCWAonThisPredNameArity);
}
private void addToCWAoverrides(PredicateName pName, int arity, Map<PredicateName,Set<Integer>> map) {
Set<Integer> lookup = map.get(pName);
if (lookup == null) {
lookup = new HashSet<Integer>(4);
map.put(pName, lookup);
}
lookup.add(arity);
}
// If the first argument in a gLit is a VARIABLE, then can no longer index on the first variable.
// In this case do not add more to the index based on constants. TODO erase all old items if any, but only do so the FIRST time a variable encountered.
private void addToKnowns(GroundLiteral gLit, boolean gLitHasVars, Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> map) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
Term firstArg = (arity < 1 ? null : gLit.getArgument(0));
Map<Integer,Map<Term,Collection<GroundLiteral>>> lookup1 = map.get(pName);
if (lookup1 == null) {
lookup1 = new HashMap<Integer,Map<Term,Collection<GroundLiteral>>>(4);
map.put(pName, lookup1);
}
Map<Term,Collection<GroundLiteral>> lookup2 = lookup1.get(arity);
if (lookup2 == null) {
lookup2 = new HashMap<Term,Collection<GroundLiteral>>(4);
lookup1.put(arity, lookup2);
}
// Each gLit whose first argument is a constant is put in two lists.
if (!gLitHasVars && firstArg != null && firstArg instanceof Constant) {
Collection<GroundLiteral> lookup3a = lookup2.get(firstArg);
if (lookup3a == null) {
lookup3a = new ArrayList<GroundLiteral>(1);
lookup2.put(firstArg, lookup3a);
}
lookup3a.add(gLit);
}
// All gLit's are in the entry.
Collection<GroundLiteral> lookup3b = lookup2.get(null);
if (lookup3b == null) {
lookup3b = new ArrayList<GroundLiteral>(1);
lookup2.put(null, lookup3b);
}
lookup3b.add(gLit);
}
public boolean isaKnownLiteral(Literal gLit) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
return isaKnownLiteral(pName, arity);
}
public boolean isaKnownLiteral(PredicateName pName, int arity) {
return (Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownPosEvidenceThisPnameArity)) > 0 ||
Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownQueriesThisPnameArity)) > 0 ||
Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownHiddensThisPnameArity)) > 0 ||
Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownNegEvidenceThisPnameArity)) > 0);
}
public boolean isInQueries(Literal gLit) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
return isInQueries(pName, arity);
}
public boolean isInQueries(PredicateName pName, int arity) {
return Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownQueriesThisPnameArity)) > 0;
}
public boolean isInHiddens(Literal gLit) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
return isInHiddens(pName, arity);
}
public boolean isInHiddens(PredicateName pName, int arity) {
return Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownHiddensThisPnameArity)) > 0;
}
public boolean isInEvidence(Literal gLit) {
PredicateName pName = gLit.predicateName;
int arity = gLit.numberArgs();
return isInEvidence(pName, arity);
}
public boolean isInEvidence(PredicateName pName, int arity) {
return (Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownPosEvidenceThisPnameArity)) > 0 ||
Utils.getSizeSafely(getKnownsCollection(pName, arity, null, knownNegEvidenceThisPnameArity)) > 0);
}
public Collection<GroundLiteral> getQueryKnowns(Literal lit) {
return getKnownsCollection(lit, knownQueriesThisPnameArityHasVariables, knownQueriesThisPnameArity);
}
public Collection<GroundLiteral> getHiddenKnowns(Literal lit) {
return getKnownsCollection(lit, knownHiddensThisPnameArityHasVariables, knownHiddensThisPnameArity);
}
public Collection<GroundLiteral> getPosEvidenceKnowns(Literal lit) {
return getKnownsCollection(lit, knownPosEvidenceThisPnameArityHasVariables, knownPosEvidenceThisPnameArity);
}
public Collection<GroundLiteral> getNegEvidenceKnowns(Literal lit) {
return getKnownsCollection(lit, knownNegEvidenceThisPnameArityHasVariables, knownNegEvidenceThisPnameArity);
}
private Collection<GroundLiteral> getKnownsCollection(Literal lit, boolean hasVariables, Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> map) {
PredicateName pName = lit.predicateName;
int arity = lit.numberArgs();
Term firstArg = (hasVariables || arity < 1 ? null : lit.getArgument(0)); // If there are variables in this Map, then don't use constants index since if we did we would need to merge two lists (TODO - rethink this space-time tradeoff).
return getKnownsCollection(pName, arity, firstArg, map);
}
private Collection<GroundLiteral> getKnownsCollection(PredicateName pName, int arity, Term firstArg, Map<PredicateName,Map<Integer,Map<Term,Collection<GroundLiteral>>>> map) {
Map<Integer,Map<Term,Collection<GroundLiteral>>> lookup1 = map.get(pName);
if (lookup1 == null) { return null; }
Map<Term,Collection<GroundLiteral>> lookup2 = lookup1.get(arity);
if (lookup2 == null) { return null; }
if (firstArg != null && firstArg instanceof Constant) { return lookup2.get(firstArg); }
return lookup2.get(null);
}
public Set<GroundLiteral> getQueryLiterals() {
return queryLiterals;
}
public void setQueryLiterals(Collection<Literal> queryLiterals) {
setQueryLiterals(queryLiterals, true);
}
public void setQueryLiterals(Collection<Literal> queryLiterals, boolean complainIfNonNull) {
if (initialized) { Utils.error("Should not call after initialization."); }
if (complainIfNonNull && this.queryLiterals != null) {
Utils.error("Already have queryLiterals = " + Utils.limitLengthOfPrintedList(this.queryLiterals, 25));
}
if (queryLiterals == null) { Utils.error("Should not call with queryLiterals = null."); }
this.queryLiterals = new HashSet<GroundLiteral>(4);
int counter = 0;
if (queryLiterals != null) for (Literal literal : queryLiterals) {
GroundLiteral gLit = null;
boolean hasVariables = literal.containsVariables();
if (hasVariables) { // Handle facts with variables specially - they are pulled out by GroundThisMarkovNetwork in factsWithVariables.
collectTypedConstants(literal.predicateName, literal.getArguments()); // Check for new constants.
gLit = new GroundLiteral(literal);
} else {
gLit = getCanonicalRepresentative(literal);
}
this.queryLiterals.add(gLit);
knownQueriesThisPnameArityHasVariables = hasVariables || knownQueriesThisPnameArityHasVariables;
addToKnowns(gLit, knownQueriesThisPnameArityHasVariables, knownQueriesThisPnameArity);
gLit.setValue(Utils.random() > 0.5, null, timeStamp); // Give a random setting to query variables.
counter++; if (counter % 10000 == 0) { Utils.println("% Have hashed and collected constants from " + Utils.comma(counter) + " query literals."); }
}
}
public Collection<GroundLiteral> getQueryLiteralsForTraining(boolean pos) {
if (pos) { return posQueryLiteralsForTraining; } else { return negQueryLiteralsForTraining; }
}
public Set<GroundLiteral> setQueryLiteralsForTraining(Set<GroundLiteral> queryLiterals, boolean pos) {
return setQueryLiteralsForTraining(queryLiterals, pos, true);
}
public Set<GroundLiteral> setQueryLiteralsForTraining(Set<GroundLiteral> queryLiterals, boolean pos, boolean complainIfNonNull) {
if (initialized) { Utils.error("Should not call after initialization."); }
if (complainIfNonNull && pos && posQueryLiteralsForTraining != null) {
Utils.error("Already have posQueryLiteralsForTraining = " + Utils.limitLengthOfPrintedList(posQueryLiteralsForTraining, 25));
}
if (complainIfNonNull && !pos && this.negQueryLiteralsForTraining != null) {
Utils.error("Already have negQueryLiteralsForTraining = " + Utils.limitLengthOfPrintedList(negQueryLiteralsForTraining, 25));
}
if (queryLiterals == null) { Utils.error("Should not call with queryLiterals = null."); }
if (pos) {posQueryLiteralsForTraining = new HashSet<GroundLiteral>(4); } else { negQueryLiteralsForTraining = new HashSet<GroundLiteral>(4); }
Collection<GroundLiteral> queryLiteralsToUse = (pos ? posQueryLiteralsForTraining : negQueryLiteralsForTraining);
int counter = 0;
if (queryLiterals != null) for (Literal literal : queryLiterals) {
queryLiteralsToUse.add(getCanonicalRepresentative(literal));
counter++; if (counter % 10000 == 0) { Utils.println("% Have hashed and collected constants from " + Utils.comma(counter) + (pos ? " positive" : " negative") + " query literals for training."); }
}
if (pos) { return posQueryLiteralsForTraining; }
return negQueryLiteralsForTraining;
}
public void setAllQueryVariablesToTheirTrainingValues() {
if (negQueryLiteralsForTraining != null) { // If the negatives are provided, assume that fraction of positives and negatives applies to the all the "unlabelled" examples as well.
int totalPos = Utils.getSizeSafely(posQueryLiteralsForTraining);
int totalNeg = Utils.getSizeSafely(negQueryLiteralsForTraining);
int total = Utils.getSizeSafely(queryLiterals);
double fractionNeg = (total - totalPos) / (double)total;
if (totalPos + totalNeg < total) { Utils.println("% Assuming that " + Utils.truncate(100 * fractionNeg, 2) + " of the " + Utils.comma(total - (totalPos + totalNeg)) + " unlabeled training examples are negative."); }
if (totalPos + totalNeg < total) { setAllQueryVariablesToFalseWithThisProbability(fractionNeg); } // Ignores any block information. TODO
}
Set<GroundClause> updateSatForClauses = new HashSet<GroundClause>();
if (negQueryLiteralsForTraining != null) for (GroundLiteral gLit : negQueryLiteralsForTraining) {
if (debugLevel > 2) { Utils.println("% Setting to FALSE this train-set query literal: '" + gLit + "'."); }
gLit.setValueOnly(false, timeStamp);
if (gLit.getGndClauseSet() != null) updateSatForClauses.addAll(gLit.getGndClauseSet());
} else { // If NO negatives are provided, assume ALL are negative, then override those said to be positive.
if (debugLevel > 0) { Utils.println("% Setting to FALSE all the " + Utils.comma(Utils.getSizeSafely(queryLiterals)) + " query literals (some of which might be next changed to TRUE)."); }
setAllQueryVariablesToFalseWithThisProbability(1.001);
}
// Do the POSITIVES second so that it is correct to first set all query values to false.
if (posQueryLiteralsForTraining != null) for (GroundLiteral gLit : posQueryLiteralsForTraining) {
if (debugLevel > 2) { Utils.println("% Setting to TRUE this train-set query literal: '" + gLit + "'."); }
gLit.setValueOnly(true, timeStamp);
if (gLit.getGndClauseSet() != null) updateSatForClauses.addAll(gLit.getGndClauseSet());
}
// Update the isSatisfiedCached value for these clauses
for (GroundClause gndClause : updateSatForClauses) {
if (gndClause == null) Utils.error("% MLNTask: GndClause shouldn't be null");
//boolean sat =
gndClause.checkIfSatisfied(timeStamp);
// Utils.println("% MLNTASK Set " + sat + " to " + gndClause.toPrettyString());
}
}
public void setAllQueryVariablesToFalseWithThisProbability(double probOfBeingFalse) {
if (queryLiterals != null) for (GroundLiteral gLit : queryLiterals) { gLit.setValueOnly(Utils.random() > probOfBeingFalse, timeStamp); }
}
public Collection<GroundLiteral> getHiddenLiterals() {
return hiddenLiterals;
}
public void setHiddenLiterals(Collection<Literal> hiddenLiterals) {
if (initialized) { Utils.error("Should not call after initialization."); }
if (hiddenLiterals == null) { Utils.error("Should not have called with hiddenLiterals = null."); }
this.hiddenLiterals = new HashSet<GroundLiteral>(4);
int counter = 0;
if (hiddenLiterals != null) for (Literal literal : hiddenLiterals) {
GroundLiteral gLit = null;
boolean hasVariables = literal.containsVariables();
if (hasVariables) { // Handle facts with variables specially - they are pulled out by GroundThisMarkovNetwork in factsWithVariables.
collectTypedConstants(literal.predicateName, literal.getArguments()); // Check for new constants.
gLit = new GroundLiteral(literal);
} else {
gLit = getCanonicalRepresentative(literal);
}
this.hiddenLiterals.add(gLit);
knownHiddensThisPnameArityHasVariables = hasVariables || knownHiddensThisPnameArityHasVariables;
addToKnowns(gLit, knownHiddensThisPnameArityHasVariables, knownHiddensThisPnameArity);
gLit.setValueOnly(Utils.random() > 0.5, timeStamp); // Give a random initial setting to hidden variables.
counter++; if (counter % 10000 == 0) { Utils.println("% Have hashed and collected constants from " + Utils.comma(counter) + " hidden literals."); }
}
}
public Collection<GroundLiteral> getPosEvidenceLiterals() {
return posEvidenceLiterals;
}
public void setPosEvidenceLiterals(Collection<Literal> posEvidenceLiterals) {
if (initialized) { Utils.error("Should not call after initialization."); }
if (posEvidenceLiterals == null) { Utils.error("Should not have called with posEvidenceLiterals = null."); }
this.posEvidenceLiterals = new HashSet<GroundLiteral>(4);
int counter = 0;
if (posEvidenceLiterals != null) for (Literal literal : posEvidenceLiterals) {
GroundLiteral gLit = null;
Utils.println(literal.toString());
boolean hasVariables = literal.containsVariables();
if (hasVariables) { // Handle facts with variables specially - they are pulled out by GroundThisMarkovNetwork in factsWithVariables.
collectTypedConstants(literal.predicateName, literal.getArguments()); // Check for new constants.
gLit = new GroundLiteral(literal);
} else {
gLit = getCanonicalRepresentative(literal);
}
this.posEvidenceLiterals.add(gLit);
knownPosEvidenceThisPnameArityHasVariables = hasVariables || knownPosEvidenceThisPnameArityHasVariables;
addToKnowns(gLit, knownPosEvidenceThisPnameArityHasVariables, knownPosEvidenceThisPnameArity) ;
gLit.setValue(true, null, timeStamp);
counter++; if (counter % 10000 == 0) { Utils.println("% Have hashed and collected constants from " + Utils.comma(counter) + " positive-evidence literals."); }
}
}
public Collection<GroundLiteral> getNegEvidenceLiterals() {
return negEvidenceLiterals;
}
public void setNegEvidenceLiterals(Collection<Literal> negEvidenceLiterals) {
if (initialized) { Utils.error("Should not call after initialization."); }
if (negEvidenceLiterals == null) { Utils.error("Should not have called with negEvidenceLiterals = null."); }
this.negEvidenceLiterals = new HashSet<GroundLiteral>(4);
int counter = 0;
if (negEvidenceLiterals != null) for (Literal literal : negEvidenceLiterals) {
GroundLiteral gLit = null;
boolean hasVariables = literal.containsVariables();
if (hasVariables) { // Handle facts with variables specially - they are pulled out by GroundThisMarkovNetwork in factsWithVariables.
collectTypedConstants(literal.predicateName, literal.getArguments()); // Check for new constants.
gLit = new GroundLiteral(literal);
} else {
gLit = getCanonicalRepresentative(literal);
}
this.negEvidenceLiterals.add(gLit);
knownNegEvidenceThisPnameArityHasVariables = hasVariables || knownNegEvidenceThisPnameArityHasVariables;
addToKnowns(gLit, knownNegEvidenceThisPnameArityHasVariables, knownNegEvidenceThisPnameArity);
gLit.setValue(false, null, timeStamp);
counter++; if (counter % 10000 == 0) { Utils.println("% Have hashed and collected constants from " + Utils.comma(counter) + " negative-evidence literals."); }
}
}
public Collection<PredNameArityPair> getQueryPredNames() { return queryPredNames; }
public Collection<PredNameArityPair> getPosEvidencePredNames() { return posEvidencePredNames; }
public Collection<PredNameArityPair> getNegEvidencePredNames() { return negEvidencePredNames; }
public Collection<PredNameArityPair> getHiddenPredNames() { return hiddenPredNames; }
// See if this literal contains any Skolems; if so, return them.
public Collection<Term> getSkolemsInThisNewLiteral(Literal lit) {
Collection<Term> results = null;
if (lit.numberArgs() < 1) { return null; }
for (Term term : lit.getArguments()) if (setOfSkolemMarkers.contains(term)) {
if (results == null) { results = new HashSet<Term>(4); }
results.add(term);
}
return results;
}
private boolean initialized = false;
private void initialize() {
if (initialized) { return; }
checkForNewConstants = false;
constantTypePairsHandled.clear(); // Return this memory. No harm if later used again (other than some wasted cycles).
List<PredicateName> queryPredNamesReadIn = stringHandler.getQueryPredicates();
List<Integer> queryPredAritiesReadIn = stringHandler.getQueryPredArities();
if (queryPredNamesReadIn != null) for (int i = 0; i < queryPredNamesReadIn.size(); i++) {
PredicateName pName = queryPredNamesReadIn.get(i); // See if this is already known, say from reading examples.
int arity = queryPredAritiesReadIn.get(i);
boolean done = false;
PredNameArityPair pair = new PredNameArityPair(pName, arity);
if (queryPredNames != null && queryPredNames.contains(pair)) { break; }
if (queryLiterals != null) for (Literal qLit : queryLiterals) {
if (qLit.predicateName == pName && qLit.numberArgs() == arity) { done = true; break; }
}
if (done) { break; }
if (queryPredNames == null) { queryPredNames = new HashSet<PredNameArityPair>(4); }
queryPredNames.add(new PredNameArityPair(pName, arity));
}
List<PredicateName> hiddenPredNamesReadIn = stringHandler.getHiddenPredicates();
List<Integer> hiddenPredAritiesReadIn = stringHandler.getHiddenPredArities();
if (hiddenPredNamesReadIn != null) for (int i = 0; i < hiddenPredNamesReadIn.size(); i++) {
PredicateName pName = hiddenPredNamesReadIn.get(i); // See if this is already known, say from reading examples.
int arity = hiddenPredAritiesReadIn.get(i);
boolean done = false;
PredNameArityPair pair = new PredNameArityPair(pName, arity);
if (queryPredNames != null && queryPredNames.contains(pair)) { break; }
if (hiddenLiterals != null) for (Literal hLit : hiddenLiterals) {
if (hLit.predicateName == pName && hLit.numberArgs() == arity) { done = true; break; }
}
if (done) { break; }
if (hiddenPredNames == null) { hiddenPredNames = new HashSet<PredNameArityPair>(4); }
hiddenPredNames.add(new PredNameArityPair(pName, arity));
}
createTrueLiteralAndClause();
indexLiteralsAndClauses();
checkForConflictsInPredNames();
removeAnyEvidenceFromQuery();
timeStamp = new TimeStamp("initializing an MLN task");
initialized = true;
}
// Expand the information provided as predicate-name/arity pairs. BUT DO NOT DO THIS UNLESS (AND UNTIL) NECESSARY,
// SINCE THESE EXPANSIONS CAN BE LARGE (and can also greatly slow down the network-reduction process).
public void expandAllPnameArityPairs() {
createAllQueryLiterals();
createAllHiddenLiterals();
createAllPositiveEvidence();
createAllNegativeEvidence();
}
private void indexLiteralsAndClauses() {
pNameArityToLiteralMap = new HashMap<PredicateName,Map<Integer,Set<Literal>>>(4);
literalToClauseMap = new HashMap<Literal,Clause>(4);
if (debugLevel > 0) { Utils.println("\n% Indexing all the literals in the " + Utils.comma(Utils.getSizeSafely(allClauses))+ " clauses."); }
if (allClauses != null) for (Clause c : allClauses) {
if (c.posLiterals != null) for (Literal pLit : c.posLiterals) { indexLiterals(c, pLit); }
if (c.negLiterals != null) for (Literal nLit : c.negLiterals) { indexLiterals(c, nLit); }
}
if (debugLevel > 0) { // Note: here 'arity' is the NUMBER OF ARGUMENTS (rather than the # of distinct variables).
Utils.println("\n% The mapping from predicateNames/arities to the clauses containing such literals.");
for (PredicateName pName : pNameArityToLiteralMap.keySet()) {
Utils.println( "% '" + pName + "'");
Set<Integer> arities = pNameArityToLiteralMap.get(pName).keySet();
for (Integer arity : arities) {
if (arities.size() > 1) { Utils.println( "% arity = " + arity); }
for (Literal lit : pNameArityToLiteralMap.get(pName).get(arity)) {
Clause clause = literalToClauseMap.get(lit);
Utils.println("% " + (clause.getSign(lit) ? " '" : "'~") + lit + "' in '" + clause.toString(Integer.MAX_VALUE) + "'.");
}
}
}
}
}
public Collection<Clause> getClausesContainingThisPredNameAndArity(PredicateName pName, int arity) {
Collection<Literal> literals = getLiteralsContainingThisPredNameAndArity(pName, arity);
if (literals == null) { return null; }
Collection<Clause> results = new HashSet<Clause>(4);
for (Literal lit : literals) {
results.add(literalToClauseMap.get(lit));
}
return results;
}
// Use a LIST here since a literal might appear in one clause multiple times. TODO - return the binding as well????
public List<Clause> getClausesThatUnifyWithThisLiteral(Literal lit, boolean applyBindingsToResults) {
return getClausesThatUnifyWithThisLiteral(lit, applyBindingsToResults, null);
}
public List<Clause> getClausesThatUnifyWithThisLiteral(Literal lit, boolean applyBindingsToResults, BindingList bindingList) {
Collection<Literal> literals = getLiteralsContainingThisPredNameAndArity(lit.predicateName, lit.numberArgs());
if (literals == null) { return null; }
List<Clause> results = new ArrayList<Clause>(literals.size());
boolean origBLisEmpty = (bindingList == null || Utils.getSizeSafely(bindingList.theta) < 1);
for (Literal litInTheory : literals) {
if (origBLisEmpty) {
BindingList bl = unifier.unify(lit, litInTheory);
if (bl != null) {
if (applyBindingsToResults) { results.add(literalToClauseMap.get(litInTheory).applyTheta(bl.theta)); }
else { results.add(literalToClauseMap.get(litInTheory)); }
}
} else { // Need to copy because we want a fresh start for each literal (rather than a 'global' unification).
BindingList bl = unifier.unify(lit, litInTheory, bindingList.copy());
if (bl != null) {
if (applyBindingsToResults) { results.add(literalToClauseMap.get(litInTheory).applyTheta(bl.theta)); }
else { results.add(literalToClauseMap.get(litInTheory)); }
}
}
}
return results;
}
public Collection<Literal> getLiteralsContainingThisPredNameAndArity(PredicateName pName, int arity) {
Map<Integer,Set<Literal>> pNameResults = pNameArityToLiteralMap.get(pName);
if (pNameResults == null) { return null; }
return pNameResults.get(arity);
}
public Collection<Literal> getLiteralsThatUnifyWithThisLiteral(Literal lit, BindingList bindingList) {
Map<Integer,Set<Literal>> pNameResults = pNameArityToLiteralMap.get(lit.predicateName);
if (pNameResults == null) { return null; }
Collection<Literal> literals = pNameResults.get(lit.numberArgs());
if (literals == null) { return null; }
Collection<Literal> results = new HashSet<Literal>(literals.size());
boolean origBLisEmpty = (bindingList == null || Utils.getSizeSafely(bindingList.theta) < 1);
for (Literal litInTheory : literals) {
if (origBLisEmpty) {
if (unifier.unify(lit, litInTheory) != null) { results.add(litInTheory); }
} else { // Need to copy because we want a fresh start for each literal (rather than a 'global' unification).
if (unifier.unify(lit, litInTheory, bindingList.copy()) != null) { results.add(litInTheory); }
}
}
return results;
}
private void indexLiterals(Clause clause, Literal lit) {
// Record 'reverse' pointers from literals to the clauses in which they appear.
Map<Integer,Set<Literal>> lookup1 = pNameArityToLiteralMap.get(lit.predicateName);
if (lookup1 == null) {
lookup1 = new HashMap<Integer,Set<Literal>>(4);
pNameArityToLiteralMap.put(lit.predicateName, lookup1);
}
Set<Literal> lookup2 = lookup1.get(lit.numberArgs());
if (lookup2 == null) {
lookup2 = new HashSet<Literal>(4);
lookup1.put(lit.numberArgs(), lookup2);
}
lookup2.add(lit);
literalToClauseMap.put(lit, clause);
}
private void collectTypedConstants(PredicateName pName, List<Term> args) {
// These might already have been collected, but play it safe.
if (debugLevel > 2) { Utils.println("% collectTypedConstants: " + pName + "/" + args); }
if (!checkForNewConstants) { Utils.error("Checking for new constants, but should not happen at this stage."); }
int numberOfArgs = Utils.getSizeSafely(args);
if (numberOfArgs < 1) { return; }
List<TypeSpec> typeSpecs = collectLiteralArgumentTypes(pName, numberOfArgs);
if (debugLevel > 2) { Utils.println("% typeSpecs(" + pName + "/" + numberOfArgs + ") = " + typeSpecs); }
for (int i = 0; i < numberOfArgs; i++) if (args.get(i) instanceof Constant) {
Constant c = (Constant) args.get(i);
// See if already dealt with this constant/type pair.
Set<Constant> lookup1 = constantTypePairsHandled.get(typeSpecs.get(i).isaType);
if (lookup1 == null) { // Never saw this type before.
stringHandler.addNewConstantOfThisType(c, typeSpecs.get(i).isaType);
lookup1 = new HashSet<Constant>(4);
constantTypePairsHandled.put(typeSpecs.get(i).isaType, lookup1);
}
if (!lookup1.contains(c)) { // Save a call to the stringHandler if this constant has already been processed.
if (debugLevel > 1) { Utils.println("% Add constant '" + c + "' of type '" + typeSpecs.get(i).isaType + "'."); }
stringHandler.addNewConstantOfThisType(c, typeSpecs.get(i).isaType);
lookup1.add(c);
}
}
}
public boolean isClosedWorldAssumption(Literal lit) { // Require NULL so calling code explicitly makes sure this is a generic query.
if (lit == null) { return closedWorldAssumption; }
if (closedWorldAssumption) {
return !neverCWAonThisLiteral(lit);
} else {
return alwaysCWAonThisLiteral(lit);
}
}
private boolean neverCWAonThisLiteral( Literal lit) {
if (neverCWAonThisPredNameArity != null) {
Collection<Integer> arities = neverCWAonThisPredNameArity.get(lit.predicateName);
if (arities == null) { return false; }
return arities.contains(lit.numberArgs());
}
return false;
}
private boolean alwaysCWAonThisLiteral(Literal lit) {
if (alwaysCWAonThisPredNameArity != null) {
Collection<Integer> arities = alwaysCWAonThisPredNameArity.get(lit.predicateName);
if (arities == null) { return false; }
return arities.contains(lit.numberArgs());
}
return false;
}
public void setClosedWorldAssumption(boolean evidenceClosedWorldAssumption) {
this.closedWorldAssumption = evidenceClosedWorldAssumption;
}
// Check for literals that need not have modes specified. NO LONGER USED, but keep since might be needed later.
public boolean isaBuiltInLiteral(Literal lit) { // TODO Add more here? prover.getProcedurallyDefinedPredicates()
if (lit.predicateName == stringHandler.trueLiteral.predicateName) { return true; }
if (lit.predicateName == stringHandler.falseLiteral.predicateName) { return true; }
return false;
}
public void setWorkingDirectory(String workingDirectory) {
this.workingDirectory = workingDirectory;
}
public Map<GroundLiteral,String> makeQueryLabelsCanonical(Map<GroundLiteral,String> queryLabels) {
if (queryLabels == null) { return null; }
Map<GroundLiteral,String> results = new HashMap<GroundLiteral,String>(queryLabels.size());
for (GroundLiteral gLit : queryLabels.keySet()) { // TODO - can this be done in place?
results.put(getCanonicalRepresentative(gLit), queryLabels.get(gLit));
}
return results;
}
}
| gpl-3.0 |
b2renger/PdDroidPublisher | pd-party/src/net/mgsx/ppp/widget/core/Subpatch.java | 8873 | package net.mgsx.ppp.widget.core;
import java.util.ArrayList;
import java.util.List;
import net.mgsx.ppp.view.PdDroidPatchView;
import net.mgsx.ppp.widget.Widget;
import org.puredata.core.PdBase;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Region.Op;
public class Subpatch extends Widget
{
public static class Array
{
public final static int DRAWTYPE_POLYGON = 0;
public final static int DRAWTYPE_POINTS = 1;
public final static int DRAWTYPE_BEZIER = 2;
public String name;
public int length;
public String type;
/** 0 : polygon, 1 : points, 2 : bezier */
public int drawType;
public boolean save;
public float [] buffer;
}
protected WImage background = new WImage();
protected Array array;
// TODO use dRect instead
protected int top, bottom, left, right, zoneWidth, zoneHeight, HMargin, VMargin;
protected int x, y;
protected boolean graphOnParent;
public List<Widget> widgets = new ArrayList<Widget>();
/**
* Constructor overridden by custom Subpatch.
* @param subpatch
*/
public Subpatch(Subpatch subpatch) {
super(subpatch.parent);
background = subpatch.background;
array = subpatch.array;
top = subpatch.top;
bottom = subpatch.bottom;
left = subpatch.left;
right = subpatch.right;
zoneWidth = subpatch.zoneWidth;
zoneHeight = subpatch.zoneHeight;
HMargin = subpatch.HMargin;
VMargin = subpatch.VMargin;
x = subpatch.x;
y = subpatch.y;
graphOnParent = subpatch.graphOnParent;
widgets = subpatch.widgets;
dRect = subpatch.dRect;
label = subpatch.label;
}
public Subpatch(PdDroidPatchView app, String[] atomline) {
super(app);
}
public boolean isGraphOnParent() {
return graphOnParent;
}
@Override
public boolean touchmove(int pid, float x, float y)
{
if(dRect.contains(x, y))
{
if(array != null)
{
int index = (int)(left + (float)(right - left) * (x - this.x) / (float)(this.zoneWidth));
if(index >= 0 && index < array.length)
{
float value = ((y - this.y) / (float)(zoneHeight)) * (top - bottom) + bottom;
array.buffer[index] = value;
PdBase.writeArray(array.name, index, array.buffer, index, 1);
return true;
}
}
else
{
float localX = x - (this.x - HMargin);
float localY = y - (this.y - VMargin);
for(Widget widget : widgets)
{
if(widget.touchmove(pid, localX, localY)) return true;
}
}
}
return false;
}
public void parse(String[] atomline)
{
if(atomline.length >= 2)
{
if(atomline[1].equals("array"))
{
array = new Array();
label = array.name = atomline[2];
array.length = Integer.parseInt(atomline[3]);
array.type = atomline[4];
int options = Integer.parseInt(atomline[5]);
array.drawType = options >> 1;
array.save = (options & 1) != 0;
array.buffer = new float [array.length];
background.load("Array", "background", array.name);
}
else if(atomline[1].equals("coords"))
{
left = Integer.parseInt(atomline[2]);
bottom = Integer.parseInt(atomline[3]);
right = Integer.parseInt(atomline[4]);
top = Integer.parseInt(atomline[5]);
zoneWidth = Integer.parseInt(atomline[6]);
zoneHeight = Integer.parseInt(atomline[7]);
graphOnParent = Integer.parseInt(atomline[8]) != 0;
// optional margin h/v
if(atomline.length >= 11)
{
HMargin = Integer.parseInt(atomline[9]);
VMargin = Integer.parseInt(atomline[10]);
}
dRect.right += zoneWidth;
dRect.bottom += zoneHeight;
}
else if(atomline[1].equals("restore"))
{
x = Integer.parseInt(atomline[2]);
y = Integer.parseInt(atomline[3]);
dRect.left += x;
dRect.right += x;
dRect.top += y;
dRect.bottom += y;
if(atomline.length >= 6)
{
label = atomline[5];
}
}
// TODO handle array definition (saved)
}
}
@Override
public void updateData()
{
if(array != null)
{
PdBase.readArray(array.buffer, 0, array.name, 0, array.buffer.length);
}
else
{
for(Widget widget : widgets)
{
widget.updateData();
}
}
}
protected void drawBackground(Canvas canvas)
{
if(background.draw(canvas))
{
paint.setStyle(Paint.Style.FILL);
paint.setColor(bgcolor);
canvas.drawRect(x, y, x + zoneWidth, y + zoneHeight, paint);
}
}
protected void drawEdges(Canvas canvas)
{
paint.setStyle(Paint.Style.STROKE);
paint.setColor(fgcolor);
paint.setStrokeWidth(1);
canvas.drawRect(x, y, x + zoneWidth, y + zoneHeight, paint);
}
protected void drawArrayCurve(Canvas canvas)
{
paint.setStyle(Paint.Style.STROKE);
paint.setColor(fgcolor);
if(array.drawType == Array.DRAWTYPE_POINTS)
{
paint.setStrokeWidth(3);
float ppx = 0, ppy = 0;
if(array.length < zoneWidth)
{
for(int i=0 ; i<array.buffer.length+1 ; i++)
{
float px = x + (float)i * (float)zoneWidth / (float)array.buffer.length;
if(i > 0){
float value = array.buffer[i-1];
float py = y + zoneHeight * (float)(value - bottom) / (float)(top - bottom);
canvas.drawLine(ppx, py, px, py, paint);
}
ppx = px;
}
}
else
{
paint.setStrokeWidth(0);
for(int i=0 ; i<zoneWidth ; i++)
{
int index = (int)((float)array.buffer.length * (float)i / (float)(zoneWidth));
float value = array.buffer[index];
float px = x + (float)i;
float py = y + zoneHeight * (float)(value - bottom) / (float)(top - bottom);
if(i > 0){
canvas.drawLine(ppx, ppy, px, py, paint);
}
ppx = px;
ppy = py;
}
}
}
// TODO handle bezier drawing
else
{
float ppx = 0, ppy = 0;
if(array.length < zoneWidth)
{
for(int i=0 ; i<array.buffer.length ; i++)
{
float value = array.buffer[i];
float px = x + (float)i * (float)zoneWidth / (float)array.buffer.length;
float py = y + zoneHeight * (float)(value - bottom) / (float)(top - bottom);
if(i > 0){
canvas.drawLine(ppx, ppy, px, py, paint);
}
ppx = px;
ppy = py;
}
}
else
{
for(int i=0 ; i<zoneWidth ; i++)
{
int index = (int)((float)array.buffer.length * (float)i / (float)(zoneWidth));
float value = array.buffer[index];
float px = x + (float)i;
float py = y + zoneHeight * (float)(value - bottom) / (float)(top - bottom);
if(i > 0){
canvas.drawLine(ppx, ppy, px, py, paint);
}
ppx = px;
ppy = py;
}
}
}
}
@Override
public void drawLabel(Canvas canvas)
{
if(label != null)
{
paint.setStrokeWidth(0);
paint.setStyle(Paint.Style.FILL);
paint.setColor(labelcolor);
paint.setTextSize(fontsize);
paint.setTypeface(font);
canvas.drawText(label, dRect.left, dRect.top - paint.descent() - 2, paint);
}
}
protected void drawSubpatchContent(Canvas canvas)
{
canvas.save();
Matrix matrix = new Matrix();
matrix.postTranslate(x - HMargin, y - VMargin);
canvas.concat(matrix);
canvas.clipRect(new RectF(HMargin, VMargin, HMargin + dRect.width(), VMargin + dRect.height()), Op.INTERSECT);
for(Widget widget : widgets)
{
widget.draw(canvas);
}
canvas.restore();
}
@Override
public void draw(Canvas canvas)
{
if(!graphOnParent) return;
drawBackground(canvas);
drawEdges(canvas);
if(array != null)
{
drawArrayCurve(canvas);
}
// sub patch mode !
else
{
drawSubpatchContent(canvas);
}
drawLabel(canvas);
}
@Override
public boolean touchdown(int pid, float x, float y)
{
if(dRect.contains(x, y))
{
float localX = x - (this.x - HMargin);
float localY = y - (this.y - VMargin);
for(Widget widget : widgets)
{
if(widget.touchdown(pid, localX, localY)) return true;
}
}
return false;
}
@Override
public boolean touchup(int pid, float x, float y) {
if(dRect.contains(x, y))
{
float localX = x - (this.x - HMargin);
float localY = y - (this.y - VMargin);
for(Widget widget : widgets)
{
if(widget.touchup(pid, localX, localY)) return true;
}
}
return false;
}
@Override
public void receiveAny() {
for(Widget widget : widgets)
{
widget.receiveAny();
}
}
@Override
public void receiveBang() {
for(Widget widget : widgets)
{
widget.receiveBang();;
}
}
@Override
public void receiveFloat(float x) {
for(Widget widget : widgets)
{
widget.receiveFloat(x);
}
}
@Override
public void receiveList(Object... args) {
for(Widget widget : widgets)
{
widget.receiveList(args);
}
}
@Override
public void receiveMessage(String symbol, Object... args) {
for(Widget widget : widgets)
{
widget.receiveMessage(symbol, args);
}
}
@Override
public void receiveSymbol(String symbol) {
for(Widget widget : widgets)
{
widget.receiveSymbol(symbol);
}
}
}
| gpl-3.0 |
msgoon/SACSA | src/java/entidades/Nota.java | 4973 | /*
* 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 entidades;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author msgoon6
*/
@Entity
@Table(name = "nota", catalog = "db_stanford", schema = "public")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Nota.findAll", query = "SELECT n FROM Nota n"),
@NamedQuery(name = "Nota.findByCodigo", query = "SELECT n FROM Nota n WHERE n.codigo = :codigo"),
@NamedQuery(name = "Nota.findByCalificacion", query = "SELECT n FROM Nota n WHERE n.calificacion = :calificacion"),
@NamedQuery(name = "Nota.findByCalificacion2", query = "SELECT n FROM Nota n WHERE n.calificacion2 = :calificacion2"),
@NamedQuery(name = "Nota.findByCalificacion3", query = "SELECT n FROM Nota n WHERE n.calificacion3 = :calificacion3"),
@NamedQuery(name = "Nota.findByCalificacion4", query = "SELECT n FROM Nota n WHERE n.calificacion4 = :calificacion4"),
@NamedQuery(name = "Nota.findByAsistencia", query = "SELECT n FROM Nota n WHERE n.asistencia = :asistencia")})
public class Nota implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "codigo")
private Integer codigo;
@Basic(optional = false)
@NotNull
@Column(name = "calificacion")
private Double calificacion;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "calificacion2")
private Float calificacion2;
@Column(name = "calificacion3")
private Float calificacion3;
@Column(name = "calificacion4")
private Float calificacion4;
@Column(name = "asistencia")
private Float asistencia;
@JoinColumn(name = "materia_matricula", referencedColumnName = "codigo")
@ManyToOne
private MateriasMatricula materiaMatricula;
public Nota() {
}
public Nota(Integer codigo) {
this.codigo = codigo;
}
public Nota(Integer codigo, Double calificacion) {
this.codigo = codigo;
this.calificacion = calificacion;
}
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public Double getCalificacion() {
return calificacion;
}
public void setCalificacion(Double calificacion) {
this.calificacion = calificacion;
}
public Float getCalificacion2() {
return calificacion2;
}
public void setCalificacion2(Float calificacion2) {
this.calificacion2 = calificacion2;
}
public Float getCalificacion3() {
return calificacion3;
}
public void setCalificacion3(Float calificacion3) {
this.calificacion3 = calificacion3;
}
public Float getCalificacion4() {
return calificacion4;
}
public void setCalificacion4(Float calificacion4) {
this.calificacion4 = calificacion4;
}
public Float getAsistencia() {
return asistencia;
}
public void setAsistencia(Float asistencia) {
this.asistencia = asistencia;
}
public MateriasMatricula getMateriaMatricula() {
return materiaMatricula;
}
public void setMateriaMatricula(MateriasMatricula materiaMatricula) {
this.materiaMatricula = materiaMatricula;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codigo != null ? codigo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Nota)) {
return false;
}
Nota other = (Nota) object;
if ((this.codigo == null && other.codigo != null) || (this.codigo != null && !this.codigo.equals(other.codigo))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidades.Nota[ codigo=" + codigo + " ]";
}
public Nota(int codigo, TipoNota tipo_nota, MateriasMatricula materia_matricula, Double calificacion) {
this.codigo = codigo;
this.materiaMatricula = materia_matricula;
this.calificacion = calificacion;
}
}
| gpl-3.0 |
dzonekl/oss2nms | plugins/com.netxforge.oss2.config.model/src/com/netxforge/oss2/config/vacuumd/descriptors/ActionEventDescriptor.java | 12320 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package com.netxforge.oss2.config.vacuumd.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import com.netxforge.oss2.config.vacuumd.ActionEvent;
/**
* Class ActionEventDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class ActionEventDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ActionEventDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/vacuumd";
_xmlName = "action-event";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _name
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_name", "name", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ActionEvent target = (ActionEvent) object;
return target.getName();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ActionEvent target = (ActionEvent) object;
target.setName( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _name
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _forEachResult
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Boolean.TYPE, "_forEachResult", "for-each-result", org.exolab.castor.xml.NodeType.Attribute);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ActionEvent target = (ActionEvent) object;
if (!target.hasForEachResult()) { return null; }
return (target.getForEachResult() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE);
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ActionEvent target = (ActionEvent) object;
// if null, use delete method for optional primitives
if (value == null) {
target.deleteForEachResult();
return;
}
target.setForEachResult( ((java.lang.Boolean) value).booleanValue());
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("boolean");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _forEachResult
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.BooleanValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.BooleanValidator();
fieldValidator.setValidator(typeValidator);
}
desc.setValidator(fieldValidator);
//-- _addAllParms
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Boolean.TYPE, "_addAllParms", "add-all-parms", org.exolab.castor.xml.NodeType.Attribute);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ActionEvent target = (ActionEvent) object;
if (!target.hasAddAllParms()) { return null; }
return (target.getAddAllParms() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE);
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ActionEvent target = (ActionEvent) object;
// if null, use delete method for optional primitives
if (value == null) {
target.deleteAddAllParms();
return;
}
target.setAddAllParms( ((java.lang.Boolean) value).booleanValue());
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("boolean");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _addAllParms
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.BooleanValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.BooleanValidator();
fieldValidator.setValidator(typeValidator);
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _assignmentList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(com.netxforge.oss2.config.vacuumd.Assignment.class, "_assignmentList", "assignment", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ActionEvent target = (ActionEvent) object;
return target.getAssignment();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ActionEvent target = (ActionEvent) object;
target.addAssignment( (com.netxforge.oss2.config.vacuumd.Assignment) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
ActionEvent target = (ActionEvent) object;
target.removeAllAssignment();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new com.netxforge.oss2.config.vacuumd.Assignment();
}
};
desc.setSchemaType("com.netxforge.oss2.config.vacuumd.Assignment");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/vacuumd");
desc.setRequired(true);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _assignmentList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return com.netxforge.oss2.config.vacuumd.ActionEvent.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| gpl-3.0 |
bsaunder/cs517-project | src/main/java/net/bryansaunders/dss/model/Technician.java | 359 | /**
*
*/
package net.bryansaunders.dss.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Shop Technician Entity.
*
* @author Bryan Saunders <btsaunde@gmail.com>
*
*/
@Entity
@Table(name = "technician")
@XmlRootElement
public class Technician extends CertifiedStaff {
}
| gpl-3.0 |
sheldonabrown/core | transitimeQuickStart/src/test/java/org/transitime/config/CreateApiTest.java | 1091 | package org.transitime.config;
import static org.junit.Assert.*;
import java.net.URL;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.junit.Test;
import org.transitime.config.ConfigFileReader.ConfigException;
import org.transitime.config.ConfigValue.ConfigParamException;
import org.transitime.db.webstructs.ApiKey;
import org.transitime.db.webstructs.ApiKeyManager;
public class CreateApiTest {
@Test
public void test() {
String fileName = "transiTimeconfig.xml";
try {
ConfigFileReader.processConfig(this.getClass().getClassLoader()
.getResource(fileName).getPath());
} catch (ConfigException e) {
e.printStackTrace();
} catch (ConfigParamException e) {
}
String name="Brendan";
String url="http://www.transitime.org";
String email="egan129129@gmail.com";
String phone="123456789";
String description="Foo";
ApiKeyManager manager = ApiKeyManager.getInstance();
ApiKey apiKey = manager.generateApiKey(name,
url, email,
phone, description);
assert(manager.isKeyValid(apiKey.getKey()));
}
}
| gpl-3.0 |
johnthegreat/morphy-chess-server | src/morphy/command/admin/AnnunregCommand.java | 1713 | /*
* Morphy Open Source Chess Server
* Copyright (C) 2008-2011 http://code.google.com/p/morphy-chess-server/
*
* 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 morphy.command.admin;
import morphy.command.AbstractCommand;
import morphy.service.UserService;
import morphy.user.UserSession;
public class AnnunregCommand extends AbstractCommand {
public AnnunregCommand() {
super("admin/annunreg");
}
public void process(String arguments, UserSession userSession) {
UserSession[] all = UserService.getInstance().getLoggedInUsers();
if (arguments.equals("")) {
userSession.send(getContext().getUsage());
return;
}
int sentTo = 0;
for(UserSession sess : all) {
if (!sess.getUser().isRegistered() ||
sess.getUser().getUserName().equals(userSession.getUser().getUserName())) {
sess.send(" ** UNREG ANNOUNCEMENT ** from " + userSession.getUser().getUserName() + ": " + arguments + "\n");
sentTo++;
}
}
sentTo--; // The sending user doesn't count
userSession.send("(Announcement sent to " + sentTo + " unregistered players)");
}
}
| gpl-3.0 |
SerenityEnterprises/SerenityCE | src/main/java/host/serenity/serenity/commands/Echo.java | 443 | package host.serenity.serenity.commands;
import host.serenity.serenity.api.command.Command;
import host.serenity.serenity.api.command.parser.CommandBranch;
import host.serenity.serenity.api.command.parser.argument.impl.StringArgument;
public class Echo extends Command {
public Echo() {
branches.add(new CommandBranch(ctx -> {
out(ctx.getArgumentValue("message"));
}, new StringArgument("message")));
}
}
| gpl-3.0 |
dapperbasket22/TwoStrings | app/src/main/java/pelicula/shiri/twostrings/adapter/RecommendedAdapter.java | 2661 | package pelicula.shiri.twostrings.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
import pelicula.shiri.twostrings.MovieDescriptionActivity;
import pelicula.shiri.twostrings.R;
import pelicula.shiri.twostrings.model.RecommendedObject;
import pelicula.shiri.twostrings.utilities.TMAUrl;
public class RecommendedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<RecommendedObject> mDataSet;
private ImageLoader mImgLoader;
private Context mContext;
public RecommendedAdapter(ArrayList<RecommendedObject> data, ImageLoader loader, Context context) {
mDataSet = data;
mImgLoader = loader;
mContext = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View movie = LayoutInflater.from(parent.getContext()).
inflate(R.layout.list_item_recommended, parent, false);
return new ViewHolderRecommended(movie);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ViewHolderRecommended holderMovie = (ViewHolderRecommended) holder;
final RecommendedObject object = mDataSet.get(position);
String url = TMAUrl.IMAGE_MED_URL + object.getmPoster();
holderMovie.imgPoster.setImageUrl(url, mImgLoader);
holderMovie.textTitle.setText(object.getmTitle());
holderMovie.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MovieDescriptionActivity.class);
intent.putExtra("id", object.getmId());
intent.putExtra("name", object.getmTitle());
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mDataSet.size();
}
private class ViewHolderRecommended extends RecyclerView.ViewHolder {
NetworkImageView imgPoster;
TextView textTitle;
ViewHolderRecommended(View itemView) {
super(itemView);
imgPoster = (NetworkImageView) itemView.findViewById(R.id.imageMovieRecommendedPoster);
textTitle = (TextView) itemView.findViewById(R.id.textMovieRecommendedTitle);
}
}
}
| gpl-3.0 |
TheMrNomis/TP_ALG | projet/src/projet/Allocateur.java | 6413 | /**
Squelette a completer de la classe implementant votre allocateur.
Si necessaire, vous pouvez creer d'autres classes qui seront
utilises dans Allocateur. Mais la classe principale Racine ne
s'adressera qu'a la classe Allocateur.
Dans chaque methode, verifiez bien que les parametres sont
valides. Par exemple, pour creer un processus 'p', il faut que 'p'
ne soit pas deja un numero de processus valide. Dans le cas
contraire, on levera une exception de type IllegalArgumentException
avec un message pertinent.
Completer egalement les commentaires associes a chaque methode si
necessaire.
*/
package src.projet;
import java.util.*;
import graphe.*;
import graphe.customException.*;
public class Allocateur {
// attributs
private int max_proc; // nombre maximum de processus
private int nb_proc; // nombre effectif de processus
private int nb_ress;
private Graphe g;
// constructeurs
/**
Creation d'un allocateur pouvant gerer jusqu'a 'nmaxProc' processus (numerotes de 0 a (nmaxProc-1))
et exactement 'nRess' ressources (numerotees de 0 a (nRess-1).
*/
public Allocateur(int nmaxProc, int nRess) {
g = new GrapheImp();
max_proc = nmaxProc;
nb_proc = 0;
nb_ress = nRess;
try {
g.ajoutSommet(0);
for(int i = 0; i < nRess; i++) {
g.ajoutArc(new Arc(0, 0, i));
}
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
// methodes
/**
Retourne vrai si et seulement si 'p' est un processus connu de l'allocateur
*/
public boolean validProc(int p) {
return p > 0 && g.verifSommet(p);
}
/**
Retourne vrai si et seulement si 'r' est une ressource connue de l'allocateur
*/
public boolean validRess(int r) {
return r >=0 && r < nb_ress;
}
/**
O1: Creation du nouveau processus 'p'.
* @throws Exception si il y n'y a plus d'emplacement processus disponible
*/
public void creerProc(int p) throws Exception {
System.out.println("Creation du processus " + p);
nb_proc++;
if(p > 0 && p <= max_proc)
g.ajoutSommet(p);
else
throw new Exception("impossible de creer le processus "+p);
}
/**
O2: Destruction du processus 'p'.
*/
public void detruireProc(int p) {
System.out.println("Destruction du processus " + p);
for(Arc a : g.getArcsArrivantA(p))
libererRess(p, a.getValeur());
g.supprSommet(p);
nb_proc--;
}
/**
O3: Demande d'un ensemble de ressources 'lr' par le processus 'p'.
*/
public void demanderRess(int p, Set<Integer> lr) {
System.out.println("Demande de " + lr.size() + " ressource(s) par le processus " + p);
try {
//Si le processus n'existe pas, on le cr�e
if (!this.validProc(p))
this.creerProc(p);
//demande de la ressource
//Pour chaque ressource
for(Integer elem : lr)
{
//Si la ressource existe
if (this.validRess(elem))
{
demanderUniqueRess(p, elem);
}
}
}
catch(Exception e) {
System.out.println("Impossible de demander la ressource (ressource inconnue ou processus impossible � cr�er).");
}
}
private void demanderUniqueRess(int p, Integer r)
{
Integer s = 0;
try {
while(true) {
s = g.suivreArcDescendant(s, r);
}
}
catch(AucunSucesseur e) {}
catch(SommetArriveeEquDepart e) {
//on a trouvé un arc réflecteur. On le supprime avant d'ajouter le sommet
g.supprArc(new Arc(s, s, r));
}
finally {
g.ajoutArc(new Arc(s, p, r));
}
}
/**
O4: Liberation d'une ressource 'r' par le processus 'p'.
*/
public void libererRess(int p, int r) {
System.out.println("Liberation de la ressource " + r + " par le processus " + p);
try {
Integer predecesseur = g.suivreArcRemontant(p, r);
try {
Integer sucesseur = g.suivreArcDescendant(p, r);
g.ajoutArc(new Arc(predecesseur, sucesseur, r));
g.supprArc(new Arc(p, sucesseur, r));
}
catch (SommetArriveeEquDepart e) {}
catch (AucunSucesseur e) {
//si la file est vide après p,
//on ajoute un arc réflecteur sur le processus 0
//pour préciser que la ressource est libre
if(predecesseur.equals(0))
g.ajoutArc(new Arc(0, 0, r));
}
g.supprArc(new Arc(predecesseur, p, r));
}
catch (SommetArriveeEquDepart e) {}
catch (AucunPredecesseur e) {}
}
/**
O5: Affichage des files d'attentes des ressources.
*/
public void afficherFiles() {
System.out.println("Affichage des files d'attentes");
for(int r = 0; r < nb_ress; r++) {
System.out.print(r + " : [");
Integer s = 0;
try {
while(true) {
s = g.suivreArcDescendant(s, r);
System.out.print(s+" ");
}
}
catch(AucunSucesseur e) {}
catch(SommetArriveeEquDepart e) {}
finally {
System.out.println("]");
}
}
}
/**
O6: Affichage des processus actifs.
*/
public void afficherActifs() {
System.out.println("Affichage des processus actifs");
System.out.print("processus actifs : {");
for(Integer p : g.getSommets()) {
boolean isActif = true;
for(Arc a : g.getArcsArrivantA(p))
if(a.getDepart() != 0)
isActif = false;
if(isActif && p != 0)
System.out.print(p+", ");
}
System.out.println("}");
}
/**
O7: Affichage des attentes entre processus.
*/
public void afficherAttentes() {
System.out.println("Affichage des attentes entre processus");
for(Integer p : g.getSommets()) {
System.out.print(p + " : [");
for(Arc a : g.getArcsArrivantA(p))
if(a.getDepart() != 0)
System.out.print(a.getDepart() + " ");
System.out.println("]");
}
}
/**
O8: Affichage des interblocages.
*/
public void afficherInterblocages() {
System.out.println("Affichage des interblocages");
List< Set<Integer>> tarjan = Algorithmes.Tarjan(g);
// System.out.println(tarjan);
for(Set<Integer> CFC : tarjan) {
if(!CFC.contains(0) && CFC.size() > 1) {//Le Set de CFC ne contiendra plus que des process actif
Set<Integer> interblocage = new HashSet<Integer>();
for(Integer i : CFC)
for(Arc a : g.getArcsArrivantA(i))
if(a.getDepart() == 0)
interblocage.add(i);
System.out.println("interblocage : " + interblocage);
}
}
}
//----fonctions de test----
public String toString() {
return g.toString();
}
public boolean validLien(Integer p1, Integer p2, Integer r) {
return g.verifArc(new Arc(p1, p2, r));
}
public int getNb_proc() {
return nb_proc;
}
} // class
| gpl-3.0 |
GlacierSoft/netloan-project | netloan-module/src/main/java/com/glacier/netloan/service/borrow/AttentionBorrowingService.java | 10778 | package com.glacier.netloan.service.borrow;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.glacier.basic.util.RandomGUID;
import com.glacier.jqueryui.util.JqGridReturn;
import com.glacier.jqueryui.util.JqPager;
import com.glacier.jqueryui.util.JqReturnJson;
import com.glacier.netloan.dao.borrow.AttentionBorrowingMapper;
import com.glacier.netloan.dao.borrow.BorrowingLoanMapper;
import com.glacier.netloan.dto.query.borrow.AttentionBorrowingQueryDTO;
import com.glacier.netloan.entity.basicdatas.ParameterCredit;
import com.glacier.netloan.entity.borrow.AttentionBorrowing;
import com.glacier.netloan.entity.borrow.AttentionBorrowingExample;
import com.glacier.netloan.entity.borrow.AttentionBorrowingExample.Criteria;
import com.glacier.netloan.entity.member.Member;
import com.glacier.netloan.service.basicdatas.ParameterCreditService;
/**
* @ClassName: AttentionBorrowingService
* @Description: TODO(关注借款业务层)
* @author yuzexu
* @email 804346249@QQ.com
* @date 2014-5-20下午5:28:30
*/
@Service
@Transactional(readOnly = true , propagation = Propagation.REQUIRED)
public class AttentionBorrowingService {
@Autowired
private AttentionBorrowingMapper attentionBorrowingMapper;
@Autowired
private BorrowingLoanMapper borrowingLoanMapper;
@Autowired
private ParameterCreditService parameterCreditService;
/**
* @Title: getAttentionBorrowing
* @Description: TODO(根据关注借款Id获取关注借款信息)
* @param @param attentionBorrowingId
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
public Object getAttentionBorrowing(String attentionBorrowingId) {
AttentionBorrowing attentionBorrowing = attentionBorrowingMapper.selectByPrimaryKey(attentionBorrowingId);
return attentionBorrowing;
}
/**
* @Title: listAsGridWebsite
* @Description: TODO(前台关注借款列表)
* @param @param jqPager
* @param @param borrowingLoanQueryDTO
* @param @param pagetype
* @param @param p
* @param @return设定文件
* @return Object 返回类型
* @throws
*
*/
@SuppressWarnings("unchecked")
public Object listAsGridWebsite(AttentionBorrowingQueryDTO attentionBorrowingQueryDTO,JqPager jqPager,int p,String memberId) {
JqGridReturn returnResult = new JqGridReturn();
AttentionBorrowingExample attentionBorrowingExample = new AttentionBorrowingExample();
Criteria queryCriteria = attentionBorrowingExample.createCriteria();
attentionBorrowingQueryDTO.setQueryCondition(queryCriteria);//根据dto,进行查询
if(memberId != null){
queryCriteria.andMemberIdEqualTo(memberId);//查询相对应的还款人的关注借款
}
jqPager.setSort("createTime");// 定义排序字段
jqPager.setOrder("DESC");// 升序还是降序
if (StringUtils.isNotBlank(jqPager.getSort()) && StringUtils.isNotBlank(jqPager.getOrder())) {// 设置排序信息
attentionBorrowingExample.setOrderByClause(jqPager.getOrderBy("temp_attention_borrowing_"));
}
int startTemp = ((p-1)*10);//根据前台返回的页数进行设置
attentionBorrowingExample.setLimitStart(startTemp);
attentionBorrowingExample.setLimitEnd(10);
List<AttentionBorrowing> attentionBorrowings = attentionBorrowingMapper.selectByExample(attentionBorrowingExample); // 查询所有借款列表
//查询基础信用积分的所有数据
List<ParameterCredit> parameterCredits = (List<ParameterCredit>) parameterCreditService.listCredits();
List<AttentionBorrowing> allAttentionBorrowings = new ArrayList<AttentionBorrowing>();//定义一个空的收款列表
//通过嵌套for循环,将会员的信用图标加到关注借款对象中去
for(AttentionBorrowing attentionBorrowing : attentionBorrowings){
for(ParameterCredit parameterCredit : parameterCredits){
if(attentionBorrowing.getCreditIntegral() >= parameterCredit.getCreditBeginIntegral() && attentionBorrowing.getCreditIntegral() < parameterCredit.getCreditEndIntegral()){
attentionBorrowing.setCreditPhoto(parameterCredit.getCreditPhoto());
break;
}
}
allAttentionBorrowings.add(attentionBorrowing);
}
int total = attentionBorrowingMapper.countByExample(attentionBorrowingExample); // 查询总页数
returnResult.setRows(allAttentionBorrowings);//设置查询数据
returnResult.setTotal(total);//设置总条数
returnResult.setP(p);//设置当前页
return returnResult;// 返回ExtGrid表
}
/**
* @Title: listAsGrid
* @Description: TODO(获取所有关注借款信息)
* @param @param pager
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
public Object listAsGrid(JqPager pager,AttentionBorrowingQueryDTO attentionBorrowingQueryDTO) {
JqGridReturn returnResult = new JqGridReturn();
AttentionBorrowingExample attentionBorrowingExample = new AttentionBorrowingExample();
Criteria queryCriteria = attentionBorrowingExample.createCriteria();
attentionBorrowingQueryDTO.setQueryCondition(queryCriteria);
if (null != pager.getPage() && null != pager.getRows()) {// 设置排序信息
attentionBorrowingExample.setLimitStart((pager.getPage() - 1) * pager.getRows());
attentionBorrowingExample.setLimitEnd(pager.getRows());
}
if (StringUtils.isNotBlank(pager.getSort()) && StringUtils.isNotBlank(pager.getOrder())) {// 设置排序信息
attentionBorrowingExample.setOrderByClause(pager.getOrderBy("temp_attention_borrowing_"));
}
List<AttentionBorrowing> attentionBorrowings = attentionBorrowingMapper.selectByExample(attentionBorrowingExample); // 查询所有关注借款列表
int total = attentionBorrowingMapper.countByExample(attentionBorrowingExample); // 查询总页数
returnResult.setRows(attentionBorrowings);
returnResult.setTotal(total);
return returnResult;// 返回ExtGrid表
}
/**
* @Title: addAttentionBorrowing
* @Description: TODO(新增关注借款)
* @param @param attentionBorrowing
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
@Transactional(readOnly = false)
public Object addAttentionBorrowing(AttentionBorrowing attentionBorrowing) {
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
int count = 0;
Subject pricipalSubject = SecurityUtils.getSubject();
Member pricipalMember = (Member) pricipalSubject.getPrincipal();
AttentionBorrowingExample attentionBorrowingExample = new AttentionBorrowingExample();
attentionBorrowingExample.createCriteria().andLoanIdEqualTo(attentionBorrowing.getLoanId())
.andMemberIdEqualTo(attentionBorrowing.getMemberId());
count = attentionBorrowingMapper.countByExample(attentionBorrowingExample);// 查询是否已经关注此借款
if (count > 0) {
returnResult.setMsg("您已经关注此借款!");
return returnResult;
}
attentionBorrowing.setAttentionBorrowingId(RandomGUID.getRandomGUID());
attentionBorrowing.setCreater(pricipalMember.getMemberId());
attentionBorrowing.setCreateTime(new Date());
attentionBorrowing.setUpdater(pricipalMember.getMemberId());
attentionBorrowing.setUpdateTime(new Date());
count = attentionBorrowingMapper.insert(attentionBorrowing);
if (count == 1) {
returnResult.setSuccess(true);
returnResult.setObj(attentionBorrowing);
returnResult.setMsg("关注借款信息成功");
} else {
returnResult.setMsg("发生未知错误,关注借款信息保存失败");
}
return returnResult;
}
/**
* @Title: editAttentionBorrowing
* @Description: TODO(修改关注借款)
* @param @param attentionBorrowing
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
@Transactional(readOnly = false)
public Object editAttentionBorrowing(AttentionBorrowing attentionBorrowing) {
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
int count = 0;
count = attentionBorrowingMapper.updateByPrimaryKeySelective(attentionBorrowing);
if (count == 1) {
returnResult.setSuccess(true);
returnResult.setMsg("关注借款信息已修改");
} else {
returnResult.setMsg("发生未知错误,关注借款信息修改失败");
}
return returnResult;
}
/**
* @Title: delAttentionBorrowing
* @Description: TODO(删除关注借款)
* @param @param attentionBorrowingIds
* @param @param annThemes
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
@Transactional(readOnly = false)
public Object delAttentionBorrowing(String attentionBorrowingId, String loanTitle) {
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
int count = 0;
if (attentionBorrowingId != null) {
AttentionBorrowingExample attentionBorrowingExample = new AttentionBorrowingExample();
attentionBorrowingExample.createCriteria().andAttentionBorrowingIdEqualTo(attentionBorrowingId);
count = attentionBorrowingMapper.deleteByExample(attentionBorrowingExample);
if (count > 0) {
returnResult.setSuccess(true);
returnResult.setMsg("成功删除了关注借款信息");
} else {
returnResult.setMsg("发生未知错误,关注借款信息删除失败");
}
}
return returnResult;
}
}
| gpl-3.0 |
SmitKabrawala/LogicAlarmClock | 1/app/src/main/java/com/alarm/sak/clock/AlarmReceiver.java | 1243 | package com.alarm.sak.clock;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| gpl-3.0 |
oxygen-plugins/common-xml | src/main/java/com/github/oxygenPlugins/common/xml/staxParser/StringNode.java | 5829 | package com.github.oxygenPlugins.common.xml.staxParser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.github.oxygenPlugins.common.process.log.DefaultProcessLoger;
import com.github.oxygenPlugins.common.process.log.ProcessLoger;
import com.github.oxygenPlugins.common.text.TextSource;
import com.github.oxygenPlugins.common.xml.xpath.XPathReader;
public class StringNode {
private TextSource textSource;
private Document docNode;
private String absPath;
private static PositionalXMLReader pxr = new PositionalXMLReader();
private ProcessLoger processLogger;
private final LineColumnInfo lineColumns;
public StringNode(TextSource source) throws IOException, SAXException, XMLStreamException{
this(source, DefaultProcessLoger.getDefaultProccessLogger());
}
public StringNode(TextSource source, ProcessLoger processLogger) throws IOException, SAXException, XMLStreamException{
this.absPath = source.getFile().getAbsolutePath();
this.processLogger = processLogger;
this.lineColumns = new LineColumnInfo(this);
setTextReader(source);
}
public StringNode(File file, ProcessLoger processLogger) throws IOException, SAXException, XMLStreamException{
this(TextSource.readTextFile(file, false), processLogger);
}
public StringNode(File file) throws IOException, SAXException, XMLStreamException{
this(TextSource.readTextFile(file, false));
}
@SuppressWarnings("unused")
private StringNode(TextSource textReader, Document docNode, String absPath){
this.textSource = textReader;
this.docNode = docNode;
this.absPath = absPath;
this.lineColumns = new LineColumnInfo(this);
}
public void setTextReader(TextSource source) throws IOException, SAXException, XMLStreamException{
TextSource backupSource = this.textSource;
try {
this.textSource = source;
this.processLogger.log("Finished text reading, start parsing xml");
actualizeNode();
this.lineColumns.updateLineColumns(this);
this.processLogger.log("Finished parsing xml");
} catch (IOException e){
this.textSource = backupSource;
this.lineColumns.updateLineColumns(this);
throw e;
} catch(SAXException e) {
this.textSource = backupSource;
this.lineColumns.updateLineColumns(this);
throw e;
}
}
public void setString(String string, boolean parse) throws IOException, SAXException, XMLStreamException {
String backupString = this.textSource.toString();
try {
this.textSource.updateData(string);
this.lineColumns.updateLineColumns(this);
if(parse){
this.processLogger.log("Start parsing xml");
actualizeNode();
}
this.processLogger.log("Finished parsing xml");
} catch (IOException e){
this.textSource.setData(backupString);
this.lineColumns.updateLineColumns(this);
throw e;
} catch(SAXException e) {
this.textSource.setData(backupString);
this.lineColumns.updateLineColumns(this);
throw e;
} catch (XMLStreamException e) {
this.textSource.setData(backupString);
this.lineColumns.updateLineColumns(this);
throw e;
}
}
private void actualizeNode() throws IOException, SAXException, XMLStreamException{
this.docNode = pxr.readXML(this.textSource);
}
public TextSource getTextSource(){
return this.textSource;
}
public Document getDocument(){
return this.docNode;
}
public String toString(){
return this.textSource.toString();
}
public String getAbsPath(){
return this.absPath;
}
public File getFile(){
return this.textSource.getFile();
}
public void setProcessLogger(ProcessLoger logger){
this.processLogger = logger;
}
private final XPathReader xpr = new XPathReader();
// XPath:
public Node getNode(String xpath) throws XPathExpressionException{
return xpr.getNode(xpath, this.docNode);
}
public NodeList getNodeSet(String xpath) throws XPathExpressionException{
return xpr.getNodeSet(xpath, this.docNode);
}
public NodeInfo getNodeInfo(String xpath) throws XPathExpressionException{
return PositionalXMLReader.getNodeInfo(this.getNode(xpath));
}
public ArrayList<NodeInfo> getNodeSetInfo(String xpath) throws XPathExpressionException{
return PositionalXMLReader.getNodeInfo(this.getNodeSet(xpath));
}
public String getNodeValue(String xpath) throws XPathExpressionException{
return xpr.getString(xpath, this.docNode);
}
public boolean getXPathBoolean(String xpath) throws XPathExpressionException{
return xpr.getBoolean(xpath, this.docNode);
}
public StringNode copy(){
StringNode copy;
try {
copy = new StringNode(this.textSource.copy(), this.processLogger);
return copy;
} catch (Exception e) {
return null;
}
}
public String getCode(NodeInfo nodeInfo) {
return this.textSource.toString().substring(nodeInfo.getStartOffset(), nodeInfo.getEndOffset());
}
public String getCode(String xpath) throws XPathExpressionException {
return this.getCode(this.getNodeInfo(xpath));
}
public LineColumnInfo getLineColumnInfo(){
return this.lineColumns;
}
public boolean equals(Object obj, boolean codeSensitive) {
if(!(obj instanceof StringNode)){
return false;
}
StringNode objSN = (StringNode) obj;
if(codeSensitive){
return this.toString().equals(objSN.toString());
} else {
return this.docNode.equals(objSN.docNode);
}
}
@Override
public boolean equals(Object obj) {
return this.equals(obj, false);
}
public String getCompareString(boolean codeSensitive){
if(codeSensitive){
return this.toString();
}
return getCompareString(this.docNode);
}
private String getCompareString(Document docNode2) {
return null;
}
}
| gpl-3.0 |
idega/is.idega.idegaweb.egov.citizen | src/java/is/idega/idegaweb/egov/citizen/data/CitizenRemoteServicesHome.java | 507 | package is.idega.idegaweb.egov.citizen.data;
import java.util.Collection;
import com.idega.data.IDOHome;
import com.idega.data.IDORelationshipException;
public interface CitizenRemoteServicesHome extends IDOHome {
public Collection<CitizenRemoteServices> getRemoteServicesByNames(Collection <String> names);
public Collection<CitizenRemoteServices> getRemoteServices(int maxAmount);
public Collection<CitizenRemoteServices> getRemoteServicesByUserId(String userId) throws IDORelationshipException ;
}
| gpl-3.0 |
Fogest/MCTrade | MCTrade/src/me/fogest/mctrade/DatabaseManager.java | 13133 | /*
* MCTrade
* Copyright (C) 2012 Fogest <http://fogest.net16.net> and contributors
*
* 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.fogest.mctrade;
import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Level;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import me.fogest.mctrade.MCTrade;
import me.fogest.mctrade.SQLibrary.*;
public class DatabaseManager {
private static MCTrade plugin = MCTrade.getPlugin();
public static File dbFolder = new File("plugins/MCTrade");
public static me.fogest.mctrade.SQLibrary.MySQL db = new me.fogest.mctrade.SQLibrary.MySQL(MCTrade.getPlugin().getLogger(), "[MCTrade]", MCTrade.mysqlHostname, MCTrade.mysqlPort,
MCTrade.mysqlDatabase, MCTrade.mysqlUsername, MCTrade.mysqlPassword);
/**
* Initializes, opens and confirms the tables and database.
*/
public static void enableDB() {
db.initialize();
db.open();
confirmTables();
plugin.getLogger().info("Database Connectioned Sucessfully Established!");
}
/**
* Closes the database.
*/
public static void disableDB() {
if (db.checkConnection())
db.close();
}
private static void confirmTables() {
if (!db.checkTable("MCTrade_users")) {
String queryString = "CREATE TABLE IF NOT EXISTS `MCTrade_users` (" + "`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + "`password` text COLLATE latin1_general_ci NOT NULL,"
+ "`username` text COLLATE latin1_general_ci NOT NULL," + "`user_level` int(11) NOT NULL," + "`ip` text COLLATE latin1_general_ci NOT NULL," + "PRIMARY KEY (`user_id`))";
try {
db.query(queryString);
MCTrade.getPlugin().getLogger().log(Level.INFO, "Successfully created the requests table.");
} catch (Exception e) {
MCTrade.getPlugin().getLogger().log(Level.SEVERE, "Unable to create the requests table.");
e.printStackTrace();
}
}
if (!db.checkTable("MCTrade_trades")) {
String queryString = "CREATE TABLE IF NOT EXISTS `mctrade_trades` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`Minecraft_Username` text NOT NULL,`Block_ID` int(5) NOT NULL,`Block_Name` text CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,`Durability` int(11) NOT NULL,`Quantity` int(3) NOT NULL,`Enchantment` text NOT NULL,`Cost` double NOT NULL,`Trade_Status` int(11) NOT NULL COMMENT '1 = Open Trade, 2 = Closed Trade, 3 = Hidden Trade',PRIMARY KEY (`id`))";
try {
db.query(queryString);
MCTrade.getPlugin().getLogger().log(Level.INFO, "Successfully created the trades table.");
} catch (Exception e) {
MCTrade.getPlugin().getLogger().log(Level.SEVERE, "Unable to create the trades table.");
e.printStackTrace();
}
}
}
public static int getUserId(String player) {
if (!db.checkConnection())
return 0;
int userId = 0;
try {
PreparedStatement ps = db.getConnection().prepareStatement("SELECT `user_id` FROM `mctrade_users` WHERE `username` = ?");
ps.setString(1, player);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
userId = rs.getInt("user_id");
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return userId;
}
public static String getUsername(String player) {
if (!db.checkConnection())
return "";
String username = "";
try {
PreparedStatement ps = db.getConnection().prepareStatement("SELECT `username` FROM `mctrade_users` WHERE `username` = ?");
ps.setString(1, player);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
username = rs.getString("username");
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return username;
}
public static int createUser(String password, String player, String ip) {
if (!db.checkConnection())
return 0;
int userId = 0;
String hashtext = "";
try {
MessageDigest m;
m = MessageDigest.getInstance("MD5");
m.update(password.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1, digest);
hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32
// chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
PreparedStatement ps = db.getConnection().prepareStatement("INSERT INTO mctrade_users VALUES (NULL,?,?,'1',?)");
ps.setString(1, hashtext);
ps.setString(2, player);
ps.setString(3, ip);
ps.executeUpdate();
ps.close();
ps = db.getConnection().prepareStatement("SELECT MAX(user_id) FROM mctrade_trades");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
userId = rs.getInt("MAX(user_id)");
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return userId;
}
public static int createTrade(Trade trade) {
int id = 0;
try {
PreparedStatement ps = db.getConnection().prepareStatement("INSERT INTO mctrade_trades VALUES (NULL,?,?,?,?,?,?,?,?)");
ps.setString(1, trade.getUsername());
ps.setInt(2, trade.getItemId());
ps.setString(3, trade.getItemName());
ps.setInt(4, trade.getDurability());
ps.setInt(5, trade.getAmount());
ps.setString(6, encodeEnchantments(trade.getItem()));
ps.setDouble(7, trade.getCost());
ps.setInt(8, trade.getStatus());
ps.executeUpdate();
ps.close();
ps = db.getConnection().prepareStatement("SELECT MAX(id) FROM mctrade_trades");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
id = rs.getInt("MAX(id)");
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return id;
}
public static Trade getTrade(int id) {
Trade trade = null;
if (!db.checkConnection())
return null;
try {
PreparedStatement ps = db.getConnection().prepareStatement(
"SELECT `id`,`Minecraft_Username`, `Block_ID`, `Block_Name`, `Durability`, `Quantity`, `Enchantment`, `Cost`, `Trade_Status` FROM `mctrade_trades` WHERE `id` = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
ItemStack stack = new ItemStack(rs.getInt("Block_ID"), rs.getInt("Quantity"), rs.getShort("Durability"));
decodeEnchantments(stack, rs.getString("Enchantment"));
trade = new Trade(stack, rs.getString("Block_Name"), rs.getString("Minecraft_Username"), rs.getInt("Cost"), rs.getInt("Trade_Status"));
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return trade;
}
public static void acceptTrade(int id) {
try {
PreparedStatement ps = db.getConnection().prepareStatement("UPDATE `mctrade_trades` SET `Trade_Status` = '2' WHERE `mctrade_trades`.`id` =?");
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static int getUserLevel(String mcUsername) {
int userLevel = 0;
if (!db.checkConnection())
return 0;
try {
PreparedStatement ps = db.getConnection().prepareStatement("SELECT `user_level` FROM `mctrade_users` WHERE `username` = ?");
ps.setString(1, mcUsername);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
userLevel = rs.getInt("user_level");
}
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return userLevel;
}
public static void setUserLevelForMod(String mcUsername) {
int curLevel = getUserLevel(mcUsername);
if (curLevel != 3) {
try {
PreparedStatement ps = db.getConnection().prepareStatement("UPDATE `mctrade_users` SET `user_level` = ? WHERE `mctrade_users`.`username` = ?");
ps.setInt(1, (3));
ps.setString(2, mcUsername);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void setUserLevelForAdmin(String mcUsername) {
int curLevel = getUserLevel(mcUsername);
if (curLevel != 4) {
try {
PreparedStatement ps = db.getConnection().prepareStatement("UPDATE `mctrade_users` SET `user_level` = ? WHERE `mctrade_users`.`username` = ?");
ps.setInt(1, (4));
ps.setString(2, mcUsername);
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// encode/decode enchantments for database storage
public static String encodeEnchantments(ItemStack stack) {
if (stack == null)
return "";
Map<Enchantment, Integer> enchantments = stack.getEnchantments();
if (enchantments == null || enchantments.isEmpty())
return "";
// get enchantments
HashMap<Integer, Integer> enchMap = new HashMap<Integer, Integer>();
boolean removedUnsafe = false;
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
// check safe enchantments
int level = checkSafeEnchantments(stack, entry.getKey(), entry.getValue());
if (level == 0) {
removedUnsafe = true;
continue;
}
enchMap.put(entry.getKey().getId(), level);
}
// sort by enchantment id
SortedSet<Integer> enchSorted = new TreeSet<Integer>(enchMap.keySet());
// build string
String enchStr = "";
for (int enchId : enchSorted) {
int level = enchMap.get(enchId);
if (!enchStr.isEmpty())
enchStr += ",";
enchStr += Integer.toString(enchId) + ":" + Integer.toString(level);
}
return enchStr;
}
// decode enchantments from database
public static boolean decodeEnchantments(ItemStack stack, String enchStr) {
if (enchStr == null || enchStr.isEmpty())
return false;
Map<Enchantment, Integer> ench = new HashMap<Enchantment, Integer>();
String[] parts = enchStr.split(",");
boolean removedUnsafe = false;
for (String part : parts) {
if (part == null || part.isEmpty())
continue;
String[] split = part.split(":");
if (split.length != 2) {
plugin.getLogger().warning("Invalid enchantment data found: " + part);
continue;
}
int enchId = -1;
int level = -1;
try {
enchId = Integer.valueOf(split[0]);
level = Integer.valueOf(split[1]);
} catch (Exception ignore) {
}
if (enchId < 0 || level < 1) {
plugin.getLogger().warning("Invalid enchantment data found: " + part);
continue;
}
Enchantment enchantment = Enchantment.getById(enchId);
if (enchantment == null) {
plugin.getLogger().warning("Invalid enchantment id found: " + part);
continue;
}
// check safe enchantments
level = checkSafeEnchantments(stack, enchantment, level);
if (level == 0) {
removedUnsafe = true;
continue;
}
// add enchantment to map
ench.put(enchantment, level);
}
// add enchantments to stack
stack.addEnchantments(ench);
return removedUnsafe;
}
// check natural enchantment
public static int checkSafeEnchantments(ItemStack stack, Enchantment enchantment, int level) {
if (stack == null || enchantment == null)
return 0;
if (level < 1)
return 0;
// can enchant item
if (!enchantment.canEnchantItem(stack)) {
plugin.getLogger().warning("Removed unsafe enchantment: " + stack.toString() + " " + enchantment.toString());
return 0;
}
// level too low
if (level < enchantment.getStartLevel()) {
plugin.getLogger()
.warning("Raised unsafe enchantment: " + Integer.toString(level) + " " + stack.toString() + " " + enchantment.toString() + " to level: " + enchantment.getStartLevel());
level = enchantment.getStartLevel();
}
// level too high
if (level > enchantment.getMaxLevel()) {
plugin.getLogger().warning("Lowered unsafe enchantment: " + Integer.toString(level) + " " + stack.toString() + " " + enchantment.toString() + " to level: " + enchantment.getMaxLevel());
level = enchantment.getMaxLevel();
}
return level;
}
public static boolean resetDB() {
db.query("DELETE FROM MCTrade_trades");
db.query("DELETE FROM MCTrade_users");
return true;
}
} | gpl-3.0 |
vpac-innovations/rsa | src/rsaquery/src/main/java/org/vpac/ndg/query/sampling/Prototype.java | 7101 | /*
* This file is part of the Raster Storage Archive (RSA).
*
* The RSA 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.
*
* The RSA 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
* the RSA. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013 CRCSI - Cooperative Research Centre for Spatial Information
* http://www.crcsi.com.au/
*/
package org.vpac.ndg.query.sampling;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.vpac.ndg.query.QueryException;
import org.vpac.ndg.query.QueryDefinition.AttributeDefinition;
import org.vpac.ndg.query.QueryDimensionalityException;
import org.vpac.ndg.query.QueryException;
import org.vpac.ndg.query.StringUtils;
import org.vpac.ndg.query.math.Element;
import org.vpac.ndg.query.math.Type;
import org.vpac.ndg.query.math.VectorElement;
/**
* Metatdata for connections between filters.
* @author Alex Fraser
*/
public class Prototype implements HasDimensions {
// There is one nodata strategy for each prototypical element.
private Type[] types;
private NodataStrategy[] nodataStrategies;
// null until getElement is called
private Element<?> element;
// Arbitrary attributes can be passed along with the data type.
private AttributeDefinition[][] attributes;
// Dimensions are completely separate from the data type and nodata values
private String[] dimensions;
public Prototype(Type[] types, NodataStrategy[] ndss,
AttributeDefinition[][] attributes, String[] dims) {
int ncomponents = types.length;
if (ncomponents != ndss.length) {
throw new IllegalArgumentException(String.format(
"Number of nodata strategies (%d) does not match number " +
"of element components (%d)", ndss.length, ncomponents));
}
this.types = types;
this.attributes = attributes;
nodataStrategies = ndss;
dimensions = dims;
}
public Prototype copy() {
NodataStrategy[] ndss = new NodataStrategy[nodataStrategies.length];
AttributeDefinition[][] attrs = new AttributeDefinition[attributes.length][];
for (int i = 0; i < nodataStrategies.length; i++) {
ndss[i] = nodataStrategies[i].copy();
attrs[i] = new AttributeDefinition[attributes[i].length];
for (int j = 0; j < attributes[i].length; j++) {
attrs[i][j] = attributes[i][j].copy();
}
}
return new Prototype(types.clone(), ndss, attributes.clone(), dimensions.clone());
}
/**
* @see #combine(Prototype[], String[])
*/
public static Prototype combine(Collection<? extends HasPrototype> sources,
String[] dimensions) throws QueryException {
Prototype[] prototypes = new Prototype[sources.size()];
int i = 0;
for (HasPrototype source : sources) {
prototypes[i] = source.getPrototype();
i++;
}
return combine(prototypes, dimensions);
}
/**
* Create a new prototype that is the combination of a bunch of other
* prototypes.
*
* @param prototypes The prototypes to combine.
* @param dimensions The dimensions of the new prototype. If null, the
* dimensions will be inherited from the sources, in which case all
* sources must have the same dimensions.
* @return The new prototype.
*/
public static Prototype combine(Prototype[] prototypes, String[] dimensions)
throws QueryException {
List<Type> types = new ArrayList<Type>();
List<NodataStrategy> ndss = new ArrayList<NodataStrategy>();
List<AttributeDefinition[]> attributes = new ArrayList<AttributeDefinition[]>();
String[] dims = dimensions;
for (Prototype pt : prototypes) {
if (dimensions != null) {
// Caller has overridden dimensions; don't need to inherit.
} else if (dims == null) {
dims = pt.getDimensions();
} else if (!Arrays.equals(dims, pt.getDimensions())) {
throw new QueryDimensionalityException(
"Can't create prototype: components have " +
"differing dimensionality.");
}
types.addAll(Arrays.asList(pt.types));
for (NodataStrategy nds : pt.getNodataStrategies()) {
ndss.add(nds.copy());
}
for (AttributeDefinition[] ads : pt.attributes) {
AttributeDefinition[] newAds = new AttributeDefinition[ads.length];
for (int i = 0; i < newAds.length; i++) {
newAds[i] = ads[i].copy();
}
attributes.add(newAds);
}
}
if (types.size() != ndss.size()) {
throw new QueryException("Number of element components " +
"does not match number of nodata strategies.");
}
if (types.size() != attributes.size()) {
throw new QueryException("Number of element components " +
"does not match number of attributes.");
}
Type[] typeArray = new Type[types.size()];
typeArray = types.toArray(typeArray);
NodataStrategy[] ndsArray = new NodataStrategy[ndss.size()];
ndsArray = ndss.toArray(ndsArray);
AttributeDefinition[][] attrsArray = new AttributeDefinition[attributes.size()][];
attrsArray = attributes.toArray(attrsArray);
return new Prototype(typeArray, ndsArray, attrsArray, dims);
}
/**
* @return A prototypical element for this object. This can be used by
* algorithms that don't need to know what type of data they are dealing
* with. Don't modify this element; call {@link Element#copy()} to get a
* local copy.
*/
public Element<?> getElement() {
if (element == null) {
if (types.length == 1)
element = types[0].getElement().copy();
else
element = VectorElement.create(types);
}
return element;
}
public Type[] getTypes() {
return types;
}
@Override
public String[] getDimensions() {
return dimensions;
}
public void setDimensions(String[] dimensions) {
this.dimensions = dimensions;
}
public NodataStrategy[] getNodataStrategies() {
return nodataStrategies;
}
/**
* Convert the prototype to a specific numeric type while keeping the same
* number of components.
* @param type The type to convert to (byte, short, int, ...)
*/
public void convert(String type) throws QueryException {
// Convert to specified type - this keeps the same number of components.
if (type.equals(""))
return;
// Replace all types with the one specified.
Type targetType = Type.get(type);
for (int i = 0; i < types.length; i++)
types[i] = targetType;
element = null;
for (NodataStrategy nds : nodataStrategies)
nds.convert(targetType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String dim : dimensions) {
if (sb.length() > 0)
sb.append(' ');
sb.append(dim);
}
String ts = StringUtils.join(types, " ");
return String.format("Prototype(%s, %s)", ts, sb);
}
public AttributeDefinition[][] getAttributes() {
return attributes;
}
}
| gpl-3.0 |
akraievoy/org_akraievoy_base | src/main/java/org/akraievoy/base/dump/Dump.java | 1649 | /*
Copyright 2011 Anton Kraievoy akraievoy@gmail.com
This file is part of org.akraievoy:base.
org.akraievoy:base 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.
org.akraievoy:base 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with org.akraievoy:base. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akraievoy.base.dump;
import java.io.*;
/**
* Simplistic in-memory object (de)serialization.
*/
public class Dump {
public static byte[] dumpObject(final Serializable obj) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
final ObjectOutputStream objOut = new ObjectOutputStream(baos);
objOut.writeObject(obj);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return baos.toByteArray();
}
public static Object readObject(final byte[] bytes) {
final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try {
final ObjectInputStream objIn = new ObjectInputStream(bais);
return objIn.readObject();
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| gpl-3.0 |
4Space/4Space-5 | src/main/java/micdoodle8/mods/galacticraft/core/client/gui/container/GuiExtendedInventory.java | 6763 | package micdoodle8.mods.galacticraft.core.client.gui.container;
import micdoodle8.mods.galacticraft.core.GalacticraftCore;
import micdoodle8.mods.galacticraft.core.client.gui.screen.InventoryTabGalacticraft;
import micdoodle8.mods.galacticraft.core.inventory.ContainerExtendedInventory;
import micdoodle8.mods.galacticraft.core.inventory.InventoryExtended;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.common.Loader;
import tconstruct.client.tabs.AbstractTab;
import tconstruct.client.tabs.TabRegistry;
public class GuiExtendedInventory extends InventoryEffectRenderer
{
private static final ResourceLocation inventoryTexture = new ResourceLocation(GalacticraftCore.ASSET_PREFIX, "textures/gui/inventory.png");
private float xSize_lo_2;
private float ySize_lo_2;
private int potionOffsetLast;
private static float rotation;
private boolean initWithPotion;
public GuiExtendedInventory(EntityPlayer entityPlayer, InventoryExtended inventory)
{
super(new ContainerExtendedInventory(entityPlayer, inventory));
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
GuiExtendedInventory.drawPlayerOnGui(this.mc, 33, 75, 29, 51 - this.xSize_lo_2, 75 - 50 - this.ySize_lo_2);
}
@SuppressWarnings("unchecked")
@Override
public void initGui()
{
super.initGui();
this.guiLeft = (this.width - this.xSize) / 2;
this.guiLeft += this.getPotionOffset();
this.potionOffsetLast = getPotionOffsetNEI();
int cornerX = this.guiLeft;
int cornerY = this.guiTop;
TabRegistry.updateTabValues(cornerX, cornerY, InventoryTabGalacticraft.class);
TabRegistry.addTabsToList(this.buttonList);
this.buttonList.add(new GuiButton(0, this.guiLeft + 10, this.guiTop + 71, 7, 7, ""));
this.buttonList.add(new GuiButton(1, this.guiLeft + 51, this.guiTop + 71, 7, 7, ""));
}
@Override
protected void actionPerformed(GuiButton par1GuiButton)
{
switch (par1GuiButton.id)
{
case 0:
GuiExtendedInventory.rotation += 10.0F;
break;
case 1:
GuiExtendedInventory.rotation -= 10.0F;
break;
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(GuiExtendedInventory.inventoryTexture);
final int k = this.guiLeft;
final int l = this.guiTop;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
int newPotionOffset = this.getPotionOffsetNEI();
if (newPotionOffset < this.potionOffsetLast)
{
int diff = newPotionOffset - this.potionOffsetLast;
this.potionOffsetLast = newPotionOffset;
this.guiLeft += diff;
for (int k = 0; k < this.buttonList.size(); ++k)
{
GuiButton b = (GuiButton) this.buttonList.get(k);
if (!(b instanceof AbstractTab)) b.xPosition += diff;
}
}
super.drawScreen(par1, par2, par3);
this.xSize_lo_2 = par1;
this.ySize_lo_2 = par2;
}
public static void drawPlayerOnGui(Minecraft par0Minecraft, int par1, int par2, int par3, float par4, float par5)
{
GL11.glPushMatrix();
GL11.glTranslatef(par1, par2, 50.0F);
GL11.glScalef(-par3, par3, par3);
GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F);
float f2 = par0Minecraft.thePlayer.renderYawOffset;
float f3 = par0Minecraft.thePlayer.rotationYaw;
float f4 = par0Minecraft.thePlayer.rotationPitch;
float f5 = par0Minecraft.thePlayer.rotationYawHead;
par4 -= 19;
GL11.glRotatef(135.0F, 0.0F, 1.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F);
// GL11.glRotatef(-((float) Math.atan(par5 / 40.0F)) * 20.0F, 1.0F,
// 0.0F, 0.0F);
par0Minecraft.thePlayer.renderYawOffset = GuiExtendedInventory.rotation;
par0Minecraft.thePlayer.rotationYaw = (float) Math.atan(par4 / 40.0F) * 40.0F;
par0Minecraft.thePlayer.rotationYaw = GuiExtendedInventory.rotation;
par0Minecraft.thePlayer.rotationYawHead = par0Minecraft.thePlayer.rotationYaw;
par0Minecraft.thePlayer.rotationPitch = (float)Math.sin(par0Minecraft.getSystemTime() / 500.0F) * 3.0F;
GL11.glTranslatef(0.0F, par0Minecraft.thePlayer.yOffset, 0.0F);
RenderManager.instance.playerViewY = 180.0F;
RenderManager.instance.renderEntityWithPosYaw(par0Minecraft.thePlayer, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F);
par0Minecraft.thePlayer.renderYawOffset = f2;
par0Minecraft.thePlayer.rotationYaw = f3;
par0Minecraft.thePlayer.rotationPitch = f4;
par0Minecraft.thePlayer.rotationYawHead = f5;
GL11.glPopMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GL11.glDisable(GL11.GL_TEXTURE_2D);
OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit);
RenderHelper.enableGUIStandardItemLighting();
}
public int getPotionOffset()
{
// If at least one potion is active...
if (!Minecraft.getMinecraft().thePlayer.getActivePotionEffects().isEmpty())
{
this.initWithPotion = true;
return 60 + getPotionOffsetNEI();
}
// No potions, no offset needed
this.initWithPotion = false;
return 0;
}
public int getPotionOffsetNEI()
{
if (this.initWithPotion && Loader.isModLoaded("NotEnoughItems"))
{
try
{
// Check whether NEI is hidden and enabled
Class<?> c = Class.forName("codechicken.nei.NEIClientConfig");
Object hidden = c.getMethod("isHidden").invoke(null);
Object enabled = c.getMethod("isEnabled").invoke(null);
if (hidden instanceof Boolean && enabled instanceof Boolean)
{
if ((Boolean)hidden || !((Boolean)enabled))
{
// If NEI is disabled or hidden, offset the tabs by the standard 60
return 0;
}
//Active NEI undoes the standard potion offset
return -60;
}
}
catch (Exception e)
{
}
}
//No NEI, no change
return 0;
}
}
| gpl-3.0 |
Venom590/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/model/api/tuples/package-info.java | 789 | /*
* This file is part of Gradoop.
*
* Gradoop 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.
*
* Gradoop 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 Gradoop. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Contains interfaces for tuple-type classes used by Gradoop.
*/
package org.gradoop.flink.model.api.tuples;
| gpl-3.0 |
micromata/projectforge | projectforge-rest/src/main/java/org/projectforge/web/rest/TimesheetTemplatesRest.java | 2728 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2022 Micromata GmbH, Germany (www.micromata.com)
//
// ProjectForge is dual-licensed.
//
// This community edition 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.
//
// This community edition 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.projectforge.web.rest;
import org.projectforge.business.task.TaskDao;
import org.projectforge.business.user.UserPrefDao;
import org.projectforge.framework.json.JsonUtils;
import org.projectforge.framework.persistence.user.api.UserPrefArea;
import org.projectforge.framework.persistence.user.entities.UserPrefDO;
import org.projectforge.model.rest.RestPaths;
import org.projectforge.model.rest.TimesheetTemplateObject;
import org.projectforge.web.rest.converter.TimesheetTemplateConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* REST-Schnittstelle für {@link TaskDao}
*
* @author Kai Reinhard (k.reinhard@micromata.de)
*/
@Controller
@Path(RestPaths.TIMESHEET_TEMPLATE)
public class TimesheetTemplatesRest
{
@Autowired
private UserPrefDao userPrefDao;
@Autowired
private TimesheetTemplateConverter timesheetTemplateConverter;
@GET
@Path(RestPaths.LIST)
@Produces(MediaType.APPLICATION_JSON)
public Response getList()
{
final List<UserPrefDO> list = userPrefDao.getUserPrefs(UserPrefArea.TIMESHEET_TEMPLATE);
final List<TimesheetTemplateObject> result = new ArrayList<>();
if (list != null) {
for (final UserPrefDO userPref : list) {
final TimesheetTemplateObject template = timesheetTemplateConverter.getTimesheetTemplateObject(userPref);
if (template != null) {
result.add(template);
}
}
}
final String json = JsonUtils.toJson(result);
return Response.ok(json).build();
}
}
| gpl-3.0 |
yangsong19/DayPo | src/com/other/Table.java | 294 | package com.other;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.TYPE })
public @interface Table {
String value();
}
| gpl-3.0 |
Terry-Weymouth/GA-AntWorld | SingleAnt/NestAndForaging/src/main/java/org/weymouth/ants/watchmaker/NetworkFitnessEvaluator.java | 2103 | package org.weymouth.ants.watchmaker;
import java.util.List;
import java.util.HashMap;
import org.uncommons.watchmaker.framework.FitnessEvaluator;
import org.weymouth.ants.core.AntBrain;
import org.weymouth.ants.core.AntWorld;
import org.weymouth.ants.core.AntWorldView;
import org.weymouth.ants.core.Network;
import org.weymouth.ants.core.AntWorldViewController;
public class NetworkFitnessEvaluator implements FitnessEvaluator<Network> {
private final AntWorldViewController worldController;
private final HashMap<Network, Double> cache = new HashMap<Network, Double>();
private final boolean headless;
private static int count = 0;
private boolean useCache = false;
public NetworkFitnessEvaluator(boolean flag) {
headless = flag;
if (headless) {
worldController = null;
} else {
worldController = AntWorldViewController.getController();
worldController.initialize();
}
}
@Override
public double getFitness(Network net, List<? extends Network> list) {
double score = evaluate(net);
System.out.println("Called NetworkFitnessEvaluator; returning score = " + score);
if (!headless) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
}
return score;
}
@Override
public boolean isNatural() {
return true;
}
public double evaluate(Network net) {
if (useCache) {
Double scoreHolder = cache.get(net);
if (scoreHolder != null) {
System.out.println("Evaluate-called: scored by lookup");
return scoreHolder.doubleValue();
}
}
count += 1;
System.out.println("Evaluate-called count = " + count);
AntBrain antBrain = new AntBrain(net);
AntWorldView antWorldView = null;
if (!headless) {
antWorldView = worldController.getView();
}
AntWorld antWorld = new AntWorld(antBrain);
while (antWorld.update()){
if (!headless) {
antWorldView.update(antWorld.cloneAnts(), antWorld.cloneMeals());
}
}
double score = (double)antWorld.getScore()/10000.0;
cache.put(net, new Double(score));
return score;
}
public void setUseCache(boolean flag) {
useCache = flag;
}
}
| gpl-3.0 |
mddorfli/leslie | leslie.server/src/main/java/org/leslie/server/jpa/AbstractJpaLongLookupService.java | 1430 | package org.leslie.server.jpa;
import java.util.List;
import javax.persistence.TypedQuery;
import org.eclipse.scout.rt.shared.services.lookup.ILookupCall;
import org.leslie.shared.lookup.LongLookupRow;
/**
* @author Marco Dörfliger
*/
public abstract class AbstractJpaLongLookupService extends AbstractJpaLookupService<Long> {
/**
* Must generate {@link LongLookupRow} objects using the NEW keyword.
* e.g.<br>
* <code>SELECT NEW org.leslie.server.jpa.LongLookupRow(a.id, a.name)</code>...
*
* @param call
* TODO
*
* @return JP QL select statement.
*/
protected abstract String getConfiguredJpqlSelect(ILookupCall<Long> call);
/**
* Additional parameter setting etc can be done here.
*
* @param query
* @param call
* TODO
*/
protected void execPrepareQuery(TypedQuery<LongLookupRow> query, ILookupCall<Long> call) {
// can be overridden
}
@Override
protected final List<LongLookupRow> execGenerateRowData(ILookupCall<Long> call, LookupCallType callType) {
String queryString = getConfiguredJpqlSelect(call);
TypedQuery<LongLookupRow> query = JPA.createQuery(
filterSqlByCallType(queryString, callType), LongLookupRow.class);
setCallQueryBinds(query, call, callType);
execPrepareQuery(query, call);
query.setMaxResults(call.getMaxRowCount());
return query.getResultList();
}
}
| gpl-3.0 |
null-dev/EvenWurse | MCPWrapper/src/xyz/nulldev/mcpwrapper/bukkit/entity/Entity.java | 6094 | package xyz.nulldev.mcpwrapper.bukkit.entity;
import xyz.nulldev.mcpwrapper.bukkit.Location;
import xyz.nulldev.mcpwrapper.bukkit.World;
import xyz.nulldev.mcpwrapper.bukkit.util.Vector;
import java.util.List;
import java.util.UUID;
/**
* Represents a base entity in the world
*/
public interface Entity {
/**
* Gets the entity's current position
*
* @return a new copy of Location containing the position of this entity
*/
public Location getLocation();
/**
* Stores the entity's current position in the provided Location object.
* <p>
* If the provided Location is null this method does nothing and returns
* null.
*
* @return The Location object provided or null
*/
public Location getLocation(Location loc);
/**
* Gets this entity's current velocity
*
* @return Current travelling velocity of this entity
*/
public Vector getVelocity();
/**
* Sets this entity's velocity
*
* @param velocity New velocity to travel with
*/
public void setVelocity(Vector velocity);
/**
* Returns true if the entity is supported by a block. This value is a
* state updated by the server and is not recalculated unless the entity
* moves.
*
* @return True if entity is on ground.
*/
public boolean isOnGround();
/**
* Gets the current world this entity resides in
*
* @return World
*/
public World getWorld();
/**
* Teleports this entity to the given location. If this entity is riding a
* vehicle, it will be dismounted prior to teleportation.
*
* @param location New location to teleport this entity to
* @return <code>true</code> if the teleport was successful
*/
public boolean teleport(Location location);
/**
* Teleports this entity to the target Entity. If this entity is riding a
* vehicle, it will be dismounted prior to teleportation.
*
* @param destination Entity to teleport this entity to
* @return <code>true</code> if the teleport was successful
*/
public boolean teleport(Entity destination);
/**
* Returns a list of entities within a bounding box centered around this
* entity
*
* @param x 1/2 the size of the box along x axis
* @param y 1/2 the size of the box along y axis
* @param z 1/2 the size of the box along z axis
* @return List<Entity> List of entities nearby
*/
public List<Entity> getNearbyEntities(double x, double y, double z);
/**
* Returns a unique id for this entity
*
* @return Entity id
*/
public int getEntityId();
/**
* Returns the entity's current fire ticks (ticks before the entity stops
* being on fire).
*
* @return int fireTicks
*/
public int getFireTicks();
/**
* Sets the entity's current fire ticks (ticks before the entity stops
* being on fire).
*
* @param ticks Current ticks remaining
*/
public void setFireTicks(int ticks);
/**
* Returns the entity's maximum fire ticks.
*
* @return int maxFireTicks
*/
public int getMaxFireTicks();
/**
* Mark the entity's removal.
*/
public void remove();
/**
* Returns true if this entity has been marked for removal.
*
* @return True if it is dead.
*/
public boolean isDead();
/**
* Returns false if the entity has died or been despawned for some other
* reason.
*
* @return True if valid.
*/
public boolean isValid();
/**
* Gets the primary passenger of a vehicle. For vehicles that could have
* multiple passengers, this will only return the primary passenger.
*
* @return an entity
*/
public abstract Entity getPassenger();
/**
* Set the passenger of a vehicle.
*
* @param passenger The new passenger.
* @return false if it could not be done for whatever reason
*/
public abstract boolean setPassenger(Entity passenger);
/**
* Check if a vehicle has passengers.
*
* @return True if the vehicle has no passengers.
*/
public abstract boolean isEmpty();
/**
* Eject any passenger.
*
* @return True if there was a passenger.
*/
public abstract boolean eject();
/**
* Returns the distance this entity has fallen
*
* @return The distance.
*/
public float getFallDistance();
/**
* Sets the fall distance for this entity
*
* @param distance The new distance.
*/
public void setFallDistance(float distance);
/**
* Returns a unique and persistent id for this entity
*
* @return unique id
*/
public UUID getUniqueId();
/**
* Gets the amount of ticks this entity has lived for.
* <p>
* This is the equivalent to "age" in entities.
*
* @return Age of entity
*/
public int getTicksLived();
/**
* Sets the amount of ticks this entity has lived for.
* <p>
* This is the equivalent to "age" in entities. May not be less than one
* tick.
*
* @param value Age of entity
*/
public void setTicksLived(int value);
/**
* Get the type of the entity.
*
* @return The entity type.
*/
//TODO
// public EntityType getType();
/**
* Returns whether this entity is inside a vehicle.
*
* @return True if the entity is in a vehicle.
*/
public boolean isInsideVehicle();
/**
* Leave the current vehicle. If the entity is currently in a vehicle (and
* is removed from it), true will be returned, otherwise false will be
* returned.
*
* @return True if the entity was in a vehicle.
*/
public boolean leaveVehicle();
/**
* Get the vehicle that this player is inside. If there is no vehicle,
* null will be returned.
*
* @return The current vehicle.
*/
public Entity getVehicle();
}
| mpl-2.0 |
Helioviewer-Project/JHelioviewer-SWHV | src/org/helioviewer/jhv/display/GridScale.java | 6168 | package org.helioviewer.jhv.display;
import javax.annotation.Nonnull;
import org.helioviewer.jhv.astronomy.Position;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.camera.CameraHelper;
import org.helioviewer.jhv.math.MathUtils;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
public interface GridScale {
double getInterpolatedXValue(double v, GridType gridType);
double getInterpolatedYValue(double v);
double getXValueInv(double v);
double getYValueInv(double v);
double getYstart();
double getYstop();
void set(double _xStart, double _xStop, double _yStart, double _yStop);
@Nonnull
Vec2 mouseToGrid(int px, int py, Viewport vp, Camera camera, GridType gridType);
@Nonnull
Vec2 mouseToGridInv(int px, int py, Viewport vp, Camera camera);
GridScale ortho = new GridScaleOrtho(0, 0, 0, 0);
GridScale lati = new GridScaleLati(-180, 180, -90, 90);
GridScale polar = new GridScaleIdentity(0, 360, 0, 0);
GridScale logpolar = new GridScaleLogY(0, 360, 0, 0);
abstract class GridScaleAbstract implements GridScale {
protected double xStart;
protected double xStop;
protected double yStart;
protected double yStop;
GridScaleAbstract(double _xStart, double _xStop, double _yStart, double _yStop) {
set(_xStart, _xStop, _yStart, _yStop);
}
@Override
public void set(double _xStart, double _xStop, double _yStart, double _yStop) {
xStart = _xStart;
xStop = _xStop;
yStart = scaleY(_yStart);
yStop = scaleY(_yStop);
}
@Override
public double getInterpolatedXValue(double v, GridType gridType) {
return invScaleX(xStart + v * (xStop - xStart));
}
@Override
public double getInterpolatedYValue(double v) {
return invScaleY(yStart + v * (yStop - yStart));
}
@Override
public double getXValueInv(double v) {
return (scaleX(v) - xStart) / (xStop - xStart) - 0.5;
}
@Override
public double getYValueInv(double v) {
return (scaleY(v) - yStart) / (yStop - yStart) - 0.5;
}
@Override
public double getYstart() {
return yStart;
}
@Override
public double getYstop() {
return yStop;
}
@Nonnull
@Override
public Vec2 mouseToGrid(int px, int py, Viewport vp, Camera camera, GridType gridType) {
double x = CameraHelper.computeUpX(camera, vp, px) / vp.aspect + 0.5;
double y = CameraHelper.computeUpY(camera, vp, py) + 0.5;
return new Vec2(getInterpolatedXValue(x, gridType), getInterpolatedYValue(y));
}
@Nonnull
@Override
public Vec2 mouseToGridInv(int px, int py, Viewport vp, Camera camera) {
double x = CameraHelper.computeUpX(camera, vp, px) / vp.aspect;
double y = CameraHelper.computeUpY(camera, vp, py);
return new Vec2(x, y);
}
protected abstract double scaleX(double val);
protected abstract double invScaleX(double val);
protected abstract double scaleY(double val);
protected abstract double invScaleY(double val);
}
class GridScaleLogY extends GridScaleAbstract {
GridScaleLogY(double _xStart, double _xStop, double _yStart, double _yStop) {
super(_xStart, _xStop, _yStart, _yStop);
}
@Override
public double scaleX(double val) {
return val;
}
@Override
public double invScaleX(double val) {
return val;
}
@Override
public double scaleY(double val) {
return Math.log(val);
}
@Override
public double invScaleY(double val) {
return Math.exp(val);
}
}
class GridScaleIdentity extends GridScaleAbstract {
GridScaleIdentity(double _xStart, double _xStop, double _yStart, double _yStop) {
super(_xStart, _xStop, _yStart, _yStop);
}
@Override
public double scaleX(double val) {
return val;
}
@Override
public double invScaleX(double val) {
return val;
}
@Override
public double scaleY(double val) {
return val;
}
@Override
public double invScaleY(double val) {
return val;
}
}
class GridScaleLati extends GridScaleIdentity {
GridScaleLati(double _xStart, double _xStop, double _yStart, double _yStop) {
super(_xStart, _xStop, _yStart, _yStop);
}
@Override
public double getInterpolatedXValue(double v, GridType gridType) {
double ix = super.getInterpolatedXValue(v, gridType);
if (gridType == GridType.Carrington && ix < 0)
ix += 360;
return ix;
}
}
class GridScaleOrtho extends GridScaleIdentity {
GridScaleOrtho(double _xStart, double _xStop, double _yStart, double _yStop) {
super(_xStart, _xStop, _yStart, _yStop);
}
@Nonnull
@Override
public Vec2 mouseToGrid(int px, int py, Viewport vp, Camera camera, GridType gridType) {
Vec3 p = CameraHelper.getVectorFromSphere(camera, vp, px, py, Quat.ZERO, true);
if (p == null)
return Vec2.NAN;
if (gridType != GridType.Viewpoint) {
Position viewpoint = camera.getViewpoint();
Quat q = Quat.rotateWithConjugate(viewpoint.toQuat(), gridType.toCarrington(viewpoint));
p = q.rotateInverseVector(p);
}
double theta = Math.asin(p.y) * MathUtils.radeg;
double phi = Math.atan2(p.x, p.z) * MathUtils.radeg;
if (gridType == GridType.Carrington && phi < 0)
phi += 360;
return new Vec2(phi, theta);
}
}
}
| mpl-2.0 |
ProfilingLabs/Usemon2 | usemon-domain-java/src/main/java/org/usemon/domain/graph/GMLWriterVisitor.java | 3050 | /**
* Created 14. nov.. 2007 17.42.16 by Steinar Overbeck Cook
*/
package org.usemon.domain.graph;
import java.io.IOException;
import java.io.Writer;
/**
* @author t547116 (Steinar Overbeck Cook)
*
*/
public class GMLWriterVisitor implements GraphVisitor {
public GMLWriterVisitor() {}
public void generateMarkup(Writer writer, Graph graph) {
try {
writer.append((CharSequence) graph.accept(this));
} catch (IOException e) {
throw new IllegalStateException("Error while writing graph; " + e.getMessage(),e);
}
}
public Object visit(Edge edge) {
StringBuilder sb = new StringBuilder();
sb.append("\t\nedge [");
sb.append(" source "+edge.getSource().getUid());
sb.append(" target "+edge.getTarget().getUid());
sb.append(" graphics [");
sb.append(" fill \"#000000\"");
sb.append(" targetArrow \"standard\"");
sb.append(" ]");
sb.append(" ]");
return sb;
}
public Object visit(Graph graph) {
StringBuilder sb = new StringBuilder("Creator \"Usemon\"\n");
sb.append("Version \"2.0\"\n");
sb.append("graph [");
sb.append("\t\nhierarchic 1");
sb.append("\t\nlabel \"\"");
sb.append("\t\ndirected 1");
for (Node node : graph.getNodes()) {
sb.append( node.accept(this));
}
for (Edge edge : graph.getEdges()) {
sb.append( edge.accept(this));
}
sb.append("]\n");
return sb;
}
public Object visit(Node node) {
StringBuilder sb = new StringBuilder();
sb.append("\t\nnode [\n");
sb.append("\t\t\nid ")
.append(node.getUid());
sb.append("\t\t\nlabel \""
+ node.getUid()
+"\"");
sb.append("\t\t\ngraphics [");
sb.append("\t\t\t\ntype \"rectangle\"");
sb.append("\t\t\t\nfill \"#FF0000\"");
sb.append("\t\t\t\noutline \"#000000\"");
sb.append("\t\t\n]");
sb.append(" labelgraphics [");
sb.append(" text \""
+ node.getUid()
+"\"");
sb.append(" fontSize 13");
sb.append(" fontName \"Dialog\"");
sb.append(" anchor \"c\"");
sb.append(" ]");
sb.append(" ]");
return sb;
}
public Object visit(InstanceNode node) {
StringBuilder sb = new StringBuilder();
sb.append("\t\nnode [\n");
sb.append("\t\t\nid ")
.append(node.getUid());
StringBuilder nodeLabel = new StringBuilder("");
if (node.getInstanceName() != null )
nodeLabel.append(node.getInstanceName()).append("\n");
nodeLabel.append(':').append(node.getClassName());
sb.append("\t\t\nlabel \""
+ nodeLabel
+"\"");
sb.append("\t\t\ngraphics [");
sb.append("\t\t\t\ntype \"rectangle\"");
sb.append("\t\t\t\nfill \"#FF0000\"");
sb.append("\t\t\t\noutline \"#000000\"");
sb.append("\t\t\n]");
sb.append(" labelgraphics [");
sb.append(" text \""
+ nodeLabel
+"\"");
sb.append(" fontSize 13");
sb.append(" fontName \"Dialog\"");
sb.append(" anchor \"c\"");
sb.append(" ]");
sb.append(" ]");
return sb; }
}
| mpl-2.0 |
hyb1996/NoRootScriptDroid | app/src/main/java/org/autojs/autojs/tool/AccessibilityServiceTool.java | 3294 | package org.autojs.autojs.tool;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.text.TextUtils;
import com.stardust.app.GlobalAppContext;
import org.autojs.autojs.Pref;
import org.autojs.autojs.App;
import org.autojs.autojs.R;
import com.stardust.autojs.core.util.ProcessShell;
import org.autojs.autojs.accessibility.AccessibilityService;
import com.stardust.view.accessibility.AccessibilityServiceUtils;
import java.util.Locale;
/**
* Created by Stardust on 2017/1/26.
*/
public class AccessibilityServiceTool {
private static final Class<AccessibilityService> sAccessibilityServiceClass = AccessibilityService.class;
public static void enableAccessibilityService() {
if (Pref.shouldEnableAccessibilityServiceByRoot()) {
if (!enableAccessibilityServiceByRoot(sAccessibilityServiceClass)) {
goToAccessibilitySetting();
}
} else {
goToAccessibilitySetting();
}
}
public static void goToAccessibilitySetting() {
Context context = GlobalAppContext.get();
if (Pref.isFirstGoToAccessibilitySetting()) {
GlobalAppContext.toast(context.getString(R.string.text_please_choose) + context.getString(R.string._app_name));
}
try {
AccessibilityServiceUtils.goToAccessibilitySetting(context);
} catch (ActivityNotFoundException e) {
GlobalAppContext.toast(context.getString(R.string.go_to_accessibility_settings) + context.getString(R.string._app_name));
}
}
private static final String cmd = "enabled=$(settings get secure enabled_accessibility_services)\n" +
"pkg=%s\n" +
"if [[ $enabled == *$pkg* ]]\n" +
"then\n" +
"echo already_enabled\n" +
"else\n" +
"enabled=$pkg:$enabled\n" +
"settings put secure enabled_accessibility_services $enabled\n" +
"fi\n" +
"settings put secure accessibility_enabled 1";
public static boolean enableAccessibilityServiceByRoot(Class<? extends android.accessibilityservice.AccessibilityService> accessibilityService) {
String serviceName = GlobalAppContext.get().getPackageName() + "/" + accessibilityService.getName();
try {
return TextUtils.isEmpty(ProcessShell.execCommand(String.format(Locale.getDefault(), cmd, serviceName), true).error);
} catch (Exception e) {
return false;
}
}
public static boolean enableAccessibilityServiceByRootAndWaitFor(long timeOut) {
if (enableAccessibilityServiceByRoot(sAccessibilityServiceClass)) {
return AccessibilityService.waitForEnabled(timeOut);
}
return false;
}
public static void enableAccessibilityServiceByRootIfNeeded() {
if (AccessibilityService.getInstance() == null)
if (Pref.shouldEnableAccessibilityServiceByRoot()) {
AccessibilityServiceTool.enableAccessibilityServiceByRoot(sAccessibilityServiceClass);
}
}
public static boolean isAccessibilityServiceEnabled(Context context) {
return AccessibilityServiceUtils.isAccessibilityServiceEnabled(context, sAccessibilityServiceClass);
}
}
| mpl-2.0 |
cFerg/MineJava | src/main/java/minejava/reg/security/cert/X509CRL.java | 3425 | package minejava.reg.security.cert;
import minejava.reg.lang.Object;
import minejava.reg.lang.String;
import minejava.reg.math.BigInteger;
import minejava.reg.security.InvalidKeyException;
import minejava.reg.security.NoSuchAlgorithmException;
import minejava.reg.security.NoSuchProviderException;
import minejava.reg.security.Principal;
import minejava.reg.security.Provider;
import minejava.reg.security.PublicKey;
import minejava.reg.security.SignatureException;
import minejava.rex.security.auth.x500.X500Principal;
import minejava.sun.security.x509.X509CRLImpl;
import minejava.reg.util.Arrays;
import minejava.reg.util.Date;
import minejava.reg.util.Set;
public abstract class X509CRL extends CRL implements X509Extension{
private transient X500Principal issuerPrincipal;
protected X509CRL(){
super("X.509");
}
public boolean equals(Object other){
if (this == other){
return true;
}
if (!(other instanceof X509CRL)){
return false;
}
try{
byte[] thisCRL = X509CRLImpl.getEncodedInternal(this);
byte[] otherCRL = X509CRLImpl.getEncodedInternal((X509CRL) other);
return Arrays.equals(thisCRL, otherCRL);
}catch (CRLException e){
return false;
}
}
public int hashCode(){
int retval = 0;
try{
byte[] crlData = X509CRLImpl.getEncodedInternal(this);
for (int i = 1; i < crlData.length; i++){
retval += crlData[i] * i;
}
return retval;
}catch (CRLException e){
return retval;
}
}
public abstract byte[] getEncoded() throws CRLException;
public abstract void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException;
public abstract void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException;
public void verify(PublicKey key, Provider sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, SignatureException{
X509CRLImpl.verify(this, key, sigProvider);
}
public abstract int getVersion();
public abstract Principal getIssuerDN();
public X500Principal getIssuerX500Principal(){
if (issuerPrincipal == null){
issuerPrincipal = X509CRLImpl.getIssuerX500Principal(this);
}
return issuerPrincipal;
}
public abstract Date getThisUpdate();
public abstract Date getNextUpdate();
public abstract X509CRLEntry getRevokedCertificate(BigInteger serialNumber);
public X509CRLEntry getRevokedCertificate(X509Certificate certificate){
X500Principal certIssuer = certificate.getIssuerX500Principal();
X500Principal crlIssuer = getIssuerX500Principal();
if (certIssuer.equals(crlIssuer) == false){
return null;
}
return getRevokedCertificate(certificate.getSerialNumber());
}
public abstract Set<? extends X509CRLEntry> getRevokedCertificates();
public abstract byte[] getTBSCertList() throws CRLException;
public abstract byte[] getSignature();
public abstract String getSigAlgName();
public abstract String getSigAlgOID();
public abstract byte[] getSigAlgParams();
} | mpl-2.0 |
Flaplim/MilkPp | src/main/java/net/flaplim/milkpp/item/ItemBottleMilkBanana.java | 766 | package net.flaplim.milkpp.item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Hye-Seo on 2016-02-12.
*/
public class ItemBottleMilkBanana extends ItemBottleMilk {
@Override
public String getFlavour() {
return "banana";
}
@Override
public int getColorFromItemStack(ItemStack stack, int renderPass) {
return renderPass > 0 ? 0xffffff : 0xfff77d;
}
@Override
public List<PotionEffect> getEffects(ItemStack stack) {
List<PotionEffect> effects = new ArrayList<>();
effects.add(new PotionEffect(Potion.digSpeed.getId(), 300, 0));
return effects;
}
}
| mpl-2.0 |
zamojski/TowerCollector | app/src/main/java/info/zamojski/soft/towercollector/utils/DateUtils.java | 1755 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class DateUtils {
private static final long MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
public static long getCurrentDateWithoutTime() {
long dateTime = System.currentTimeMillis();
long dateOnly = (dateTime / MILLIS_IN_DAY) * MILLIS_IN_DAY;// like integer division
return dateOnly;
}
public static Date getCurrentDate() {
return new Date(System.currentTimeMillis());
}
public static long getTimeDiff(long start, long end) {
long diffInMillis = start - end;
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillis);
return diffInDays;
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
public static Date addHours(Date date, int hours) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
return cal.getTime();
}
public static Date getTimeFrom(int year, int month, int day, int hour, int minute, int second) {
Calendar calendar = new GregorianCalendar(year, month, day, hour, minute, second);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
return calendar.getTime();
}
}
| mpl-2.0 |
ajschult/etomica | etomica-core/src/main/java/etomica/lattice/IndexIteratorRectangular.java | 4395 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.lattice;
import etomica.util.Arrays;
/**
* Iterates arrays of int, such that 0 <= a[0] <= size[0], 0 <= a[1] <= size[1], etc.,
* thereby spanning a rectangular region. For example, if size = {3,2}, iteration would give
* these values and then expire:<br>
* {0,0}<br>
* {0,1}<br>
* {1,0}<br>
* {1,1}<br>
* {2,0}<br>
* {2,1}
*/
public class IndexIteratorRectangular implements IndexIterator, IndexIteratorSizable, java.io.Serializable {
/**
* Constructs iterator that returns int arrays of length D.
* Default size is 1 for each dimension, so that only the iterate {0,0,..,0}
* is returned; setSize can be used to modify the range.
* Call to reset is required before beginning iteration, in any case.
*/
public IndexIteratorRectangular(int D) {
if(D < 0) throw new IllegalArgumentException("Iterator must have non-negative dimension. Given value is "+D);
this.D = D;
size = new int[D];
for(int i=0; i<D; i++) size[i] = 1;
setSize(size);
index = new int[D];
indexCopy = new int[D];
}
/**
* Puts iterator in a condition to begin iteration. First iterate is {0,...,0}
*/
public void reset() {
if(D == 0) {
count = maxCount;
return;
}
for(int i=0; i<D; i++) {
index[i] = 0;
}
index[D-1] = -1;
count = 0;
}
/**
* Indicates whether all iterates have been returned since last call to reset().
*/
public boolean hasNext() {
return count < maxCount;
}
/**
* Returns the next iterate, or null if hasNext is false. The same array instance
* is returned with each call to this method; only its element values are modified in accordance
* with the design of the iteration. Elements of returned array may be modified and will not
* affect iteration.
*/
public int[] next() {
if(!hasNext()) return null;
increment(index, D-1);
count++;
System.arraycopy(index, 0, indexCopy, 0, index.length);
return indexCopy;
}
/**
* Sets range of all indexes to the given value
* Indices returned vary from 0 to size-1
*/
public void setSize(int size) {
maxCount = 1;
for(int i=0; i<D; i++) {
this.size[i] = size;
maxCount *= size;
}
}
/**
* Sets the individual ranges for the elements of the returned
* array. Each element index[k] iterates over values from 0 to size[k]-1.
*/
public void setSize(int[] size) {
if(size.length != D) throw new IllegalArgumentException("Length of array inconsistent with dimension of iterator");
maxCount = 1;
for(int i=0; i<D; i++) {
this.size[i] = size[i];
maxCount *= size[i];
}
}
/**
* Returns the length of the integer array that is returned as an iterate.
*/
public int getD() {
return D;
}
private void increment(int[] idx, int d) {
idx[d]++;
while(idx[d] == size[d] && d > 0) {
idx[d] = 0;
idx[--d]++;//decrement d, then increment idx
}
}
/**
* main method to test and demonstrate class.
*/
public static void main(String[] args) {
IndexIteratorRectangular iterator = new IndexIteratorRectangular(3);
iterator.reset();
System.out.println("Start 1");
while(iterator.hasNext()) {
System.out.println(Arrays.toString(iterator.next()));
}
iterator.setSize(new int[] {5,2,4});
iterator.reset();
System.out.println("Start 2");
while(iterator.hasNext()) {
System.out.println(Arrays.toString(iterator.next()));
}
}
private final int[] size;
private final int[] index;
private final int[] indexCopy;
private final int D;
//count is the number of iterates given since last reset
//when this equals maxCount, iteration is done
private int count;
private int maxCount;
private static final long serialVersionUID = 1L;
}
| mpl-2.0 |
Bhamni/openmrs-core | api/src/main/java/org/openmrs/api/handler/PatientSaveHandler.java | 1742 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.api.handler;
import java.util.Date;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.User;
import org.openmrs.annotation.Handler;
import org.openmrs.aop.RequiredDataAdvice;
/**
* This class deals with {@link Patient} objects when they are saved via a save* method in an
* Openmrs Service. This handler is automatically called by the {@link RequiredDataAdvice} AOP
* class. <br/>
*
* @see RequiredDataHandler
* @see SaveHandler
* @see Patient
* @since 1.5
*/
@Handler(supports = Patient.class)
public class PatientSaveHandler implements SaveHandler<Patient> {
/**
* @see org.openmrs.api.handler.SaveHandler#handle(org.openmrs.OpenmrsObject, org.openmrs.User,
* java.util.Date, java.lang.String)
*/
public void handle(Patient patient, User creator, Date dateCreated, String other) {
if (patient.getIdentifiers() != null) {
for (PatientIdentifier pIdentifier : patient.getIdentifiers()) {
// make sure the identifier is associated with the current patient
if (pIdentifier.getPatient() == null)
pIdentifier.setPatient(patient);
}
}
}
}
| mpl-2.0 |
sthaiya/muzima-android | app/src/main/java/com/muzima/adapters/observations/ObservationsPagerAdapter.java | 3592 | /*
* Copyright (c) The Trustees of Indiana University, Moi University
* and Vanderbilt University Medical Center. All Rights Reserved.
*
* This version of the code is licensed under the MPL 2.0 Open Source license
* with additional health care disclaimer.
* If the user is an entity intending to commercialize any application that uses
* this code in a for-profit venture, please contact the copyright holder.
*/
package com.muzima.adapters.observations;
import android.content.Context;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.widget.SearchView;
import com.muzima.MuzimaApplication;
import com.muzima.R;
import com.muzima.adapters.MuzimaPagerAdapter;
import com.muzima.api.model.Patient;
import com.muzima.controller.ConceptController;
import com.muzima.controller.EncounterController;
import com.muzima.controller.ObservationController;
import com.muzima.utils.LanguageUtil;
import com.muzima.view.observations.ObservationByEncountersFragment;
import com.muzima.view.observations.ObservationsByConceptFragment;
import com.muzima.view.observations.ObservationsListFragment;
public class ObservationsPagerAdapter extends MuzimaPagerAdapter implements SearchView.OnQueryTextListener {
private static final int TAB_BY_DATE = 0;
private static final int TAB_BY_ENCOUNTERS = 1;
private ObservationsListFragment observationByConceptListFragment;
ObservationsListFragment observationByEncountersFragment;
private Boolean isShrData;
private Patient patient;
public ObservationsPagerAdapter(Context applicationContext, FragmentManager supportFragmentManager, Boolean isShrData, Patient patient) {
super(applicationContext, supportFragmentManager);
this.isShrData = isShrData;
this.patient = patient;
}
@Override
public void initPagerViews() {
pagers = new PagerView[2];
ConceptController conceptController = ((MuzimaApplication) context.getApplicationContext()).getConceptController();
ObservationController observationController = ((MuzimaApplication) context.getApplicationContext()).getObservationController();
EncounterController encounterController = ((MuzimaApplication) context.getApplicationContext()).getEncounterController();
observationByConceptListFragment =
ObservationsByConceptFragment.newInstance(conceptController, observationController,isShrData,patient);
observationByEncountersFragment = ObservationByEncountersFragment.newInstance(encounterController, observationController,isShrData, patient);
LanguageUtil languageUtil = new LanguageUtil();
Context localizedContext = languageUtil.getLocalizedContext(context);
pagers[TAB_BY_DATE] = new PagerView(localizedContext.getResources().getString(R.string.title_observations_by_concepts), observationByConceptListFragment);
pagers[TAB_BY_ENCOUNTERS] = new PagerView(localizedContext.getResources().getString(R.string.title_observations_by_encounters), observationByEncountersFragment);
}
@Override
public boolean onQueryTextSubmit(String query) {
return onQueryTextChange(query);
}
@Override
public boolean onQueryTextChange(String newText) {
for (PagerView pager : pagers) {
((ObservationsListFragment) pager.fragment).onSearchTextChange(newText);
}
return false;
}
public void cancelBackgroundQueryTasks() {
observationByConceptListFragment.onQueryTaskCancelled();
observationByEncountersFragment.onQueryTaskCancelled();
}
}
| mpl-2.0 |
Bhamni/openmrs-core | api/src/test/java/org/openmrs/validator/ConceptDrugValidatorTest.java | 1235 | package org.openmrs.validator;
import org.junit.Assert;
import org.junit.Test;
import org.openmrs.Drug;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
/**
* Tests methods on the {@link ConceptDrugValidator} class.
*/
public class ConceptDrugValidatorTest {
/**
* @see ConceptDrugValidator#validate(Object,Errors)
* @verifies fail if a concept is not specified
*/
@Test
public void validate_shouldFailIfAConceptIsNotSpecified() throws Exception {
Drug drug = new Drug();
Errors errors = new BindException(drug, "drug");
new ConceptDrugValidator().validate(drug, errors);
Assert.assertTrue(errors.hasErrors());
}
/**
* @see ConceptDrugValidator#supports(Class)
* @verifies reject classes not extending Drug
*/
@Test
public void supports_shouldRejectClassesNotExtendingDrug() throws Exception {
Assert.assertFalse(new ConceptDrugValidator().supports(String.class));
}
/**
* @see ConceptDrugValidator#supports(Class)
* @verifies support Drug class
*/
@Test
public void supports_shouldSupportDrug() throws Exception {
Assert.assertTrue(new ConceptDrugValidator().supports(Drug.class));
}
}
| mpl-2.0 |
mdhsl/SMLEditor | src/com/sensia/tools/client/swetools/editors/sensorml/renderer/RNGRendererSML.java | 15687 | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are Copyright (C) 2011 Sensia Software LLC.
All Rights Reserved.
Contributor(s):
Alexandre Robin <alex.robin@sensiasoftware.com>
******************************* END LICENSE BLOCK ***************************/
package com.sensia.tools.client.swetools.editors.sensorml.renderer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sensia.relaxNG.RNGAttribute;
import com.sensia.relaxNG.RNGElement;
import com.sensia.relaxNG.RNGGrammar;
import com.sensia.relaxNG.RNGTag;
import com.sensia.relaxNG.RNGTagVisitor;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.ISensorWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.ISensorWidget.TAG_DEF;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.ISensorWidget.TAG_TYPE;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.base.SensorAttributeRefWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.base.SensorGenericHorizontalContainerWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.base.SensorGenericXLinkWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.gml.GMLSensorWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLComponentWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLContactWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLDocumentWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLKeywordsWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLLinkWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorAttributeWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorEventWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorModeChoiceWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorModeWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorSetValueWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SMLSensorSpatialFrame;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SensorSectionWidget;
import com.sensia.tools.client.swetools.editors.sensorml.panels.widgets.sml.SensorSectionsWidget;
/**
* <p>
* <b>Title:</b> RNGRenderer
* </p>
*
* <p>
* <b>Description:</b><br/>
* Renders content of an RNG grammar using GWT widgets
* </p>
*
* <p>
* Copyright (c) 2011
* </p>.
*
* @author Alexandre Robin
* @date Aug 27, 2011
*/
public class RNGRendererSML extends RNGRendererSWE implements RNGTagVisitor {
/** The render sections list. */
private Map<String,String> renderSectionsList = new HashMap<String,String>();
/** The render elements. */
private Map<String,RENDER_ELEMENT_TYPE> renderElements= new HashMap<String,RENDER_ELEMENT_TYPE>();
/** The root sections list. */
private Set<String> rootSectionsList = new HashSet<String>();
/** The skip list. */
private Set<String> skipList = new HashSet<String>();
/** The Constant SML_NS_1. */
protected final static String SML_NS_1 = "http://www.opengis.net/sensorML/1.0.1";
/** The Constant SML_NS_2. */
protected final static String SML_NS_2 = "http://www.opengis.net/sensorML/2.0";
/** The Constant GML_NS_1. */
protected final static String GML_NS_1 = "http://www.opengis.net/gml";
/** The Constant GML_NS_2. */
protected final static String GML_NS_2 = "http://www.opengis.net/gml/3.2";
/** The Constant GMD. */
protected final static String GMD = "http://www.isotc211.org/2005/gmd";
/** The Constant GCO. */
protected final static String GCO = "http://www.isotc211.org/2005/gco";
/**
* The Enum RENDER_ELEMENT_TYPE.
*/
enum RENDER_ELEMENT_TYPE {
/** The line. */
LINE,
/** The generic horizontal. */
GENERIC_HORIZONTAL,
/** The generic vertical. */
GENERIC_VERTICAL
}
/**
* Instantiates a new RNG renderer sml.
*/
public RNGRendererSML() {
//render section names
renderSectionsList.put("identification","Identification");
renderSectionsList.put("typeOf","Type of");
renderSectionsList.put("characteristics","Characteristics");
renderSectionsList.put("capabilities","Capabilities");
renderSectionsList.put("outputs", "Outputs");
renderSectionsList.put("classification","Classification");
//TODO: make only one constraint section
renderSectionsList.put("validTime","Constraints (valid time)");
renderSectionsList.put("securityConstraints","Constraints (security)");
renderSectionsList.put("legalConstraints","Constraints (legal)");
renderSectionsList.put("inputs", "Inputs");
renderSectionsList.put("localReferenceFrame", "Local Reference Frame");
renderSectionsList.put("parameters", "Parameters");
renderSectionsList.put("method", "Method");
renderSectionsList.put("contacts", "Contacts");
renderSectionsList.put("documentation", "Documentation");
renderSectionsList.put("connections", "Connections");
renderSectionsList.put("components", "Components");
renderSectionsList.put("component", "Component");
renderSectionsList.put("position", "Position");
renderSectionsList.put("boundedBy", "Bounded By");
renderSectionsList.put("history", "History");
renderSectionsList.put("position", "Position");
renderSectionsList.put("configuration", "Configuration");
renderSectionsList.put("modes", "Modes");
//render default defined list elements
renderElements.put("OutputList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("InputList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("IdentifierList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ClassifierList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ParameterList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ConnectionList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("CharacteristicList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("CapabilityList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ContactList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("DocumentList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ComponentList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ConnectionList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("ContactList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("EventList", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
renderElements.put("Settings", RENDER_ELEMENT_TYPE.GENERIC_VERTICAL);
//render default defined elements
renderElements.put("input",RENDER_ELEMENT_TYPE.LINE);
renderElements.put("output",RENDER_ELEMENT_TYPE.LINE);
renderElements.put("parameter", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("field", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("coordinate", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("characteristic", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("identifier", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("capability", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("elementCount", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("classifier", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("axis", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("origin", RENDER_ELEMENT_TYPE.LINE);
renderElements.put("ObservableProperty", RENDER_ELEMENT_TYPE.LINE);
//skip list
skipList.add("event");
skipList.add("contactInfo");
skipList.add("Security");
skipList.add("Term");
skipList.add("keywords");
skipList.add("data");
skipList.add("NormalizedCurve");
skipList.add("function");
skipList.add("mode");
skipList.add("TimeInstant");
skipList.add("time");
rootSectionsList.add("PhysicalSystem");
rootSectionsList.add("ProcessModel");
rootSectionsList.add("AggregateProcess");
rootSectionsList.add("SimpleProcess");
rootSectionsList.add("PhysicalComponent");
rootSectionsList.add("Component");
//skip contact elements tags
skipList.add("CI_ResponsibleParty");
skipList.add("contactInfo");
skipList.add("CI_Contact");
skipList.add("phone");
skipList.add("CI_Telephone");
skipList.add("address");
skipList.add("CI_Address");
//skip documents tags
skipList.add("CI_OnlineResource");
skipList.add("linkage");
}
/** The root min level. */
public int rootMinLevel = 1;
/* (non-Javadoc)
* @see com.sensia.tools.client.swetools.editors.sensorml.renderer.RNGRenderer#visit(com.sensia.relaxNG.RNGGrammar)
*/
@Override
public void visit(RNGGrammar grammar) {
//create top root element
push(new SensorSectionsWidget());
super.visit(grammar);
}
/* (non-Javadoc)
* @see com.sensia.tools.client.swetools.editors.sensorml.renderer.RNGRendererSWE#visit(com.sensia.relaxNG.RNGElement)
*/
@Override
public void visit(RNGElement elt) {
String eltName = elt.getName();
String nsUri = elt.getNamespace();
//get Name Space
TAG_DEF ns = TAG_DEF.RNG;
if (nsUri.equals(SML_NS_1) || nsUri.equals(SML_NS_2)) {
ns = TAG_DEF.SML;
} else if (nsUri.equals(SWE_NS_1) || nsUri.equals(SWE_NS_2)) {
ns = TAG_DEF.SWE;
} else if (nsUri.equals(GML_NS_1) || nsUri.equals(GML_NS_2)) {
ns = TAG_DEF.GML;
} else if(nsUri.equals(GMD)) {
ns = TAG_DEF.GMD;
} else if(nsUri.equals(GCO)) {
ns = TAG_DEF.GCO;
}
//skip the element and visit children
if(skipList.contains(eltName)) {
visitChildren(elt.getChildren());
return;
}
if(elt.getChildAttribute("href") != null && elt.getName().equals("component")) {
pushAndVisitChildren(new SMLComponentWidget(), elt.getChildren());
return;
}
//if element is a section
if(getStackSize() > 2 && rootSectionsList.contains(eltName)) {
int oldRootValue = rootMinLevel;
rootMinLevel = getStackSize()+1;
SensorSectionsWidget sensorSections = new SensorSectionsWidget();
sensorSections.setInnerSections(true);
pushAndVisitChildren(sensorSections,elt.getChildren());
rootMinLevel = oldRootValue;
return;
} else if(rootSectionsList.contains(eltName)) {
visitChildren(elt.getChildren());
return;
}
//special case of component
//TODO:
boolean isNewSectionForComponent = false;
if(eltName.equalsIgnoreCase("component")) {
isNewSectionForComponent = true;
}
if(getStackSize() == rootMinLevel || isNewSectionForComponent) {
processSection(elt, eltName);
} else {
if(renderElements.containsKey(eltName)) {
RENDER_ELEMENT_TYPE type = renderElements.get(eltName);
ISensorWidget widget = null;
switch(type) {
case GENERIC_VERTICAL : widget = renderVerticalWidget(eltName, ns, TAG_TYPE.ELEMENT);break;
case GENERIC_HORIZONTAL : widget = renderHorizontalWidget(eltName, ns, TAG_TYPE.ELEMENT);break;
case LINE : widget = renderLineWidget(eltName, ns, TAG_TYPE.ELEMENT);break;
default:break;
}
pushAndVisitChildren(widget, elt.getChildren());
} else {
if(eltName.equals("contact")) {
pushAndVisitChildren(new SMLContactWidget(), elt.getChildren());
} else if(eltName.equals("document") || eltName.equals("Document")) {
pushAndVisitChildren(new SMLDocumentWidget(), elt.getChildren());
} else if(eltName.equals("Link")) {
pushAndVisitChildren(new SMLLinkWidget(), elt.getChildren());
} else if(eltName.equals("SpatialFrame")) {
pushAndVisitChildren(new SMLSensorSpatialFrame(), elt.getChildren());
} else if(elt.getChildAttribute("href") != null) {
pushAndVisitChildren(new SensorGenericXLinkWidget(eltName,ns), elt.getChildren());
} else if(eltName.equals("ModeChoice")) {
pushAndVisitChildren(new SMLSensorModeChoiceWidget(), elt.getChildren());
} else if(eltName.equals("Mode")) {
pushAndVisitChildren(new SMLSensorModeWidget(), elt.getChildren());
} else if(eltName.equals("setValue") || eltName.equals("setMode")) {
pushAndVisitChildren(new SMLSensorSetValueWidget(getRoot(),getGrammar()), elt.getChildren());
} else if(eltName.equals("Event")) {
pushAndVisitChildren(new SMLSensorEventWidget(), elt.getChildren());
} else if(nsUri.equals(GML_NS_1) || nsUri.equals(GML_NS_2)) {
pushAndVisitChildren(new SensorGenericHorizontalContainerWidget(elt.getName(), TAG_DEF.GML, TAG_TYPE.ELEMENT), elt.getChildren());
} else if (nsUri.equals(SML_NS_1) || nsUri.equals(SML_NS_2)) {
pushAndVisitChildren(new SensorGenericHorizontalContainerWidget(elt.getName(), TAG_DEF.SML, TAG_TYPE.ELEMENT), elt.getChildren());
} else if (nsUri.equals(GMD)) {
pushAndVisitChildren(new SensorGenericHorizontalContainerWidget(elt.getName(), TAG_DEF.GMD, TAG_TYPE.ELEMENT), elt.getChildren());
} else if (nsUri.equals(GCO)) {
pushAndVisitChildren(new SensorGenericHorizontalContainerWidget(elt.getName(), TAG_DEF.GCO, TAG_TYPE.ELEMENT), elt.getChildren());
}else {
super.visit(elt);
}
}
}
}
/* (non-Javadoc)
* @see com.sensia.tools.client.swetools.editors.sensorml.renderer.RNGRenderer#visit(com.sensia.relaxNG.RNGAttribute)
*/
@Override
public void visit(RNGAttribute att) {
//get ns
TAG_DEF ns = TAG_DEF.RNG;
String nsUri = att.getNamespace();
if (nsUri.equals(SML_NS_1) || nsUri.equals(SML_NS_2)) {
ns = TAG_DEF.SML;
} else if (nsUri.equals(SWE_NS_1) || nsUri.equals(SWE_NS_2)) {
ns = TAG_DEF.SWE;
} else if (nsUri.equals(GML_NS_1) || nsUri.equals(GML_NS_2)) {
ns = TAG_DEF.GML;
} else if(nsUri.equals(GMD)) {
ns = TAG_DEF.GMD;
} else if(nsUri.equals(GCO)) {
ns = TAG_DEF.GCO;
}
if(att.getName().equals("referenceFrame") || att.getName().equals("definition") || att.getName().equals("name")
|| att.getName().equals("role") || att.getName().equals("arcrole")) {
pushAndVisitChildren(new SMLSensorAttributeWidget(att), att.getChildren());
} else if(att.getName().equals("href")) {
pushAndVisitChildren(new SensorGenericXLinkWidget(att.getName(),ns), att.getChildren());
} /*else if(att.getName().equals("ref")) {
pushAndVisitChildren(new SensorAttributeRefWidget(getRoot()), att.getChildren());
}*/ else {
super.visit(att);
}
}
/**
* Process section.
*
* @param elt the elt
* @param eltName the elt name
*/
protected void processSection(RNGElement elt, String eltName) {
List<RNGTag> children = elt.getChildren();
ISensorWidget widget = null;
if(eltName.equals("name") || eltName.equals("identifier") || eltName.equals("description")) {
widget = new GMLSensorWidget(elt);
} else if(eltName.equals("KeywordList")) {
widget = new SMLKeywordsWidget();
} else {
//it is a non pre-defined section
//add default name
String sectionName = "No Supported Name";
if(renderSectionsList.containsKey(eltName)) {
//for custom is to get section name from attribute->value children
//lets the renderer find them and add to the section
sectionName = renderSectionsList.get(eltName);
}
widget = new SensorSectionWidget(eltName,sectionName);
ISensorWidget existingTagSection = getWidget(eltName);
if(existingTagSection != null) {
List<RNGTag> revisitedNodes = new ArrayList<RNGTag>();
revisitedNodes.add(elt);
children = revisitedNodes;
}
}
pushAndVisitChildren(widget,children);
}
}
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | mobile/android/base/java/org/mozilla/gecko/trackingprotection/TrackingProtectionPrompt.java | 4362 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.trackingprotection;
import org.mozilla.gecko.Locales;
import org.mozilla.gecko.R;
import org.mozilla.gecko.preferences.GeckoPreferences;
import org.mozilla.gecko.util.HardwareUtils;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
public class TrackingProtectionPrompt extends Locales.LocaleAwareActivity {
public static final String LOGTAG = "Gecko" + TrackingProtectionPrompt.class.getSimpleName();
// Flag set during animation to prevent animation multiple-start.
private boolean isAnimating;
private View containerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showPrompt();
}
private void showPrompt() {
setContentView(R.layout.tracking_protection_prompt);
findViewById(R.id.ok_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onConfirmButtonPressed();
}
});
findViewById(R.id.link_text).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
slideOut();
final Intent settingsIntent = new Intent(TrackingProtectionPrompt.this, GeckoPreferences.class);
GeckoPreferences.setResourceToOpen(settingsIntent, "preferences_privacy");
startActivity(settingsIntent);
// Don't use a transition to settings if we're on a device where that
// would look bad.
if (HardwareUtils.IS_KINDLE_DEVICE) {
overridePendingTransition(0, 0);
}
}
});
containerView = findViewById(R.id.tracking_protection_inner_container);
containerView.setTranslationY(500);
containerView.setAlpha(0);
final Animator translateAnimator = ObjectAnimator.ofFloat(containerView, "translationY", 0);
translateAnimator.setDuration(400);
final Animator alphaAnimator = ObjectAnimator.ofFloat(containerView, "alpha", 1);
alphaAnimator.setStartDelay(200);
alphaAnimator.setDuration(600);
final AnimatorSet set = new AnimatorSet();
set.playTogether(alphaAnimator, translateAnimator);
set.setStartDelay(400);
set.start();
}
@Override
public void finish() {
super.finish();
// Don't perform an activity-dismiss animation.
overridePendingTransition(0, 0);
}
private void onConfirmButtonPressed() {
slideOut();
}
/**
* Slide the overlay down off the screen and destroy it.
*/
private void slideOut() {
if (isAnimating) {
return;
}
isAnimating = true;
ObjectAnimator animator = ObjectAnimator.ofFloat(containerView, "translationY", containerView.getHeight());
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
finish();
}
});
animator.start();
}
/**
* Close the dialog if back is pressed.
*/
@Override
public void onBackPressed() {
slideOut();
}
/**
* Close the dialog if the anything that isn't a button is tapped.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
slideOut();
return true;
}
}
| mpl-2.0 |
miloszpiglas/h2mod | src/main/org/h2/bnf/context/DbTableOrView.java | 2430 | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.util.New;
/**
* Contains meta data information about a table or a view.
* This class is used by the H2 Console.
*/
public class DbTableOrView {
/**
* The schema this table belongs to.
*/
private final DbSchema schema;
/**
* The table name.
*/
private final String name;
/**
* The quoted table name.
*/
private final String quotedName;
/**
* True if this represents a view.
*/
private final boolean isView;
/**
* The column list.
*/
private DbColumn[] columns;
public DbTableOrView(DbSchema schema, ResultSet rs) throws SQLException {
this.schema = schema;
name = rs.getString("TABLE_NAME");
String type = rs.getString("TABLE_TYPE");
isView = "VIEW".equals(type);
quotedName = schema.getContents().quoteIdentifier(name);
}
/**
* @return The schema this table belongs to.
*/
public DbSchema getSchema() {
return schema;
}
/**
* @return The column list.
*/
public DbColumn[] getColumns() {
return columns;
}
/**
* @return The table name.
*/
public String getName() {
return name;
}
/**
* @return True if this represents a view.
*/
public boolean isView() {
return isView;
}
/**
* @return The quoted table name.
*/
public String getQuotedName() {
return quotedName;
}
/**
* Read the column for this table from the database meta data.
*
* @param meta the database meta data
*/
public void readColumns(DatabaseMetaData meta) throws SQLException {
ResultSet rs = meta.getColumns(null, schema.name, name, null);
ArrayList<DbColumn> list = New.arrayList();
while (rs.next()) {
DbColumn column = DbColumn.getColumn(schema.getContents(), rs);
list.add(column);
}
rs.close();
columns = new DbColumn[list.size()];
list.toArray(columns);
}
}
| mpl-2.0 |
powsybl/powsybl-core | iidm/iidm-impl/src/main/java/com/powsybl/iidm/network/impl/SubstationAdderImpl.java | 2024 | /**
* Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.powsybl.iidm.network.impl;
import com.powsybl.iidm.network.impl.util.Ref;
import com.powsybl.iidm.network.Country;
import com.powsybl.iidm.network.Substation;
import com.powsybl.iidm.network.SubstationAdder;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
class SubstationAdderImpl extends AbstractIdentifiableAdder<SubstationAdderImpl> implements SubstationAdder {
private final Ref<NetworkImpl> networkRef;
private Country country;
private String tso;
private String[] tags;
SubstationAdderImpl(Ref<NetworkImpl> networkRef) {
this.networkRef = networkRef;
}
@Override
protected NetworkImpl getNetwork() {
return networkRef.get();
}
@Override
protected String getTypeDescription() {
return "Substation";
}
@Override
public SubstationAdder setCountry(Country country) {
this.country = country;
return this;
}
@Override
public SubstationAdder setTso(String tso) {
this.tso = tso;
return this;
}
@Override
public SubstationAdder setGeographicalTags(String... tags) {
this.tags = tags;
return this;
}
@Override
public Substation add() {
String id = checkAndGetUniqueId();
SubstationImpl substation = new SubstationImpl(id, getName(), isFictitious(), country, tso, networkRef);
if (tags != null) {
for (String tag : tags) {
substation.addGeographicalTag(tag);
}
}
getNetwork().getIndex().checkAndAdd(substation);
getNetwork().getListeners().notifyCreation(substation);
return substation;
}
}
| mpl-2.0 |
llggkk1117/GoBTJ | workspace/GoBTJ/src/org/gene/test/JsonTest.java | 1779 | package org.gene.test;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.gene.dao.UserDAO;
import org.gene.model.User;
import org.gene.modules.utils.JsonUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JsonTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException
{
DataObject obj = new DataObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
System.out.println(json);
DataObject oo = (DataObject) gson.fromJson(json, DataObject.class);
System.out.println(oo.toString());
HashMap<String, Object> hs = new HashMap<String, Object>();
HashMap<String, Object> sub_hs = new HashMap<String, Object>();
hs.put("1", "aa");
hs.put("2", "bb");
hs.put("3", "cc");
sub_hs.put("4", "dd");
sub_hs.put("5", "ee");
sub_hs.put("6", null);
hs.put("4", sub_hs);
json = gson.toJson(hs);
System.out.println(json);
Type collectionType = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> hm2 = gson.fromJson(json, collectionType);
System.out.println(hm2);
User user = UserDAO.retrieveUser(1L);
json = JsonUtils.objectToJson(user);
System.out.println(json);
}
}
class DataObject
{
private int data1 = 100;
private String data2 = null;
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
@Override
public String toString() {
return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
| mpl-2.0 |
servinglynk/hmis-lynk-open-source | hmis-service-v2016/src/main/java/com/servinglynk/hmis/warehouse/service/converter/DateofengagementConverter.java | 943 | package com.servinglynk.hmis.warehouse.service.converter;
import com.servinglynk.hmis.warehouse.core.model.Dateofengagement;
public class DateofengagementConverter extends BaseConverter {
public static com.servinglynk.hmis.warehouse.model.v2016.Dateofengagement modelToEntity (Dateofengagement model ,com.servinglynk.hmis.warehouse.model.v2016.Dateofengagement entity) {
if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2016.Dateofengagement();
entity.setId(model.getDateofengagementId());
entity.setDateofengagement(model.getDateofengagement());
return entity;
}
public static Dateofengagement entityToModel (com.servinglynk.hmis.warehouse.model.v2016.Dateofengagement entity) {
Dateofengagement model = new Dateofengagement();
model.setDateofengagementId(entity.getId());
model.setDateofengagement(entity.getDateofengagement());
return model;
}
}
| mpl-2.0 |
PCNI/outreach-app | src/outreach-mobile-web/src/test/java/ResourceBundleEntryTest.java | 4278 | import com.innoppl.outreach.AppContext;
import com.innoppl.outreach.service.Errors;
import com.innoppl.outreach.service.Messages;
import java.util.Locale;
import org.apache.commons.lang.LocaleUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @author Jerald Mejarla
*/
@ContextConfiguration("/root-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class ResourceBundleEntryTest {
final Locale[] locale = new Locale[]{LocaleUtils.toLocale("en")};
public ResourceBundleEntryTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void encode() {
String password = "sal#1234";
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
//System.out.println(hashedPassword);
}
@Test
public void verifyResourceBundles() {
StringBuilder errorBuilder = new StringBuilder();
final Errors[] errorValues = Errors.values();
for (Locale y : locale) {
for (Errors x : errorValues) {
try {
String message = AppContext.getApplicationContext().getMessage(x.name(),
new Object[]{}, y);
if (message == null) {
errorBuilder.append("Error Resouce Bundle with name [")
.append(x.name())
.append("] not available for Locale [")
.append(y.toString())
.append("]")
.append("\n");
}
} catch (Exception ex) {
errorBuilder.append("Error Resouce Bundle with name [")
.append(x.name())
.append("] not available for Locale [")
.append(y.toString())
.append("]")
.append("\n");
}
}
}
final Messages[] messageValues = Messages.values();
for (Locale y : locale) {
for (Messages x : messageValues) {
try {
String message = AppContext.getApplicationContext().getMessage(x.name(),
new Object[]{}, y);
if (message == null) {
errorBuilder.append("Message Resouce Bundle with name [")
.append(x.name())
.append("] not available for Locale [")
.append(y.toString())
.append("]")
.append("\n");
}
} catch (Exception ex) {
errorBuilder.append("Message Resouce Bundle with name [")
.append(x.name())
.append("] not available for Locale [")
.append(y.toString())
.append("]")
.append("\n");
}
}
}
if (errorBuilder.length() > 0) {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Resource Bundle Missing");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(errorBuilder.toString());
fail("\n" + errorBuilder.toString());
}
}
} | mpl-2.0 |
deerwalk/voltdb | tests/frontend/org/voltdb/regressionsuites/TestSqlDeleteSuite.java | 24816 | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.regressionsuites;
import java.util.Arrays;
import org.voltdb.BackendTarget;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb_testprocs.regressionsuites.delete.DeleteOrderByLimit;
import org.voltdb_testprocs.regressionsuites.delete.DeleteOrderByLimitOffset;
import org.voltdb_testprocs.regressionsuites.fixedsql.Insert;
/**
* System tests for DELETE
* This is mostly cloned and modified from TestSqlUpdateSuite
*/
public class TestSqlDeleteSuite extends RegressionSuite {
/** Procedures used by this suite */
static final Class<?>[] PROCEDURES = {
DeleteOrderByLimit.class,
DeleteOrderByLimitOffset.class
};
static final int ROWS = 10;
private static void insertOneRow(Client client, String tableName,
long id, String desc, long num, double ratio) throws Exception {
VoltTable vt = client.callProcedure("@AdHoc",
"insert into " + tableName + " values ("
+ id + ", '" + desc + "', " + num + ", " + ratio + ")")
.getResults()[0];
vt.advanceRow();
assertEquals(vt.getLong(0), 1);
}
private static void insertRows(Client client, String tableName, int numRows)
throws Exception {
for (int i = 0; i < numRows; ++i) {
insertOneRow(client, tableName, i, "desc", i, 14.5);
}
}
private void executeAndTestDelete(String tableName, String deleteStmt, int numExpectedRowsChanged)
throws Exception {
Client client = getClient();
insertRows(client, tableName, ROWS);
VoltTable[] results = client.callProcedure("@AdHoc", deleteStmt).getResults();
assertEquals(numExpectedRowsChanged, results[0].asScalarLong());
int indexOfWhereClause = deleteStmt.toLowerCase().indexOf("where");
String deleteWhereClause = "";
if (indexOfWhereClause != -1) {
deleteWhereClause = deleteStmt.substring(indexOfWhereClause);
}
else {
deleteWhereClause = "";
}
String query = String.format("select count(*) from %s %s",
tableName, deleteWhereClause);
results = client.callProcedure("@AdHoc", query).getResults();
assertEquals(0, results[0].asScalarLong());
}
private static void insertMoreRows(Client client, String tableName,
int tens, int ones) throws Exception {
for (int i = 0; i < tens; ++i) {
for (int j = 0; j < ones; ++j) {
insertOneRow(client, tableName,
i * 10, "desc", i * 10 + j, 14.5);
}
}
}
public void testDelete()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s",
table, table);
// Expect all rows to be deleted
executeAndTestDelete(table, delete, ROWS);
}
verifyStmtFails(getClient(), "DELETE FROM P1 WHERE COUNT(*) = 1", "invalid WHERE expression");
}
public void testDeleteWithEqualToIndexPredicate()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s where %s.ID = 5",
table, table);
// Only row with ID = 5 should be deleted
executeAndTestDelete(table, delete, 1);
}
}
public void testDeleteWithEqualToNonIndexPredicate()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s where %s.NUM = 5",
table, table);
// Only row with NUM = 5 should be deleted
executeAndTestDelete(table, delete, 1);
}
}
// This tests a bug found by the SQL coverage tool. The code in HSQL
// which generates the XML eaten by the planner didn't generate
// anything in the <condition> element output for > or >= on an index
public void testDeleteWithGreaterThanIndexPredicate()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s where %s.ID > 5",
table, table);
// Rows 6-9 should be deleted
executeAndTestDelete(table, delete, 4);
}
}
public void testDeleteWithGreaterThanNonIndexPredicate()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s where %s.NUM > 5",
table, table);
// rows 6-9 should be deleted
executeAndTestDelete(table, delete, 4);
}
}
public void testDeleteWithLessThanIndexPredicate()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = String.format("delete from %s where %s.ID < 5",
table, table);
// Rows 0-4 should be deleted
executeAndTestDelete(table, delete, 5);
}
}
// This tests a bug found by the SQL coverage tool. The code in HSQL
// which generates the XML eaten by the planner wouldn't combine
// the various index and non-index join and where conditions, so the planner
// would end up only seeing the first subnode written to the <condition>
// element
public void testDeleteWithOnePredicateAgainstIndexAndOneFalse()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete = "delete from " + table +
" where " + table + ".NUM = 1000 and " + table + ".ID = 4";
executeAndTestDelete(table, delete, 0);
}
}
// This tests a bug found by the SQL coverage tool. The code in HSQL
// which generates the XML eaten by the planner wouldn't combine (AND)
// the index begin and end conditions, so the planner would only see the
// begin condition in the <condition> element.
public void testDeleteWithRangeAgainstIndex()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete =
String.format("delete from %s where %s.ID < 8 and %s.ID > 5",
table, table, table);
executeAndTestDelete(table, delete, 2);
}
}
public void testDeleteWithRangeAgainstNonIndex()
throws Exception
{
String[] tables = {"P1", "R1"};
for (String table : tables)
{
String delete =
String.format("delete from %s where %s.NUM < 8 and %s.NUM > 5",
table, table, table);
executeAndTestDelete(table, delete, 2);
}
}
// Test replicated case with no where clause
public void testDeleteWithOrderBy() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
String[] stmtTemplates = { "DELETE FROM %s ORDER BY NUM ASC LIMIT 1",
"DELETE FROM %s ORDER BY NUM DESC LIMIT 2",
"DELETE FROM %s ORDER BY NUM LIMIT 3",
"DELETE FROM %s ORDER BY NUM OFFSET 2",
"DELETE FROM %s ORDER BY NUM OFFSET 0",
};
// Table starts with 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
long[][] expectedResults = {
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 4, 5, 6, 7 },
{ 4, 5 },
{}
};
insertRows(client, "P3", 10);
insertRows(client, "R3", 10);
for (int i = 0; i < stmtTemplates.length; ++i) {
long numRowsBefore = client.callProcedure("@AdHoc", "select count(*) from R3")
.getResults()[0].asScalarLong();
// Should succeed on replicated table
String replStmt = String.format(stmtTemplates[i], "R3");
long expectedRows = numRowsBefore - expectedResults[i].length;
validateTableOfScalarLongs(client , replStmt, new long[] { expectedRows });
validateTableOfScalarLongs(client, "SELECT NUM FROM R3 ORDER BY NUM ASC",
expectedResults[i]);
// In the partitioned case, we expect to get an error
String partStmt = String.format(stmtTemplates[i], "P3");
verifyStmtFails(
client,
partStmt,
"DELETE statements affecting partitioned tables must "
+ "be able to execute on one partition "
+ "when ORDER BY and LIMIT or OFFSET clauses "
+ "are present.");
}
}
public void testDeleteWithWhereAndOrderBy() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
for (String table : Arrays.asList("P3", "R3")) {
insertMoreRows(client, table, 10, 3);
// table now contains rows like this
// ID NUM [other columns omitted]
// 0 0
// 0 1
// 0 2
// 10 10
// 10 11
// 10 12
// ...
// 90 90
// 90 91
// 90 92
String countStmt = "select count(*) from " + table;
// This statement avoids sorting by using index on NUM
String stmt = "DELETE FROM " + table + " WHERE ID = 0 ORDER BY NUM ASC LIMIT 1";
validateTableOfScalarLongs(client, stmt, new long[] {1});
// verify the rows that are left are what we expect
validateTableOfScalarLongs(client,
"select num from " + table + " where id = 0 order by num asc",
new long[] {1, 2});
// Total row count-- make sure we didn't delete any other rows
validateTableOfScalarLongs(client, countStmt, new long[] {29});
/// ---------------------------------------------------------------------------------
// Delete rows where num is 12, 11
stmt = "DELETE FROM " + table
+ " WHERE DESC LIKE 'de%' AND ID = 10 ORDER BY NUM DESC LIMIT 2";
validateTableOfScalarLongs(client, stmt, new long[] { 2 });
// verify the rows that are left are what we expect
stmt = "select num from " + table + " where id = 10 order by num asc";
validateTableOfScalarLongs(client, stmt, new long[] { 10 });
// Total row count-- make sure we didn't delete any other rows
stmt = "select count(*) from " + table;
validateTableOfScalarLongs(client, stmt, new long[] { 27 });
/// ---------------------------------------------------------------------------------
// Delete rows where num is 22
stmt = "DELETE FROM " + table
+ " WHERE ID = 20 ORDER BY NUM LIMIT 10 OFFSET 2";
validateTableOfScalarLongs(client, stmt, new long[] { 1 });
// verify the rows that are left are what we expect
stmt ="select num from " + table + " where id = 20 order by num asc";
validateTableOfScalarLongs(client, stmt, new long[] { 20, 21 });
// Total row count-- make sure we didn't delete any other rows
validateTableOfScalarLongs(client, countStmt, new long[] { 26 });
/// ---------------------------------------------------------------------------------
// Delete rows where num is 31
stmt = "DELETE FROM " + table
+ " WHERE ID = 30 ORDER BY NUM LIMIT 1 OFFSET 1";
validateTableOfScalarLongs(client, stmt, new long[] { 1 });
// verify the rows that are left are what we expect
stmt = "select num from " + table + " where id = 30 order by num asc";
validateTableOfScalarLongs(client, stmt, new long[] { 30, 32 });
// Total row count-- make sure we didn't delete any other rows
validateTableOfScalarLongs(client, countStmt, new long[] { 25 });
/// ---------------------------------------------------------------------------------
// index used to evaluate predicate can also be used for order by
stmt = "DELETE FROM " + table
+ " WHERE ID = 40 AND NUM = 41 ORDER BY NUM LIMIT 1";
validateTableOfScalarLongs(client, stmt, new long[] { 1 });
// verify the rows that are left are what we expect
stmt = "select num from " + table + " where id = 40 order by num asc";
validateTableOfScalarLongs(client, stmt, new long[] { 40, 42 });
// Total row count-- make sure we didn't delete any other rows
validateTableOfScalarLongs(client, countStmt, new long[] { 24 });
/// ---------------------------------------------------------------------------------
// Indexes can't be used for either ORDER BY or WHERE
stmt = "DELETE FROM " + table
+ " WHERE ID = 50 AND RATIO > 0 ORDER BY DESC, NUM LIMIT 1";
validateTableOfScalarLongs(client, stmt, new long[] { 1 });
// verify the rows that are left are what we expect
stmt = "select num from " + table + " where id = 50 order by num asc";
validateTableOfScalarLongs(client, stmt, new long[] { 51, 52 });
// Total row count-- make sure we didn't delete any other rows
validateTableOfScalarLongs(client, countStmt, new long[] { 23 });
}
}
public void testDeleteWithOrderByDeterminism() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
// ORDER BY must have a LIMIT or OFFSET.
// LIMIT or OFFSET may not appear by themselves.
verifyStmtFails(client, "DELETE FROM R1 ORDER BY NUM ASC",
"DELETE statement with ORDER BY but no LIMIT or OFFSET is not allowed.");
verifyStmtFails(
client,
"DELETE FROM R1 LIMIT 1",
"DELETE statement with LIMIT or OFFSET but no ORDER BY would produce non-deterministic results.");
// This fails in a different way due to a bug in HSQL. OFFSET with no
// LIMIT confuses HSQL.
verifyStmtFails(client, "DELETE FROM R1 OFFSET 1",
"PlanningErrorException");
verifyStmtFails(
client,
"DELETE FROM R1 LIMIT 1 OFFSET 1",
"DELETE statement with LIMIT or OFFSET but no ORDER BY would produce non-deterministic results.");
verifyStmtFails(
client,
"DELETE FROM R1 OFFSET 1 LIMIT 1",
"DELETE statement with LIMIT or OFFSET but no ORDER BY would produce non-deterministic results.");
verifyStmtFails(client, "DELETE FROM P1_VIEW ORDER BY ID ASC LIMIT 1",
"DELETE with ORDER BY, LIMIT or OFFSET is currently unsupported on views");
// Check failure for partitioned table where where clause cannot infer
// partitioning
verifyStmtFails(
client,
"DELETE FROM P1 WHERE ID < 50 ORDER BY NUM DESC LIMIT 1",
"DELETE statements affecting partitioned tables must "
+ "be able to execute on one partition "
+ "when ORDER BY and LIMIT or OFFSET clauses "
+ "are present.");
// Non-deterministic ordering should fail!
// RATIO is not unique.
verifyStmtFails(client,
"DELETE FROM P1 WHERE ID = 1 ORDER BY RATIO LIMIT 1",
"statement manipulates data in a non-deterministic way");
// Table P4 has a two-column unique constraint on RATIO and NUM
// Ordering by only one column in a two column unique constraint should
// fail, but both should work.
verifyStmtFails(client,
"DELETE FROM P4 WHERE ID = 1 ORDER BY RATIO LIMIT 1",
"statement manipulates data in a non-deterministic way");
verifyStmtFails(client,
"DELETE FROM P4 WHERE ID = 1 ORDER BY NUM LIMIT 1",
"statement manipulates data in a non-deterministic way");
insertMoreRows(client, "P4", 1, 12);
String stmt = "DELETE FROM P4 WHERE ID = 0 ORDER BY RATIO, NUM LIMIT 9";
validateTableOfScalarLongs(client, stmt, new long[] { 9 });
validateTableOfScalarLongs(client, "select num from P4 order by num",
new long[] {9, 10, 11});
// Ordering by all columns should be ok.
// P5 has no unique or primary key constraints
insertMoreRows(client, "P5", 1, 15);
stmt = "DELETE FROM P5 WHERE ID = 0 ORDER BY NUM, DESC, ID, RATIO LIMIT 13";
validateTableOfScalarLongs(client, stmt, new long[] { 13 });
validateTableOfScalarLongs(client, "select num from P5 order by num",
new long[] {13, 14});
}
public void testDeleteLimitParam() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
// insert rows where ID is 0..19
insertRows(client, "R1", 20);
VoltTable vt;
// delete the first 10 rows, ordered by ID
vt = client.callProcedure("DeleteOrderByLimit", 10)
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 10 });
String stmt = "select id from R1 order by id asc";
validateTableOfScalarLongs(client, stmt, new long[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 });
}
public void testDeleteLimitOffsetParam() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
// insert rows where ID is 0..9
insertRows(client, "R1", 10);
VoltTable vt;
// delete 5 rows, skipping the first three
vt = client.callProcedure("DeleteOrderByLimitOffset", 5, 3)
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 5 });
String stmt = "select id from R1 order by id asc";
validateTableOfScalarLongs(client, stmt, new long[] { 0, 1, 2, 8, 9 });
}
public void testDeleteOffsetParam() throws Exception {
if (isHSQL()) {
return;
}
Client client = getClient();
String tables[] = {"P3", "R3"};
for (String table : tables) {
// insert rows where ID is 0 and num is 0..9
insertMoreRows(client, table, 1, 10);
// delete the last 2 rows where ID = 0, ordered by NUM
VoltTable vt = client.callProcedure("@AdHoc",
"DELETE FROM " + table + " WHERE ID = 0 ORDER BY NUM OFFSET 8")
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 2 });
validateTableOfScalarLongs(client,
"select num from " + table + " order by num asc",
new long[] {0, 1, 2, 3, 4, 5, 6, 7});
// Offset by 8 rows, but there are only 8 rows, so should delete nothing
vt = client.callProcedure("@AdHoc",
"DELETE FROM " + table + " WHERE ID = 0 ORDER BY NUM OFFSET 8")
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 0 });
validateTableOfScalarLongs(client,
"select num from " + table + " order by num asc",
new long[] {0, 1, 2, 3, 4, 5, 6, 7});
// offset with a where clause, and also some parameters.
// This should delete rows where num is 4 and 5.
String stmt = "delete from " + table + " where id = 0 and num between ? and ? order by num offset ?";
vt = client.callProcedure("@AdHoc", stmt, 2, 5, 2)
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] {2});
validateTableOfScalarLongs(client,
"select num from " + table + " order by num asc",
new long[] {0, 1, 2, 3, 6, 7});
// Offset by 0 rows: should delete all rows.
vt = client.callProcedure("@AdHoc",
"DELETE FROM " + table + " WHERE ID = 0 ORDER BY NUM OFFSET 0")
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 6 });
validateTableOfScalarLongs(client,
"select num from " + table + " order by num asc",
new long[] {});
}
}
public void testDeleteWithExpresionSubquery() throws Exception {
Client client = getClient();
String tables[] = {"P3", "R3"};
// insert rows where ID is 0..3
insertRows(client, "R1", 4);
for (String table : tables) {
// insert rows where ID is 0 and num is 0..9
insertRows(client, table, 10);
// delete rows where ID is IN 0..3
VoltTable vt = client.callProcedure("@AdHoc",
"DELETE FROM " + table + " WHERE ID IN (SELECT NUM FROM R1)")
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 4 });
String stmt = "SELECT ID FROM " + table + " ORDER BY ID";
validateTableOfScalarLongs(client, stmt, new long[] { 4, 5, 6, 7, 8, 9 });
// delete rows where NUM is 4 and 5
vt = client.callProcedure("@AdHoc",
"DELETE FROM " + table + " WHERE NUM IN (SELECT NUM + 2 FROM R1 WHERE R1.ID + 2 = " +
table + ".ID)")
.getResults()[0];
validateTableOfScalarLongs(vt, new long[] { 2 });
stmt = "SELECT NUM FROM " + table + " ORDER BY NUM";
validateTableOfScalarLongs(client, stmt, new long[] { 6, 7, 8, 9 });
}
}
//
// JUnit / RegressionSuite boilerplate
//
public TestSqlDeleteSuite(String name) {
super(name);
}
static public junit.framework.Test suite() {
VoltServerConfig config = null;
MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestSqlDeleteSuite.class);
VoltProjectBuilder project = new VoltProjectBuilder();
project.addSchema(Insert.class.getResource("sql-update-ddl.sql"));
project.addProcedures(PROCEDURES);
config = new LocalCluster("sqldelete-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
config = new LocalCluster("sqldelete-hsql.jar", 1, 1, 0, BackendTarget.HSQLDB_BACKEND);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
// Cluster
config = new LocalCluster("sqldelete-cluster.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI);
if (!config.compile(project)) fail();
builder.addServerConfig(config);
return builder;
}
}
| agpl-3.0 |
devmix/openjst | client/android/commons/src/main/java/org/openjst/client/android/commons/events/types/JobEvent.java | 1002 | /*
* Copyright (C) 2013 OpenJST Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openjst.client.android.commons.events.types;
import org.openjst.client.android.commons.events.Event;
/**
* new, update, remove
*
* @author Sergey Grachev
*/
public class JobEvent implements Event {
public static enum Type {
CREATE, UPDATE, DELETE
}
}
| agpl-3.0 |
jasolangi/jasolangi.github.io | modules/report/src/main/java/org/openlmis/report/builder/RegimenSummaryQueryBuilder.java | 9594 | /*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla 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 Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
package org.openlmis.report.builder;
import org.openlmis.report.model.params.RegimenSummaryReportParam;
import java.util.Map;
public class RegimenSummaryQueryBuilder {
public static String getData(Map params) {
RegimenSummaryReportParam filter = (RegimenSummaryReportParam) params.get("filterCriteria");
String sql = "";
sql = "WITH temp as ( select regimen,district,facilityname,\n" +
"SUM(patientsontreatment) patientsontreatment,\n" +
"SUM(patientstoinitiatetreatment) patientstoinitiatetreatment,\n" +
"SUM(patientsstoppedtreatment) patientsstoppedtreatment\n" +
"from vw_regimen_district_distribution\n" +
writePredicates(filter) +
"group by regimen,district,facilityname\n" +
"order by regimen,district ) \n" +
" \n" +
"select t.district,t.regimen,t.facilityname,\n" +
"t.patientsontreatment patientsontreatment,\n" +
"t.patientstoinitiatetreatment patientsToInitiateTreatment,\n" +
"t.patientsstoppedtreatment patientsstoppedtreatment,\n" +
"COALESCE( case when temp2.total > 0 THEN round(((t.patientsontreatment*100)/temp2.total),0) ELSE temp2.total END ) \n" +
" totalOnTreatmentPercentage, \n" +
" COALESCE( case when temp2.total2 > 0 THEN round(((t.patientstoinitiatetreatment*100)/temp2.total2),0) ELSE temp2.total2 END ) \n" +
" totalpatientsToInitiateTreatmentPercentage,\n" +
" COALESCE( case when temp2.total3 > 0 THEN round(((t.patientsstoppedtreatment*100)/temp2.total3),0) \n" +
" ELSE temp2.total3 END ) stoppedTreatmentPercentage from temp t\n" +
"INNER JOIN (select district,SUM(patientsontreatment) total,SUM(patientstoinitiatetreatment) total2,\n" +
" SUM(patientsstoppedtreatment) total3 from temp GROUP BY district ) temp2 ON t.district= temp2.district ";
return sql;
}
private static String writePredicates(RegimenSummaryReportParam filter) {
String predicate = "";
predicate = " WHERE status in ('APPROVED','RELEASED') ";
if (filter != null) {
if (filter.getZoneId() != 0) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " zoneId = #{filterCriteria.zoneId} " +
" or districtid=#{filterCriteria.zoneId} " +
"or regionid = #{filterCriteria.zoneId} " +
"or parentId = #{filterCriteria.zoneId}";
}
if (filter.getScheduleId() != 0 && filter.getScheduleId() != -1) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " scheduleid= #{filterCriteria.scheduleId}";
}
if (filter.getProgramId() != 0 && filter.getProgramId() != -1) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " programid = #{filterCriteria.programId}";
}
if (filter.getPeriodId() != 0 && filter.getPeriodId() != -1) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " periodid= #{filterCriteria.periodId}";
}
if (filter.getRegimenId() != 0 && filter.getRegimenId() != -1) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " regimenid = #{filterCriteria.regimenId}";
}
if (filter.getRegimenCategoryId() != 0) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " categoryid = #{filterCriteria.regimenCategoryId}";
}
if (filter.getFacilityId() != 0) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " facilityid = #{filterCriteria.facilityId}";
}
if (filter.getFacilityTypeId() != 0) {
predicate = predicate.isEmpty() ? " where " : predicate + " and ";
predicate = predicate + " facilitytypeid = #{filterCriteria.facilityTypeId}";
}
}
return predicate;
}
public static String getAggregateRegimenDistribution(Map params) {
RegimenSummaryReportParam filter = (RegimenSummaryReportParam) params.get("filterCriteria");
String predicates = "";
if (filter.getRegimenId() > 0) {
predicates = predicates + " and regimens.id = " + filter.getRegimenId();
}
if (filter.getRegimenCategoryId() > 0) {
predicates = predicates + " and regimens.categoryId = " + filter.getRegimenCategoryId();
}
if (filter.getZoneId() != 0) {
predicates = predicates + " and ( f.geographicZoneId = " + filter.getZoneId() + " or gz.parentId = " + filter.getZoneId() + " or zone.parentId = " + filter.getZoneId() + " or c.parentId = " + filter.getZoneId() + ") ";
}
String query = "";
query = "SELECT DISTINCT\n" +
" regimens.name regimen,sum(li.patientsontreatment) patientsontreatment, SUM(li.patientstoinitiatetreatment)\n" +
"patientstoinitiatetreatment, \n" +
"SUM(li.patientsstoppedtreatment) patientsstoppedtreatment" +
" FROM regimen_line_items li\n" +
" JOIN requisitions r ON r.id = li.rnrid\n" +
" JOIN facilities f ON r.facilityid = f.id\n" +
" JOIN geographic_zones gz ON gz.id = f.geographiczoneid\n" +
" JOIN geographic_zones zone ON gz.parentid = zone.id\n" +
" JOIN geographic_zones c ON zone.parentid = c.id\n" +
" JOIN requisition_group_members rgm ON rgm.facilityid = r.facilityid\n" +
" JOIN programs_supported ps ON ps.programid = r.programid AND r.facilityid = ps.facilityid\n" +
" JOIN processing_periods pp ON r.periodid = pp.id\n" +
" JOIN requisition_group_program_schedules rgps ON rgps.requisitiongroupid = rgm.requisitiongroupid AND pp.scheduleid = rgps.scheduleid\n" +
" JOIN regimens ON r.programid = regimens.programid\n" +
" WHERE r.periodid = " + filter.getPeriodId() + " and r.programId = " + filter.getProgramId() + "and r.status in ('APPROVED','RELEASED') " + predicates +
" GROUP BY regimens.name\n" +
" ORDER BY regimens.name ";
return query;
}
public static String getRegimenDistributionData(Map params) {
RegimenSummaryReportParam filter = (RegimenSummaryReportParam) params.get("filterCriteria");
String sql = "";
sql = "WITH temp as ( select regimen,district,\n" +
"SUM(patientsontreatment) patientsontreatment,\n" +
"SUM(patientstoinitiatetreatment) patientstoinitiatetreatment,\n" +
"SUM(patientsstoppedtreatment) patientsstoppedtreatment\n" +
"from vw_regimen_district_distribution\n" +
writePredicates(filter) +
"group by regimen,district\n" +
"order by regimen,district ) \n" +
"select t.district,t.regimen,\n" +
"t.patientsontreatment patientsontreatment,\n" +
"t.patientstoinitiatetreatment patientsToInitiateTreatment,\n" +
"t.patientsstoppedtreatment patientsstoppedtreatment,\n" +
"COALESCE( case when temp2.total > 0 THEN round(((t.patientsontreatment*100)/temp2.total),0) ELSE temp2.total END ) \n" +
" totalOnTreatmentPercentage, \n" +
" COALESCE( case when temp2.total2 > 0 THEN round(((t.patientstoinitiatetreatment*100)/temp2.total2),0) ELSE temp2.total2 END ) \n" +
" totalpatientsToInitiateTreatmentPercentage,\n" +
" COALESCE( case when temp2.total3 > 0 THEN round(((t.patientsstoppedtreatment*100)/temp2.total3),0) \n" +
" ELSE temp2.total3 END ) stoppedTreatmentPercentage from temp t\n" +
"INNER JOIN (select regimen ,SUM(patientsontreatment) total,SUM(patientstoinitiatetreatment) total2,\n" +
" SUM(patientsstoppedtreatment) total3 from temp GROUP BY regimen ) temp2 ON t.regimen= temp2.regimen ";
return sql;
}
}
| agpl-3.0 |
RestComm/jss7 | cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/errors/CAPErrorMessageFactory.java | 1964 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.cap.api.errors;
/**
* The factory of CAP ReturnError messages
*
* @author sergey vetyutnev
*
*/
public interface CAPErrorMessageFactory {
/**
* Generate the empty message depends of the error code (for incoming messages)
*
* @param errorCode
* @return
*/
CAPErrorMessage createMessageFromErrorCode(Long errorCode);
CAPErrorMessageParameterless createCAPErrorMessageParameterless(Long errorCode);
CAPErrorMessageCancelFailed createCAPErrorMessageCancelFailed(CancelProblem cancelProblem);
CAPErrorMessageRequestedInfoError createCAPErrorMessageRequestedInfoError(
RequestedInfoErrorParameter requestedInfoErrorParameter);
CAPErrorMessageSystemFailure createCAPErrorMessageSystemFailure(UnavailableNetworkResource unavailableNetworkResource);
CAPErrorMessageTaskRefused createCAPErrorMessageTaskRefused(TaskRefusedParameter taskRefusedParameter);
}
| agpl-3.0 |
CeON/CERMINE | cermine-impl/src/main/java/pl/edu/icm/cermine/bibref/extraction/features/PrevEndsWithDotFeature.java | 1614 | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.bibref.extraction.features;
import java.util.regex.Pattern;
import pl.edu.icm.cermine.bibref.extraction.model.BxDocumentBibReferences;
import pl.edu.icm.cermine.structure.model.BxLine;
import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PrevEndsWithDotFeature extends FeatureCalculator<BxLine, BxDocumentBibReferences> {
@Override
public double calculateFeatureValue(BxLine refLine, BxDocumentBibReferences refs) {
if (refs.getLines().indexOf(refLine) == 0) {
return 0.9;
}
String text = refs.getLines().get(refs.getLines().indexOf(refLine)-1).toText();
if (Pattern.matches("^.*\\d\\.$", text)) {
return 1;
}
return Pattern.matches("^.*\\.$", text) ? 0.8 : 0;
}
}
| agpl-3.0 |
TMS-v113/server | src/client/messages/commands/PlayerCommand.java | 6669 | package client.messages.commands;
import client.inventory.IItem;
import client.inventory.MapleInventoryType;
import constants.GameConstants;
import client.MapleClient;
import constants.ServerConstants.PlayerGMRank;
import handling.world.World;
import scripting.NPCScriptManager;
import server.MapleInventoryManipulator;
import tools.ArrayMap;
import tools.MaplePacketCreator;
import tools.Pair;
import java.util.Map;
/**
* @author Emilyx3
* @author freedom
*/
public class PlayerCommand {
public static PlayerGMRank getPlayerLevelRequired()
{
return PlayerGMRank.NORMAL;
}
/**
* 清除物品欄
*/
public static class ClearInv extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
String errMsg = "格式錯誤: @clearinv <eqp/eq/u/s/e/c> (穿著裝備/裝備/消耗/裝飾/其他/特殊)";
if (2 != splitted.length) {
c.getPlayer().dropMessage(6, errMsg);
return 0;
}
MapleInventoryType inventory = null;
switch (splitted[1]) {
case "eqp": inventory = MapleInventoryType.EQUIPPED; break;
case "eq": inventory = MapleInventoryType.EQUIP; break;
case "u": inventory = MapleInventoryType.USE; break;
case "s": inventory = MapleInventoryType.SETUP; break;
case "e": inventory = MapleInventoryType.ETC; break;
case "c": inventory = MapleInventoryType.CASH; break;
default: c.getPlayer().dropMessage(6, errMsg); break;
}
if (null == inventory) {
return 0;
}
java.util.Map<Pair<Short, Short>, MapleInventoryType> eqs = new ArrayMap<Pair<Short, Short>, MapleInventoryType>();
for (IItem item : c.getPlayer().getInventory(inventory)) {
eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), inventory);
}
for (Map.Entry<Pair<Short, Short>, MapleInventoryType> eq : eqs.entrySet()) {
MapleInventoryManipulator.removeFromSlot(c, eq.getValue(), eq.getKey().left, eq.getKey().right, false, false);
}
c.getPlayer().dropMessage(6, "清除成功");
return 0;
}
}
/**
* 丟棄點數商品
*/
public static class DropCash extends CommandExecute
{
private MapleClient client;
private int endSession()
{
client.getPlayer().dropMessage(1, "此地圖無法使用指此令");
return 0;
}
@Override
public int execute(MapleClient c, String[] splitted)
{
client = c;
for (int i : GameConstants.blockedMaps) {
if (c.getPlayer().getMapId() == i) {
return endSession();
}
}
if (c.getPlayer().getMap().getSquadByMap() != null || c.getPlayer().getEventInstance() != null || c.getPlayer().getMap().getEMByMap() != null || c.getPlayer().getMapId() >= 990000000/* || FieldLimitType.VipRock.check(c.getPlayer().getMap().getFieldLimit())*/) {
return endSession();
}
if ((c.getPlayer().getMapId() >= 680000210 && c.getPlayer().getMapId() <= 680000502) || (c.getPlayer().getMapId() / 1000 == 980000 && c.getPlayer().getMapId() != 980000000) || (c.getPlayer().getMapId() / 100 == 1030008) || (c.getPlayer().getMapId() / 100 == 922010) || (c.getPlayer().getMapId() / 10 == 13003000)) {
return endSession();
}
NPCScriptManager.getInstance().start(c, 9010017);
return 0;
}
}
/**
* 解除卡定狀態
*/
public static class EA extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
NPCScriptManager.getInstance().dispose(c);
c.getSession().write(MaplePacketCreator.enableActions());
c.getPlayer().dropMessage(1, "解卡完畢");
return 0;
}
}
/**
* 顯示伺服器線上人數
*/
public static class Online extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
c.getPlayer().dropMessage(6, "目前在線人數:" + World.getConnected().get(0) + " 人");
return 0;
}
}
/**
* 顯示伺服器倍率
*/
public static class Rate extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
c.getPlayer().dropMessage(6, "經驗值倍率:" + c.getChannelServer().getExpRate() + " 掉寶倍率:" + c.getChannelServer().getDropRate() + " 楓幣倍率:" + c.getChannelServer().getMesoRate());
return 0;
}
}
/**
* 儲存玩家資料
*/
public static class Save extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
c.getPlayer().saveToDB(false, true);
c.getPlayer().dropMessage(6, "儲存完畢");
return 0;
}
}
/**
* 顯示目前所在地圖代號及角色座標
*/
public static class WhereAmI extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
c.getPlayer().dropMessage(5, "目前地圖 " + c.getPlayer().getMap().getId() + " 座標 (" + String.valueOf(c.getPlayer().getPosition().x) + " , " + String.valueOf(c.getPlayer().getPosition().y) + ")");
return 1;
}
}
/**
* 顯示玩家指令
*/
public static class Help extends CommandExecute
{
@Override
public int execute(MapleClient c, String[] splitted)
{
c.getPlayer().dropMessage(5, "指令列表 :");
c.getPlayer().dropMessage(5, "@clearinv <all/eqp/eq/u/s/e/c> - 清除物品欄 (全部/穿著裝備/裝備/消耗/裝飾/其他/特殊)");
c.getPlayer().dropMessage(5, "@ea - 解除卡定狀態");
c.getPlayer().dropMessage(5, "@dropcash - 丟棄點裝");
c.getPlayer().dropMessage(5, "@online - 查看在線人數");
c.getPlayer().dropMessage(5, "@rate - 查看倍率");
c.getPlayer().dropMessage(5, "@save - 存檔");
c.getPlayer().dropMessage(5, "@whereami - 顯示目前所在地圖 id 及座標");
return 0;
}
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-library/src/main/java/org/silverpeas/core/socialnetwork/SocialNetworkUserListener.java | 2936 | /*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.socialnetwork;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.silverpeas.core.admin.user.notification.UserEvent;
import org.silverpeas.core.annotation.Service;
import org.silverpeas.core.notification.system.CDIResourceEventListener;
import org.silverpeas.core.socialnetwork.invitation.InvitationService;
import org.silverpeas.core.socialnetwork.relationship.RelationShip;
import org.silverpeas.core.socialnetwork.relationship.RelationShipService;
import org.silverpeas.core.socialnetwork.service.SocialNetworkService;
import org.silverpeas.core.util.logging.SilverLogger;
import javax.inject.Inject;
import java.util.List;
/**
* Listens events about the deletion of a user in Silverpeas to clean up all the data relative
* to the deleted user in the Silverpeas social network service.
* @author mmoquillon
*/
@Service
public class SocialNetworkUserListener extends CDIResourceEventListener<UserEvent> {
@Inject
private SocialNetworkService socialNetworkService;
@Inject
private InvitationService invitationService;
@Inject
private RelationShipService relationShipService;
@Override
public void onDeletion(final UserEvent event) throws Exception {
UserDetail user = event.getTransition().getBefore();
SilverLogger.getLogger(this)
.debug("Delete all the social network data of user {0}", user.getId());
List<RelationShip> relationShips =
relationShipService.getAllMyRelationShips(Integer.valueOf(user.getId()));
relationShips.forEach(
relationShip -> relationShipService.removeRelationShip(relationShip.getUser1Id(),
relationShip.getUser2Id()));
invitationService.deleteAllMyInvitations(user.getId());
socialNetworkService.removeAllExternalAccount(user.getId());
}
}
| agpl-3.0 |
WASP-System/central | wasp-core/src/main/java/edu/yu/einstein/wasp/dao/impl/UiFieldDaoImpl.java | 3419 |
/**
*
* DAO to manage UIField table
* @author Sasha Levchuk
*
**/
package edu.yu.einstein.wasp.dao.impl;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import edu.yu.einstein.wasp.model.UiField;
@Transactional("entityManager")
@Repository
public class UiFieldDaoImpl extends WaspDaoImpl<UiField> implements edu.yu.einstein.wasp.dao.UiFieldDao {
public UiFieldDaoImpl() {
super();
this.entityClass = UiField.class;
}
//returns list of unique areas
@SuppressWarnings("unchecked")
@Override
public List<String> getUniqueAreas() {
String query="SELECT DISTINCT u.area FROM UiField u ORDER BY u.area";
return entityManager.createQuery(query).getResultList();
}
//returns true if a combination of locale, area, name, attrName already exists
@Override
public boolean exists(final String locale, final String area, final String name, final String attrName) {
String query=
"SELECT 1 from UiField u \n"+
"WHERE u.locale=:locale\n"+
"AND u.area=:area\n"+
"AND u.name=:name\n"+
"AND u.attrName=:attrname\n";
Query q = entityManager.createQuery(query)
.setParameter("locale", locale)
.setParameter("area", area)
.setParameter("name", name)
.setParameter("attrname", attrName);
return !q.getResultList().isEmpty();
}
//utility functions to format SQL insert queries
private void process(StringBuilder result,String value) {
if (value==null) {
result.append("NULL");
} else {
String outputValue = value.toString();
outputValue = outputValue.replaceAll("'","''");
result.append("'"+outputValue+"'");
}
}
/*
private void process(StringBuilder result,Integer value) {
if (value==null) {
result.append("NULL");
} else {
String outputValue = value.toString();
result.append(outputValue);
}
}
*/
//returns content of UIField table as a list of SQL insert statements
@Override
public String dumpUiFieldTable() {
final List<UiField> all = super.findAll();
StringBuilder result = new StringBuilder("truncate table uifield;\n");
for(UiField f:all) {
result.append("insert into uifield(locale,area,name,attrName,attrValue,lastupduser) values(");
process(result,f.getLocale());
result.append(",");
process(result,f.getArea());
result.append(",");
process(result,f.getName());
result.append(",");
process(result,f.getAttrName());
result.append(",");
process(result,f.getAttrValue());
result.append(",");
process(result,1+"");
result.append(");\n");
}
return result+"";
}
@Override
public UiField get(String locale, String area, String name, String attrName) {
String query = "SELECT u FROM UiField AS u " +
"WHERE locale=:locale " +
"AND area=:area " +
"AND name=:name " +
"AND attrname=:attrname";
TypedQuery<UiField> q = entityManager.createQuery(query, UiField.class)
.setParameter("locale", locale)
.setParameter("area", area)
.setParameter("name", name)
.setParameter("attrname", attrName);
if (!exists(locale, area, name, attrName)) {
return null;
}
return q.getResultList().get(0);
}
}
| agpl-3.0 |
automenta/narchy | lab/lab_x/main/java/jhelp/util/list/Bag2D.java | 14693 | package jhelp.util.list;
import jhelp.util.debug.Debug;
import jhelp.util.debug.DebugLevel;
import jhelp.util.text.UtilText;
import java.util.ArrayList;
import java.util.Iterator;
/**
* A bag in two dimension.<br>
* The bag is a table with a fixed number of cell in width and in height.<br>
* It can contains objects that have a size (width and height) that occupied cells of the bag.<br>
* Two objects can't itersect each other,.<br>
* Each time an object is add, free space are use to put it, if not enough room for put the object, then the bag will be
* reorderes=d automatically to try to add the new object, if its not possible to add the new object, it is not added
*
* @author JHelp
* @param <OBJECT>
* Objects type
*/
public class Bag2D<OBJECT extends SizedObject>
implements Iterable<ObjectPosition<OBJECT>>
{
/**
* Area in the bag
*
* @author JHelp
*/
class Area
{
/** Area priority */
long priority;
/** X top-left corner */
int x;
/** Y top-left corner */
int y;
/**
* Create a new instance of Area
*
* @param x
* X top-left corner
* @param y
* Y top-left corner
* @param width
* Width
* @param height
* Height
*/
Area(final int x, final int y, final int width, final int height)
{
this.x = x;
this.y = y;
final int h = Bag2D.this.height;
final int w = Bag2D.this.width;
for(int yy = (y + height) - 1; yy >= y; yy--)
{
for(int xx = (x + width) - 1; xx >= x; xx--)
{
Bag2D.this.bag[xx][yy] = -1;
}
}
this.priority = 0;
long ww;
long hh;
int mx;
boolean eliminateLine;
for(int yy = 0; yy < h; yy++)
{
for(int xx = 0; xx < w; xx++)
{
if(Bag2D.this.bag[xx][yy] == 0)
{
ww = hh = 1;
Bag2D.this.bag[xx][yy] = -1;
for(mx = xx + 1; (mx < w) && (Bag2D.this.bag[mx][yy] == 0); mx++)
{
ww++;
Bag2D.this.bag[mx][yy] = -1;
}
eliminateLine = true;
for(int yyy = yy + 1; (yyy < h) && (eliminateLine == true); yyy++)
{
for(int xxx = xx; xxx < mx; xxx++)
{
if(Bag2D.this.bag[xxx][yyy] != 0)
{
eliminateLine = false;
break;
}
}
if(eliminateLine == true)
{
for(int xxx = xx; xxx < mx; xxx++)
{
Bag2D.this.bag[xxx][yyy] = -1;
}
hh++;
}
}
this.priority += ww * hh * ww * hh;
}
}
}
for(int yy = 0; yy < h; yy++)
{
for(int xx = 0; xx < w; xx++)
{
if(Bag2D.this.bag[xx][yy] < 0)
{
Bag2D.this.bag[xx][yy] = 0;
}
}
}
}
/**
* String representation <br>
* <br>
* <b>Parent documentation:</b><br>
* {@inheritDoc}
*
* @return String representation
* @see Object#toString()
*/
@Override
public String toString()
{
return this.x + "," + this.y + " : " + this.priority;
}
}
/** Objects stored */
private final SortedArray<ObjectPosition<OBJECT>> objects;
/** The bag */
final int[][] bag;
/** Bag height */
final int height;
/** Bag width */
final int width;
/**
* Create a new instance of Bag2D
*
* @param width
* Bag width
* @param height
* Bag height
*/
@SuppressWarnings(
{
"unchecked", "rawtypes"
})
public Bag2D(final int width, final int height)
{
this.width = Math.max(1, width);
this.height = Math.max(1, height);
this.bag = new int[this.width][this.height];
this.objects = new SortedArray(ObjectPosition.class);
}
/**
* Compute the best location of free space to put an object
*
* @param w
* Object width
* @param h
* Object height
* @return The bet location or {@code null} if not enough room for put the object (Mat have to reorder the bag before try
* again)
*/
private Point searchBestFreeSpace(final int w, final int h)
{
Area area = null;
Area a;
final int maxX = this.width - w;
final int maxY = this.height - h;
boolean found;
for(int y = 0; y <= maxY; y++)
{
for(int x = 0; x <= maxX; x++)
{
if(this.bag[x][y] == 0)
{
found = true;
for(int yy = (y + h) - 1; (yy >= y) && (found == true); yy--)
{
for(int xx = (x + w) - 1; xx >= x; xx--)
{
if(this.bag[xx][yy] != 0)
{
found = false;
break;
}
}
}
if(found == true)
{
a = new Area(x, y, w, h);
if((area == null) || (area.priority < a.priority))
{
area = a;
}
}
}
}
}
if(area == null)
{
return null;
}
return new Point(area.x, area.y);
}
/**
* Clear the bag. The bag is empty after this
*/
public void clearBag()
{
for(int y = 0; y < this.height; y++)
{
for(int x = 0; x < this.width; x++)
{
this.bag[x][y] = 0;
}
}
this.objects.clear();
}
/**
* Obtain the object coresponding to the index
*
* @param index
* Index
* @return Corresponding object
*/
public OBJECT getObject(final int index)
{
return this.getObjectPosition(index).getObject();
}
/**
* Obtain object position (That embed the object it self) at given cell
*
* @param x
* Cell x
* @param y
* Cell y
* @return Object position or {@code null} if cell is empty
*/
public ObjectPosition<OBJECT> getObjectAt(final int x, final int y)
{
if((x < 0) || (x >= this.width) || (y < 0) || (y >= this.height))
{
throw new IllegalArgumentException("The point (" + x + ", " + y + ") is outside of the bag : " + this.width + "x" + this.height);
}
final int index = this.bag[x][y];
if(index == 0)
{
return null;
}
for(final ObjectPosition<OBJECT> objectPosition : this.objects)
{
if(objectPosition.index == index)
{
return objectPosition;
}
}
Debug.println(DebugLevel.WARNING, "Shouldn't arrive here ! x=", x, " y=", y, " bag[x][y]=", this.bag[x][y], "\n", this);
this.bag[x][y] = 0;
return null;
}
/**
* Obtain position (That embed the object it self) the object coresponding to the index
*
* @param index
* Index
* @return Corresponding object position
*/
public ObjectPosition<OBJECT> getObjectPosition(final int index)
{
return this.objects.getElement(index);
}
/**
* Index of object inside bag
*
* @param object
* Searched object
* @return Index object or -1 if not found
*/
public int indexOf(final OBJECT object)
{
final int size = this.objects.getSize();
for(int i = 0; i < size; i++)
{
if(this.objects.getElement(i).equals(object) == true)
{
return i;
}
}
return -1;
}
/**
* Index of object position inside bag
*
* @param objectPosition
* Searched object position
* @return Index object position or -1 if not found
*/
public int indexOf(final ObjectPosition<OBJECT> objectPosition)
{
return this.objects.indexOf(objectPosition);
}
/**
* List of all objects postion (Embed the objects) inside the bag <br>
* <br>
* <b>Parent documentation:</b><br>
* {@inheritDoc}
*
* @return List of all objects postion (Embed the objects) inside the bag
* @see Iterable#iterator()
*/
@Override
public Iterator<ObjectPosition<OBJECT>> iterator()
{
return this.objects.iterator();
}
/**
* Number of objects in the bag
*
* @return Number of objects in the bag
*/
public int numberOfObjects()
{
return this.objects.getSize();
}
/**
* Try to add an object in the bag.<br>
* The bag is eventually reordered to be able add the object.<br>
* If it is not possible to add the object (Reorder is not enough) the object is not added and {@code null} is return
*
* @param object
* Object to add
* @return Object position in the bag after loacate it or {@code null} if is impossible to add the object (Reorder is not
* enough)
*/
public ObjectPosition<OBJECT> put(final OBJECT object)
{
final int w = object.getWidth();
final int h = object.getHeight();
if((w < 1) || (h < 1))
{
throw new IllegalArgumentException("Object must have size at least 1x1, not " + w + "x" + h);
}
if((w > this.width) || (h > this.height))
{
return null;
}
Point point = this.searchBestFreeSpace(w, h);
if(point != null)
{
final ObjectPosition<OBJECT> objectPosition = new ObjectPosition<OBJECT>(object, this.width, this.height);
objectPosition.x = point.x;
objectPosition.y = point.y;
final int index = objectPosition.index;
for(int yy = (point.y + h) - 1; yy >= point.y; yy--)
{
for(int xx = (point.x + w) - 1; xx >= point.x; xx--)
{
this.bag[xx][yy] = index;
}
}
this.objects.add(objectPosition);
return objectPosition;
}
final int[][] oldBag = new int[this.width][this.height];
for(int y = 0; y < this.height; y++)
{
for(int x = 0; x < this.width; x++)
{
oldBag[x][y] = this.bag[x][y];
this.bag[x][y] = 0;
}
}
final ObjectPosition<OBJECT> objectPos = new ObjectPosition<OBJECT>(object, this.width, this.height);
this.objects.add(objectPos);
OBJECT obj;
int index, ww, hh;
final ArrayList<Point> positions = new ArrayList<Point>();
for(final ObjectPosition<OBJECT> objectPosition : this.objects)
{
obj = objectPosition.getObject();
index = objectPosition.index;
ww = obj.getWidth();
hh = obj.getHeight();
point = this.searchBestFreeSpace(ww, hh);
if(point == null)
{
break;
}
positions.add(point);
for(int yy = (point.y + hh) - 1; yy >= point.y; yy--)
{
for(int xx = (point.x + ww) - 1; xx >= point.x; xx--)
{
this.bag[xx][yy] = index;
}
}
}
if(point == null)
{
for(int y = 0; y < this.height; y++)
{
for(int x = 0; x < this.width; x++)
{
this.bag[x][y] = oldBag[x][y];
}
}
this.objects.remove(objectPos);
return null;
}
final int nb = this.objects.getSize();
ObjectPosition<OBJECT> objectPosition;
for(int i = 0; i < nb; i++)
{
point = positions.get(i);
objectPosition = this.objects.getElement(i);
objectPosition.x = point.x;
objectPosition.y = point.y;
}
return objectPos;
}
/**
* Remove an object on the bag
*
* @param index
* Object index to remove
*/
public void remove(int index)
{
final ObjectPosition<OBJECT> objectPosition = this.objects.remove(index);
if(objectPosition == null)
{
return;
}
index = objectPosition.index;
for(int y = 0; y < this.height; y++)
{
for(int x = 0; x < this.width; x++)
{
if(this.bag[x][y] == index)
{
this.bag[x][y] = 0;
}
}
}
}
/**
* Remove an object of the bag
*
* @param object
* Object to remove
*/
public void remove(final OBJECT object)
{
final int index = this.indexOf(object);
if(index < 0)
{
return;
}
this.remove(index);
}
/**
* Remove an object of the bag
*
* @param objectPosition
* Object position with embed object to remove
*/
public void remove(ObjectPosition<OBJECT> objectPosition)
{
objectPosition = this.objects.remove(objectPosition);
if(objectPosition == null)
{
return;
}
final int index = objectPosition.index;
for(int y = 0; y < this.height; y++)
{
for(int x = 0; x < this.width; x++)
{
if(this.bag[x][y] == index)
{
this.bag[x][y] = 0;
}
}
}
}
/**
* String representation <br>
* <br>
* <b>Parent documentation:</b><br>
* {@inheritDoc}
*
* @return String representation
* @see Object#toString()
*/
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder(UtilText.concatenate("Bag2D : "));
builder.append(this.width);
builder.append("x");
builder.append(this.height);
for(int y = 0; y < this.height; y++)
{
builder.append('\n');
for(int x = 0; x < this.width; x++)
{
builder.append('\t');
builder.append(this.bag[x][y]);
}
}
builder.append("\n");
builder.append(this.objects);
return builder.toString();
}
} | agpl-3.0 |
kdhrubo/crx | lead/src/main/java/co/hooghly/crm/repository/LeadRepository.java | 418 | package co.hooghly.crm.repository;
import java.util.stream.Stream;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import co.hooghly.crm.domain.Lead;
@Repository
public interface LeadRepository extends JpaRepository<Lead, Long> {
Stream<Lead> findAllByDeleted(Pageable pageable, boolean deleted);
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Components | mailinglist/mailinglist-jar/src/test/java/com/silverpeas/mailinglist/service/model/beans/TestMessage.java | 3478 | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.mailinglist.service.model.beans;
import junit.framework.TestCase;
public class TestMessage extends TestCase {
public void testHashCode() {
Message message1 = new Message();
message1.setId("id");
message1.setVersion(1);
Message message2 = new Message();
message2.setId("id");
message2.setVersion(1);
assertEquals(message1.hashCode(), message2.hashCode());
message2.setVersion(2);
assertFalse(message1.hashCode() == message2.hashCode());
message1 = new Message();
message1.setMessageId("0000001747b40c85");
message2 = new Message();
message2.setId(message1.getId());
message2.setMessageId("0000001747b40c85");
assertEquals(message1, message2);
message1 = new Message();
message1.setId("id");
message1.setVersion(1);
message1.setMessageId("0000001747b40c85");
message2 = new Message();
message2.setId("id");
message2.setVersion(1);
message2.setMessageId("0000001747b40c85");
assertEquals(message1.hashCode(), message2.hashCode());
message2.setVersion(2);
assertFalse(message1.hashCode() == message2.hashCode());
message2.setVersion(1);
message2.setMessageId("0000001747b40c90");
assertFalse(message1.hashCode() == message2.hashCode());
}
public void testEqualsById() {
Message message1 = new Message();
message1.setId("id");
message1.setVersion(1);
Message message2 = new Message();
message2.setId("id");
message2.setVersion(1);
assertEquals(message1, message2);
message2.setVersion(2);
assertFalse(message1.equals(message2));
message1 = new Message();
message1.setMessageId("0000001747b40c85");
message2 = new Message();
message2.setId(message1.getId());
message2.setMessageId("0000001747b40c85");
assertEquals(message1, message2);
message1 = new Message();
message1.setId("id");
message1.setVersion(1);
message1.setMessageId("0000001747b40c85");
message2 = new Message();
message2.setId("id");
message2.setVersion(1);
message2.setMessageId("0000001747b40c85");
assertEquals(message1, message2);
message2.setVersion(2);
assertFalse(message1.equals(message2));
message2.setVersion(1);
message2.setMessageId("0000001747b40c90");
assertFalse(message1.equals(message2));
}
}
| agpl-3.0 |
AlessioDP/Parties | bukkit/src/main/java/com/alessiodp/parties/bukkit/commands/main/BukkitCommandP.java | 423 | package com.alessiodp.parties.bukkit.commands.main;
import com.alessiodp.parties.bukkit.configuration.data.BukkitConfigMain;
import com.alessiodp.parties.common.PartiesPlugin;
import com.alessiodp.parties.common.commands.main.CommandP;
public class BukkitCommandP extends CommandP {
public BukkitCommandP(PartiesPlugin instance) {
super(instance);
description = BukkitConfigMain.COMMANDS_MAIN_P_DESCRIPTION;
}
}
| agpl-3.0 |
urieli/talismane | talismane_core/src/main/java/com/joliciel/talismane/tokeniser/features/FirstWordInSentenceFeature.java | 3520 | ///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2014 Joliciel Informatique
//
//This file is part of Talismane.
//
//Talismane is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Talismane 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 Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with Talismane. If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////////////////
package com.joliciel.talismane.tokeniser.features;
import java.util.regex.Pattern;
import com.joliciel.talismane.TalismaneException;
import com.joliciel.talismane.machineLearning.features.BooleanFeature;
import com.joliciel.talismane.machineLearning.features.FeatureResult;
import com.joliciel.talismane.machineLearning.features.RuntimeEnvironment;
import com.joliciel.talismane.tokeniser.Token;
import com.joliciel.talismane.tokeniser.TokenSequence;
/**
* Returns true if this is the first word in the sentence.<br/>
* Will skip initial punctuation (e.g. quotation marks) or numbered lists,
* returning true for the first word following such constructs.
*
* @author Assaf Urieli
*
*/
public final class FirstWordInSentenceFeature extends AbstractTokenFeature<Boolean> implements BooleanFeature<TokenWrapper> {
static Pattern integerPattern = Pattern.compile("\\d+");
public FirstWordInSentenceFeature() {
}
public FirstWordInSentenceFeature(TokenAddressFunction<TokenWrapper> addressFunction) {
this.setAddressFunction(addressFunction);
}
@Override
public FeatureResult<Boolean> checkInternal(TokenWrapper tokenWrapper, RuntimeEnvironment env) throws TalismaneException {
TokenWrapper innerWrapper = this.getToken(tokenWrapper, env);
if (innerWrapper == null)
return null;
Token token = innerWrapper.getToken();
FeatureResult<Boolean> result = null;
boolean firstWord = (token.getIndex() == 0);
if (!firstWord) {
TokenSequence tokenSequence = token.getTokenSequence();
int startIndex = 0;
String word0 = "";
String word1 = "";
String word2 = "";
if (tokenSequence.size() > 0)
word0 = tokenSequence.get(0).getAnalyisText();
if (tokenSequence.size() > 1)
word1 = tokenSequence.get(1).getAnalyisText();
if (tokenSequence.size() > 2)
word2 = tokenSequence.get(2).getAnalyisText();
boolean word0IsInteger = integerPattern.matcher(word0).matches();
boolean word1IsInteger = integerPattern.matcher(word1).matches();
if (word0.equals("\"") || word0.equals("-") || word0.equals("--") || word0.equals("—") || word0.equals("*") || word0.equals("(")) {
startIndex = 1;
} else if ((word0IsInteger || word0.length() == 1) && (word1.equals(")") || word1.equals("."))) {
startIndex = 2;
} else if (word0.equals("(") && (word1IsInteger || word1.length() == 1) && word2.equals(")")) {
startIndex = 3;
}
firstWord = (token.getIndex() == startIndex);
} // have token
result = this.generateResult(firstWord);
return result;
}
}
| agpl-3.0 |
m4tx/arroch | app/controllers/groups/Groups.java | 643 | package controllers.groups;
import models.SocialGroup;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.mvc.Result;
import utils.SimpleQuery;
import views.html.pages.group.groupList;
import java.util.List;
import static play.mvc.Results.ok;
public class Groups {
@Transactional
public Result get() {
return getPage(1);
}
@Transactional
public Result getPage(int page) {
List<? extends SocialGroup> groups = (new SimpleQuery<>(JPA.em(), SocialGroup.class)
.orderByAsc("name")
).getResultList();
return ok(groupList.render(groups, 25, page));
}
}
| agpl-3.0 |
gnosygnu/xowa_android | _150_gfui/src/main/java/gplx/gfui/kits/swts/Swt_win.java | 5701 | package gplx.gfui.kits.swts; import gplx.*; import gplx.gfui.*; import gplx.gfui.kits.*;
//#{swt
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import gplx.Bool_;
import gplx.Gfo_invk_cmd;
import gplx.GfoMsg;
import gplx.GfsCtx;
import gplx.Io_url_;
import gplx.gfui.controls.gxws.GxwCbkHost;
import gplx.gfui.controls.gxws.GxwCbkHost_;
import gplx.gfui.controls.gxws.GxwCore_base;
import gplx.gfui.controls.gxws.GxwElem;
import gplx.gfui.controls.gxws.GxwWin;
import gplx.gfui.imgs.IconAdp;
import gplx.gfui.ipts.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Swt_win implements GxwWin, Swt_control {
private Swt_lnr_resize resize_lnr; private Swt_lnr_show show_lnr; // use ptr to dispose later
void ctor(boolean window_is_dialog, Shell shell, Display display) {
this.shell = shell;
this.display = display;
this.ctrl_mgr = new Swt_core_cmds(shell);
this.show_lnr = new Swt_lnr_show(this);
this.resize_lnr = new Swt_lnr_resize(this);
shell.addListener(SWT.Show, show_lnr);
shell.addListener(SWT.Resize, resize_lnr);
if (window_is_dialog) {
shell.addListener(SWT.Traverse, new Swt_lnr_traverse());
}
}
public Display UnderDisplay() {return display;} private Display display;
public Shell UnderShell() {return shell;} private Shell shell;
@Override public Control Under_control() {return shell;}
@Override public Composite Under_composite() {return shell;}
@Override public Control Under_menu_control() {return shell;}
public Swt_win(Shell owner) {ctor(Bool_.Y, new Shell(owner, SWT.RESIZE | SWT.DIALOG_TRIM), owner.getDisplay());}
public Swt_win(Display display) {ctor(Bool_.N, new Shell(display), display); }
public void ShowWin() {shell.setVisible(true);}
public void HideWin() {shell.setVisible(false);}
public boolean Maximized() {return shell.getMaximized();} public void Maximized_(boolean v) {shell.setMaximized(v);}
public boolean Minimized() {return shell.getMinimized();} public void Minimized_(boolean v) {shell.setMinimized(v);}
public void CloseWin() {shell.close();}
public boolean Pin() {return pin;}
public void Pin_set(boolean val) {
// shell.setAlwaysOnTop(val);
pin = val;
} boolean pin = false;
public IconAdp IconWin() {return icon;} IconAdp icon;
public void IconWin_set(IconAdp i) {
if (i == null || i.Url() == Io_url_.Empty) return;
icon = i;
Image image = null;
try {
image = new Image(display, new FileInputStream(i.Url().Xto_api()));
} catch (FileNotFoundException e1) {e1.printStackTrace();}
shell.setImage(image);
}
public void OpenedCmd_set(Gfo_invk_cmd v) {when_loaded_cmd = v;} private Gfo_invk_cmd when_loaded_cmd = Gfo_invk_cmd.Noop;
public void Opened() {when_loaded_cmd.Exec();}
public GxwCore_base Core() {return ctrl_mgr;} private GxwCore_base ctrl_mgr;
public GxwCbkHost Host() {return host;} public void Host_set(GxwCbkHost host) {this.host = host;} private GxwCbkHost host = GxwCbkHost_.Null;
public String TextVal() {return shell.getText();}
public void TextVal_set(String v) {shell.setText(v);}
public Object Invk(GfsCtx ctx, int ikey, String k, GfoMsg m) {return this;}
public void SendKeyDown(IptKey key) {}
public void SendMouseMove(int x, int y) {}
public void SendMouseDown(IptMouseBtn btn) {}
//public void windowActivated(WindowEvent e) {}
//public void windowClosed(WindowEvent e) {}
//public void windowClosing(WindowEvent e) {host.DisposeCbk();}
//public void windowDeactivated(WindowEvent e) {}
//public void windowDeiconified(WindowEvent e) {host.SizeChangedCbk();}
//public void windowIconified(WindowEvent e) {host.SizeChangedCbk();}
//public void windowOpened(WindowEvent e) {when_loaded_cmd.Invk();}
//@Override public void processKeyEvent(KeyEvent e) {if (GxwCbkHost_.ExecKeyEvent(host, e)) super.processKeyEvent(e);}
//@Override public void processMouseEvent(MouseEvent e) {if (GxwCbkHost_.ExecMouseEvent(host, e)) super.processMouseEvent(e);}
//@Override public void processMouseWheelEvent(MouseWheelEvent e) {if (GxwCbkHost_.ExecMouseWheel(host, e)) super.processMouseWheelEvent(e);}
//@Override public void processMouseMotionEvent(MouseEvent e) {if (host.MouseMoveCbk(IptEvtDataMouse.new_(IptMouseBtn_.None, IptMouseWheel_.None, e.getX(), e.getY()))) super.processMouseMotionEvent(e);}
//@Override public void paint(Graphics g) {
// if (host.PaintCbk(PaintArgs.new_(GfxAdpBase.new_((Graphics2D)g), RectAdp_.Zero))) // ClipRect not used by any clients; implement when necessary
// super.paint(g);
//}
public void EnableDoubleBuffering() {}
public void TaskbarVisible_set(boolean val) {} public void TaskbarParkingWindowFix(GxwElem form) {}
void ctor_GxwForm() {
// this.setLayout(null); // use gfui layout
// this.ctrl_mgr.BackColor_set(ColorAdp_.White); // default form backColor to white
// this.setUndecorated(true); // remove icon, titleBar, minimize, maximize, close, border
// this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // JAVA: cannot cancel alt+f4; set Close to noop, and manually control closing by calling this.CloseForm
// enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
// this.addWindowListener(this);
// GxwBoxListener lnr = new GxwBoxListener(this);
// this.addComponentListener(lnr);
// this.addFocusListener(lnr);
}
}
//#}
| agpl-3.0 |
Orichievac/FallenGalaxy | src-client/fr/fg/client/map/item/FakeWardItem.java | 2572 | /*
Copyright 2010 Jeremie Gottero
This file is part of Fallen Galaxy.
Fallen Galaxy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fallen Galaxy 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Fallen Galaxy. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.fg.client.map.item;
import fr.fg.client.data.FakeWardData;
import fr.fg.client.map.UIItemRenderingHints;
public class FakeWardItem extends AnimatedItem {
// ------------------------------------------------------- CONSTANTES -- //
// -------------------------------------------------------- ATTRIBUTS -- //
private FakeWardData fakeWardData;
// ---------------------------------------------------- CONSTRUCTEURS -- //
public FakeWardItem(FakeWardData fakeWardData, UIItemRenderingHints hints) {
super(fakeWardData.getX(), fakeWardData.getY(), hints);
this.fakeWardData = fakeWardData;
getElement().setClassName("ward ward-" +
fakeWardData.getType().replace("_", "-")); //$NON-NLS-1$
getElement().setAttribute("unselectable", "on"); //$NON-NLS-1$ //$NON-NLS-2$
getElement().setInnerHTML("<div class=\"setupMask\"></div>");
updateData(fakeWardData);
}
// --------------------------------------------------------- METHODES -- //
@Override
public void onDataUpdate(Object newData) {
FakeWardData newFakeWardData = (FakeWardData) newData;
if (fakeWardData.getX() != newFakeWardData.getX() ||
fakeWardData.getY() != newFakeWardData.getY())
setLocation(newFakeWardData.getX(), newFakeWardData.getY());
if (fakeWardData.isValid() != newFakeWardData.isValid())
updateData(newFakeWardData);
fakeWardData = newFakeWardData;
}
@Override
public void onDestroy() {
super.onDestroy();
fakeWardData = null;
}
@Override
public int hashCode() {
return 1;
}
// ------------------------------------------------- METHODES PRIVEES -- //
private void updateData(FakeWardData fakeWardData) {
if (fakeWardData.isValid())
getElement().getFirstChildElement().setClassName("setupMask");
else
getElement().getFirstChildElement().setClassName("setupMask invalid");
}
}
| agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Core | ejb-core/pdc/src/main/java/com/silverpeas/pdc/ejb/PdcBmHome.java | 1430 | /**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.pdc.ejb;
import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import java.rmi.RemoteException;
/**
* Interface declaration
* @author neysseri
*/
public interface PdcBmHome extends EJBHome {
PdcBm create() throws RemoteException, CreateException;
}
| agpl-3.0 |
eriklupander/ifkstat | src/main/java/se/ifkgoteborg/stat/controller/PlayerPositionStatsDTO.java | 878 | package se.ifkgoteborg.stat.controller;
public class PlayerPositionStatsDTO {
private Long playerId;
private String positionName;
private String formationName;
private Integer games;
private Integer goals;
public Long getPlayerId() {
return playerId;
}
public void setPlayerId(Long playerId) {
this.playerId = playerId;
}
public String getPositionName() {
return positionName;
}
public void setPositionName(String positionName) {
this.positionName = positionName;
}
public String getFormationName() {
return formationName;
}
public void setFormationName(String formationName) {
this.formationName = formationName;
}
public Integer getGames() {
return games;
}
public void setGames(Integer games) {
this.games = games;
}
public Integer getGoals() {
return goals;
}
public void setGoals(Integer goals) {
this.goals = goals;
}
}
| agpl-3.0 |
moskiteau/KalturaGeneratedAPIClientsJava | src/com/kaltura/client/services/KalturaFileAssetService.java | 5856 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2015 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.services;
import com.kaltura.client.KalturaClient;
import com.kaltura.client.KalturaServiceBase;
import com.kaltura.client.types.*;
import org.w3c.dom.Element;
import com.kaltura.client.utils.ParseUtils;
import com.kaltura.client.KalturaParams;
import com.kaltura.client.KalturaApiException;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
* @date Mon, 10 Aug 15 02:02:11 -0400
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
/** Manage file assets */
@SuppressWarnings("serial")
public class KalturaFileAssetService extends KalturaServiceBase {
public KalturaFileAssetService(KalturaClient client) {
this.kalturaClient = client;
}
/** Add new file asset */
public KalturaFileAsset add(KalturaFileAsset fileAsset) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("fileAsset", fileAsset);
this.kalturaClient.queueServiceCall("fileasset", "add", kparams, KalturaFileAsset.class);
if (this.kalturaClient.isMultiRequest())
return null;
Element resultXmlElement = this.kalturaClient.doQueue();
return ParseUtils.parseObject(KalturaFileAsset.class, resultXmlElement);
}
/** Get file asset by id */
public KalturaFileAsset get(int id) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("id", id);
this.kalturaClient.queueServiceCall("fileasset", "get", kparams, KalturaFileAsset.class);
if (this.kalturaClient.isMultiRequest())
return null;
Element resultXmlElement = this.kalturaClient.doQueue();
return ParseUtils.parseObject(KalturaFileAsset.class, resultXmlElement);
}
/** Update file asset by id */
public KalturaFileAsset update(int id, KalturaFileAsset fileAsset) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("id", id);
kparams.add("fileAsset", fileAsset);
this.kalturaClient.queueServiceCall("fileasset", "update", kparams, KalturaFileAsset.class);
if (this.kalturaClient.isMultiRequest())
return null;
Element resultXmlElement = this.kalturaClient.doQueue();
return ParseUtils.parseObject(KalturaFileAsset.class, resultXmlElement);
}
/** Delete file asset by id */
public void delete(int id) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("id", id);
this.kalturaClient.queueServiceCall("fileasset", "delete", kparams);
if (this.kalturaClient.isMultiRequest())
return ;
this.kalturaClient.doQueue();
}
/** Serve file asset by id */
public String serve(int id) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("id", id);
this.kalturaClient.queueServiceCall("fileasset", "serve", kparams);
return this.kalturaClient.serve();
}
/** Set content of file asset */
public KalturaFileAsset setContent(String id, KalturaContentResource contentResource) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("id", id);
kparams.add("contentResource", contentResource);
this.kalturaClient.queueServiceCall("fileasset", "setContent", kparams, KalturaFileAsset.class);
if (this.kalturaClient.isMultiRequest())
return null;
Element resultXmlElement = this.kalturaClient.doQueue();
return ParseUtils.parseObject(KalturaFileAsset.class, resultXmlElement);
}
public KalturaFileAssetListResponse list(KalturaFileAssetFilter filter) throws KalturaApiException {
return this.list(filter, null);
}
/** List file assets by filter and pager */
public KalturaFileAssetListResponse list(KalturaFileAssetFilter filter, KalturaFilterPager pager) throws KalturaApiException {
KalturaParams kparams = new KalturaParams();
kparams.add("filter", filter);
kparams.add("pager", pager);
this.kalturaClient.queueServiceCall("fileasset", "list", kparams, KalturaFileAssetListResponse.class);
if (this.kalturaClient.isMultiRequest())
return null;
Element resultXmlElement = this.kalturaClient.doQueue();
return ParseUtils.parseObject(KalturaFileAssetListResponse.class, resultXmlElement);
}
}
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/neural/feedforward/FullyConnectedFeedforwardBrain.java | 4567 | /******************************************************************************
* *
* Copyright: (c) Syncleus, Inc. *
* *
* You may redistribute and modify this source code under the terms and *
* conditions of the Open Source Community License - Type C version 1.0 *
* or any later version as published by Syncleus, Inc. at www.syncleus.com. *
* There should be a copy of the license included with this file. If a copy *
* of the license is not included you are granted no right to distribute or *
* otherwise use this file except through a legal and valid license. You *
* should also contact Syncleus, Inc. at the information below if you cannot *
* find a license: *
* *
* Syncleus, Inc. *
* 2604 South 12th Street *
* Philadelphia, PA 19148 *
* *
******************************************************************************/
package syncleus.dann.neural.feedforward;
import java.util.concurrent.ExecutorService;
import syncleus.dann.graph.AbstractBidirectedAdjacencyGraph;
import syncleus.dann.neural.Synapse;
import syncleus.dann.neural.feedforward.graph.AbstractFullyConnectedFeedforwardBrain;
import syncleus.dann.neural.feedforward.graph.BackpropNeuron;
import syncleus.dann.neural.feedforward.graph.InputBackpropNeuron;
import syncleus.dann.neural.feedforward.graph.OutputBackpropNeuron;
import syncleus.dann.neural.feedforward.graph.SimpleBackpropNeuron;
import syncleus.dann.neural.feedforward.graph.SimpleInputBackpropNeuron;
import syncleus.dann.neural.feedforward.graph.SimpleOutputBackpropNeuron;
import syncleus.dann.neural.util.activation.DannActivationFunction;
public final class FullyConnectedFeedforwardBrain<IN extends InputBackpropNeuron, ON extends OutputBackpropNeuron, N extends BackpropNeuron, S extends Synapse<N>>
extends AbstractFullyConnectedFeedforwardBrain<IN, ON, N, S> {
private static final long serialVersionUID = 3666884827880527998L;
private final double learningRate;
private final DannActivationFunction activationFunction;
/**
* Uses the given threadExecutor for executing tasks.
*
* @param threadExecutor executor to use for executing tasks.
* @since 2.0
*/
public FullyConnectedFeedforwardBrain(final int[] neuronsPerLayer,
final double learningRate,
final DannActivationFunction activationFunction,
final ExecutorService threadExecutor) {
super(threadExecutor);
this.learningRate = learningRate;
this.activationFunction = activationFunction;
this.initalizeNetwork(neuronsPerLayer);
}
/**
* Default constructor initializes a default threadExecutor based on the
* number of processors.
*
* @since 2.0
*/
public FullyConnectedFeedforwardBrain(final int[] neuronsPerLayer,
final double learningRate,
final DannActivationFunction activationFunction) {
super();
this.learningRate = learningRate;
this.activationFunction = activationFunction;
this.initalizeNetwork(neuronsPerLayer);
}
@Override
protected N createNeuron(final int layer, final int index) {
final BackpropNeuron neuron;
if (layer == 0) {
neuron = new SimpleInputBackpropNeuron(this);
} else if (layer >= (getLayerCount() - 1)) {
neuron = new SimpleOutputBackpropNeuron(this, activationFunction,
learningRate);
} else {
neuron = new SimpleBackpropNeuron(this, activationFunction,
learningRate);
}
// TODO fix typing
return (N) neuron;
}
@Override
public AbstractBidirectedAdjacencyGraph<N, S> clone() {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/MPweixinManagerJaxrsFilter.java | 303 | package com.x.program.center.jaxrs;
import com.x.base.core.project.jaxrs.CipherManagerJaxrsFilter;
import javax.servlet.annotation.WebFilter;
@WebFilter(urlPatterns = "/jaxrs/mpweixin/menu/*", asyncSupported = true)
public class MPweixinManagerJaxrsFilter extends CipherManagerJaxrsFilter {
}
| agpl-3.0 |
GrowthcraftCE/Growthcraft-1.11 | src/main/java/growthcraft/core/api/schema/MultiFluidStackSchema.java | 5369 | package growthcraft.core.api.schema;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import growthcraft.core.api.CoreRegistry;
import growthcraft.core.api.definition.IMultiFluidStacks;
import growthcraft.core.api.fluids.FluidTag;
import growthcraft.core.api.fluids.FluidTest;
import growthcraft.core.api.fluids.GrowthcraftFluidUtils;
import growthcraft.core.api.fluids.MultiFluidStacks;
import growthcraft.core.api.fluids.TaggedFluidStacks;
import growthcraft.core.api.utils.StringUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
public class MultiFluidStackSchema implements ICommentable, IValidatable, IMultiFluidStacks
{
public String name;
public List<String> names = new ArrayList<String>();
public List<String> inclusion_tags = new ArrayList<String>();
public List<String> exclusion_tags = new ArrayList<String>();
public String comment = "";
public int amount;
public MultiFluidStackSchema(@Nonnull IMultiFluidStacks fluidStacks)
{
if (fluidStacks instanceof TaggedFluidStacks)
{
final TaggedFluidStacks taggedStack = (TaggedFluidStacks)fluidStacks;
inclusion_tags.addAll(taggedStack.getTags());
exclusion_tags.addAll(taggedStack.getExclusionTags());
}
else if (fluidStacks instanceof MultiFluidStacks)
{
names.addAll(((MultiFluidStacks)fluidStacks).getNames());
}
else
{
throw new IllegalArgumentException("Expected a TaggedFluidStacks or a MultiFluidStacks");
}
this.amount = fluidStacks.getAmount();
}
public MultiFluidStackSchema(@Nonnull FluidStack fluidStack)
{
this.name = fluidStack.getFluid().getName();
this.amount = fluidStack.amount;
}
public MultiFluidStackSchema() {}
@Override
public void setComment(String comm)
{
this.comment = comm;
}
@Override
public String getComment()
{
return comment;
}
private List<FluidTag> expandTagNames(@Nonnull List<String> tagNames)
{
return CoreRegistry.instance().fluidTags().expandTagNames(tagNames);
}
public List<FluidTag> expandInclusionTags()
{
return expandTagNames(inclusion_tags);
}
public List<FluidTag> expandExclusionTags()
{
return expandTagNames(exclusion_tags);
}
public Collection<Fluid> getFluidsByTags()
{
final Set<Fluid> result = new HashSet<Fluid>();
final Collection<Fluid> fluids = CoreRegistry.instance().fluidDictionary().getFluidsByTags(expandInclusionTags());
final Collection<Fluid> exfluids = CoreRegistry.instance().fluidDictionary().getFluidsByTags(expandExclusionTags());
result.addAll(fluids);
result.removeAll(exfluids);
return result;
}
public Collection<Fluid> getFluidsByNames()
{
final Set<Fluid> result = new HashSet<Fluid>();
if (name != null)
{
final Fluid fluid = FluidRegistry.getFluid(name);
if (fluid != null)
{
result.add(fluid);
}
}
for (String fluidName : names)
{
final Fluid fluid = FluidRegistry.getFluid(fluidName);
if (fluid != null)
{
result.add(fluid);
}
}
return result;
}
public Collection<Fluid> getFluids()
{
final Set<Fluid> result = new HashSet<Fluid>();
result.addAll(getFluidsByTags());
result.addAll(getFluidsByNames());
return result;
}
@Override
public int getAmount()
{
return amount;
}
@Override
public List<FluidStack> getFluidStacks()
{
final List<FluidStack> stacks = new ArrayList<FluidStack>();
for (Fluid fluid : getFluids())
{
stacks.add(new FluidStack(fluid, amount));
}
return stacks;
}
public List<IMultiFluidStacks> getMultiFluidStacks()
{
final List<IMultiFluidStacks> result = new ArrayList<IMultiFluidStacks>();
result.add(new TaggedFluidStacks(amount, inclusion_tags, exclusion_tags));
final List<FluidStack> fluidStacks = new ArrayList<FluidStack>();
for (Fluid fluid : getFluidsByNames())
{
fluidStacks.add(new FluidStack(fluid, amount));
}
result.add(new MultiFluidStacks(fluidStacks));
return result;
}
@Override
public boolean containsFluid(Fluid expectedFluid)
{
if (FluidTest.isValid(expectedFluid))
{
for (Fluid fluid : getFluids())
{
if (fluid == expectedFluid) return true;
}
}
return false;
}
@Override
public boolean containsFluidStack(FluidStack stack)
{
if (FluidTest.isValid(stack))
{
final Fluid expected = stack.getFluid();
return containsFluid(expected);
}
return false;
}
@Override
public boolean isValid()
{
return !getFluids().isEmpty();
}
@Override
public boolean isInvalid()
{
return !isValid();
}
@Override
public String toString()
{
return String.format("Schema<MultiFluidStack>(comment: '%s', name: '%s', names: %s, inclusion_tags: %s, exclusion_tags: %s, amount: %d)",
StringUtils.inspect(comment),
StringUtils.inspect(name),
names, inclusion_tags, exclusion_tags, amount);
}
public static MultiFluidStackSchema newWithTags(int amount, String... tags)
{
final MultiFluidStackSchema schema = new MultiFluidStackSchema();
for (String tag : tags)
{
schema.inclusion_tags.add(tag);
}
schema.amount = amount;
return schema;
}
@Override
public List<ItemStack> getItemStacks()
{
return GrowthcraftFluidUtils.getFluidContainers(getFluidStacks());
}
}
| agpl-3.0 |
ProtocolSupport/ProtocolSupport | src/protocolsupport/protocol/packet/middle/impl/clientbound/play/v_13_14r1_14r2_15_16r1_16r2_17r1_17r2_18/QueryNBTResponse.java | 1827 | package protocolsupport.protocol.packet.middle.impl.clientbound.play.v_13_14r1_14r2_15_16r1_16r2_17r1_17r2_18;
import protocolsupport.protocol.packet.ClientBoundPacketData;
import protocolsupport.protocol.packet.ClientBoundPacketType;
import protocolsupport.protocol.packet.middle.base.clientbound.play.MiddleQueryNBTResponse;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV13;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV14r1;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV14r2;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV15;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV16r1;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV16r2;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV17r1;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV17r2;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV18;
public class QueryNBTResponse extends MiddleQueryNBTResponse implements
IClientboundMiddlePacketV13,
IClientboundMiddlePacketV14r1,
IClientboundMiddlePacketV14r2,
IClientboundMiddlePacketV15,
IClientboundMiddlePacketV16r1,
IClientboundMiddlePacketV16r2,
IClientboundMiddlePacketV17r1,
IClientboundMiddlePacketV17r2,
IClientboundMiddlePacketV18 {
public QueryNBTResponse(IMiddlePacketInit init) {
super(init);
}
@Override
protected void write() {
ClientBoundPacketData querynbtresponse = ClientBoundPacketData.create(ClientBoundPacketType.PLAY_QUERY_NBT_RESPONSE);
querynbtresponse.writeBytes(data);
io.writeClientbound(querynbtresponse);
}
}
| agpl-3.0 |
FullMetal210/milton2 | milton-client-app/src/main/java/bradswebdavclient/DragImage.java | 3601 | /*
* Copyright 2012 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 bradswebdavclient;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
public class DragImage {
public static void main(String args[]) {
JFrame frame = new JFrame("Drag Image");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
final Clipboard clipboard =
frame.getToolkit().getSystemClipboard();
final JLabel label = new JLabel();
// Icon icon = new ImageIcon("/home/j2ee/Desktop/war.103.gif");
// label.setIcon(icon);
label.setTransferHandler(new ImageSelection());
MouseListener mouseListener =
new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent comp = (JComponent) e.getSource();
TransferHandler handler =
comp.getTransferHandler();
handler.exportAsDrag(
comp, e, TransferHandler.COPY);
}
};
label.addMouseListener(mouseListener);
JScrollPane pane = new JScrollPane(label);
contentPane.add(pane, BorderLayout.CENTER);
JButton copy = new JButton("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// fire TransferHandler's built-in copy
// action with a new actionEvent having
// "label" as the source
Action copyAction =
TransferHandler.getCopyAction();
copyAction.actionPerformed(
new ActionEvent(
label, ActionEvent.ACTION_PERFORMED,
(String) copyAction.getValue(Action.NAME),
EventQueue.getMostRecentEventTime(),
0));
}
});
JButton clear = new JButton("Clear");
clear.addActionListener(new ActionListener() {
public void actionPerformed(
ActionEvent actionEvent) {
label.setIcon(null);
}
});
JButton paste = new JButton("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(
ActionEvent actionEvent) {
// use TransferHandler's built-in
// paste action
Action pasteAction =
TransferHandler.getPasteAction();
pasteAction.actionPerformed(
new ActionEvent(label,
ActionEvent.ACTION_PERFORMED,
(String) pasteAction.getValue(Action.NAME),
EventQueue.getMostRecentEventTime(),
0));
}
});
JPanel p = new JPanel();
p.add(copy);
p.add(clear);
p.add(paste);
contentPane.add(p, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.show();
}
}
| agpl-3.0 |
rapidminer/rapidminer-studio | src/main/java/com/rapidminer/operator/preprocessing/transformation/aggregation/CountPercentageAggregationFunction.java | 2039 | /**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.transformation.aggregation;
import com.rapidminer.example.Attribute;
/**
* This function first behaves like {@link CountAggregationFunction}, but it delivers percentages of
* the total count instead of absolute values. E.g. {@link SumAggregationFunction} delivers [2, 5,
* 3] this function would deliver [20, 50, 30]
*
* @author Marco Boeck
*
*/
public class CountPercentageAggregationFunction extends AbstractCountRatioAggregationFunction {
public static final String FUNCTION_COUNT_PERCENTAGE = "percentage_count";
public CountPercentageAggregationFunction(Attribute sourceAttribute, boolean ignoreMissings, boolean countOnlyDisctinct) {
super(sourceAttribute, ignoreMissings, countOnlyDisctinct, FUNCTION_COUNT_PERCENTAGE);
}
public CountPercentageAggregationFunction(Attribute sourceAttribute, boolean ignoreMissings, boolean countOnlyDisctinct,
String functionName, String separatorOpen, String separatorClose) {
super(sourceAttribute, ignoreMissings, countOnlyDisctinct, functionName, separatorOpen, separatorClose);
}
@Override
public double getRatioFactor() {
return 100.0;
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | ejb-core/formtemplate/src/main/java/com/silverpeas/workflow/engine/instance/WorkingUser.java | 7226 | /**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.workflow.engine.instance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.silverpeas.util.StringUtil;
import com.silverpeas.workflow.api.WorkflowException;
import com.silverpeas.workflow.api.instance.Actor;
import com.silverpeas.workflow.api.model.State;
import com.silverpeas.workflow.api.user.User;
import com.silverpeas.workflow.engine.AbstractReferrableObject;
import com.silverpeas.workflow.engine.WorkflowHub;
/**
* @table SB_Workflow_WorkingUser
* @depends com.silverpeas.workflow.engine.instance.ProcessInstanceImpl
* @key-generator MAX
*/
public class WorkingUser extends AbstractReferrableObject {
/**
* Used for persistence
* @primary-key
* @field-name id
* @field-type string
* @sql-type integer
*/
private String id = null;
/**
* @field-name processInstance
* @field-type com.silverpeas.workflow.engine.instance.ProcessInstanceImpl
* @sql-name instanceId
*/
private ProcessInstanceImpl processInstance = null;
/**
* @field-name userId
*/
private String userId = null;
/**
* @field-name usersRole
*/
private String usersRole = null;
/**
* @field-name state
*/
private String state = null;
/**
* @field-name role
*/
private String role = null;
/**
* @field-name groupId
*/
private String groupId = null;
/**
* Default Constructor
*/
public WorkingUser() {
}
/**
* For persistence in database Get this object id
* @return this object id
*/
public String getId() {
return id;
}
/**
* For persistence in database Set this object id
* @param this object id
*/
public void setId(String id) {
this.id = id;
}
/**
* Get state name for which user is affected
* @return state name
*/
public String getState() {
return (state == null) ? "" : state;
}
/**
* Set state name for which user is affected
* @param state state name
*/
public void setState(String state) {
this.state = state;
}
/**
* Get state role for which user is affected
* @return state role
*/
public String getRole() {
return role;
}
/**
* Get state role for which user is affected
* @return state role
*/
public List<String> getRoles() {
return Arrays.asList(role.split(":"));
}
/**
* Set state role for which user is affected
* @param state state role
*/
public void setRole(String role) {
this.role = role;
}
/**
* Get the user id
* @return user id
*/
public String getUserId() {
return userId;
}
/**
* Set the user id
* @param userId user id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Get the user role
* @return user role name
*/
public String getUsersRole() {
return usersRole;
}
/**
* Set the user role
* @param usersRole role
*/
public void setUsersRole(String usersRole) {
this.usersRole = usersRole;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* Get the instance for which user is affected
* @return instance
*/
public ProcessInstanceImpl getProcessInstance() {
return processInstance;
}
/**
* Set the instance for which user is affected
* @param processInstance instance
*/
public void setProcessInstance(ProcessInstanceImpl processInstance) {
this.processInstance = processInstance;
}
/**
* Converts WorkingUser to User
* @return an object implementing User interface and containing user details
*/
public User toUser() throws WorkflowException {
return WorkflowHub.getUserManager().getUser(this.getUserId());
}
/**
* Converts WorkingUser to Actor
* @return an object implementing Actor interface
*/
public Actor toActor() throws WorkflowException {
State state = processInstance.getProcessModel().getState(this.state);
User user = WorkflowHub.getUserManager().getUser(this.getUserId());
return new ActorImpl(user, role, state);
}
/**
* Converts WorkingUser to Actors
* @return an object implementing Actor interface
*/
public Collection<Actor> toActors() throws WorkflowException {
State state = processInstance.getProcessModel().getState(this.state);
Collection<Actor> actors = new ArrayList<Actor>();
// first add user by id
if (this.getUserId() != null) {
User user = WorkflowHub.getUserManager().getUser(this.getUserId());
actors.add(new ActorImpl(user, role, state));
}
// then add users by group or role
if (StringUtil.isDefined(getGroupId())) {
User[] users =
WorkflowHub.getUserManager().getUsersInGroup(getGroupId());
for (User anUser : users) {
actors.add(new ActorImpl(anUser, role, state));
}
} else {
// then add users by role
if (this.usersRole != null) {
User[] users =
WorkflowHub.getUserManager().getUsersInRole(usersRole, processInstance.getModelId());
for (User anUser : users) {
actors.add(new ActorImpl(anUser, role, state));
}
}
}
return actors;
}
/**
* Get User information from an array of workingUsers
* @param workingUsers an array of WorkingUser objects
* @return an array of objects implementing User interface and containing user details
*/
static public User[] toUser(WorkingUser[] workingUsers)
throws WorkflowException {
String[] userIds = new String[workingUsers.length];
for (int i = 0; i < workingUsers.length; i++) {
userIds[i] = workingUsers[i].getUserId();
}
return WorkflowHub.getUserManager().getUsers(userIds);
}
/**
* This method has to be implemented by the referrable object it has to compute the unique key
* @return The unique key.
*/
public String getKey() {
return (this.getUserId() + "--" + this.getState() + "--" + this.getRole() + "--" + this
.getUsersRole());
}
} | agpl-3.0 |
TelefonicaED/liferaylms-portlet | docroot/WEB-INF/src/com/liferay/lms/service/persistence/TestAnswerPersistenceImpl.java | 76081 | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library 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 2.1 of the License, or (at your option)
* any later version.
*
* This library 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.
*/
package com.liferay.lms.service.persistence;
import com.liferay.lms.NoSuchTestAnswerException;
import com.liferay.lms.model.TestAnswer;
import com.liferay.lms.model.impl.TestAnswerImpl;
import com.liferay.lms.model.impl.TestAnswerModelImpl;
import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The persistence implementation for the test answer service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author TLS
* @see TestAnswerPersistence
* @see TestAnswerUtil
* @generated
*/
public class TestAnswerPersistenceImpl extends BasePersistenceImpl<TestAnswer>
implements TestAnswerPersistence {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link TestAnswerUtil} to access the test answer persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
public static final String FINDER_CLASS_NAME_ENTITY = TestAnswerImpl.class.getName();
public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List1";
public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List2";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUuid",
new String[] {
String.class.getName(),
"java.lang.Integer", "java.lang.Integer",
"com.liferay.portal.kernel.util.OrderByComparator"
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid",
new String[] { String.class.getName() },
TestAnswerModelImpl.UUID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid",
new String[] { String.class.getName() });
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_AC = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByac",
new String[] {
Long.class.getName(),
"java.lang.Integer", "java.lang.Integer",
"com.liferay.portal.kernel.util.OrderByComparator"
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_AC = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByac",
new String[] { Long.class.getName() },
TestAnswerModelImpl.ACTID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_AC = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByac",
new String[] { Long.class.getName() });
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_Q = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByq",
new String[] {
Long.class.getName(),
"java.lang.Integer", "java.lang.Integer",
"com.liferay.portal.kernel.util.OrderByComparator"
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_Q = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByq",
new String[] { Long.class.getName() },
TestAnswerModelImpl.QUESTIONID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_Q = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByq",
new String[] { Long.class.getName() });
public static final FinderPath FINDER_PATH_FETCH_BY_UUID_ACTID = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_ENTITY, "fetchByUuid_ActId",
new String[] { String.class.getName(), Long.class.getName() },
TestAnswerModelImpl.UUID_COLUMN_BITMASK |
TestAnswerModelImpl.ACTID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_ACTID = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid_ActId",
new String[] { String.class.getName(), Long.class.getName() });
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, TestAnswerImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
/**
* Caches the test answer in the entity cache if it is enabled.
*
* @param testAnswer the test answer
*/
public void cacheResult(TestAnswer testAnswer) {
EntityCacheUtil.putResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, testAnswer.getPrimaryKey(), testAnswer);
FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
new Object[] {
testAnswer.getUuid(), Long.valueOf(testAnswer.getActId())
}, testAnswer);
testAnswer.resetOriginalValues();
}
/**
* Caches the test answers in the entity cache if it is enabled.
*
* @param testAnswers the test answers
*/
public void cacheResult(List<TestAnswer> testAnswers) {
for (TestAnswer testAnswer : testAnswers) {
if (EntityCacheUtil.getResult(
TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, testAnswer.getPrimaryKey()) == null) {
cacheResult(testAnswer);
}
else {
testAnswer.resetOriginalValues();
}
}
}
/**
* Clears the cache for all test answers.
*
* <p>
* The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache() {
if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
CacheRegistryUtil.clear(TestAnswerImpl.class.getName());
}
EntityCacheUtil.clearCache(TestAnswerImpl.class.getName());
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
/**
* Clears the cache for the test answer.
*
* <p>
* The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache(TestAnswer testAnswer) {
EntityCacheUtil.removeResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, testAnswer.getPrimaryKey());
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
clearUniqueFindersCache(testAnswer);
}
@Override
public void clearCache(List<TestAnswer> testAnswers) {
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
for (TestAnswer testAnswer : testAnswers) {
EntityCacheUtil.removeResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, testAnswer.getPrimaryKey());
clearUniqueFindersCache(testAnswer);
}
}
protected void clearUniqueFindersCache(TestAnswer testAnswer) {
FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
new Object[] {
testAnswer.getUuid(), Long.valueOf(testAnswer.getActId())
});
}
/**
* Creates a new test answer with the primary key. Does not add the test answer to the database.
*
* @param answerId the primary key for the new test answer
* @return the new test answer
*/
public TestAnswer create(long answerId) {
TestAnswer testAnswer = new TestAnswerImpl();
testAnswer.setNew(true);
testAnswer.setPrimaryKey(answerId);
String uuid = PortalUUIDUtil.generate();
testAnswer.setUuid(uuid);
return testAnswer;
}
/**
* Removes the test answer with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param answerId the primary key of the test answer
* @return the test answer that was removed
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer remove(long answerId)
throws NoSuchTestAnswerException, SystemException {
return remove(Long.valueOf(answerId));
}
/**
* Removes the test answer with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param primaryKey the primary key of the test answer
* @return the test answer that was removed
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public TestAnswer remove(Serializable primaryKey)
throws NoSuchTestAnswerException, SystemException {
Session session = null;
try {
session = openSession();
TestAnswer testAnswer = (TestAnswer)session.get(TestAnswerImpl.class,
primaryKey);
if (testAnswer == null) {
if (_log.isWarnEnabled()) {
_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchTestAnswerException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(testAnswer);
}
catch (NoSuchTestAnswerException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
@Override
protected TestAnswer removeImpl(TestAnswer testAnswer)
throws SystemException {
testAnswer = toUnwrappedModel(testAnswer);
Session session = null;
try {
session = openSession();
BatchSessionUtil.delete(session, testAnswer);
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
clearCache(testAnswer);
return testAnswer;
}
@Override
public TestAnswer updateImpl(com.liferay.lms.model.TestAnswer testAnswer,
boolean merge) throws SystemException {
testAnswer = toUnwrappedModel(testAnswer);
boolean isNew = testAnswer.isNew();
TestAnswerModelImpl testAnswerModelImpl = (TestAnswerModelImpl)testAnswer;
if (Validator.isNull(testAnswer.getUuid())) {
String uuid = PortalUUIDUtil.generate();
testAnswer.setUuid(uuid);
}
Session session = null;
try {
session = openSession();
BatchSessionUtil.update(session, testAnswer, merge);
testAnswer.setNew(false);
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
if (isNew || !TestAnswerModelImpl.COLUMN_BITMASK_ENABLED) {
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
else {
if ((testAnswerModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
testAnswerModelImpl.getOriginalUuid()
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
args = new Object[] { testAnswerModelImpl.getUuid() };
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
}
if ((testAnswerModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_AC.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
Long.valueOf(testAnswerModelImpl.getOriginalActId())
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_AC, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_AC,
args);
args = new Object[] { Long.valueOf(testAnswerModelImpl.getActId()) };
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_AC, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_AC,
args);
}
if ((testAnswerModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_Q.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
Long.valueOf(testAnswerModelImpl.getOriginalQuestionId())
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_Q, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_Q,
args);
args = new Object[] {
Long.valueOf(testAnswerModelImpl.getQuestionId())
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_Q, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_Q,
args);
}
}
EntityCacheUtil.putResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, testAnswer.getPrimaryKey(), testAnswer);
if (isNew) {
FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
new Object[] {
testAnswer.getUuid(), Long.valueOf(testAnswer.getActId())
}, testAnswer);
}
else {
if ((testAnswerModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_ACTID.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
testAnswerModelImpl.getOriginalUuid(),
Long.valueOf(testAnswerModelImpl.getOriginalActId())
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID_ACTID,
args);
FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
args);
FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
new Object[] {
testAnswer.getUuid(),
Long.valueOf(testAnswer.getActId())
}, testAnswer);
}
}
return testAnswer;
}
protected TestAnswer toUnwrappedModel(TestAnswer testAnswer) {
if (testAnswer instanceof TestAnswerImpl) {
return testAnswer;
}
TestAnswerImpl testAnswerImpl = new TestAnswerImpl();
testAnswerImpl.setNew(testAnswer.isNew());
testAnswerImpl.setPrimaryKey(testAnswer.getPrimaryKey());
testAnswerImpl.setUuid(testAnswer.getUuid());
testAnswerImpl.setAnswerId(testAnswer.getAnswerId());
testAnswerImpl.setQuestionId(testAnswer.getQuestionId());
testAnswerImpl.setActId(testAnswer.getActId());
testAnswerImpl.setPrecedence(testAnswer.getPrecedence());
testAnswerImpl.setAnswer(testAnswer.getAnswer());
testAnswerImpl.setIsCorrect(testAnswer.isIsCorrect());
testAnswerImpl.setFeedbackCorrect(testAnswer.getFeedbackCorrect());
testAnswerImpl.setFeedbacknocorrect(testAnswer.getFeedbacknocorrect());
return testAnswerImpl;
}
/**
* Returns the test answer with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
*
* @param primaryKey the primary key of the test answer
* @return the test answer
* @throws com.liferay.portal.NoSuchModelException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public TestAnswer findByPrimaryKey(Serializable primaryKey)
throws NoSuchModelException, SystemException {
return findByPrimaryKey(((Long)primaryKey).longValue());
}
/**
* Returns the test answer with the primary key or throws a {@link com.liferay.lms.NoSuchTestAnswerException} if it could not be found.
*
* @param answerId the primary key of the test answer
* @return the test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByPrimaryKey(long answerId)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByPrimaryKey(answerId);
if (testAnswer == null) {
if (_log.isWarnEnabled()) {
_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + answerId);
}
throw new NoSuchTestAnswerException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
answerId);
}
return testAnswer;
}
/**
* Returns the test answer with the primary key or returns <code>null</code> if it could not be found.
*
* @param primaryKey the primary key of the test answer
* @return the test answer, or <code>null</code> if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public TestAnswer fetchByPrimaryKey(Serializable primaryKey)
throws SystemException {
return fetchByPrimaryKey(((Long)primaryKey).longValue());
}
/**
* Returns the test answer with the primary key or returns <code>null</code> if it could not be found.
*
* @param answerId the primary key of the test answer
* @return the test answer, or <code>null</code> if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByPrimaryKey(long answerId)
throws SystemException {
TestAnswer testAnswer = (TestAnswer)EntityCacheUtil.getResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, answerId);
if (testAnswer == _nullTestAnswer) {
return null;
}
if (testAnswer == null) {
Session session = null;
boolean hasException = false;
try {
session = openSession();
testAnswer = (TestAnswer)session.get(TestAnswerImpl.class,
Long.valueOf(answerId));
}
catch (Exception e) {
hasException = true;
throw processException(e);
}
finally {
if (testAnswer != null) {
cacheResult(testAnswer);
}
else if (!hasException) {
EntityCacheUtil.putResult(TestAnswerModelImpl.ENTITY_CACHE_ENABLED,
TestAnswerImpl.class, answerId, _nullTestAnswer);
}
closeSession(session);
}
}
return testAnswer;
}
/**
* Returns all the test answers where uuid = ?.
*
* @param uuid the uuid
* @return the matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByUuid(String uuid) throws SystemException {
return findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the test answers where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @return the range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByUuid(String uuid, int start, int end)
throws SystemException {
return findByUuid(uuid, start, end, null);
}
/**
* Returns an ordered range of all the test answers where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByUuid(String uuid, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid, start, end, orderByComparator };
}
List<TestAnswer> list = (List<TestAnswer>)FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (TestAnswer testAnswer : list) {
if (!Validator.equals(uuid, testAnswer.getUuid())) {
list = null;
break;
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else {
if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
}
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (uuid != null) {
qPos.add(uuid);
}
list = (List<TestAnswer>)QueryUtil.list(q, getDialect(), start,
end);
}
catch (Exception e) {
throw processException(e);
}
finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
}
else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Returns the first test answer in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByUuid_First(String uuid,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByUuid_First(uuid, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the first test answer in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByUuid_First(String uuid,
OrderByComparator orderByComparator) throws SystemException {
List<TestAnswer> list = findByUuid(uuid, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last test answer in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByUuid_Last(String uuid,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByUuid_Last(uuid, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the last test answer in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByUuid_Last(String uuid,
OrderByComparator orderByComparator) throws SystemException {
int count = countByUuid(uuid);
List<TestAnswer> list = findByUuid(uuid, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the test answers before and after the current test answer in the ordered set where uuid = ?.
*
* @param answerId the primary key of the current test answer
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer[] findByUuid_PrevAndNext(long answerId, String uuid,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = findByPrimaryKey(answerId);
Session session = null;
try {
session = openSession();
TestAnswer[] array = new TestAnswerImpl[3];
array[0] = getByUuid_PrevAndNext(session, testAnswer, uuid,
orderByComparator, true);
array[1] = testAnswer;
array[2] = getByUuid_PrevAndNext(session, testAnswer, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected TestAnswer getByUuid_PrevAndNext(Session session,
TestAnswer testAnswer, String uuid,
OrderByComparator orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(6 +
(orderByComparator.getOrderByFields().length * 6));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else {
if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
}
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (uuid != null) {
qPos.add(uuid);
}
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(testAnswer);
for (Object value : values) {
qPos.add(value);
}
}
List<TestAnswer> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Returns all the test answers where actId = ?.
*
* @param actId the act ID
* @return the matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByac(long actId) throws SystemException {
return findByac(actId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the test answers where actId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param actId the act ID
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @return the range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByac(long actId, int start, int end)
throws SystemException {
return findByac(actId, start, end, null);
}
/**
* Returns an ordered range of all the test answers where actId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param actId the act ID
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByac(long actId, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_AC;
finderArgs = new Object[] { actId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_AC;
finderArgs = new Object[] { actId, start, end, orderByComparator };
}
List<TestAnswer> list = (List<TestAnswer>)FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (TestAnswer testAnswer : list) {
if ((actId != testAnswer.getActId())) {
list = null;
break;
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_AC_ACTID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(actId);
list = (List<TestAnswer>)QueryUtil.list(q, getDialect(), start,
end);
}
catch (Exception e) {
throw processException(e);
}
finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
}
else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Returns the first test answer in the ordered set where actId = ?.
*
* @param actId the act ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByac_First(long actId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByac_First(actId, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("actId=");
msg.append(actId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the first test answer in the ordered set where actId = ?.
*
* @param actId the act ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByac_First(long actId,
OrderByComparator orderByComparator) throws SystemException {
List<TestAnswer> list = findByac(actId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last test answer in the ordered set where actId = ?.
*
* @param actId the act ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByac_Last(long actId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByac_Last(actId, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("actId=");
msg.append(actId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the last test answer in the ordered set where actId = ?.
*
* @param actId the act ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByac_Last(long actId,
OrderByComparator orderByComparator) throws SystemException {
int count = countByac(actId);
List<TestAnswer> list = findByac(actId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the test answers before and after the current test answer in the ordered set where actId = ?.
*
* @param answerId the primary key of the current test answer
* @param actId the act ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer[] findByac_PrevAndNext(long answerId, long actId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = findByPrimaryKey(answerId);
Session session = null;
try {
session = openSession();
TestAnswer[] array = new TestAnswerImpl[3];
array[0] = getByac_PrevAndNext(session, testAnswer, actId,
orderByComparator, true);
array[1] = testAnswer;
array[2] = getByac_PrevAndNext(session, testAnswer, actId,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected TestAnswer getByac_PrevAndNext(Session session,
TestAnswer testAnswer, long actId, OrderByComparator orderByComparator,
boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(6 +
(orderByComparator.getOrderByFields().length * 6));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_AC_ACTID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(actId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(testAnswer);
for (Object value : values) {
qPos.add(value);
}
}
List<TestAnswer> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Returns all the test answers where questionId = ?.
*
* @param questionId the question ID
* @return the matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByq(long questionId) throws SystemException {
return findByq(questionId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the test answers where questionId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param questionId the question ID
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @return the range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByq(long questionId, int start, int end)
throws SystemException {
return findByq(questionId, start, end, null);
}
/**
* Returns an ordered range of all the test answers where questionId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param questionId the question ID
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findByq(long questionId, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_Q;
finderArgs = new Object[] { questionId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_Q;
finderArgs = new Object[] { questionId, start, end, orderByComparator };
}
List<TestAnswer> list = (List<TestAnswer>)FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (TestAnswer testAnswer : list) {
if ((questionId != testAnswer.getQuestionId())) {
list = null;
break;
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_Q_QUESTIONID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(questionId);
list = (List<TestAnswer>)QueryUtil.list(q, getDialect(), start,
end);
}
catch (Exception e) {
throw processException(e);
}
finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
}
else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Returns the first test answer in the ordered set where questionId = ?.
*
* @param questionId the question ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByq_First(long questionId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByq_First(questionId, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("questionId=");
msg.append(questionId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the first test answer in the ordered set where questionId = ?.
*
* @param questionId the question ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByq_First(long questionId,
OrderByComparator orderByComparator) throws SystemException {
List<TestAnswer> list = findByq(questionId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last test answer in the ordered set where questionId = ?.
*
* @param questionId the question ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByq_Last(long questionId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByq_Last(questionId, orderByComparator);
if (testAnswer != null) {
return testAnswer;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("questionId=");
msg.append(questionId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchTestAnswerException(msg.toString());
}
/**
* Returns the last test answer in the ordered set where questionId = ?.
*
* @param questionId the question ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByq_Last(long questionId,
OrderByComparator orderByComparator) throws SystemException {
int count = countByq(questionId);
List<TestAnswer> list = findByq(questionId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the test answers before and after the current test answer in the ordered set where questionId = ?.
*
* @param answerId the primary key of the current test answer
* @param questionId the question ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a test answer with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer[] findByq_PrevAndNext(long answerId, long questionId,
OrderByComparator orderByComparator)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = findByPrimaryKey(answerId);
Session session = null;
try {
session = openSession();
TestAnswer[] array = new TestAnswerImpl[3];
array[0] = getByq_PrevAndNext(session, testAnswer, questionId,
orderByComparator, true);
array[1] = testAnswer;
array[2] = getByq_PrevAndNext(session, testAnswer, questionId,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected TestAnswer getByq_PrevAndNext(Session session,
TestAnswer testAnswer, long questionId,
OrderByComparator orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(6 +
(orderByComparator.getOrderByFields().length * 6));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_Q_QUESTIONID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(questionId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(testAnswer);
for (Object value : values) {
qPos.add(value);
}
}
List<TestAnswer> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Returns the test answer where uuid = ? and actId = ? or throws a {@link com.liferay.lms.NoSuchTestAnswerException} if it could not be found.
*
* @param uuid the uuid
* @param actId the act ID
* @return the matching test answer
* @throws com.liferay.lms.NoSuchTestAnswerException if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer findByUuid_ActId(String uuid, long actId)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = fetchByUuid_ActId(uuid, actId);
if (testAnswer == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", actId=");
msg.append(actId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
if (_log.isWarnEnabled()) {
_log.warn(msg.toString());
}
throw new NoSuchTestAnswerException(msg.toString());
}
return testAnswer;
}
/**
* Returns the test answer where uuid = ? and actId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
*
* @param uuid the uuid
* @param actId the act ID
* @return the matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByUuid_ActId(String uuid, long actId)
throws SystemException {
return fetchByUuid_ActId(uuid, actId, true);
}
/**
* Returns the test answer where uuid = ? and actId = ? or returns <code>null</code> if it could not be found, optionally using the finder cache.
*
* @param uuid the uuid
* @param actId the act ID
* @param retrieveFromCache whether to use the finder cache
* @return the matching test answer, or <code>null</code> if a matching test answer could not be found
* @throws SystemException if a system exception occurred
*/
public TestAnswer fetchByUuid_ActId(String uuid, long actId,
boolean retrieveFromCache) throws SystemException {
Object[] finderArgs = new Object[] { uuid, actId };
Object result = null;
if (retrieveFromCache) {
result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
finderArgs, this);
}
if (result instanceof TestAnswer) {
TestAnswer testAnswer = (TestAnswer)result;
if (!Validator.equals(uuid, testAnswer.getUuid()) ||
(actId != testAnswer.getActId())) {
result = null;
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_TESTANSWER_WHERE);
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_1);
}
else {
if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_3);
}
else {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_2);
}
}
query.append(_FINDER_COLUMN_UUID_ACTID_ACTID_2);
query.append(TestAnswerModelImpl.ORDER_BY_JPQL);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (uuid != null) {
qPos.add(uuid);
}
qPos.add(actId);
List<TestAnswer> list = q.list();
result = list;
TestAnswer testAnswer = null;
if (list.isEmpty()) {
FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
finderArgs, list);
}
else {
testAnswer = list.get(0);
cacheResult(testAnswer);
if ((testAnswer.getUuid() == null) ||
!testAnswer.getUuid().equals(uuid) ||
(testAnswer.getActId() != actId)) {
FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
finderArgs, testAnswer);
}
}
return testAnswer;
}
catch (Exception e) {
throw processException(e);
}
finally {
if (result == null) {
FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_ACTID,
finderArgs);
}
closeSession(session);
}
}
else {
if (result instanceof List<?>) {
return null;
}
else {
return (TestAnswer)result;
}
}
}
/**
* Returns all the test answers.
*
* @return the test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findAll() throws SystemException {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the test answers.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @return the range of test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findAll(int start, int end)
throws SystemException {
return findAll(start, end, null);
}
/**
* Returns an ordered range of all the test answers.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of test answers
* @param end the upper bound of the range of test answers (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of test answers
* @throws SystemException if a system exception occurred
*/
public List<TestAnswer> findAll(int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = new Object[] { start, end, orderByComparator };
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
finderArgs = FINDER_ARGS_EMPTY;
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
finderArgs = new Object[] { start, end, orderByComparator };
}
List<TestAnswer> list = (List<TestAnswer>)FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if (list == null) {
StringBundler query = null;
String sql = null;
if (orderByComparator != null) {
query = new StringBundler(2 +
(orderByComparator.getOrderByFields().length * 3));
query.append(_SQL_SELECT_TESTANSWER);
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
sql = query.toString();
}
else {
sql = _SQL_SELECT_TESTANSWER.concat(TestAnswerModelImpl.ORDER_BY_JPQL);
}
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
if (orderByComparator == null) {
list = (List<TestAnswer>)QueryUtil.list(q, getDialect(),
start, end, false);
Collections.sort(list);
}
else {
list = (List<TestAnswer>)QueryUtil.list(q, getDialect(),
start, end);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
}
else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Removes all the test answers where uuid = ? from the database.
*
* @param uuid the uuid
* @throws SystemException if a system exception occurred
*/
public void removeByUuid(String uuid) throws SystemException {
for (TestAnswer testAnswer : findByUuid(uuid)) {
remove(testAnswer);
}
}
/**
* Removes all the test answers where actId = ? from the database.
*
* @param actId the act ID
* @throws SystemException if a system exception occurred
*/
public void removeByac(long actId) throws SystemException {
for (TestAnswer testAnswer : findByac(actId)) {
remove(testAnswer);
}
}
/**
* Removes all the test answers where questionId = ? from the database.
*
* @param questionId the question ID
* @throws SystemException if a system exception occurred
*/
public void removeByq(long questionId) throws SystemException {
for (TestAnswer testAnswer : findByq(questionId)) {
remove(testAnswer);
}
}
/**
* Removes the test answer where uuid = ? and actId = ? from the database.
*
* @param uuid the uuid
* @param actId the act ID
* @return the test answer that was removed
* @throws SystemException if a system exception occurred
*/
public TestAnswer removeByUuid_ActId(String uuid, long actId)
throws NoSuchTestAnswerException, SystemException {
TestAnswer testAnswer = findByUuid_ActId(uuid, actId);
return remove(testAnswer);
}
/**
* Removes all the test answers from the database.
*
* @throws SystemException if a system exception occurred
*/
public void removeAll() throws SystemException {
for (TestAnswer testAnswer : findAll()) {
remove(testAnswer);
}
}
/**
* Returns the number of test answers where uuid = ?.
*
* @param uuid the uuid
* @return the number of matching test answers
* @throws SystemException if a system exception occurred
*/
public int countByUuid(String uuid) throws SystemException {
Object[] finderArgs = new Object[] { uuid };
Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_UUID,
finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_TESTANSWER_WHERE);
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else {
if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (uuid != null) {
qPos.add(uuid);
}
count = (Long)q.uniqueResult();
}
catch (Exception e) {
throw processException(e);
}
finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_UUID,
finderArgs, count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Returns the number of test answers where actId = ?.
*
* @param actId the act ID
* @return the number of matching test answers
* @throws SystemException if a system exception occurred
*/
public int countByac(long actId) throws SystemException {
Object[] finderArgs = new Object[] { actId };
Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_AC,
finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_AC_ACTID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(actId);
count = (Long)q.uniqueResult();
}
catch (Exception e) {
throw processException(e);
}
finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_AC, finderArgs,
count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Returns the number of test answers where questionId = ?.
*
* @param questionId the question ID
* @return the number of matching test answers
* @throws SystemException if a system exception occurred
*/
public int countByq(long questionId) throws SystemException {
Object[] finderArgs = new Object[] { questionId };
Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_Q,
finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_TESTANSWER_WHERE);
query.append(_FINDER_COLUMN_Q_QUESTIONID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(questionId);
count = (Long)q.uniqueResult();
}
catch (Exception e) {
throw processException(e);
}
finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_Q, finderArgs,
count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Returns the number of test answers where uuid = ? and actId = ?.
*
* @param uuid the uuid
* @param actId the act ID
* @return the number of matching test answers
* @throws SystemException if a system exception occurred
*/
public int countByUuid_ActId(String uuid, long actId)
throws SystemException {
Object[] finderArgs = new Object[] { uuid, actId };
Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_UUID_ACTID,
finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_TESTANSWER_WHERE);
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_1);
}
else {
if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_3);
}
else {
query.append(_FINDER_COLUMN_UUID_ACTID_UUID_2);
}
}
query.append(_FINDER_COLUMN_UUID_ACTID_ACTID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (uuid != null) {
qPos.add(uuid);
}
qPos.add(actId);
count = (Long)q.uniqueResult();
}
catch (Exception e) {
throw processException(e);
}
finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_UUID_ACTID,
finderArgs, count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Returns the number of test answers.
*
* @return the number of test answers
* @throws SystemException if a system exception occurred
*/
public int countAll() throws SystemException {
Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, this);
if (count == null) {
Session session = null;
try {
session = openSession();
Query q = session.createQuery(_SQL_COUNT_TESTANSWER);
count = (Long)q.uniqueResult();
}
catch (Exception e) {
throw processException(e);
}
finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Initializes the test answer persistence.
*/
public void afterPropertiesSet() {
String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
com.liferay.util.service.ServiceProps.get(
"value.object.listener.com.liferay.lms.model.TestAnswer")));
if (listenerClassNames.length > 0) {
try {
List<ModelListener<TestAnswer>> listenersList = new ArrayList<ModelListener<TestAnswer>>();
for (String listenerClassName : listenerClassNames) {
listenersList.add((ModelListener<TestAnswer>)InstanceFactory.newInstance(
listenerClassName));
}
listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
}
catch (Exception e) {
_log.error(e);
}
}
}
public void destroy() {
EntityCacheUtil.removeCache(TestAnswerImpl.class.getName());
FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
@BeanReference(type = ActivityTriesDeletedPersistence.class)
protected ActivityTriesDeletedPersistence activityTriesDeletedPersistence;
@BeanReference(type = AsynchronousProcessAuditPersistence.class)
protected AsynchronousProcessAuditPersistence asynchronousProcessAuditPersistence;
@BeanReference(type = AuditEntryPersistence.class)
protected AuditEntryPersistence auditEntryPersistence;
@BeanReference(type = CheckP2pMailingPersistence.class)
protected CheckP2pMailingPersistence checkP2pMailingPersistence;
@BeanReference(type = CompetencePersistence.class)
protected CompetencePersistence competencePersistence;
@BeanReference(type = CoursePersistence.class)
protected CoursePersistence coursePersistence;
@BeanReference(type = CourseCompetencePersistence.class)
protected CourseCompetencePersistence courseCompetencePersistence;
@BeanReference(type = CourseResultPersistence.class)
protected CourseResultPersistence courseResultPersistence;
@BeanReference(type = CourseTypePersistence.class)
protected CourseTypePersistence courseTypePersistence;
@BeanReference(type = CourseTypeRelationPersistence.class)
protected CourseTypeRelationPersistence courseTypeRelationPersistence;
@BeanReference(type = LearningActivityPersistence.class)
protected LearningActivityPersistence learningActivityPersistence;
@BeanReference(type = LearningActivityResultPersistence.class)
protected LearningActivityResultPersistence learningActivityResultPersistence;
@BeanReference(type = LearningActivityTryPersistence.class)
protected LearningActivityTryPersistence learningActivityTryPersistence;
@BeanReference(type = LmsPrefsPersistence.class)
protected LmsPrefsPersistence lmsPrefsPersistence;
@BeanReference(type = ModulePersistence.class)
protected ModulePersistence modulePersistence;
@BeanReference(type = ModuleResultPersistence.class)
protected ModuleResultPersistence moduleResultPersistence;
@BeanReference(type = P2pActivityPersistence.class)
protected P2pActivityPersistence p2pActivityPersistence;
@BeanReference(type = P2pActivityCorrectionsPersistence.class)
protected P2pActivityCorrectionsPersistence p2pActivityCorrectionsPersistence;
@BeanReference(type = SchedulePersistence.class)
protected SchedulePersistence schedulePersistence;
@BeanReference(type = SurveyResultPersistence.class)
protected SurveyResultPersistence surveyResultPersistence;
@BeanReference(type = TestAnswerPersistence.class)
protected TestAnswerPersistence testAnswerPersistence;
@BeanReference(type = TestQuestionPersistence.class)
protected TestQuestionPersistence testQuestionPersistence;
@BeanReference(type = UserCertificateDownloadPersistence.class)
protected UserCertificateDownloadPersistence userCertificateDownloadPersistence;
@BeanReference(type = UserCompetencePersistence.class)
protected UserCompetencePersistence userCompetencePersistence;
@BeanReference(type = ResourcePersistence.class)
protected ResourcePersistence resourcePersistence;
@BeanReference(type = UserPersistence.class)
protected UserPersistence userPersistence;
private static final String _SQL_SELECT_TESTANSWER = "SELECT testAnswer FROM TestAnswer testAnswer";
private static final String _SQL_SELECT_TESTANSWER_WHERE = "SELECT testAnswer FROM TestAnswer testAnswer WHERE ";
private static final String _SQL_COUNT_TESTANSWER = "SELECT COUNT(testAnswer) FROM TestAnswer testAnswer";
private static final String _SQL_COUNT_TESTANSWER_WHERE = "SELECT COUNT(testAnswer) FROM TestAnswer testAnswer WHERE ";
private static final String _FINDER_COLUMN_UUID_UUID_1 = "testAnswer.uuid IS NULL";
private static final String _FINDER_COLUMN_UUID_UUID_2 = "testAnswer.uuid = ?";
private static final String _FINDER_COLUMN_UUID_UUID_3 = "(testAnswer.uuid IS NULL OR testAnswer.uuid = ?)";
private static final String _FINDER_COLUMN_AC_ACTID_2 = "testAnswer.actId = ?";
private static final String _FINDER_COLUMN_Q_QUESTIONID_2 = "testAnswer.questionId = ?";
private static final String _FINDER_COLUMN_UUID_ACTID_UUID_1 = "testAnswer.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_ACTID_UUID_2 = "testAnswer.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_ACTID_UUID_3 = "(testAnswer.uuid IS NULL OR testAnswer.uuid = ?) AND ";
private static final String _FINDER_COLUMN_UUID_ACTID_ACTID_2 = "testAnswer.actId = ?";
private static final String _ORDER_BY_ENTITY_ALIAS = "testAnswer.";
private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No TestAnswer exists with the primary key ";
private static final String _NO_SUCH_ENTITY_WITH_KEY = "No TestAnswer exists with the key {";
private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
private static Log _log = LogFactoryUtil.getLog(TestAnswerPersistenceImpl.class);
private static TestAnswer _nullTestAnswer = new TestAnswerImpl() {
@Override
public Object clone() {
return this;
}
@Override
public CacheModel<TestAnswer> toCacheModel() {
return _nullTestAnswerCacheModel;
}
};
private static CacheModel<TestAnswer> _nullTestAnswerCacheModel = new CacheModel<TestAnswer>() {
public TestAnswer toEntityModel() {
return _nullTestAnswer;
}
};
} | agpl-3.0 |
rakam-io/rakam | mapper/rakam-mapper-geoip-maxmind/src/main/java/org/rakam/collection/mapper/geoip/maxmind/MaxmindGeoIPEventMapper.java | 13526 | package org.rakam.collection.mapper.geoip.maxmind;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.AddressNotFoundException;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.ConnectionTypeResponse;
import com.maxmind.geoip2.model.IspResponse;
import io.airlift.log.Logger;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.cookie.Cookie;
import org.apache.avro.generic.GenericRecord;
import org.rakam.Mapper;
import org.rakam.collection.Event;
import org.rakam.collection.FieldDependencyBuilder;
import org.rakam.collection.FieldType;
import org.rakam.collection.SchemaField;
import org.rakam.plugin.SyncEventMapper;
import org.rakam.plugin.user.ISingleUserBatchOperation;
import org.rakam.plugin.user.UserPropertyMapper;
import org.rakam.util.MapProxyGenericRecord;
import javax.inject.Inject;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.maxmind.db.Reader.FileMode.MEMORY;
import static org.rakam.collection.FieldType.STRING;
import static org.rakam.util.AvroUtil.put;
@Mapper(name = "Maxmind Event mapper", description = "Looks up geolocation data from _ip field using Maxmind and attaches geo-related attributed")
public class MaxmindGeoIPEventMapper
implements SyncEventMapper, UserPropertyMapper {
private static final Logger LOGGER = Logger.get(MaxmindGeoIPEventMapper.class);
private static final String ERROR_MESSAGE = "You need to set %s config in order to have '%s' field.";
private final static List<String> CITY_DATABASE_ATTRIBUTES = ImmutableList
.of("city", "region", "country_code", "latitude", "longitude", "timezone");
private static final String IP_ADDRESS_REGEX = "([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})";
private static final String PRIVATE_IP_ADDRESS_REGEX = "(^127\\.0\\.0\\.1)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)";
private static Pattern IP_ADDRESS_PATTERN = null;
private static Pattern PRIVATE_IP_ADDRESS_PATTERN = null;
private final String[] attributes;
private final DatabaseReader connectionTypeLookup;
private final DatabaseReader ispLookup;
private final DatabaseReader cityLookup;
private final boolean attachIp;
@Inject
public MaxmindGeoIPEventMapper(MaxmindGeoIPModuleConfig config) {
Preconditions.checkNotNull(config, "config is null");
DatabaseReader connectionTypeLookup = null, ispLookup = null, cityLookup = null;
boolean attachIp = false;
if (config.getAttributes() != null) {
for (String attr : config.getAttributes()) {
if (CITY_DATABASE_ATTRIBUTES.contains(attr)) {
if (config.getDatabaseUrl() == null) {
throw new IllegalStateException(String.format(ERROR_MESSAGE, "plugin.geoip.database.url", attr));
}
if (cityLookup == null) {
cityLookup = getReader(config.getDatabaseUrl());
}
continue;
} else if ("isp".equals(attr)) {
if (config.getIspDatabaseUrl() == null) {
throw new IllegalStateException(String.format(ERROR_MESSAGE, "plugin.geoip.isp-database.url", attr));
}
if (ispLookup == null) {
ispLookup = getReader(config.getIspDatabaseUrl());
}
continue;
} else if ("connection_type".equals(attr)) {
if (config.getConnectionTypeDatabaseUrl() == null) {
throw new IllegalStateException(String.format(ERROR_MESSAGE, "plugin.geoip.connection-type-database.url", attr));
}
if (connectionTypeLookup == null) {
connectionTypeLookup = getReader(config.getConnectionTypeDatabaseUrl());
}
continue;
} else if ("_ip".equals(attr)) {
attachIp = true;
continue;
}
throw new IllegalArgumentException("Attribute " + attr + " is not valid. Available attributes: " +
Joiner.on(", ").join(CITY_DATABASE_ATTRIBUTES));
}
attributes = config.getAttributes().stream().toArray(String[]::new);
} else {
if (config.getDatabaseUrl() != null) {
cityLookup = getReader(config.getDatabaseUrl());
attributes = CITY_DATABASE_ATTRIBUTES.stream().toArray(String[]::new);
} else {
attributes = null;
}
attachIp = true;
}
this.attachIp = attachIp;
if (config.getIspDatabaseUrl() != null) {
ispLookup = getReader(config.getIspDatabaseUrl());
}
if (config.getConnectionTypeDatabaseUrl() != null) {
connectionTypeLookup = getReader(config.getConnectionTypeDatabaseUrl());
}
this.cityLookup = cityLookup;
this.ispLookup = ispLookup;
this.connectionTypeLookup = connectionTypeLookup;
}
private static FieldType getType(String attr) {
switch (attr) {
case "country_code":
case "region":
case "city":
case "timezone":
case "_ip":
return STRING;
case "latitude":
case "longitude":
return FieldType.DOUBLE;
default:
throw new IllegalStateException();
}
}
private static String findNonPrivateIpAddress(String s) {
if (IP_ADDRESS_PATTERN == null) {
IP_ADDRESS_PATTERN = Pattern.compile(IP_ADDRESS_REGEX);
PRIVATE_IP_ADDRESS_PATTERN = Pattern.compile(PRIVATE_IP_ADDRESS_REGEX);
}
Matcher matcher = IP_ADDRESS_PATTERN.matcher(s);
while (matcher.find()) {
String group = matcher.group(0);
if (group != null && !PRIVATE_IP_ADDRESS_PATTERN.matcher(group).find()) {
return group;
}
matcher.region(matcher.end(), s.length());
}
return null;
}
private DatabaseReader getReader(URL url) {
try {
FileInputStream cityDatabase = new FileInputStream(MaxmindGeoIPModule.downloadOrGetFile(url));
return new DatabaseReader.Builder(cityDatabase).fileMode(MEMORY).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public List<Cookie> map(Event event, RequestParams extraProperties, InetAddress sourceAddress, HttpHeaders responseHeaders) {
Object ip = event.properties().get("_ip");
InetAddress addr;
if ((ip instanceof String)) {
try {
// it may be slow because java performs reverse hostname lookup.
addr = Inet4Address.getByName((String) ip);
} catch (UnknownHostException e) {
return null;
}
} else if (Boolean.TRUE == ip) {
String forwardedFor = extraProperties.headers().get("X-Forwarded-For");
if (forwardedFor != null && (forwardedFor = findNonPrivateIpAddress(forwardedFor)) != null) {
try {
// it may be slow because java performs reverse hostname lookup.
addr = Inet4Address.getByName(forwardedFor);
} catch (UnknownHostException e) {
return null;
}
} else {
addr = sourceAddress;
}
} else {
if (cityLookup != null) {
// Cloudflare country code header (Only works when the request passed through CF servers)
String countryCode = extraProperties.headers().get("HTTP_CF_IPCOUNTRY");
if (countryCode != null) {
put(event.properties(),"_country_code", countryCode);
}
}
return null;
}
if (addr == null) {
return null;
}
if (attachIp) {
put(event.properties(),"__ip", addr.getHostAddress());
}
if (connectionTypeLookup != null) {
setConnectionType(addr, event.properties());
}
if (ispLookup != null) {
setIsp(addr, event.properties());
}
if (cityLookup != null) {
setGeoFields(addr, event.properties());
}
return null;
}
@Override
public List<Cookie> map(String project, List<? extends ISingleUserBatchOperation> user, RequestParams requestParams, InetAddress sourceAddress) {
for (ISingleUserBatchOperation data : user) {
if (data.getSetProperties() != null) {
mapInternal(data.getSetProperties(), sourceAddress);
}
if (data.getSetPropertiesOnce() != null) {
mapInternal(data.getSetPropertiesOnce(), sourceAddress);
}
}
return null;
}
public void mapInternal(ObjectNode data, InetAddress sourceAddress) {
Object ip = data.get("_ip");
if (ip == null) {
return;
}
if ((ip instanceof String)) {
try {
// it may be slow because java performs reverse hostname lookup.
sourceAddress = Inet4Address.getByName((String) ip);
} catch (UnknownHostException e) {
return;
}
}
if (sourceAddress == null) {
return;
}
GenericRecord record = new MapProxyGenericRecord(data);
if (connectionTypeLookup != null) {
setConnectionType(sourceAddress, record);
}
if (ispLookup != null) {
setIsp(sourceAddress, record);
}
if (cityLookup != null) {
setGeoFields(sourceAddress, record);
}
}
@Override
public void addFieldDependency(FieldDependencyBuilder builder) {
List<SchemaField> fields = Arrays.stream(attributes)
.map(attr -> new SchemaField("_" + attr, getType(attr)))
.collect(Collectors.toList());
if (ispLookup != null) {
fields.add(new SchemaField("_isp", STRING));
}
if (connectionTypeLookup != null) {
fields.add(new SchemaField("_connection_type", STRING));
}
fields.add(new SchemaField("__ip", STRING));
builder.addFields("_ip", fields);
}
private void setConnectionType(InetAddress address, GenericRecord properties) {
ConnectionTypeResponse connectionType;
try {
connectionType = connectionTypeLookup.connectionType(address);
} catch (AddressNotFoundException e) {
return;
} catch (Exception e) {
LOGGER.error(e, "Error while searching for location information.");
return;
}
ConnectionTypeResponse.ConnectionType connType = connectionType.getConnectionType();
if (connType != null) {
put(properties,"_connection_type", connType.name());
}
}
private void setIsp(InetAddress address, GenericRecord properties) {
IspResponse isp;
try {
isp = ispLookup.isp(address);
} catch (AddressNotFoundException e) {
return;
} catch (Exception e) {
LOGGER.error(e, "Error while searching for location information.");
return;
}
put(properties,"_isp", isp.getIsp());
}
private void setGeoFields(InetAddress address, GenericRecord properties) {
CityResponse city;
try {
city = cityLookup.city(address);
} catch (AddressNotFoundException e) {
return;
} catch (Exception e) {
LOGGER.error(e, "Error while searching for location information.");
return;
}
for (String attribute : attributes) {
switch (attribute) {
case "country_code":
put(properties,"_country_code", city.getCountry().getIsoCode());
break;
case "region":
put(properties,"_region", city.getContinent().getName());
break;
case "city":
put(properties,"_city", city.getCity().getName());
break;
case "latitude":
put(properties,"_latitude", city.getLocation().getLatitude());
break;
case "longitude":
put(properties,"_longitude", city.getLocation().getLongitude());
break;
case "timezone":
put(properties,"_timezone", city.getLocation().getTimeZone());
break;
}
}
}
}
| agpl-3.0 |
Glamdring/scientific-publishing | src/main/java/com/scipub/dto/RegistrationDto.java | 2309 | /**
* Scientific publishing
* Copyright (C) 2015-2016 Bozhidar Bozhanov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.scipub.dto;
import java.util.ArrayList;
import java.util.List;
import org.springframework.social.connect.Connection;
public class RegistrationDto {
private String email;
private String firstName;
private String lastName;
private String degree;
private Connection<?> connection;
private boolean loginAutomatically;
private List<Long> branchIds = new ArrayList<>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public Connection<?> getConnection() {
return connection;
}
public void setConnection(Connection<?> connection) {
this.connection = connection;
}
public boolean isLoginAutomatically() {
return loginAutomatically;
}
public void setLoginAutomatically(boolean loginAutomatically) {
this.loginAutomatically = loginAutomatically;
}
public List<Long> getBranchIds() {
return branchIds;
}
public void setBranchIds(List<Long> branchIds) {
this.branchIds = branchIds;
}
}
| agpl-3.0 |
moosetra/SpiritDistillery | src/main/java/com/moosetra/spiritdistillery/block/BlockCarboniteBomb.java | 917 | package com.moosetra.spiritdistillery.block;
import com.moosetra.spiritdistillery.creativetab.CreativeTabSD;
import com.moosetra.spiritdistillery.init.ModBlocks;
import com.moosetra.spiritdistillery.reference.Names;
import com.moosetra.spiritdistillery.reference.Reference;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemMultiTexture;
import net.minecraft.util.IIcon;
import java.util.Random;
public class BlockCarboniteBomb extends BlockSD
{
public BlockCarboniteBomb()
{
super();
this.setBlockName(Names.Blocks.BlockCarboniteBomb);
this.setBlockTextureName("CarboniteBomb");
this.setHardness(2.0f);
this.setStepSound(Block.soundTypeMetal);
}
public int blockDropped(int metadata, Random random, int fortune) {
return getIdFromBlock(ModBlocks.CarboniteBomb);
}
}
| agpl-3.0 |
gsun83/cbioportal | model/src/main/java/org/cbioportal/model/PatientClinicalData.java | 613 | package org.cbioportal.model;
import org.cbioportal.model.summary.ClinicalDataSummary;
public class PatientClinicalData extends ClinicalDataSummary {
private Patient patient;
private ClinicalAttribute clinicalAttribute;
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public ClinicalAttribute getClinicalAttribute() {
return clinicalAttribute;
}
public void setClinicalAttribute(ClinicalAttribute clinicalAttribute) {
this.clinicalAttribute = clinicalAttribute;
}
}
| agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/gui/look/ui/ToolbarButtonUI.java | 2731 | /**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.look.ui;
import com.rapidminer.gui.look.ButtonListener;
import com.rapidminer.gui.look.RapidLookTools;
import com.vlsolutions.swing.toolbars.VLToolBar;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JToolBar;
import javax.swing.plaf.basic.BasicButtonListener;
import javax.swing.plaf.basic.BasicButtonUI;
/**
* The UI for toolbar buttons.
*
* @author Ingo Mierswa
*/
public class ToolbarButtonUI extends BasicButtonUI {
protected static boolean isToolbarButton(JComponent c) {
return RapidLookTools.isToolbarButton(c);
}
@Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
}
@Override
protected void uninstallDefaults(AbstractButton b) {
super.uninstallDefaults(b);
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
}
@Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
}
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
}
public boolean isOpaque() {
return false;
}
@Override
public Dimension getPreferredSize(JComponent c) {
if (c.getParent() instanceof JToolBar) {
return super.getPreferredSize(c);
}
if (c.getParent() instanceof VLToolBar) {
return super.getPreferredSize(c);
}
return new Dimension(22, 22);
}
@Override
protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
// do nothing
}
@Override
protected void paintButtonPressed(Graphics g, AbstractButton b) {
setTextShiftOffset();
}
@Override
protected BasicButtonListener createButtonListener(AbstractButton b) {
return new ButtonListener(b);
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-services/questioncontainer/src/main/java/org/silverpeas/core/questioncontainer/score/model/ScoreRuntimeException.java | 1663 | /*
* Copyright (C) 2000 - 2021 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "https://www.silverpeas.org/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.core.questioncontainer.score.model;
import org.silverpeas.core.SilverpeasRuntimeException;
public class ScoreRuntimeException extends SilverpeasRuntimeException {
private static final long serialVersionUID = 3758095556999976753L;
public ScoreRuntimeException(final String message) {
super(message);
}
public ScoreRuntimeException(final String message, final Throwable cause) {
super(message, cause);
}
public ScoreRuntimeException(final Throwable cause) {
super(cause);
}
}
| agpl-3.0 |
WebDataConsulting/billing | src/java/com/sapienter/jbilling/server/util/search/SearchResult.java | 1482 | package com.sapienter.jbilling.server.util.search;
import javax.xml.bind.annotation.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Search result object containing a total row count, row columns names
* and the content.
*
* CXF can not marshall List<List<T>>. Subclasses must be generated with XmlAdapters to help with marshalling
* See SearchResultString
* @author Gerhard
* @since 27/12/13
* @see SearchResultString
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class SearchResult<T> implements Serializable {
private int total;
private List<String> columnNames = new ArrayList<String>();
protected List<List<T>> rows = new ArrayList<List<T>>();
@XmlAttribute
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
@XmlElement
public List<String> getColumnNames() {
return columnNames;
}
public void setColumnNames(List<String> columnNames) {
this.columnNames = columnNames;
}
public List<List<T>> getRows() {
return rows;
}
public void setRows(List<List<T>> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "SearchResult{" +
"total=" + total +
", columnNames=" + columnNames +
", rows.size=" + (rows == null ? 0 : rows.size()) +
'}';
}
}
| agpl-3.0 |
lpellegr/programming | programming-test/src/test/java/functionalTests/activeobject/request/terminate/Test.java | 2885 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package functionalTests.activeobject.request.terminate;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.util.wrapper.StringWrapper;
import functionalTests.FunctionalTest;
import functionalTests.TestDisabler;
import functionalTests.activeobject.request.A;
/**
* Test sending termination method
*/
public class Test extends FunctionalTest {
A a1;
A a2;
StringWrapper returnedValue;
@BeforeClass
public static void disable() {
TestDisabler.unstable();
}
@Before
public void action() throws Exception {
a1 = PAActiveObject.newActive(A.class, new Object[0]);
a1.method1();
a1.exit();
// test with remaining ACs
a2 = PAActiveObject.newActive(A.class, new Object[0]);
a2.initDeleguate();
returnedValue = a2.getDelegateValue();
a2.exit();
}
@org.junit.Test
public void postConditions() {
assertTrue(returnedValue.getStringValue().equals("Returned value"));
int exceptionCounter = 0;
try {
a1.method1();
} catch (RuntimeException e) {
exceptionCounter++;
}
try {
a2.method1();
} catch (RuntimeException e) {
exceptionCounter++;
}
assertTrue(exceptionCounter == 2);
}
}
| agpl-3.0 |
torakiki/sejda | sejda-model/src/main/java/org/sejda/model/notification/EventListener.java | 1269 | /*
* Created on 17/apr/2010
* Copyright (C) 2010 by Andrea Vacondio (andrea.vacondio@gmail.com).
*
* This library 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 2.1 of the License.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.sejda.model.notification;
import org.sejda.model.notification.event.AbstractNotificationEvent;
/**
* Listen for the event. Any listener can generically declare the event it is interested in.
*
* @author Andrea Vacondio
*
* @param <T>
* event type
*/
public interface EventListener<T extends AbstractNotificationEvent> {
/**
* event notification
*
* @param event
*/
void onEvent(T event);
}
| agpl-3.0 |
opencadc/dal | cadc-dali/src/main/java/ca/nrc/cadc/dali/tables/votable/VOTableTable.java | 4830 | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2011. (c) 2011.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 5 $
*
************************************************************************
*/
package ca.nrc.cadc.dali.tables.votable;
import ca.nrc.cadc.dali.tables.TableData;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author pdowler
*/
public class VOTableTable {
private List<VOTableInfo> infos = new ArrayList<VOTableInfo>();
private List<VOTableParam> params = new ArrayList<VOTableParam>();
private List<VOTableField> fields = new ArrayList<VOTableField>();
private TableData tableData;
public VOTableTable() {
}
public List<VOTableInfo> getInfos() {
return infos;
}
public List<VOTableParam> getParams() {
return params;
}
public List<VOTableField> getFields() {
return fields;
}
public TableData getTableData() {
return tableData;
}
public void setTableData(TableData tableData) {
this.tableData = tableData;
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/parameter/value/ParameterValueList.java | 3031 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.parameter.value;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.rapidminer.operator.Operator;
import com.rapidminer.parameter.ParameterType;
/**
* A list of parameter values.
*
* @author Tobias Malbrecht
*/
public class ParameterValueList extends ParameterValues implements Iterable<String> {
List<String> values;
public ParameterValueList(Operator operator, ParameterType type) {
this(operator, type, new LinkedList<String>());
}
public ParameterValueList(Operator operator, ParameterType type, String[] valuesArray) {
super(operator, type);
this.values = new ArrayList<>(Arrays.asList(valuesArray));
}
public ParameterValueList(Operator operator, ParameterType type, List<String> values) {
super(operator, type);
this.values = values;
}
@Override
public void move(int index, int direction) {
int newPosition = index + direction;
if (newPosition >= 0 && newPosition < values.size()) {
String object = values.remove(index);
values.add(newPosition, object);
}
}
public List<String> getValues() {
return values;
}
@Override
public String[] getValuesArray() {
String[] valuesArray = new String[values.size()];
values.toArray(valuesArray);
return valuesArray;
}
public void add(String value) {
values.add(value);
}
public boolean contains(String value) {
return values.contains(value);
}
public void remove(String value) {
values.remove(value);
}
@Override
public Iterator<String> iterator() {
return values.iterator();
}
@Override
public int getNumberOfValues() {
return values.size();
}
@Override
public String getValuesString() {
StringBuffer valuesStringBuffer = new StringBuffer();
boolean first = true;
for (String value : values) {
if (!first) {
valuesStringBuffer.append(",");
}
first = false;
valuesStringBuffer.append(value);
}
return valuesStringBuffer.toString();
}
@Override
public String toString() {
return "list: " + getValuesString();
}
}
| agpl-3.0 |
egelke/eIDSuite | app/src/main/java/net/egelke/android/eid/viewmodel/Address.java | 1491 | /*
This file is part of eID Suite.
Copyright (C) 2014-2015 Egelke BVBA
eID Suite is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
eID Suite 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with eID Suite. If not, see <http://www.gnu.org/licenses/>.
*/
package net.egelke.android.eid.viewmodel;
import android.content.Context;
public class Address extends ViewObject {
private net.egelke.android.eid.model.Address address;
public Address(Context ctx) {
super(ctx);
}
public void setAddress(net.egelke.android.eid.model.Address value) {
this.address = value;
}
public net.egelke.android.eid.model.Address getAddress() {
return this.address;
}
public String getStreet() {
return address != null ? address.streetAndNumber : "";
}
public String getZip() {
return address != null ? address.zip : "";
}
public String getMunicipality() {
return address != null ? address.municipality : "";
}
}
| agpl-3.0 |
cgi-eoss/ftep | f-tep-logging/src/main/java/com/cgi/eoss/ftep/logging/Logging.java | 1757 | package com.cgi.eoss.ftep.logging;
import lombok.experimental.UtilityClass;
import org.apache.logging.log4j.CloseableThreadContext;
@UtilityClass
public class Logging {
public static final String USER_LOG_MESSAGE_FIELD = "userMessage";
public static CloseableThreadContext.Instance userLoggingContext() {
return CloseableThreadContext.put(USER_LOG_MESSAGE_FIELD, "1");
}
public static void withUserLoggingContext(Runnable runnable) {
try (CloseableThreadContext.Instance userCtc = Logging.userLoggingContext()) {
runnable.run();
}
}
public static CloseableThreadContext.Instance imageBuildLoggingContext(String serviceName, String buildFingerprint) {
return CloseableThreadContext
.put("serviceName", serviceName)
.put("buildFingerprint", buildFingerprint);
}
public static CloseableThreadContext.Instance jobLoggingContext(String extId, String jobId, String userId, String serviceId) {
return CloseableThreadContext
.put("zooId", extId)
.put("jobId", jobId)
.put("userId", userId)
.put("serviceId", serviceId);
}
public static void withJobLoggingContext(String extId, String jobId, String userId, String serviceId, Runnable runnable) {
try (CloseableThreadContext.Instance ctc = jobLoggingContext(extId, jobId, userId, serviceId)) {
runnable.run();
}
}
public static void withImageBuildLoggingContext(String serviceName, String buildFingerprint, Runnable runnable) {
try (CloseableThreadContext.Instance ctc = imageBuildLoggingContext(serviceName, buildFingerprint)) {
runnable.run();
}
}
}
| agpl-3.0 |
MCPTech/mycp | src/main/java/in/mycp/workers/ComputeWorker.java | 29207 | /*
mycloudportal - Self Service Portal for the cloud.
Copyright (C) 2012-2013 Mycloudportal Technologies Pvt Ltd
This file is part of mycloudportal.
mycloudportal is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mycloudportal 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with mycloudportal. If not, see <http://www.gnu.org/licenses/>.
*/
package in.mycp.workers;
import in.mycp.domain.AddressInfoP;
import in.mycp.domain.Asset;
import in.mycp.domain.AssetType;
import in.mycp.domain.Infra;
import in.mycp.domain.InstanceP;
import in.mycp.domain.ProductCatalog;
import in.mycp.remote.AccountLogService;
import in.mycp.utils.Commons;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.xerox.amazonws.ec2.InstanceType;
import com.xerox.amazonws.ec2.Jec2;
import com.xerox.amazonws.ec2.LaunchConfiguration;
import com.xerox.amazonws.ec2.ReservationDescription;
import com.xerox.amazonws.ec2.ReservationDescription.Instance;
/**
*
* @author Charudath Doddanakatte
* @author cgowdas@gmail.com
*
*/
@Component("computeWorker")
public class ComputeWorker extends Worker {
@Autowired
AccountLogService accountLogService;
protected static Logger logger = Logger.getLogger(ComputeWorker.class);
@Async
public void restartCompute(final Infra infra, final int instancePId,
final String userId) {
try {
logger.info("restartCompute " + infra.getCompany().getName()
+ " instance : " + instancePId);
accountLogService.saveLog(
"Started: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for " + InstanceP.findInstanceP(instancePId).getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
Jec2 ec2 = getNewJce2(infra);
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(InstanceP.findInstanceP(instancePId)
.getInstanceId());
ec2.rebootInstances(instanceIds);
for (Iterator iterator = instanceIds.iterator(); iterator.hasNext();) {
String instanceId = (String) iterator.next();
int SLEEP_TIME = 5000;
int preparationSleepTime = 0;
ReservationDescription reservationDescription = ec2
.describeInstances(
Collections.singletonList(instanceId)).get(0);
Instance instanceEc2 = reservationDescription.getInstances()
.get(0);
InstanceP instanceP = InstanceP
.findInstancePsByInstanceIdEquals(instanceId)
.getSingleResult();
while (!instanceEc2.isRunning() && !instanceEc2.isTerminated()) {
try {
instanceP.setState(Commons.REQUEST_STATUS.RESTARTING
+ "");
instanceP.merge();
logger.info("Instance " + instanceEc2.getInstanceId()
+ " still rebooting; sleeping " + SLEEP_TIME
+ "ms");
Thread.sleep(SLEEP_TIME);
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceEc2
.getInstanceId())).get(0);
instanceEc2 = reservationDescription.getInstances()
.get(0);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
logger.info("out of while loop, instanceEc2.isRunning() "
+ instanceEc2.isRunning());
if (instanceEc2.isRunning()) {
logger.info("EC2 instance is now running");
if (preparationSleepTime > 0) {
logger.info("Sleeping "
+ preparationSleepTime
+ "ms allowing instance services to start up properly.");
Thread.sleep(preparationSleepTime);
logger.info("Instance prepared - proceeding");
}
instanceP.setState(Commons.REQUEST_STATUS.running + "");
instanceP.merge();
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
} else {
instanceP.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instanceP.getAsset());
instanceP.merge();
accountLogService.saveLogAndSendMail(
"Error in: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
}
}
} catch (Exception e) {
logger.error(e.getMessage());// e.printStackTrace();
accountLogService
.saveLog(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instancePId + ", " + e.getMessage(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
}
}// end rebootInstances
@Async
public void startCompute(final Infra infra, final int instancePId,
final String userId) {
InstanceP instanceP = null;
try {
logger.info("startCompute " + infra.getCompany().getName()
+ " instance : " + instancePId);
accountLogService.saveLog(
"Started: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for " + InstanceP.findInstanceP(instancePId).getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
Jec2 ec2 = getNewJce2(infra);
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(InstanceP.findInstanceP(instancePId)
.getInstanceId());
ec2.startInstances(instanceIds);
for (Iterator iterator = instanceIds.iterator(); iterator.hasNext();) {
String instanceId = (String) iterator.next();
int SLEEP_TIME = 5000;
int preparationSleepTime = 0;
ReservationDescription reservationDescription = ec2
.describeInstances(
Collections.singletonList(instanceId)).get(0);
Instance instanceEc2 = reservationDescription.getInstances()
.get(0);
instanceP = InstanceP.findInstancePsByInstanceIdEquals(
instanceId).getSingleResult();
int INSTANCE_START_SLEEP_TIME = 5000;
long timeout = INSTANCE_START_SLEEP_TIME * 100;
long runDuration = 0;
while (!instanceEc2.isRunning() && !instanceEc2.isTerminated()) {
runDuration = runDuration + INSTANCE_START_SLEEP_TIME;
if (runDuration > timeout) {
logger.info("Tried enough.Am bored, quitting.");
break;
}
try {
instanceP
.setState(Commons.REQUEST_STATUS.STARTING + "");
instanceP.merge();
logger.info("Instance " + instanceEc2.getInstanceId()
+ " still booting; sleeping " + SLEEP_TIME
+ "ms");
Thread.sleep(SLEEP_TIME);
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceEc2
.getInstanceId())).get(0);
instanceEc2 = reservationDescription.getInstances()
.get(0);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
logger.info("out of while loop, instanceEc2.isRunning() "
+ instanceEc2.isRunning());
if (instanceEc2.isRunning()) {
logger.info("EC2 instance is now running");
if (preparationSleepTime > 0) {
logger.info("Sleeping "
+ preparationSleepTime
+ "ms allowing instance services to start up properly.");
Thread.sleep(preparationSleepTime);
logger.info("Instance prepared - proceeding");
}
instanceP.setState(Commons.REQUEST_STATUS.running + "");
instanceP.merge();
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
} else {
instanceP.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instanceP.getAsset());
instanceP.merge();
accountLogService.saveLogAndSendMail(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ InstanceP.findInstanceP(instancePId).getName(), Commons.task_name.COMPUTE
.name(),
Commons.task_status.FAIL.ordinal(), userId);
}
}
} catch (Exception e) {
logger.error(e.getMessage());// e.printStackTrace();
accountLogService
.saveLog(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instancePId + ", " + e.getMessage(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
try {
InstanceP instance1 = InstanceP.findInstanceP(instancePId);
instance1.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instance1.getAsset());
instance1.merge();
} catch (Exception e2) {
logger.error(e);
e.printStackTrace();
}
}
}// end startInstances
@Async
public void stopCompute(final Infra infra, final int instancePId,
final String userId) {
InstanceP instanceP = null;
try {
logger.info("stopCompute " + infra.getCompany().getName()
+ " instance: " + instancePId);
accountLogService.saveLog(
"Started: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for " + InstanceP.findInstanceP(instancePId).getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
Jec2 ec2 = getNewJce2(infra);
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(InstanceP.findInstanceP(instancePId)
.getInstanceId());
ec2.stopInstances(instanceIds, true);
for (Iterator iterator = instanceIds.iterator(); iterator.hasNext();) {
String instanceId = (String) iterator.next();
int SLEEP_TIME = 10000;
int preparationSleepTime = 0;
ReservationDescription reservationDescription = ec2
.describeInstances(
Collections.singletonList(instanceId)).get(0);
Instance instanceEc2 = reservationDescription.getInstances()
.get(0);
instanceP = InstanceP.findInstancePsByInstanceIdEquals(
instanceId).getSingleResult();
int INSTANCE_START_SLEEP_TIME = 5000;
long timeout = INSTANCE_START_SLEEP_TIME * 100;
long runDuration = 0;
while (instanceEc2.isRunning() || instanceEc2.isShuttingDown()) {
runDuration = runDuration + INSTANCE_START_SLEEP_TIME;
if (runDuration > timeout) {
logger.info("Tried enough.Am bored, quitting, is this not and EBS backed instance?");
break;
}
try {
instanceP.setState(Commons.REQUEST_STATUS.STOPPING
+ "");
instanceP.merge();
logger.info("Instance " + instanceEc2.getInstanceId()
+ " still shutting down; sleeping "
+ SLEEP_TIME + "ms");
Thread.sleep(SLEEP_TIME);
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceEc2
.getInstanceId())).get(0);
instanceEc2 = reservationDescription.getInstances()
.get(0);
} catch (Exception e) {
logger.error(e.getMessage());
// e.printStackTrace();
}
}
logger.info("out of while loop, instanceEc2.isRunning() "
+ instanceEc2.isRunning());
if (!instanceEc2.isRunning()) {
logger.info("EC2 instance is now stopped");
instanceP.setState(Commons.REQUEST_STATUS.STOPPED + "");
instanceP.merge();
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
}else{
logger.info("EC2 instance is still running");
instanceP.setState(Commons.REQUEST_STATUS.running + "");
instanceP.merge();
instanceP.getAsset().setEndTime(null);
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
}
}
} catch (Exception e) {
logger.error(e.getMessage());// e.printStackTrace();
accountLogService
.saveLog(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instancePId + ", " + e.getMessage(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
try {
InstanceP instance1 = InstanceP.findInstanceP(instancePId);
instance1.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instance1.getAsset());
instance1.merge();
} catch (Exception e2) {
logger.error(e);
e.printStackTrace();
}
}
}// end stopInstances
@Async
public void terminateCompute(final Infra infra, final int instancePId,
final String userId) {
try {
logger.info("terminateCompute " + infra.getCompany().getName()
+ " instance : " + instancePId);
accountLogService.saveLog(
"Started: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for " + InstanceP.findInstanceP(instancePId).getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
Jec2 ec2 = getNewJce2(infra);
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(InstanceP.findInstanceP(instancePId)
.getInstanceId());
try {
ec2.terminateInstances(instanceIds);
} catch (Exception e) {
logger.error(e.getMessage());// e.printStackTrace();
}
for (Iterator iterator = instanceIds.iterator(); iterator.hasNext();) {
String instanceId = (String) iterator.next();
int SLEEP_TIME = 5000;
int preparationSleepTime = 0;
ReservationDescription reservationDescription = null;
try {
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceId)).get(0);
} catch (Exception e) {
if (e.getMessage().contains("Index: 0, Size: 0")) {
throw new Exception(
"this instance is no more in the backend infra");
}
}
Instance instanceEc2 = reservationDescription.getInstances()
.get(0);
/*InstanceP instanceP = InstanceP
.findInstancePsByInstanceIdEquals(instanceId)
.getSingleResult();*/
InstanceP instanceP = InstanceP.findInstanceP(instancePId);
String ip4AddressInfoRemoval = instanceP.getIpAddress();
String instanceId4AddressInfoRemoval = instanceP.getInstanceId();
int INSTANCE_START_SLEEP_TIME = 5000;
long timeout = INSTANCE_START_SLEEP_TIME * 100;
long runDuration = 0;
while (!instanceEc2.isTerminated()) {
runDuration = runDuration + INSTANCE_START_SLEEP_TIME;
if (runDuration > timeout) {
logger.info("Tried enough.Am bored, quitting.");
break;
}
try {
instanceP.setState(Commons.REQUEST_STATUS.TERMINATING
+ "");
instanceP.merge();
logger.info("Instance " + instanceEc2.getInstanceId()
+ " pending termination; sleeping "
+ SLEEP_TIME + "ms");
Thread.sleep(SLEEP_TIME);
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceEc2
.getInstanceId())).get(0);
instanceEc2 = reservationDescription.getInstances()
.get(0);
} catch (Exception e) {
logger.error(e.getMessage());
// e.printStackTrace();
}
}
logger.info("out of while loop, instanceEc2.isTerminated() "
+ instanceEc2.isTerminated());
if (instanceEc2.isTerminated()) {
logger.info("EC2 instance is now Terminated");
if (preparationSleepTime > 0) {
logger.info("Sleeping "
+ preparationSleepTime
+ "ms allowing instance services to start up properly.");
Thread.sleep(preparationSleepTime);
logger.info("Instance prepared - proceeding");
}
instanceP.setState(Commons.REQUEST_STATUS.TERMINATED + "");
instanceP.merge();
setAssetEndTime(instanceP.getAsset());
try {
AddressInfoP a = AddressInfoP.findAddressInfoPsBy(infra, instanceId4AddressInfoRemoval, ip4AddressInfoRemoval).getSingleResult();
a.setStatus(Commons.ipaddress_STATUS.nobody+"");
setAssetEndTime(a.getAsset());
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
}
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instanceP.getName(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.SUCCESS.ordinal(), userId);
}
}
} catch (Exception e) {
logger.error(e.getMessage()); // e.printStackTrace();
accountLogService
.saveLog(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instancePId + ", " + e.getMessage(),
Commons.task_name.COMPUTE.name(),
Commons.task_status.FAIL.ordinal(), userId);
try {
InstanceP instance1 = InstanceP.findInstanceP(instancePId);
instance1.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instance1.getAsset());
instance1.merge();
} catch (Exception e2) {
logger.error(e2);
e2.printStackTrace();
}
}
}// end terminateInstances
@Async
public void createCompute(final Infra infra, final InstanceP instance,
final String userId) {
InstanceP instanceLocal = null;
try {
//String imageName = instance.getImageId();
String imageName = instance.getImage().getImageId();
String keypairName = instance.getKeyName();
String groupName = instance.getGroupName();
String instanceType = instance.getInstanceType();
logger.info("Launching " + infra.getCompany().getName()
+ " instance " + instance.getId() + " for image: "
+ imageName);
accountLogService.saveLog(
"Started: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instance.getName(), Commons.task_name.COMPUTE
.name(), Commons.task_status.SUCCESS.ordinal(),
userId);
Jec2 ec2 = getNewJce2(infra);
LaunchConfiguration launchConfiguration = new LaunchConfiguration(
imageName);
launchConfiguration.setKeyName(keypairName);
launchConfiguration.setSecurityGroup(Collections
.singletonList(groupName));
launchConfiguration.setInstanceType(InstanceType
.getTypeFromString(instanceType));
launchConfiguration.setMinCount(1);
launchConfiguration.setMaxCount(1);
ReservationDescription reservationDescription = ec2.runInstances(launchConfiguration);
instanceLocal = InstanceP.findInstanceP(instance.getId());
Instance instanceEc2 = reservationDescription.getInstances().get(0);
instanceLocal.setInstanceId(instanceEc2.getInstanceId());
instanceLocal.setDnsName(instanceEc2.getDnsName());
instanceLocal.setLaunchTime(instanceEc2.getLaunchTime().getTime());
instanceLocal.setKernelId(instanceEc2.getKernelId());
instanceLocal.setRamdiskId(instanceEc2.getRamdiskId());
instanceLocal.setPlatform(instanceEc2.getPlatform());
instanceLocal.setState(Commons.REQUEST_STATUS.STARTING + "");
instanceLocal = instanceLocal.merge();
int INSTANCE_START_SLEEP_TIME = 5000;
int preparationSleepTime = 0;
long timeout = INSTANCE_START_SLEEP_TIME * 400;
long runDuration = 0;
while (!instanceEc2.isRunning() && !instanceEc2.isTerminated()) {
runDuration = runDuration + INSTANCE_START_SLEEP_TIME;
if (runDuration > timeout) {
logger.info("Tried enough.Am bored, quitting.");
break;
}
try {
logger.info("Instance " + instanceEc2.getInstanceId()
+ " still starting up; sleeping "
+ INSTANCE_START_SLEEP_TIME + "ms");
Thread.sleep(INSTANCE_START_SLEEP_TIME);
reservationDescription = ec2.describeInstances(
Collections.singletonList(instanceEc2
.getInstanceId())).get(0);
instanceEc2 = reservationDescription.getInstances().get(0);
} catch (Exception e) {
logger.error(e.getMessage());
// e.printStackTrace();
}
}
logger.info("out of while loop, instanceEc2.isRunning() "
+ instanceEc2.isRunning());
if (instanceEc2.isRunning()) {
logger.info("EC2 instance is now running");
if (preparationSleepTime > 0) {
logger.info("Sleeping "
+ preparationSleepTime
+ "ms allowing instance services to start up properly.");
Thread.sleep(preparationSleepTime);
logger.info("Instance prepared - proceeding");
}
instanceLocal.setInstanceId(instanceEc2.getInstanceId());
instanceLocal.setDnsName(instanceEc2.getDnsName());
instanceLocal.setLaunchTime(instanceEc2.getLaunchTime()
.getTime());
instanceLocal.setKernelId(instanceEc2.getKernelId());
instanceLocal.setRamdiskId(instanceEc2.getRamdiskId());
instanceLocal.setPlatform(instanceEc2.getPlatform());
instanceLocal.setState(Commons.REQUEST_STATUS.running + "");
instanceLocal.setIpAddress(instanceEc2.getIpAddress());
instanceLocal.setPrivateIpAddress(instanceEc2.getPrivateIpAddress());
instanceLocal = instanceLocal.merge();
/*
* AddressInfoP addressInfoP = new AddressInfoP();
* addressInfoP.setInstanceId(instanceLocal.getInstanceId());
* addressInfoP.setName("Ip for " + instanceLocal.getName());
* addressInfoP.setPublicIp(instanceLocal.getDnsName());
* addressInfoP.setStatus(Commons.ipaddress_STATUS.associated +
* ""); addressInfoP = addressInfoP.merge();
*/
// create an addressInfo object for this compute's IP.
try {
AddressInfoP a = new AddressInfoP();//.findAddressInfoPsBy(infra, instanceLocal.getIpAddress()).getSingleResult();
ProductCatalog pc = null;
// Set<ProductCatalog> products = ;
List products = ProductCatalog.findProductCatalogsByInfra(
infra).getResultList();
for (Iterator iterator = products.iterator(); iterator
.hasNext();) {
ProductCatalog productCatalog = (ProductCatalog) iterator
.next();
if (productCatalog.getProductType().equals(
Commons.ProductType.IpAddress.getName())) {
pc = productCatalog;
}
}
/*
* ProductCatalog pc =
* ProductCatalog.findProductCatalogsByInfra(infra)
*
* .findProductCatalogsByProductTypeAndCompany(Commons.
* ProductType.IpAddress.getName(),
* instanceLocal.getAsset().
* getUser().getProject().getDepartment
* ().getCompany()).getSingleResult();
*/
/*System.out.println("finding alkl xingintg addressinfo objects with same publicIp and inactivating them "+instanceLocal.getIpAddress());*/
List<AddressInfoP> addresses = AddressInfoP.findAddressInfoPsBy(infra, instanceLocal.getIpAddress()).getResultList();
for (Iterator iterator = addresses.iterator(); iterator.hasNext(); ) {
AddressInfoP addressInfoP = (AddressInfoP) iterator.next();
setAssetEndTime(addressInfoP.getAsset());
}
a.setAsset(Commons.getNewAsset(
AssetType.findAssetTypesByNameEquals(
Commons.ProductType.IpAddress + "")
.getSingleResult(), instanceLocal
.getAsset().getUser(), pc));
a.setInstanceId(instanceLocal.getInstanceId());
a.setName("Ip for " + instanceLocal.getName());
a.setPublicIp(instanceLocal.getIpAddress());
a.setStatus(Commons.ipaddress_STATUS.auto_assigned + "");
a.setReason("Automatic Ip addres assigned");
setAssetStartTime(a.getAsset());
a.merge();
} catch (Exception e) {
Commons.setSessionMsg("Error while createrCompute, Instance "
+ instance.getName()
+ "<br> Reason: "
+ e.getMessage());
e.printStackTrace();
logger.error(e);
}
setAssetStartTime(instanceLocal.getAsset());
logger.info("Done creating " + instance.getName()
+ " and assigning ip " + instanceEc2.getDnsName());
accountLogService.saveLogAndSendMail(
"Complete: "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instance.getName(), Commons.task_name.COMPUTE
.name(), Commons.task_status.SUCCESS.ordinal(),
userId);
} else {
instanceLocal.setInstanceId(instanceEc2.getInstanceId());
instanceLocal.setDnsName(instanceEc2.getDnsName());
instanceLocal.setLaunchTime(instanceEc2.getLaunchTime()
.getTime());
instanceLocal.setKernelId(instanceEc2.getKernelId());
instanceLocal.setRamdiskId(instanceEc2.getRamdiskId());
instanceLocal.setPlatform(instanceEc2.getPlatform());
instanceLocal.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instanceLocal.getAsset());
instanceLocal = instanceLocal.merge();
setAssetEndTime(instanceLocal.getAsset());
throw new IllegalStateException(
"Failed to start a new instance");
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Error while creating instance");
accountLogService.saveLogAndSendMail(
"Error in "
+ this.getClass().getName()
+ " : "
+ Thread.currentThread().getStackTrace()[1]
.getMethodName().subSequence(0, Thread.currentThread().getStackTrace()[1]
.getMethodName().indexOf("_")) + " for "
+ instance.getName() + ", " + e.getMessage(),
Commons.task_name.COMPUTE.name(), Commons.task_status.FAIL
.ordinal(), userId);
try {
InstanceP instance1 = InstanceP.findInstanceP(instance.getId());
instance1.setState(Commons.REQUEST_STATUS.FAILED + "");
setAssetEndTime(instance1.getAsset());
instance1.merge();
setAssetEndTime(instance1.getAsset());
} catch (Exception e2) {
logger.error(e);
e.printStackTrace();
}
Thread.currentThread().interrupt();
}
}// work
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/processversion/ActionGet.java | 2172 | package com.x.processplatform.assemble.designer.jaxrs.processversion;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.processplatform.assemble.designer.Business;
import com.x.processplatform.core.entity.element.Application;
import com.x.processplatform.core.entity.element.Process;
import com.x.processplatform.core.entity.element.ProcessVersion;
class ActionGet extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
ProcessVersion processVersion = emc.find(id, ProcessVersion.class);
if (null == processVersion) {
throw new ExceptionEntityNotExist(id, ProcessVersion.class);
}
Process process = emc.find(processVersion.getProcess(), Process.class);
if (null == process) {
throw new ExceptionEntityNotExist(processVersion.getProcess(), Process.class);
}
Application application = emc.find(process.getApplication(), Application.class);
if (null == application) {
throw new ExceptionEntityNotExist(process.getApplication(), Application.class);
}
if (!business.editable(effectivePerson, application)) {
throw new ExceptionAccessDenied(effectivePerson);
}
Wo wo = Wo.copier.copy(processVersion);
result.setData(wo);
return result;
}
}
public static class Wo extends ProcessVersion {
private static final long serialVersionUID = 1541438199059150837L;
static WrapCopier<ProcessVersion, Wo> copier = WrapCopierFactory.wo(ProcessVersion.class, Wo.class, null,
JpaObject.FieldsInvisible);
}
}
| agpl-3.0 |
kuzavas/ephesoft | dcma-core/src/main/java/com/ephesoft/dcma/core/common/Order.java | 3012 | /*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Ephesoft, Inc. headquarters at 111 Academy Way,
* Irvine, CA 92617, USA. or at email address info@ephesoft.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Ephesoft" logo.
* If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by Ephesoft".
********************************************************************************/
package com.ephesoft.dcma.core.common;
import java.io.Serializable;
/**
* This class handles the ordering.
*
* @author Ephesoft
* @version 1.0
* @see java.io.Serializable
*/
public class Order implements Serializable {
/**
* serialVersionUID long.
*/
private static final long serialVersionUID = 1L;
/**
* sortProperty DomainProperty.
*/
private DomainProperty sortProperty;
/**
* ascending boolean.
*/
private boolean ascending;
/**
* Constructor.
*/
public Order() {
super();
}
/**
* Constructor.
* @param sortProperty DomainProperty
* @param ascending boolean
*/
public Order(DomainProperty sortProperty, boolean ascending) {
super();
this.sortProperty = sortProperty;
this.ascending = ascending;
}
/**
* To get Sort Property.
* @return the sortProperty
*/
public DomainProperty getSortProperty() {
return sortProperty;
}
/**
* To check whether ascending or not.
* @return the ascending
*/
public boolean isAscending() {
return ascending;
}
}
| agpl-3.0 |
hbz/etikett | test/tests/TestLobidLabelResolver.java | 1300 | /*Copyright (c) 2019 "hbz"
This file is part of etikett.
etikett is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tests;
import org.junit.Assert;
import org.junit.Test;
import helper.EtikettMaker;
import helper.LobidLabelResolver;
/**
* @author Jan Schnasse
*
*/
public class TestLobidLabelResolver {
@Test
public void test() {
String label = LobidLabelResolver.lookup("https://lobid.org/resources/HT018920238", null);
Assert.assertEquals("Digitales Archiv NRW", label);
}
@Test
public void testEtikett() {
String label = EtikettMaker.lookUpLabel("https://lobid.org/resources/HT018920238", "de");
Assert.assertEquals("Digitales Archiv NRW", label);
}
}
| agpl-3.0 |
Sage-Bionetworks/rstudio | src/gwt/src/org/rstudio/core/client/layout/FadeInAnimation.java | 1921 | /*
* FadeInAnimation.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.core.client.layout;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Widget;
import java.util.ArrayList;
public class FadeInAnimation extends Animation
{
public FadeInAnimation(Widget widget,
double targetOpacity,
Command callback)
{
this(new ArrayList<Widget>(), targetOpacity, callback);
widgets_.add(widget);
}
public FadeInAnimation(ArrayList<Widget> widgets,
double targetOpacity,
Command callback)
{
this.widgets_ = widgets;
targetOpacity_ = targetOpacity;
callback_ = callback;
}
@Override
protected void onStart()
{
for (Widget w : widgets_)
w.getElement().getStyle().setDisplay(Style.Display.BLOCK);
super.onStart();
}
@Override
protected void onUpdate(double progress)
{
for (Widget w : widgets_)
w.getElement().getStyle().setOpacity(targetOpacity_ * progress);
}
@Override
protected void onComplete()
{
for (Widget w : widgets_)
{
w.getElement().getStyle().setOpacity(targetOpacity_);
}
if (callback_ != null)
callback_.execute();
}
private ArrayList<Widget> widgets_;
private final double targetOpacity_;
private final Command callback_;
}
| agpl-3.0 |
WebDataConsulting/billing | src/java/com/sapienter/jbilling/server/order/db/OrderLineTypeDTO.java | 3414 | /*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jbilling 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with jbilling. If not, see <http://www.gnu.org/licenses/>.
This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015.
You may download the latest source from webdataconsulting.github.io.
*/
package com.sapienter.jbilling.server.order.db;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.sapienter.jbilling.server.util.ServerConstants;
import com.sapienter.jbilling.server.util.db.AbstractDescription;
@Entity
@Table(name="order_line_type")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class OrderLineTypeDTO extends AbstractDescription implements java.io.Serializable {
private int id;
private Integer editable;
private Set<OrderLineDTO> orderLineDTOs = new HashSet<OrderLineDTO>(0);
public OrderLineTypeDTO() {
}
public OrderLineTypeDTO(int id, Integer editable) {
this.id = id;
this.editable = editable;
}
public OrderLineTypeDTO(int id, Integer editable, Set<OrderLineDTO> orderLineDTOs) {
this.id = id;
this.editable = editable;
this.orderLineDTOs = orderLineDTOs;
}
@Id
@Column(name="id", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="editable", nullable=false)
public Integer getEditable() {
return this.editable;
}
public void setEditable(Integer editable) {
this.editable = editable;
}
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="orderLineType")
public Set<OrderLineDTO> getOrderLines() {
return this.orderLineDTOs;
}
public void setOrderLines(Set<OrderLineDTO> orderLineDTOs) {
this.orderLineDTOs = orderLineDTOs;
}
public void addOrderLine ( OrderLineDTO orderLineDTO){this.orderLineDTOs.add(orderLineDTO);}
public void removeOrderLine ( OrderLineDTO orderLineDTO){this.orderLineDTOs.remove(orderLineDTO);}
@Transient
protected String getTable() {
return ServerConstants.TABLE_ORDER_LINE_TYPE;
}
@Transient
public String getTitle(Integer languageId) {
return getDescription(languageId, "description");
}
}
| agpl-3.0 |
CodeSphere/termitaria | TermitariaTS/src/ro/cs/ts/cm/Project.java | 5935 | /*******************************************************************************
* This file is part of Termitaria, a project management tool
* Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro
*
* Termitaria is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Termitaria. If not, see <http://www.gnu.org/licenses/> .
******************************************************************************/
package ro.cs.ts.cm;
import ro.cs.ts.business.BLProjectDetails;
import ro.cs.ts.exception.BusinessException;
import ro.cs.ts.om.Person;
/**
*
* @author Adelina
*/
public class Project {
private int projectId;
private String name;
private Integer clientId;
private Integer managerId;
private Integer organizationId;
private Client client;
private String clientName;
private Person manager;
private byte status;
private boolean hasProjectDetail;
private ProjectTeam projectTeam;
private String panelHeaderName; // header name for the info panel
public Project() {
}
public ProjectTeam getProjectTeam() {
return projectTeam;
}
public void setProjectTeam(ProjectTeam projectTeam) {
this.projectTeam = projectTeam;
}
/**
* @return the projectId
*/
public int getProjectId() {
return projectId;
}
/**
* @param projectId the projectId to set
*/
public void setProjectId(int projectId) {
this.projectId = projectId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the clientId
*/
public Integer getClientId() {
return clientId;
}
/**
* @param clientId the clientId to set
*/
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
/**
* @return the managerId
*/
public Integer getManagerId() {
return managerId;
}
/**
* @param managerId the managerId to set
*/
public void setManagerId(Integer managerId) {
this.managerId = managerId;
}
/**
* @return the organizationId
*/
public Integer getOrganizationId() {
return organizationId;
}
/**
* @param organizationId the organizationId to set
*/
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
/**
* @return the status
*/
public byte getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(byte status) {
this.status = status;
}
/**
* @return the client
*/
public Client getClient() {
return client;
}
/**
* @param client the client to set
*/
public void setClient(Client client) {
this.client = client;
}
/**
* @return the manager
*/
public Person getManager() {
return manager;
}
/**
* @param manager the manager to set
*/
public void setManager(Person manager) {
this.manager = manager;
}
/**
* @return the hasProjectDetail
*/
public boolean isHasProjectDetail() {
try {
hasProjectDetail = BLProjectDetails.getInstance().hasProjectDetails(getProjectId());
} catch (BusinessException e) {
e.printStackTrace();
}
return hasProjectDetail;
}
/**
* @param hasProjectDetail the hasProjectDetail to set
*/
public void setHasProjectDetail(boolean hasProjectDetail) {
this.hasProjectDetail = hasProjectDetail;
}
/**
* @return the panelHeaderName
*/
public String getPanelHeaderName() {
return panelHeaderName;
}
/**
* @param panelHeaderName the panelHeaderName to set
*/
public void setPanelHeaderName(String panelHeaderName) {
this.panelHeaderName = panelHeaderName;
}
/**
* @return the clientName
*/
public String getClientName() {
return clientName;
}
/**
* @param clientName the clientName to set
*/
public void setClientName(String clientName) {
this.clientName = clientName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
sb.append(this.getClass().getSimpleName());
sb.append(": ");
sb.append("projectId = ") .append(projectId) .append(", ");
sb.append("name = ") .append(name) .append(", ");
sb.append("organisationId = ") .append(organizationId) .append(", ");
sb.append("clientId = ") .append(clientId) .append(", ");
sb.append("status = ") .append(status) .append(", ");
sb.append("managerId = ") .append(managerId) .append("] ");
return sb.toString();
}
@Override
public boolean equals (Object obj){
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Project other = (Project) obj;
if (this.projectId != other.projectId) {
return false;
}
if ((this.name == null) ? (other.name != null)
: !this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public int hashCode(){
int hash = 5;
hash = 67 * hash + this.projectId;
hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
}
| agpl-3.0 |
FullMetal210/milton2 | milton-client/src/main/java/io/milton/httpclient/Utils.java | 9088 | /*
* Copyright 2012 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 io.milton.httpclient;
import io.milton.common.Path;
import io.milton.http.exceptions.BadRequestException;
import io.milton.http.exceptions.ConflictException;
import io.milton.http.exceptions.NotAuthorizedException;
import io.milton.http.exceptions.NotFoundException;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author mcevoyb
*/
public class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
/**
* Convert the path to a url encoded string, by url encoding each path of the
* path. Will not be suffixed with a slash
*
* @param path
* @return
*/
public static String buildEncodedUrl(Path path) {
String url = "";
String[] arr = path.getParts();
for (int i = 0; i < arr.length; i++) {
String s = arr[i];
if (i > 0) {
url += "/";
}
url += io.milton.common.Utils.percentEncode(s);
}
return url;
}
/**
* Execute the given request, populate any returned content to the outputstream,
* and return the status code
*
* @param client
* @param m
* @param out - may be null
* @return
* @throws IOException
*
*/
public static int executeHttpWithStatus(HttpClient client, HttpUriRequest m, OutputStream out, HttpContext context) throws IOException {
HttpResult result = executeHttpWithResult(client, m, out, context);
return result.getStatusCode();
}
public static HttpResult executeHttpWithResult(HttpClient client, HttpUriRequest m, OutputStream out, HttpContext context) throws IOException {
HttpResponse resp = client.execute(m, context);
HttpEntity entity = resp.getEntity();
if( entity != null ) {
InputStream in = null;
try {
in = entity.getContent();
if( out != null ) {
IOUtils.copy(in, out);
}
} finally {
IOUtils.closeQuietly(in);
}
}
Map<String,String> mapOfHeaders = new HashMap<String, String>();
Header[] respHeaders = resp.getAllHeaders();
for( Header h : respHeaders) {
mapOfHeaders.put(h.getName(), h.getValue()); // TODO: should concatenate multi-valued headers
}
HttpResult result = new HttpResult(resp.getStatusLine().getStatusCode(), mapOfHeaders);
return result;
}
public static void close(InputStream in) {
try {
if (in == null) {
return;
}
in.close();
} catch (IOException ex) {
log.warn("Exception closing stream: " + ex.getMessage());
}
}
public static void close(OutputStream out) {
try {
if (out == null) {
return;
}
out.close();
} catch (IOException ex) {
log.warn("Exception closing stream: " + ex.getMessage());
}
}
public static long write(InputStream in, OutputStream out, final ProgressListener listener) throws IOException {
long bytes = 0;
byte[] arr = new byte[1024];
int s = in.read(arr);
bytes += s;
try {
while (s >= 0) {
if (listener != null && listener.isCancelled()) {
throw new CancelledException();
}
out.write(arr, 0, s);
s = in.read(arr);
bytes += s;
if (listener != null) {
listener.onProgress(bytes, null, null);
}
}
} catch (IOException e) {
throw e;
} catch (Throwable e) {
log.error("exception copying bytes", e);
throw new RuntimeException(e);
}
return bytes;
}
/**
* Wraps the outputstream in a bufferedoutputstream and writes to it
*
* the outputstream is closed and flushed before returning
*
* @param in
* @param out
* @param listener
* @throws IOException
*/
public static long writeBuffered(InputStream in, OutputStream out, final ProgressListener listener) throws IOException {
BufferedOutputStream bout = null;
try {
bout = new BufferedOutputStream(out);
long bytes = Utils.write(in, out, listener);
bout.flush();
out.flush();
return bytes;
} finally {
Utils.close(bout);
Utils.close(out);
}
}
public static void processResultCode(int result, String href) throws io.milton.httpclient.HttpException, NotAuthorizedException, ConflictException, BadRequestException, NotFoundException {
if (result >= 200 && result < 300) {
return;
} else if (result >= 300 && result < 400) {
switch (result) {
case 301:
throw new RedirectException(result, href);
case 302:
throw new RedirectException(result, href);
case 304:
break;
default:
throw new RedirectException(result, href);
}
} else if (result >= 400 && result < 500) {
switch (result) {
case 400:
throw new BadRequestException(href);
case 401:
throw new NotAuthorizedException(href, null);
case 403:
throw new NotAuthorizedException(href, null);
case 404:
throw new NotFoundException(href);
case 405:
throw new MethodNotAllowedException(result, href);
case 409:
throw new ConflictException(href);
default:
throw new GenericHttpException(result, href);
}
} else if (result >= 500 && result < 600) {
throw new InternalServerError(href, result);
} else {
throw new GenericHttpException(result, href);
}
}
public static class CancelledException extends IOException {
}
public static String format (Map<String,String> parameters, final String encoding) {
final StringBuilder result = new StringBuilder();
for ( Entry<String, String> p : parameters.entrySet()) {
final String encodedName = encode(p.getKey(), encoding);
final String value = p.getValue();
final String encodedValue = value != null ? encode(value, encoding) : "";
if (result.length() > 0) {
result.append("&");
}
result.append(encodedName);
result.append("=");
result.append(encodedValue);
}
return result.toString();
}
// private static String decode (final String content, final String encoding) {
// try {
// return URLDecoder.decode(content,
// encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET);
// } catch (UnsupportedEncodingException problem) {
// throw new IllegalArgumentException(problem);
// }
// }
private static String encode (final String content, final String encoding) {
try {
return URLEncoder.encode(content, encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET);
} catch (UnsupportedEncodingException problem) {
throw new IllegalArgumentException(problem);
}
}
}
| agpl-3.0 |
torakiki/sejda | sejda-model/src/test/java/org/sejda/model/pdf/headerfooter/NumberingTest.java | 1564 | /*
* Created on 29/dic/2012
* Copyright 2011 by Andrea Vacondio (andrea.vacondio@gmail.com).
*
* This file is part of the Sejda source code
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sejda.model.pdf.headerfooter;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
/**
* @author Andrea Vacondio
*
*/
public class NumberingTest {
@Test
public void testFormatForLabelArabic() {
Numbering victim = new Numbering(NumberingStyle.ARABIC, 100);
assertThat(victim.styledLabelFor(110), is("110"));
}
@Test
public void testFormatForLabelRoman() {
Numbering victim = new Numbering(NumberingStyle.ROMAN, 100);
assertThat(victim.styledLabelFor(110), is("CX"));
}
@Test(expected = IllegalArgumentException.class)
public void testRequiredStyle() {
new Numbering(null, 100);
}
}
| agpl-3.0 |