repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
cabralje/niem-tools | niemtools-bouml/src/fr/bouml/UmlSequenceMessage.java | 165 | package fr.bouml;
/**
* this class manages messages in a sequence diagram,
* you can modify it
*/
class UmlSequenceMessage extends UmlBaseSequenceMessage {
}
| gpl-3.0 |
endlos99/xdt99 | ide/idea/src/main/gen/net/endlos/xdt99/xbas99l/psi/Xbas99LSubprog.java | 253 | // This is a generated file. Not intended for manual editing.
package net.endlos.xdt99.xbas99l.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface Xbas99LSubprog extends PsiElement {
}
| gpl-3.0 |
Martin-Spamer/java-coaching | src/main/java/coaching/model/Driver.java | 306 | /**
* Created on 06-Jul-2004
*/
package coaching.model;
/**
* Driver class.
*/
public class Driver extends AbstractPerson {
/**
* Instantiates a new driver.
*
* @param name the name
*/
public Driver(final String name) {
super(name);
}
}
| gpl-3.0 |
scoutant/tf | src/org/scoutant/tf/util/ColorUtil.java | 1416 | package org.scoutant.tf.util;
import android.graphics.Color;
import android.graphics.Paint;
public class ColorUtil {
// public static final int GREEN = Color.rgb(0, 206, 0); // ZT Green // 00CE00
public static final int GREEN = Color.rgb(0, 180, 0);
public static final int ORANGE = Color.rgb( 253, 129, 38); // FD8126
public static final int RED = Color.RED;
public static final int GRAY = Color.rgb( 192, 192, 192);
// if color negative number?
public static int color(int color) {
float r = Color.red(color)+1;
float g = Color.green(color)+1;
float b = Color.blue(color)+1;
if (2*g>=3*r && g/b>=2) return GREEN;
if (r/g>4 && r/b>4) return RED;
if (r/b>=3 && g/b>=2 && r>g*1.2) return ORANGE;
// at Sytadin, yellow stands for 'works', lets consider green
if (r>150 && g>150 && b<50) return GREEN;
if (r/b>0.8 && r/b<1.3 && g/b>0.8 && g/b<1.3) return GRAY;
// Log.e(tag, "Warn : nok color extraction for: " + color + ". r : " + r +", g : " +g +", b : " + b);
return Color.BLACK;
}
public static String toRGB(int color) {
return "[" + Color.red(color) + " | " + Color.green(color) + " | " + Color.blue(color) + "]";
}
public static String toRGB(Paint paint) {
if (paint==null) return "null";
return toRGB(paint.getColor());
}
}
//public static final int GREEN2 = Color.rgb(51, 187, 0); // Google green // 33BB00
// Color.rgb( 158, 11, 11); // Red used by Google
| gpl-3.0 |
AraujoJordan/jampa-better-bus | src/heuristic/AStarNode.java | 1129 | package heuristic;
import grafo.Node;
public class AStarNode {
private int father_id;
private Node node;
private double F;
private double coast;
private double distance;
public AStarNode(Node node, int father, double coast, double distance) {
this.father_id = father;
this.node = node;
this.F = coast + distance;
this.coast = coast;
this.distance = distance;
}
public int getFatherID() {
return father_id;
}
public void setFatherID(int id) {
this.father_id = id;
}
public double getF() {
return F;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public double getCoast() {
return coast;
}
public void setCoast(double coast) {
this.coast = coast;
this.F = this.coast + this.distance;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
this.F = this.coast + this.distance;
}
}
| gpl-3.0 |
washi18/pricing_demo | src/com/android/model/CElementos.java | 14337 | package com.android.model;
import java.util.ArrayList;
import com.android.dao.CElementosDAO;
import com.android.dao.CItemsDAO;
public class CElementos {
private int cElementosCod;// integer,
private int cItemsCod;// integer,
private int cSubMenuCod;// integer,
private String cNombre1Idioma1;// varchar(200),
private String cNombre1Idioma2;// varchar(200),
private String cNombre1Idioma3;// varchar(200),
private String cNombre1Idioma4;// varchar(200),
private String cNombre1Idioma5;// varchar(200),
private String cNombre2Idioma1;// varchar(200),
private String cNombre2Idioma2;// varchar(200),
private String cNombre2Idioma3;// varchar(200),
private String cNombre2Idioma4;// varchar(200),
private String cNombre2Idioma5;// varchar(200),
private String cNombre3Idioma1;// varchar(200),
private String cNombre3Idioma2;// varchar(200),
private String cNombre3Idioma3;// varchar(200),
private String cNombre3Idioma4;// varchar(200),
private String cNombre3Idioma5;// varchar(200),
private String cImagen1;// varchar(100),
private String cImagen2;// varchar(100),
private String cImagen3;// varchar(100),
private String cDescripcionIdioma1;// text,
private String cDescripcionIdioma2;// text,
private String cDescripcionIdioma3;// text,
private String cDescripcionIdioma4;// text,
private String cDescripcionIdioma5;// text,
private String cDirigidoIdioma1;// text,
private String cDirigidoIdioma2;// text,
private String cDirigidoIdioma3;// text,
private String cDirigidoIdioma4;// text,
private String cDirigidoIdioma5;// text,
private ArrayList<CDestinoMovil> listaDestinosMovil;
private ArrayList<CDatosGenerales> listaDatosGenerales;
private String nameItem;
private String nameSubMenu;
private boolean update;
private boolean vistaMobil;
private boolean modoSubMenu;
private boolean modoItem;
private boolean abrirEditorDescripcion;
private boolean abrirEditorDirigido;
//======================================
public int getcElementosCod() {
return cElementosCod;
}
public void setcElementosCod(int cElementosCod) {
this.cElementosCod = cElementosCod;
}
public int getcItemsCod() {
return cItemsCod;
}
public void setcItemsCod(int cItemsCod) {
this.cItemsCod = cItemsCod;
}
public int getcSubMenuCod() {
return cSubMenuCod;
}
public void setcSubMenuCod(int cSubMenuCod) {
this.cSubMenuCod = cSubMenuCod;
}
public String getcNombre1Idioma1() {
return cNombre1Idioma1;
}
public void setcNombre1Idioma1(String cNombre1Idioma1) {
this.cNombre1Idioma1 = cNombre1Idioma1;
}
public String getcNombre1Idioma2() {
return cNombre1Idioma2;
}
public void setcNombre1Idioma2(String cNombre1Idioma2) {
this.cNombre1Idioma2 = cNombre1Idioma2;
}
public String getcNombre1Idioma3() {
return cNombre1Idioma3;
}
public void setcNombre1Idioma3(String cNombre1Idioma3) {
this.cNombre1Idioma3 = cNombre1Idioma3;
}
public String getcNombre1Idioma4() {
return cNombre1Idioma4;
}
public void setcNombre1Idioma4(String cNombre1Idioma4) {
this.cNombre1Idioma4 = cNombre1Idioma4;
}
public String getcNombre1Idioma5() {
return cNombre1Idioma5;
}
public void setcNombre1Idioma5(String cNombre1Idioma5) {
this.cNombre1Idioma5 = cNombre1Idioma5;
}
public String getcNombre2Idioma1() {
return cNombre2Idioma1;
}
public void setcNombre2Idioma1(String cNombre2Idioma1) {
this.cNombre2Idioma1 = cNombre2Idioma1;
}
public String getcNombre2Idioma2() {
return cNombre2Idioma2;
}
public void setcNombre2Idioma2(String cNombre2Idioma2) {
this.cNombre2Idioma2 = cNombre2Idioma2;
}
public String getcNombre2Idioma3() {
return cNombre2Idioma3;
}
public void setcNombre2Idioma3(String cNombre2Idioma3) {
this.cNombre2Idioma3 = cNombre2Idioma3;
}
public String getcNombre2Idioma4() {
return cNombre2Idioma4;
}
public void setcNombre2Idioma4(String cNombre2Idioma4) {
this.cNombre2Idioma4 = cNombre2Idioma4;
}
public String getcNombre2Idioma5() {
return cNombre2Idioma5;
}
public void setcNombre2Idioma5(String cNombre2Idioma5) {
this.cNombre2Idioma5 = cNombre2Idioma5;
}
public String getcNombre3Idioma1() {
return cNombre3Idioma1;
}
public void setcNombre3Idioma1(String cNombre3Idioma1) {
this.cNombre3Idioma1 = cNombre3Idioma1;
}
public String getcNombre3Idioma2() {
return cNombre3Idioma2;
}
public void setcNombre3Idioma2(String cNombre3Idioma2) {
this.cNombre3Idioma2 = cNombre3Idioma2;
}
public String getcNombre3Idioma3() {
return cNombre3Idioma3;
}
public void setcNombre3Idioma3(String cNombre3Idioma3) {
this.cNombre3Idioma3 = cNombre3Idioma3;
}
public String getcNombre3Idioma4() {
return cNombre3Idioma4;
}
public void setcNombre3Idioma4(String cNombre3Idioma4) {
this.cNombre3Idioma4 = cNombre3Idioma4;
}
public String getcNombre3Idioma5() {
return cNombre3Idioma5;
}
public void setcNombre3Idioma5(String cNombre3Idioma5) {
this.cNombre3Idioma5 = cNombre3Idioma5;
}
public String getcImagen1() {
return cImagen1;
}
public void setcImagen1(String cImagen1) {
this.cImagen1 = cImagen1;
}
public String getcImagen2() {
return cImagen2;
}
public void setcImagen2(String cImagen2) {
this.cImagen2 = cImagen2;
}
public String getcImagen3() {
return cImagen3;
}
public void setcImagen3(String cImagen3) {
this.cImagen3 = cImagen3;
}
public String getcDescripcionIdioma1() {
return cDescripcionIdioma1;
}
public void setcDescripcionIdioma1(String cDescripcionIdioma1) {
this.cDescripcionIdioma1 = cDescripcionIdioma1;
}
public String getcDescripcionIdioma2() {
return cDescripcionIdioma2;
}
public void setcDescripcionIdioma2(String cDescripcionIdioma2) {
this.cDescripcionIdioma2 = cDescripcionIdioma2;
}
public String getcDescripcionIdioma3() {
return cDescripcionIdioma3;
}
public void setcDescripcionIdioma3(String cDescripcionIdioma3) {
this.cDescripcionIdioma3 = cDescripcionIdioma3;
}
public String getcDescripcionIdioma4() {
return cDescripcionIdioma4;
}
public void setcDescripcionIdioma4(String cDescripcionIdioma4) {
this.cDescripcionIdioma4 = cDescripcionIdioma4;
}
public String getcDescripcionIdioma5() {
return cDescripcionIdioma5;
}
public void setcDescripcionIdioma5(String cDescripcionIdioma5) {
this.cDescripcionIdioma5 = cDescripcionIdioma5;
}
public String getcDirigidoIdioma1() {
return cDirigidoIdioma1;
}
public void setcDirigidoIdioma1(String cDirigidoIdioma1) {
this.cDirigidoIdioma1 = cDirigidoIdioma1;
}
public String getcDirigidoIdioma2() {
return cDirigidoIdioma2;
}
public void setcDirigidoIdioma2(String cDirigidoIdioma2) {
this.cDirigidoIdioma2 = cDirigidoIdioma2;
}
public String getcDirigidoIdioma3() {
return cDirigidoIdioma3;
}
public void setcDirigidoIdioma3(String cDirigidoIdioma3) {
this.cDirigidoIdioma3 = cDirigidoIdioma3;
}
public String getcDirigidoIdioma4() {
return cDirigidoIdioma4;
}
public void setcDirigidoIdioma4(String cDirigidoIdioma4) {
this.cDirigidoIdioma4 = cDirigidoIdioma4;
}
public String getcDirigidoIdioma5() {
return cDirigidoIdioma5;
}
public void setcDirigidoIdioma5(String cDirigidoIdioma5) {
this.cDirigidoIdioma5 = cDirigidoIdioma5;
}
public String getNameItem() {
return nameItem;
}
public void setNameItem(String nameItem) {
this.nameItem = nameItem;
}
public String getNameSubMenu() {
return nameSubMenu;
}
public void setNameSubMenu(String nameSubMenu) {
this.nameSubMenu = nameSubMenu;
}
public boolean isUpdate() {
return update;
}
public void setUpdate(boolean update) {
this.update = update;
}
public boolean isVistaMobil() {
return vistaMobil;
}
public void setVistaMobil(boolean vistaMobil) {
this.vistaMobil = vistaMobil;
}
public boolean isModoSubMenu() {
return modoSubMenu;
}
public void setModoSubMenu(boolean modoSubMenu) {
this.modoSubMenu = modoSubMenu;
}
public boolean isModoItem() {
return modoItem;
}
public void setModoItem(boolean modoItem) {
this.modoItem = modoItem;
}
public ArrayList<CDestinoMovil> getListaDestinosMovil() {
return listaDestinosMovil;
}
public void setListaDestinosMovil(ArrayList<CDestinoMovil> listaDestinosMovil) {
this.listaDestinosMovil = listaDestinosMovil;
}
public ArrayList<CDatosGenerales> getListaDatosGenerales() {
return listaDatosGenerales;
}
public void setListaDatosGenerales(ArrayList<CDatosGenerales> listaDatosGenerales) {
this.listaDatosGenerales = listaDatosGenerales;
}
public boolean isAbrirEditorDescripcion() {
return abrirEditorDescripcion;
}
public void setAbrirEditorDescripcion(boolean abrirEditorDescripcion) {
this.abrirEditorDescripcion = abrirEditorDescripcion;
}
public boolean isAbrirEditorDirigido() {
return abrirEditorDirigido;
}
public void setAbrirEditorDirigido(boolean abrirEditorDirigido) {
this.abrirEditorDirigido = abrirEditorDirigido;
}
//===========================================
public CElementos() {
// TODO Auto-generated constructor stub
this.cItemsCod=0;// integer,
this.cSubMenuCod=0;
this.cNombre1Idioma1="";// varchar(200),
this.cNombre1Idioma2="";// varchar(200),
this.cNombre1Idioma3="";// varchar(200),
this.cNombre1Idioma4="";// varchar(200),
this.cNombre1Idioma5="";// varchar(200),
this.cNombre2Idioma1="";// varchar(200),
this.cNombre2Idioma2="";// varchar(200),
this.cNombre2Idioma3="";// varchar(200),
this.cNombre2Idioma4="";// varchar(200),
this.cNombre2Idioma5="";// varchar(200),
this.cNombre3Idioma1="";// varchar(200),
this.cNombre3Idioma2="";// varchar(200),
this.cNombre3Idioma3="";// varchar(200),
this.cNombre3Idioma4="";// varchar(200),
this.cNombre3Idioma5="";// varchar(200),
this.cImagen1="";// varchar(100),
this.cImagen2="";// varchar(100),
this.cImagen3="";// varchar(100),
this.cDescripcionIdioma1="";
this.cDescripcionIdioma2="";
this.cDescripcionIdioma3="";
this.cDescripcionIdioma4="";
this.cDescripcionIdioma5="";
this.cDirigidoIdioma1="";// text,
this.cDirigidoIdioma2="";// text,
this.cDirigidoIdioma3="";// text,
this.cDirigidoIdioma4="";// text,
this.cDirigidoIdioma5="";
this.update=false;
this.vistaMobil=false;
this.modoItem=false;
this.modoSubMenu=false;
this.abrirEditorDescripcion=false;
this.abrirEditorDirigido=false;
}
public CElementos(int cElementosCod, int cItemsCod,int cSubMenuCod, String cNombre1Idioma1, String cNombre1Idioma2,
String cNombre1Idioma3, String cNombre1Idioma4, String cNombre1Idioma5, String cNombre2Idioma1,
String cNombre2Idioma2, String cNombre2Idioma3, String cNombre2Idioma4, String cNombre2Idioma5,
String cNombre3Idioma1, String cNombre3Idioma2, String cNombre3Idioma3, String cNombre3Idioma4,
String cNombre3Idioma5, String cImagen1, String cImagen2, String cImagen3, String cDescripcionIdioma1,
String cDescripcionIdioma2,String cDescripcionIdioma3,String cDescripcionIdioma4,String cDescripcionIdioma5,
String cDirigidoIdioma1,String cDirigidoIdioma2, String cDirigidoIdioma3, String cDirigidoIdioma4,
String cDirigidoIdioma5) {
this.cElementosCod = cElementosCod;
this.cItemsCod = cItemsCod;
this.cSubMenuCod = cSubMenuCod;
this.cNombre1Idioma1 = cNombre1Idioma1;
this.cNombre1Idioma2 = cNombre1Idioma2;
this.cNombre1Idioma3 = cNombre1Idioma3;
this.cNombre1Idioma4 = cNombre1Idioma4;
this.cNombre1Idioma5 = cNombre1Idioma5;
this.cNombre2Idioma1 = cNombre2Idioma1;
this.cNombre2Idioma2 = cNombre2Idioma2;
this.cNombre2Idioma3 = cNombre2Idioma3;
this.cNombre2Idioma4 = cNombre2Idioma4;
this.cNombre2Idioma5 = cNombre2Idioma5;
this.cNombre3Idioma1 = cNombre3Idioma1;
this.cNombre3Idioma2 = cNombre3Idioma2;
this.cNombre3Idioma3 = cNombre3Idioma3;
this.cNombre3Idioma4 = cNombre3Idioma4;
this.cNombre3Idioma5 = cNombre3Idioma5;
this.cImagen1 = cImagen1;
this.cImagen2 = cImagen2;
this.cImagen3 = cImagen3;
this.cDescripcionIdioma1=cDescripcionIdioma1;
this.cDescripcionIdioma2=cDescripcionIdioma2;
this.cDescripcionIdioma3=cDescripcionIdioma3;
this.cDescripcionIdioma4=cDescripcionIdioma4;
this.cDescripcionIdioma5=cDescripcionIdioma5;
this.cDirigidoIdioma1 = cDirigidoIdioma1;
this.cDirigidoIdioma2 = cDirigidoIdioma2;
this.cDirigidoIdioma3 = cDirigidoIdioma3;
this.cDirigidoIdioma4 = cDirigidoIdioma4;
this.cDirigidoIdioma5 = cDirigidoIdioma5;
this.vistaMobil=false;
//==========================
this.update=true;
this.abrirEditorDescripcion=false;
this.abrirEditorDirigido=false;
if(cItemsCod!=0)
{
obtenerNameItem(cItemsCod);
this.modoItem=true;
this.modoSubMenu=false;
}
else if(cSubMenuCod!=0)
{
obtenerNameSubMenu(cSubMenuCod);
this.modoSubMenu=true;
this.modoItem=false;
}
recuperarListaDestinosMovil(cElementosCod);
recuperarListaDatosGenerales(cElementosCod);
}
public void obtenerNameItem(int cItemsCod)
{
CElementosDAO elementosDao=new CElementosDAO();
elementosDao.asignarNameItem(elementosDao.recuperarNombreItem(cItemsCod));
setNameItem(elementosDao.getNameItem());
}
public void obtenerNameSubMenu(int cSubMenuCod)
{
CElementosDAO elementosDao=new CElementosDAO();
elementosDao.asignarNameSubMenu(elementosDao.recuperarNombreSubMenu(cSubMenuCod));
setNameSubMenu(elementosDao.getNameSubMenu());
}
public void recuperarListaDestinosMovil(int cElementosCod)
{
listaDestinosMovil=new ArrayList<CDestinoMovil>();
CElementosDAO elementoDao=new CElementosDAO();
elementoDao.asignarListaDestinosElemento(elementoDao.recuperarListaDestinosBD_Elemento(cElementosCod));
setListaDestinosMovil(elementoDao.getListaDestinosMovil());
}
public void recuperarListaDatosGenerales(int cElementosCod)
{
listaDatosGenerales=new ArrayList<CDatosGenerales>();
CElementosDAO elementoDao=new CElementosDAO();
elementoDao.asignarListaDatosGeneralesElemento(elementoDao.recuperarListaDatosGeneralesBD_Elemento(cElementosCod));
setListaDatosGenerales(elementoDao.getListaDatosGenerales());
}
}
| gpl-3.0 |
iChun/iChunUtil | src/main/java/us/ichun/mods/ichunutil/common/core/packet/PacketDataFragment.java | 1683 | package us.ichun.mods.ichunutil.common.core.packet;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import us.ichun.mods.ichunutil.common.core.network.AbstractPacket;
public abstract class PacketDataFragment extends AbstractPacket
{
public String fileName;
public short packetTotal;
public short packetNumber;
public int fragmentSize;
public byte[] data;
public PacketDataFragment(){}
public PacketDataFragment(String fileName, int packetTotal, int packetNumber, int fragmentSize, byte[] data)
{
this.fileName = fileName;
this.packetTotal = (short)packetTotal;
this.packetNumber = (short)packetNumber;
this.fragmentSize = fragmentSize;
this.data = data;
}
@Override
public void writeTo(ByteBuf buffer, Side side)
{
ByteBufUtils.writeUTF8String(buffer, fileName);
buffer.writeShort(packetTotal);
buffer.writeShort(packetNumber);
buffer.writeInt(fragmentSize);
buffer.writeBytes(data);
}
@Override
public void readFrom(ByteBuf buffer, Side side)
{
fileName = ByteBufUtils.readUTF8String(buffer);
packetTotal = buffer.readShort();
packetNumber = buffer.readShort();
fragmentSize = buffer.readInt();
data = new byte[fragmentSize];
buffer.readBytes(data);
}
@Override
public void execute(Side side, EntityPlayer player)
{
execution(side, player);
}
public abstract void execution(Side side, EntityPlayer player);
}
| gpl-3.0 |
Andrey11/capybaramobile | android/app/src/main/java/com/mobilecapybara/MainActivity.java | 373 | package com.mobilecapybara;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "mobilecapybara";
}
}
| gpl-3.0 |
dotCMS/core | dotCMS/src/main/java/com/dotmarketing/portlets/workflows/model/WorkflowHistory.java | 4382 | package com.dotmarketing.portlets.workflows.model;
import com.dotcms.util.marshal.MarshalFactory;
import com.dotmarketing.util.StringUtils;
import com.dotmarketing.util.UtilMethods;
import com.google.common.collect.ImmutableMap;
import com.liferay.util.StringPool;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WorkflowHistory implements Serializable, WorkflowTimelineItem
{
private static final long serialVersionUID = 1L;
String id;
Date creationDate;
String madeBy;
String changeDescription;
String workflowtaskId;
String actionId;
String stepId;
public String getStepId() {
return stepId;
}
public void setStepId(String stepId) {
this.stepId = stepId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setInode(String id){
setId(id);
}
public String getInode(){
return id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getChangeDescription() {
if (UtilMethods.isSet(this.changeDescription) && StringUtils.isJson(this.changeDescription.trim())) {
// if it is json
return(String) this.getChangeMap().get("description");
}
// if the representation of the json, if it is json. otherwise is gonna be description, getChangeDescription
return this.changeDescription;
}
public String getRawChangeDescription() {
return this.changeDescription;
}
public Map<String, Object> getChangeMap () {
if (UtilMethods.isSet(this.changeDescription) && StringUtils.isJson(this.changeDescription.trim())) {
// if it is json
return MarshalFactory
.getInstance().getMarshalUtils().unmarshal(this.changeDescription, Map.class);
}
// if the representation of the json, if it is json. otherwise is gonna be description, getChangeDescription
return ImmutableMap.of("description", null == this.changeDescription? StringPool.BLANK:this.changeDescription,
"type", WorkflowHistoryType.COMMENT.name(), "state", WorkflowHistoryState.NONE.name());
}
public void setChangeDescription(String changeDescription) {
this.changeDescription = changeDescription;
}
public String getMadeBy() {
return madeBy;
}
public void setMadeBy(String madeBy) {
this.madeBy = madeBy;
}
public String getWorkflowtaskId() {
return workflowtaskId;
}
public void setWorkflowtaskId(String workflowtaskId) {
this.workflowtaskId = workflowtaskId;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public Map getMap () {
Map oMap = new HashMap ();
oMap.put("creationDate", this.getCreationDate());
oMap.put("madeBy", this.getMadeBy());
oMap.put("changeDescription", this.getChangeDescription());
oMap.put("workflowTaskId",this.workflowtaskId);
return oMap;
}
public boolean isNew(){
return UtilMethods.isSet(id);
}
@Override
public Date createdDate() {
return this.getCreationDate();
}
@Override
public String roleId() {
return this.getMadeBy();
}
@Override
public String actionId() {
return this.getActionId();
}
@Override
public String stepId() {
return this.getStepId();
}
@Override
public String commentDescription() {
return this.getChangeDescription();
}
@Override
public String taskId() {
return this.getWorkflowtaskId();
}
@Override
public String type() {
return this.getClass().getSimpleName();
}
}
| gpl-3.0 |
cohenadair/anglers-log | android/app/src/main/java/com/cohenadair/anglerslog/fragments/PartialListFragment.java | 1259 | package com.cohenadair.anglerslog.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cohenadair.anglerslog.R;
/**
* A simple {@link Fragment} subclass that show a list of items. Note that
* {@link #setAdapter(RecyclerView.Adapter)} must be called before displaying an instance of
* {@link PartialListFragment}.
*
* @author Cohen Adair
*/
public class PartialListFragment extends Fragment {
private RecyclerView.Adapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_simple_list, container, false);
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
return view;
}
public void setAdapter(RecyclerView.Adapter adapter) {
mAdapter = adapter;
}
}
| gpl-3.0 |
talek69/curso | 103-dominion-hibernate/src/com/dominion/hibernate/dao/VencimientosDAO.java | 4995 | package com.dominion.hibernate.dao;
import static org.hibernate.criterion.Example.create;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dominion.hibernate.entities.Vencimientos;
/**
* A data access object (DAO) providing persistence and search support for Vencimientos entities. Transaction control of the save(), update() and
* delete() operations can directly support Spring container-managed transactions or they can be augmented to handle user-managed Spring transactions.
* Each of these methods provides additional information for how to configure it for the desired type of transaction control.
*
* @see com.dominion.hibernate.entities.Vencimientos
* @author MyEclipse Persistence Tools
*/
public class VencimientosDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(VencimientosDAO.class);
// property constants
public static final String CANTIDAD_VENCIMIENTO = "cantidadVencimiento";
public static final String NUMERO_PEDIDO = "numeroPedido";
public static final String NOMBRE_BANCO = "nombreBanco";
public static final String ESTADO_VENCIMIENTO = "estadoVencimiento";
public void save(Vencimientos transientInstance) {
log.debug("saving Vencimientos instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Vencimientos persistentInstance) {
log.debug("deleting Vencimientos instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Vencimientos findById(java.lang.Long id) {
log.debug("getting Vencimientos instance with id: " + id);
try {
Vencimientos instance = (Vencimientos) getSession().get("com.dominion.hibernate.entities.Vencimientos", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
@SuppressWarnings("unchecked")
public List<Vencimientos> findByExample(Vencimientos instance) {
log.debug("finding Vencimientos instance by example");
try {
List<Vencimientos> results = (List<Vencimientos>) getSession().createCriteria("com.dominion.hibernate.entities.Vencimientos")
.add(create(instance)).list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
@SuppressWarnings("unchecked")
public List<Vencimientos> findByProperty(String propertyName, Object value) {
log.debug("finding Vencimientos instance with property: " + propertyName + ", value: " + value);
try {
String queryString = "from Vencimientos as model where model." + propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List<Vencimientos> findByCantidadVencimiento(Object cantidadVencimiento) {
return findByProperty(CANTIDAD_VENCIMIENTO, cantidadVencimiento);
}
public List<Vencimientos> findByNumeroPedido(Object numeroPedido) {
return findByProperty(NUMERO_PEDIDO, numeroPedido);
}
public List<Vencimientos> findByNombreBanco(Object nombreBanco) {
return findByProperty(NOMBRE_BANCO, nombreBanco);
}
public List<Vencimientos> findByEstadoVencimiento(Object estadoVencimiento) {
return findByProperty(ESTADO_VENCIMIENTO, estadoVencimiento);
}
@SuppressWarnings("unchecked")
public List<Vencimientos> findAll() {
log.debug("finding all Vencimientos instances");
try {
String queryString = "from Vencimientos";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Vencimientos merge(Vencimientos detachedInstance) {
log.debug("merging Vencimientos instance");
try {
Vencimientos result = (Vencimientos) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Vencimientos instance) {
log.debug("attaching dirty Vencimientos instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Vencimientos instance) {
log.debug("attaching clean Vencimientos instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
} | gpl-3.0 |
Winbobob/openmrs-core | web/src/main/java/org/openmrs/web/taglib/ForEachObsTag.java | 4556 | /**
* 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/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.web.taglib;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ReverseComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Obs;
public class ForEachObsTag extends BodyTagSupport {
public static final long serialVersionUID = 1L;
private final Log log = LogFactory.getLog(getClass());
int count = 0;
List<Obs> matchingObs = null;
// Properties accessible through tag attributes
private Collection<Obs> obs;
private Integer conceptId;
private Integer num = null;
private String sortBy;
private Boolean descending = Boolean.FALSE;
private String var;
public int doStartTag() {
if (obs == null || obs.isEmpty()) {
log.error("ForEachObsTag skipping body due to obs param = " + obs);
return SKIP_BODY;
}
// First retrieve all observations matching the passed concept id, if provided.
// If not provided, return all observations
matchingObs = new ArrayList<Obs>();
for (Iterator<Obs> i = obs.iterator(); i.hasNext();) {
Obs o = i.next();
if (conceptId == null
|| (o.getConcept() != null && o.getConcept().getConceptId().intValue() == conceptId.intValue())) {
matchingObs.add(o);
}
}
log.debug("ForEachObsTag found " + matchingObs.size() + " observations matching conceptId = " + conceptId);
// Next, sort these observations
if (sortBy == null || sortBy.equals("")) {
sortBy = "obsDatetime";
}
Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator())
: new ComparableComparator()));
Collections.sort(matchingObs, comp);
// Return appropriate number of results
if (matchingObs.isEmpty()) {
return SKIP_BODY;
} else {
pageContext.setAttribute(var, matchingObs.get(count++));
return EVAL_BODY_BUFFERED;
}
}
/**
* @see javax.servlet.jsp.tagext.IterationTag#doAfterBody()
*/
public int doAfterBody() throws JspException {
if (matchingObs.size() > count && (num == null || count < num.intValue())) {
pageContext.setAttribute(var, matchingObs.get(count++));
return EVAL_BODY_BUFFERED;
} else {
return SKIP_BODY;
}
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
try {
if (count > 0 && bodyContent != null) {
count = 0;
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
}
catch (java.io.IOException e) {
throw new JspTagException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
/**
* @return the obs
*/
public Collection<Obs> getObs() {
return obs;
}
/**
* @param obs the obs to set
*/
public void setObs(Collection<Obs> obs) {
this.obs = obs;
}
/**
* @return the conceptId
*/
public Integer getConceptId() {
return conceptId;
}
/**
* @param conceptId the conceptId to set
*/
public void setConceptId(Integer conceptId) {
this.conceptId = conceptId;
}
/**
* @return the Num
*/
public Integer getNum() {
return num;
}
/**
* @param Num the Num to set
*/
public void setNum(Integer num) {
this.num = num;
}
/**
* @param var the var to set
*/
public void setVar(String var) {
this.var = var;
}
/**
* @return the descending
*/
public Boolean getDescending() {
return descending;
}
/**
* @param descending the descending to set
*/
public void setDescending(Boolean descending) {
this.descending = descending;
}
/**
* @return the sortBy
*/
public String getSortBy() {
return sortBy;
}
/**
* @param sortBy the sortBy to set
*/
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
}
| mpl-2.0 |
PIH/openmrs-module-emrmonitor | omod/src/test/java/org/openmrs/module/emrmonitor/rest/resource/RestTest.java | 1968 | /*
* 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/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.module.emrmonitor.rest.resource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.Test;
import org.openmrs.module.emrmonitor.EmrMonitorConfig;
import org.openmrs.module.emrmonitor.api.EmrMonitorService;
import org.openmrs.web.test.BaseModuleWebContextSensitiveTest;
import javax.ws.rs.core.MediaType;
/**
* Tests the EmrMonitorServerResource
*/
@Ignore
public class RestTest extends BaseModuleWebContextSensitiveTest {
protected final Log log = LogFactory.getLog(this.getClass());
private EmrMonitorService emrMonitorService;
@Test
public void setup() throws Exception {
Client restClient = Client.create();
restClient.setReadTimeout(EmrMonitorConfig.REMOTE_SERVER_TIMEOUT);
WebResource resource = restClient.resource("http://localhost:8081/openmrs-standalone").path("ws/rest/v1/emrmonitor/server/1f30fc47-c650-4b5d-9037-eb4c0c2132ba");
resource.addFilter(new HTTPBasicAuthFilter("admin", "test"));
ClientResponse serverResponse = resource.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
System.out.println("Status: " + serverResponse.getStatus());
System.out.println("Status: " + serverResponse.toString());
}
}
| mpl-2.0 |
emlai/wge3 | core/src/wge3/engine/InputHandler.java | 2866 | /* 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 wge3.engine;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import java.util.HashMap;
import java.util.Map;
public final class InputHandler extends InputAdapter {
private final boolean[] currentKeyBuffer;
private final boolean[] previousKeyBuffer;
private final int[] keyMap;
private final Map<Integer, Command> commandMap;
public InputHandler() {
currentKeyBuffer = new boolean[Command.numberOfCommands];
previousKeyBuffer = new boolean[Command.numberOfCommands];
keyMap = new int[Command.numberOfCommands];
commandMap = new HashMap();
// Default keys. These should be loaded from a file.
setMappedKey(Command.FORWARD, Keys.UP);
setMappedKey(Command.BACKWARD, Keys.DOWN);
setMappedKey(Command.TURN_LEFT, Keys.LEFT);
setMappedKey(Command.TURN_RIGHT, Keys.RIGHT);
setMappedKey(Command.USE_ITEM, Keys.Z);
setMappedKey(Command.CHANGE_ITEM, Keys.X);
setMappedKey(Command.EXIT, Keys.ESCAPE);
setMappedKey(Command.TOGGLE_FOV, Keys.S);
setMappedKey(Command.TOGGLE_GHOST_MODE, Keys.G);
setMappedKey(Command.TOGGLE_INVENTORY, Keys.I);
setMappedKey(Command.SPAWN_WALL, Keys.C);
setMappedKey(Command.DESTROY_OBJECT, Keys.D);
setMappedKey(Command.TOGGLE_FPS, Keys.F);
setMappedKey(Command.TOGGLE_MUSIC, Keys.M);
setMappedKey(Command.ZOOM_IN, Keys.PAGE_DOWN);
setMappedKey(Command.ZOOM_OUT, Keys.PAGE_UP);
setMappedKey(Command.ZOOM_RESET, Keys.HOME);
}
public int getMappedKey(Command key) {
return keyMap[key.code];
}
public void setMappedKey(Command key, int mapping) {
commandMap.remove(mapping);
commandMap.put(mapping, key);
keyMap[key.code] = mapping;
}
public void copyKeyBuffer() {
System.arraycopy(currentKeyBuffer, 0, previousKeyBuffer, 0, Command.numberOfCommands);
}
public boolean isDown(Command key) {
return currentKeyBuffer[key.code];
}
public boolean isPressed(Command key) {
return currentKeyBuffer[key.code] && !previousKeyBuffer[key.code];
}
@Override
public boolean keyDown(int key) {
Command command = commandMap.get(key);
if (command == null) return false;
currentKeyBuffer[command.code] = true;
return true;
}
@Override
public boolean keyUp(int key) {
Command command = commandMap.get(key);
if (command == null) return false;
currentKeyBuffer[command.code] = false;
return true;
}
}
| mpl-2.0 |
Blackxxx/myTest | Framelayout/gen/com/example/framelayout/R.java | 2628 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.framelayout;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080002;
public static final int button=0x7f080001;
public static final int text0=0x7f080000;
}
public static final class layout {
public static final int black=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050002;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| mpl-2.0 |
seedstack/business | core/src/test/java/org/seedstack/business/fixtures/event/MyDomainEvent.java | 392 | /*
* Copyright © 2013-2021, The SeedStack authors <http://seedstack.org>
*
* 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.seedstack.business.fixtures.event;
public class MyDomainEvent extends AbstractDomainEvent {
}
| mpl-2.0 |
tbouvet/seed | rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/JsonHomeResource.java | 1675 | /**
* Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org>
*
* 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.seedstack.seed.rest.internal.jsonhome;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
* Exposes the JSON-HOME resource on the application root path.
*
* @author pierre.thirouin@ext.mpsa.com (Pierre Thirouin)
* @see org.seedstack.seed.rest.internal.jsonhome.JsonHome
*/
@Path("/")
public class JsonHomeResource {
private final JsonHome jsonHome;
/**
* Constructor.
*
* @param jsonHome the JSON-HOME resource
*/
@Inject
public JsonHomeResource(JsonHome jsonHome) {
this.jsonHome = jsonHome;
}
/**
* Exposes the JSON-HOME resource.
* <p>
* Returns an error 500 when a JsonProcessingException occurs.
* </p>
*
* @return JAX-RS response
*/
@GET
@Produces({"application/json", "application/json-home"})
public Response entryPoint() {
final ObjectMapper mapper = new ObjectMapper();
try {
return Response.ok(mapper.writeValueAsString(jsonHome)).build();
} catch (JsonProcessingException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error processing JSON-HOME").build();
}
}
}
| mpl-2.0 |
jmintb/syncthing-android | app/src/main/java/com/nutomic/syncthingandroid/receiver/AppConfigReceiver.java | 1690 | package com.nutomic.syncthingandroid.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.nutomic.syncthingandroid.SyncthingApp;
import com.nutomic.syncthingandroid.service.DeviceStateHolder;
import com.nutomic.syncthingandroid.service.NotificationHandler;
import com.nutomic.syncthingandroid.service.SyncthingService;
import javax.inject.Inject;
/**
* Broadcast-receiver to control and configure Syncthing remotely.
*/
public class AppConfigReceiver extends BroadcastReceiver {
/**
* Start the Syncthing-Service
*/
public static final String ACTION_START = "com.nutomic.syncthingandroid.action.START";
/**
* Stop the Syncthing-Service
* If alwaysRunInBackground is enabled the service must not be stopped. Instead a
* notification is presented to the user.
*/
public static final String ACTION_STOP = "com.nutomic.syncthingandroid.action.STOP";
@Inject NotificationHandler mNotificationHandler;
@Override
public void onReceive(Context context, Intent intent) {
((SyncthingApp) context.getApplicationContext()).component().inject(this);
switch (intent.getAction()) {
case ACTION_START:
BootReceiver.startServiceCompat(context);
break;
case ACTION_STOP:
if (DeviceStateHolder.alwaysRunInBackground(context)) {
mNotificationHandler.showStopSyncthingWarningNotification();
} else {
context.stopService(new Intent(context, SyncthingService.class));
}
break;
}
}
}
| mpl-2.0 |
langurmonkey/gaiasky | core/src/gaiasky/data/cluster/StarClusterLoader.java | 14954 | /*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.data.cluster;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import gaiasky.data.ISceneGraphLoader;
import gaiasky.data.stars.AbstractCatalogLoader;
import gaiasky.scenegraph.StarCluster;
import gaiasky.util.Constants;
import gaiasky.util.I18n;
import gaiasky.util.Logger;
import gaiasky.util.Logger.Log;
import gaiasky.util.Settings;
import gaiasky.util.coord.AstroUtils;
import gaiasky.util.coord.Coordinates;
import gaiasky.util.math.Vector3b;
import gaiasky.util.math.Vector3d;
import gaiasky.util.parse.Parser;
import gaiasky.util.ucd.UCDParser;
import gaiasky.util.units.Quantity.Angle;
import gaiasky.util.units.Quantity.Angle.AngleUnit;
import gaiasky.util.units.Quantity.Length;
import gaiasky.util.units.Quantity.Length.LengthUnit;
import org.apfloat.Apfloat;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.RowSequence;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.StarTableFactory;
import uk.ac.starlink.table.formats.AsciiTableBuilder;
import uk.ac.starlink.table.formats.CsvTableBuilder;
import uk.ac.starlink.util.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Loads the star cluster catalogs from CSV files or STIL data sources. The column order is not important. The
* column names, however, must be:
*
* <ul>
* <li>name: {@link gaiasky.util.ucd.UCDParser#idcolnames}, separate multiple names with '|'</li>
* <li>ra[deg]: {@link gaiasky.util.ucd.UCDParser#racolnames}</li>
* <li>dist[pc]: {@link gaiasky.util.ucd.UCDParser#distcolnames}</li>
* <li>pmra[mas/yr]: {@link gaiasky.util.ucd.UCDParser#pmracolnames}</li>
* <li>pmde[mas/yr]: {@link gaiasky.util.ucd.UCDParser#pmdeccolnames}</li>
* <li>rv[km/s]: {@link gaiasky.util.ucd.UCDParser#radvelcolnames}</li>
* <li>radius[deg]: {@link gaiasky.util.ucd.UCDParser#radiuscolnames}</li>
* <li>nstars: {@link gaiasky.util.ucd.UCDParser#nstarscolnames}</li>
* </ul>
*/
public class StarClusterLoader extends AbstractCatalogLoader implements ISceneGraphLoader {
private static final Log logger = Logger.getLogger(StarClusterLoader.class);
boolean active = true;
private enum ClusterProperties {
NAME, RA, DEC, DIST, PLLX, PMRA, PMDE, RV, RADIUS, NSTARS
}
@Override
public Array<StarCluster> loadData() {
Array<StarCluster> clusters = new Array<>();
if (active) {
if (files != null) {
for (String file : files) {
FileHandle f = Settings.settings.data.dataFileHandle(file);
InputStream is = f.read();
try {
loadClustersCsv(is, clusters);
} catch (IOException e) {
logger.error(e);
} finally {
try {
is.close();
} catch (IOException e) {
logger.error(e);
}
}
}
} else if (dataSource != null) {
try {
loadClustersStil(dataSource, clusters);
} catch (IOException e) {
logger.error(e);
}
}
}
logger.info(I18n.txt("notif.catalog.init", clusters.size));
return clusters;
}
/**
* Loads clusters from a STIL data source.
* @param ds The data source.
* @param clusters The clusters list.
* @throws IOException
*/
private void loadClustersStil(DataSource ds, Array<StarCluster> clusters) throws IOException {
// Add extra builders
StarTableFactory factory = new StarTableFactory();
List builders = factory.getDefaultBuilders();
builders.add(new CsvTableBuilder());
builders.add(new AsciiTableBuilder());
// Try to load
StarTable table = factory.makeStarTable(ds);
Map<ClusterProperties, Integer> indices = parseHeader(table);
if (!checkIndices(indices)) {
logger.error("At least 'ra', 'dec', 'pllx'|'dist', 'radius' and 'name' are needed, please check your columns!");
return;
}
RowSequence rs = table.getRowSequence();
while (rs.next()) {
Object[] row = rs.getRow();
String[] names = parseName(row[indices.get(ClusterProperties.NAME)].toString());
double ra = getDouble(row, ClusterProperties.RA, indices, table, "deg");
double rarad = Math.toRadians(ra);
double dec = getDouble(row, ClusterProperties.DEC, indices, table, "deg");
double decrad = Math.toRadians(dec);
double distpc = 0;
if (indices.containsKey(ClusterProperties.DIST)) {
distpc = getDouble(row, ClusterProperties.DIST, indices, table, "pc");
} else if (indices.containsKey(ClusterProperties.PLLX)) {
distpc = 1000d / getDouble(row, ClusterProperties.PLLX, indices, table, "mas");
}
double dist = distpc * Constants.PC_TO_U;
double mualphastar = getDouble(row, ClusterProperties.PMRA, indices, table, "mas/yr");
double mudelta = getDouble(row, ClusterProperties.PMDE, indices, table, "mas/yr");
double radvel = getDouble(row, ClusterProperties.RV, indices, table, "km/s");
double radius = getDouble(row, ClusterProperties.RADIUS, indices, table, "deg");
int nstars = getInteger(row, ClusterProperties.NSTARS, indices);
addCluster(names, ra, rarad, dec, decrad, dist, distpc, mualphastar, mudelta, radvel, radius, nstars, clusters);
}
for (StarCluster c : clusters) {
c.initialize();
}
}
/**
* Loads clusters from a CSV file directly.
* @param data The CSV file input stream.
* @param clusters The clusters list.
* @throws IOException
*/
private void loadClustersCsv(InputStream data, Array<StarCluster> clusters) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(data));
String header = br.readLine();
Map<ClusterProperties, Integer> indices = parseHeader(header);
if (!checkIndices(indices)) {
logger.error("At least 'ra', 'dec', 'pllx'|'dist', 'radius' and 'name' are needed, please check your columns!");
return;
}
String line;
while ((line = br.readLine()) != null) {
// Add galaxy
String[] tokens = line.split(",");
String[] names = parseName(tokens[indices.get(ClusterProperties.NAME)]);
double ra = getDouble(tokens, ClusterProperties.RA, indices);
double rarad = Math.toRadians(ra);
double dec = getDouble(tokens, ClusterProperties.DEC, indices);
double decrad = Math.toRadians(dec);
double distpc = 0;
if (indices.containsKey(ClusterProperties.DIST)) {
distpc = getDouble(tokens, ClusterProperties.DIST, indices);
} else if (indices.containsKey(ClusterProperties.PLLX)) {
distpc = 1000d / getDouble(tokens, ClusterProperties.PLLX, indices);
}
double dist = distpc * Constants.PC_TO_U;
double mualphastar = getDouble(tokens, ClusterProperties.PMRA, indices);
double mudelta = getDouble(tokens, ClusterProperties.PMDE, indices);
double radvel = getDouble(tokens, ClusterProperties.RV, indices);
double radius = getDouble(tokens, ClusterProperties.RADIUS, indices);
int nstars = getInteger(tokens, ClusterProperties.NSTARS, indices);
addCluster(names, ra, rarad, dec, decrad, dist, distpc, mualphastar, mudelta, radvel, radius, nstars, clusters);
}
for (StarCluster c : clusters) {
c.initialize();
}
}
private void addCluster(String[] names, double ra, double rarad, double dec, double decrad, double dist, double distpc, double mualphastar, double mudelta, double radvel, double radius, int nstars, Array<StarCluster> clusters){
Vector3b pos = Coordinates.sphericalToCartesian(rarad, decrad, new Apfloat(dist, Constants.PREC), new Vector3b());
Vector3d pm = AstroUtils.properMotionsToCartesian(mualphastar, mudelta, radvel, Math.toRadians(ra), Math.toRadians(dec), distpc, new Vector3d());
Vector3d posSph = new Vector3d((float) ra, (float) dec, (float) dist);
Vector3 pmSph = new Vector3((float) (mualphastar), (float) (mudelta), (float) radvel);
StarCluster c = new StarCluster(names, parentName != null ? parentName : "MWSC", pos, pm, posSph, pmSph, radius, nstars);
clusters.add(c);
}
private String[] parseName(String name) {
String[] names = name.split(Constants.nameSeparatorRegex);
for (int i = 0; i < names.length; i++)
names[i] = names[i].strip().replace("_", " ");
return names;
}
private String get(String[] tokens, ClusterProperties prop, Map<ClusterProperties, Integer> indices) {
return (!indices.containsKey(prop) || tokens[indices.get(prop)].isEmpty()) ? null : tokens[indices.get(prop)];
}
private Object get(Object[] row, ClusterProperties prop, Map<ClusterProperties, Integer> indices) {
return (!indices.containsKey(prop) || row[indices.get(prop)] == null) ? null : row[indices.get(prop)];
}
private double getDouble(String[] tokens, ClusterProperties prop, Map<ClusterProperties, Integer> indices) {
String s = get(tokens, prop, indices);
if (s != null)
return Parser.parseDouble(s);
return 0;
}
private double getDouble(Object[] row, ClusterProperties prop, Map<ClusterProperties, Integer> indices, StarTable table, String defaultUnit) {
Integer idx = indices.get(prop);
if(idx != null) {
ColumnInfo col = table.getColumnInfo(idx);
String unit = (col.getUnitString() != null && !col.getUnitString().isBlank() ? col.getUnitString() : defaultUnit);
Object obj = get(row, prop, indices);
if (obj != null) {
double val = ((Number) obj).doubleValue();
if (Angle.isAngle(unit)) {
Angle angle = new Angle(val, unit);
return angle.get(AngleUnit.valueOf(defaultUnit.toUpperCase()));
} else if (Length.isLength(unit)) {
Length length = new Length(val, unit);
return length.get(LengthUnit.valueOf(defaultUnit.toUpperCase()));
} else {
// We just assume default unit
return val;
}
}
}
return 0;
}
private int getInteger(String[] tokens, ClusterProperties prop, Map<ClusterProperties, Integer> indices) {
String s = get(tokens, prop, indices);
if (s != null)
return Parser.parseInt(s);
return 0;
}
private int getInteger(Object[] row, ClusterProperties prop, Map<ClusterProperties, Integer> indices) {
Object s = get(row, prop, indices);
if (s != null)
return ((Number)s).intValue();
return 0;
}
private Map<ClusterProperties, Integer> parseHeader(String header) {
Map<ClusterProperties, Integer> indices = new HashMap<>();
header = header.strip();
if (header.startsWith("#"))
header = header.substring(1);
String[] tokens = header.split(",");
int i = 0;
for (String token : tokens) {
if (UCDParser.isName(token))
indices.put(ClusterProperties.NAME, i);
else if (UCDParser.isRa(token))
indices.put(ClusterProperties.RA, i);
else if (UCDParser.isDec(token))
indices.put(ClusterProperties.DEC, i);
else if (UCDParser.isDist(token))
indices.put(ClusterProperties.DIST, i);
else if (UCDParser.isPllx(token))
indices.put(ClusterProperties.PLLX, i);
else if (UCDParser.isPmra(token))
indices.put(ClusterProperties.PMRA, i);
else if (UCDParser.isPmde(token))
indices.put(ClusterProperties.PMDE, i);
else if (UCDParser.isRadvel(token))
indices.put(ClusterProperties.RV, i);
else if (UCDParser.isRadius(token))
indices.put(ClusterProperties.RADIUS, i);
else if (UCDParser.isNstars(token))
indices.put(ClusterProperties.NSTARS, i);
i++;
}
return indices;
}
private boolean checkIndices(Map<ClusterProperties, Integer> indices) {
return indices.containsKey(ClusterProperties.RA)
&& indices.containsKey(ClusterProperties.DEC)
&& (indices.containsKey(ClusterProperties.DIST) || indices.containsKey(ClusterProperties.PLLX))
&& indices.containsKey(ClusterProperties.RADIUS)
&& indices.containsKey(ClusterProperties.NAME);
}
private Map<ClusterProperties, Integer> parseHeader(StarTable table) {
Map<ClusterProperties, Integer> indices = new HashMap<>();
int ncols = table.getColumnCount();
for (int i = 0; i < ncols; i++) {
ColumnInfo ci = table.getColumnInfo(i);
String cName = ci.getName();
if (UCDParser.isName(cName))
indices.put(ClusterProperties.NAME, i);
else if (UCDParser.isRa(cName))
indices.put(ClusterProperties.RA, i);
else if (UCDParser.isDec(cName))
indices.put(ClusterProperties.DEC, i);
else if (UCDParser.isDist(cName))
indices.put(ClusterProperties.DIST, i);
else if (UCDParser.isPllx(cName))
indices.put(ClusterProperties.PLLX, i);
else if (UCDParser.isPmra(cName))
indices.put(ClusterProperties.PMRA, i);
else if (UCDParser.isPmde(cName))
indices.put(ClusterProperties.PMDE, i);
else if (UCDParser.isRadvel(cName))
indices.put(ClusterProperties.RV, i);
else if (UCDParser.isRadius(cName))
indices.put(ClusterProperties.RADIUS, i);
else if (UCDParser.isNstars(cName))
indices.put(ClusterProperties.NSTARS, i);
}
return indices;
}
}
| mpl-2.0 |
hivex-unipd/swedesigner | src/test/java/controller/RequestHandlerControllerTest.java | 3124 | package controller;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import server.Configurator;
import test.TestConfigurator;
import server.controller.RequestHandlerController;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpEntity;
// vedi anche https://spring.io/guides/gs/spring-boot/
// ---------------------------------------------------
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Configurator.class, TestConfigurator.class})
public class RequestHandlerControllerTest {
@Autowired
@Qualifier("stubbedrhc")
private RequestHandlerController stubbedrhc;
@Autowired
@Qualifier("rhc")
private RequestHandlerController rhc;
// Test di unità:
// ==============
// Avviato un RequestHandlerController, questo è in grado di rispondere a una richiesta di generazione di codice.
@Test
public void controllerHandlesRequest() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(new String(Files.readAllBytes(Paths.get("src/main/resources/project.json"))));
ResponseEntity<?> result = stubbedrhc.handleGenerationRequest(request);
}
// Test di integrazione:
// =====================
// Il sistema gestisce correttamente l'interazione tra un RequestHandlerController e i suoi membri di tipo Parser, Generator, Compiler e Compressor (del swedesigner::server).
@Test
public void controllerInteractsWithComponents() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(new String(Files.readAllBytes(Paths.get("src/main/resources/project.json"))));
ResponseEntity<?> result = rhc.handleGenerationRequest(request);
// TODO? non abbiamo la cartella Uploads...
// File zip = new File("src/main/resources/sort/project.zip");
// assertTrue(zip.exists());
}
// Il sistema gestisce correttamente l'interazione tra un RequestHandlerController e un Compiler di swedesigner::server.
@Test
public void controllerInteractsWithCompiler() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(new String(Files.readAllBytes(Paths.get("src/main/resources/project.json"))));
ResponseEntity<?> result = rhc.handleGenerationRequest(request);
// TODO?
}
// Il sistema gestisce correttamente le componenti relative al package utility; in particolare, gestisce correttamente l'interazione tra un RequestHandlerController e un Compressor di swedesigner::server.
@Test
public void controllerInteractsWithCompressor() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(new String(Files.readAllBytes(Paths.get("src/main/resources/project.json"))));
ResponseEntity<?> result = rhc.handleGenerationRequest(request);
// TODO?
}
}
| mpl-2.0 |
s23m/cell-platform | org.s23m.cell.kernel/src/main/java/org/s23m/cell/impl/SemanticDomainCode.java | 6555 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* 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.
*
* The Original Code is S23M.
*
* The Initial Developer of the Original Code is
* The S23M Foundation.
* Portions created by the Initial Developer are
* Copyright (C) 2012 The S23M Foundation.
* All Rights Reserved.
*
* Contributor(s):
* Jorn Bettin
* ***** END LICENSE BLOCK ***** */
package org.s23m.cell.impl;
import static org.s23m.cell.S23MKernel.coreSets;
import static org.s23m.cell.api.models.SemanticDomain.disjunctSemanticIdentitySet;
import static org.s23m.cell.api.models.SemanticDomain.elements_to_disjunctSemanticIdentitySet;
import static org.s23m.cell.api.models.SemanticDomain.elements_to_semanticIdentitySet;
import static org.s23m.cell.api.models.SemanticDomain.semanticIdentitySet;
import static org.s23m.cell.api.models.SemanticDomain.semanticRole;
import static org.s23m.cell.api.models.SemanticDomain.variantDisjunctSemanticIdentitySet;
import static org.s23m.cell.core.F_Instantiation.identityFactory;
import org.s23m.cell.Set;
import org.s23m.cell.api.models.S23MSemanticDomains;
import org.s23m.cell.api.models.SemanticDomain;
import org.s23m.cell.core.F_Instantiation;
import org.s23m.cell.core.F_InstantiationImpl;
public class SemanticDomainCode {
public static Set addElement(final Set set, final Set element){
if ( set.category().isEqualTo(disjunctSemanticIdentitySet)
|| set.category().isEqualTo(variantDisjunctSemanticIdentitySet) ) {
return F_Instantiation.arrow(elements_to_disjunctSemanticIdentitySet,
F_Instantiation.reuseSemanticIdentity(identityFactory.element()),
element,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_TRUE,
coreSets.isContainer_FALSE,
F_Instantiation.reuseSemanticIdentity(identityFactory.set()),
set,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_TRUE,
coreSets.isContainer_FALSE
);
} else {
if ( set.category().isEqualTo(semanticIdentitySet)) {
return F_Instantiation.arrow(elements_to_semanticIdentitySet,
F_Instantiation.reuseSemanticIdentity(identityFactory.element()),
element,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_TRUE,
coreSets.isContainer_FALSE,
F_Instantiation.reuseSemanticIdentity(identityFactory.set()),
set,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_TRUE,
coreSets.isContainer_FALSE
);
} else {
return F_InstantiationImpl.raiseError(coreSets.semanticErr_operationIsIllegalOnThisInstance.identity(), coreSets.semanticErr);
}
}
}
public static Set removeElement(final Set set, final Set element){
if ( set.category().isEqualTo(disjunctSemanticIdentitySet)
|| set.category().isEqualTo(variantDisjunctSemanticIdentitySet) ) {
final Set arrows = element.filter(elements_to_disjunctSemanticIdentitySet);
// TODO rest of implementation DECOMMISSION_SEMANTICS
}
return F_InstantiationImpl.raiseError(coreSets.semanticErr_operationIsNotYetImplemented.identity(), coreSets.semanticErr);
}
// TODO unify with implementation of F_SetAlgebra.transformSemanticIdentitySetToOrderedSet(final Set set)
public static Set isElementOf(final Set semanticDomain, final Set element, final Set set) {
final Set setClass = transformSemanticRoleToEquivalenceClass(set);
final Set elementClass = transformSemanticRoleToEquivalenceClass(element);
final Set elementLinks = semanticDomain.filter(SemanticDomain.elements_to_semanticIdentitySet);
for (final Set e : elementLinks) {
if (e.from().isEqualTo(elementClass)
&& e.to().isEqualTo(setClass)) {
return S23MSemanticDomains.is_TRUE;
}
}
final Set elementLinks2 = semanticDomain.filter(elements_to_disjunctSemanticIdentitySet);
for (final Set e : elementLinks2) {
if (e.from().isEqualTo(elementClass)
&& e.to().isEqualTo(setClass)) {
return S23MSemanticDomains.is_TRUE;
}
}
return S23MSemanticDomains.is_FALSE;
}
public static Set addSemanticRole(final Set newSemanticRole, final Set equivalenceClass){
if ( newSemanticRole.category().isSuperSetOf(semanticRole).isEqualTo(coreSets.is_TRUE)) {
return linkSemanticRole(newSemanticRole, equivalenceClass);
} else {
return F_InstantiationImpl.raiseError(coreSets.semanticErr_operationIsIllegalOnThisInstance.identity(), coreSets.semanticErr);
}
}
public static Set linkSemanticRole(final Set semanticRole, final Set equivalenceClass) {
return F_Instantiation.arrow(SemanticDomain.semanticRole_to_equivalenceClass,
F_Instantiation.reuseSemanticIdentity(identityFactory.referencingSemanticRole()),
semanticRole,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_FALSE,
coreSets.isContainer_FALSE,
F_Instantiation.reuseSemanticIdentity(identityFactory.equivalenceClass()),
equivalenceClass,
coreSets.minCardinality_NOTAPPLICABLE,
coreSets.maxCardinality_NOTAPPLICABLE,
coreSets.isNavigable_TRUE,
coreSets.isContainer_FALSE);
}
public static Set transformSemanticRoleToEquivalenceClass(final Set semanticRole){
if (semanticRole.category().isEqualTo(SemanticDomain.disjunctSemanticIdentitySet)
|| semanticRole.category().isEqualTo(SemanticDomain.semanticIdentitySet)
|| semanticRole.category().isEqualTo(SemanticDomain.variantDisjunctSemanticIdentitySet)
) {
return semanticRole;
}
final Set resultSet = semanticRole.container().filter(SemanticDomain.semanticRole_to_equivalenceClass).filterByLinkedFrom(semanticRole).filterTo();
if (resultSet.size() == 1) {
if (resultSet.extractFirst().category().isEqualTo(SemanticDomain.semanticRole)) {
return transformSemanticRoleToEquivalenceClass(resultSet.extractFirst());
} else {
return resultSet.extractFirst();
}
} else {
return S23MSemanticDomains.is_NOTAPPLICABLE;
}
}
}
| mpl-2.0 |
james-wallace-ghub/ydkjx | demo/PaletteMaker.java | 1258 | package org.kjtw.main;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class PaletteMaker {
/**
* @param args
*/
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String indir = file.getAbsolutePath();
BufferedImage out = null;
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
out = new BufferedImage(256,1, BufferedImage.TYPE_INT_RGB);
String sCurrentLine;
int pos=0;
while ((sCurrentLine = br.readLine()) != null) {
String[] values = sCurrentLine.split(" ");
Color ocol = new Color(Integer.valueOf(values[0]),Integer.valueOf(values[1]),Integer.valueOf(values[2]));
out.setRGB(pos, 0, ocol.getRGB());
pos++;
}
File outputimage = new File("C:\\ydkj\\palette", "GENPALETTE.bmp");
ImageIO.write(out, "bmp", outputimage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| mpl-2.0 |
RITcraft/TradingPost | src/main/java/edu/rit/chrisbitler/ritcraft/tradingpost/cmd/TradePost.java | 15216 | package edu.rit.chrisbitler.ritcraft.tradingpost.cmd;
import edu.rit.chrisbitler.ritcraft.tradingpost.TradingPost;
import edu.rit.chrisbitler.ritcraft.tradingpost.data.Sale;
import edu.rit.chrisbitler.ritcraft.tradingpost.data.Sales;
import edu.rit.chrisbitler.ritcraft.tradingpost.json.JsonConfiguration;
import net.md_5.bungee.api.ChatColor;
import org.apache.commons.codec.digest.DigestUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Random;
/**
* Created by Chris on 11/1/2015.
*/
public class TradePost implements CommandExecutor {
public boolean onCommand(final CommandSender commandSender, final Command command, final String s, final String[] args) {
if(commandSender instanceof Player) {
if(args.length > 0) {
if (args[0].equals("register")) {
final Player p = (Player) commandSender;
if (args.length == 2) {
p.sendMessage(ChatColor.YELLOW + "Connecting to user service..");
Bukkit.getScheduler().runTaskAsynchronously(TradingPost.instance, new Runnable() {
public void run() {
try {
Statement st = TradingPost.instance.getMYSQL().createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM `users` WHERE `uuid`='" + p.getUniqueId().toString() + "'");
rs.first();
if (rs.getInt("COUNT(*)") < 1) {
String password = args[1];
SecureRandom sr = new SecureRandom();
byte[] salt = new byte[256];
sr.nextBytes(salt);
String saltString = base64Encode(salt);
String hash = hash(password, salt);
st.execute("INSERT INTO `users` (`uuid`,`password`,`salt`) VALUES ('" + p.getUniqueId().toString() + "','" + hash + "','" + saltString + "')");
p.sendMessage(ChatColor.GREEN + "You have registered and should be able to use the trading post with your username and the password you selected.");
} else {
p.sendMessage(ChatColor.RED + "You already have an account registered!");
}
} catch (SQLException e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "A database error has occured! Please try again later.");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
} else {
commandSender.sendMessage(ChatColor.DARK_RED + "Incorrect command syntax - try /tradepost register [password]");
}
} else if (args[0].equals("add")) {
if (args.length == 3) {
int amount = 0;
final int price;
try {
amount = Integer.parseInt(args[1]);
price = Integer.parseInt(args[2]);
} catch (Exception e) {
commandSender.sendMessage(ChatColor.RED + "That is not a valid number for either the amount or the price.");
return true;
}
final ItemStack inHand = ((Player) commandSender).getItemInHand();
final Player user = (Player) commandSender;
if (inHand.getAmount() >= amount && amount > 0) {
if (price > -1) {
final int finalAmount = amount;
Bukkit.getScheduler().runTaskAsynchronously(TradingPost.instance, new Runnable() {
public void run() {
try {
ItemStack toAdd = inHand.clone();
if (toAdd.getItemMeta() != null) {
if (toAdd.getItemMeta().getDisplayName() != null) {
if (toAdd.getItemMeta().getDisplayName().contains("<") || toAdd.getItemMeta().getDisplayName().contains(">")) {
commandSender.sendMessage(ChatColor.RED + "Remove the HTML tags from your item name before selling it.");
return;
}
}
}
Statement stmt = TradingPost.instance.getMYSQL().createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM `listings` WHERE `owner`='" + user.getUniqueId().toString() + "'");
rs.first();
if (rs.getInt("COUNT(*)") >= 4) {
commandSender.sendMessage(ChatColor.RED + "You cannot have more than 4 offers at once.");
return;
}
toAdd.setAmount(finalAmount);
Statement stmnt = TradingPost.instance.getMYSQL().createStatement();
JsonConfiguration config = new JsonConfiguration();
config.set("item", toAdd);
String json = config.saveToString();
String owner = ((Player) commandSender).getUniqueId().toString();
stmnt.executeUpdate("INSERT INTO `listings` (`owner`,`price`,`item`) VALUES ('" + owner + "','" + price + "','" + json + "')", Statement.RETURN_GENERATED_KEYS);
ResultSet _id = stmnt.getGeneratedKeys();
int id = -999;
if (_id.next()) {
id = _id.getInt(1);
}
if (inHand.getAmount() > finalAmount) {
inHand.setAmount(inHand.getAmount() - finalAmount);
} else {
((Player) commandSender).setItemInHand(new ItemStack(Material.AIR));
}
Sale sale = new Sale(owner, price, toAdd, id);
Sales.sales.add(sale);
commandSender.sendMessage(ChatColor.GREEN + "Listing added to the trading post!");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
} else {
commandSender.sendMessage(ChatColor.DARK_RED + "You cannot use a negative price.");
}
} else {
commandSender.sendMessage(ChatColor.DARK_RED + "You cannot add more of this item than you have.");
}
} else {
commandSender.sendMessage(ChatColor.DARK_RED + "Incorrect command snytax. Try /tradepost add [amount] [price]");
}
}else if(args[0].equalsIgnoreCase("help")){
commandSender.sendMessage(ChatColor.GOLD + "TradingPost Help");
commandSender.sendMessage(ChatColor.GOLD + "-----------------");
commandSender.sendMessage(ChatColor.YELLOW + "/tradepost register [password] " + ChatColor.WHITE + " Register for the trading post with the specified password.");
commandSender.sendMessage(ChatColor.YELLOW + "/tradepost add [amount] [price] " + ChatColor.WHITE + " Adds a new offer to the trading post of the item you are holding with the specified amount and price.");
commandSender.sendMessage(ChatColor.YELLOW + "/tradepost claim " + ChatColor.WHITE + " Claim your bought/canceled items from the trading post.");
commandSender.sendMessage(ChatColor.YELLOW + "/tradepost help " + ChatColor.WHITE + " You are reading it.");
}else if(args[0].equalsIgnoreCase("claim")) {
commandSender.sendMessage(ChatColor.YELLOW + "Contacting claims service...");
Bukkit.getScheduler().runTaskAsynchronously(TradingPost.instance, new Runnable() {
public void run() {
try {
Player p = (Player) commandSender;
Statement stmt = TradingPost.instance.getMYSQL().createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM `claims` WHERE `owner`='"+p.getUniqueId().toString()+"'");
rs.first();
int items = rs.getInt("COUNT(*)");
if(items > 0) {
p.sendMessage(ChatColor.GREEN + "You have " + items + " items to claim.");
if(p.getInventory().firstEmpty() > 0) {
int given = 0;
ResultSet rs2 = stmt.executeQuery("SELECT * FROM `claims` WHERE `owner`='" + p.getUniqueId().toString() + "'");
while(p.getInventory().firstEmpty() > 0 && rs2.next()) {
JsonConfiguration config = new JsonConfiguration();
config.loadFromString(rs2.getString("item"));
ItemStack item = config.getItemStack("item");
p.getInventory().addItem(item);
p.sendMessage(ChatColor.GREEN + "Claimed item: " + getName(item) + " x" + item.getAmount());
given+=1;
Statement stmt2 = TradingPost.instance.getMYSQL().createStatement();
stmt2.execute("DELETE FROM `claims` WHERE `owner`='" + p.getUniqueId().toString() + "' AND `id`='" + rs2.getInt("id") + "'");
stmt2.close();
}
if(given == items) {
p.sendMessage(ChatColor.GREEN + "You have claimed all of your items!");
}else{
p.sendMessage(ChatColor.YELLOW + "You have claimed " + given + " out of " + items + " items. Clear more inventory space to claim the rest.");
}
rs2.close();
rs.close();
stmt.close();
}else{
p.sendMessage(ChatColor.RED + "Please open up some inventory space before you claim your items.");
}
}else{
p.sendMessage(ChatColor.RED + "You have no items to claim.");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
});
}
}else{
commandSender.sendMessage(ChatColor.DARK_RED + "Incorrect command syntax. /tradepost [register/add/claim/help]");
}
}
return true;
}
private String hash(String password, byte[] salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(salt);
byte[] input = digest.digest(password.getBytes("UTF-8"));
for (int i = 0; i < 1000; i++) {
digest.reset();
input = digest.digest(input);
}
return base64Encode(input);
}
private String base64Encode(byte[] data) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public String getName(ItemStack item) {
if (item.getItemMeta().getDisplayName() != null) {
String name = item.getType().name().toLowerCase();
name = name.replaceAll("_", " ");
String first = name.substring(0, 1);
name = name.substring(1);
name = first.toUpperCase() + name;
return "\"" + item.getItemMeta().getDisplayName() + "\" (" + name + ")";
} else {
String name = item.getType().name().toLowerCase();
name = name.replaceAll("_", " ");
String first = name.substring(0, 1);
name = name.substring(1);
name = first.toUpperCase() + name;
return name;
}
}
}
| mpl-2.0 |
mayank-kgp/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/datatablelistfragment/DataTableListPresenter.java | 4816 | package com.mifos.mifosxdroid.online.datatablelistfragment;
import com.mifos.api.DataManager;
import com.mifos.api.datamanager.DataManagerClient;
import com.mifos.api.datamanager.DataManagerLoan;
import com.mifos.mifosxdroid.R;
import com.mifos.mifosxdroid.base.BasePresenter;
import com.mifos.objects.accounts.loan.Loans;
import com.mifos.objects.client.Client;
import com.mifos.objects.client.ClientPayload;
import com.mifos.services.data.GroupLoanPayload;
import com.mifos.services.data.LoansPayload;
import com.mifos.utils.MFErrorParser;
import javax.inject.Inject;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
public class DataTableListPresenter extends BasePresenter<DataTableListMvpView> {
private final DataManagerLoan mDataManagerLoan;
private final DataManager mDataManager;
private final DataManagerClient dataManagerClient;
private CompositeSubscription mSubscription;
@Inject
public DataTableListPresenter(DataManagerLoan dataManager, DataManager manager,
DataManagerClient dataManagerClient) {
mDataManagerLoan = dataManager;
mDataManager = manager;
this.dataManagerClient = dataManagerClient;
mSubscription = new CompositeSubscription();
}
@Override
public void attachView(DataTableListMvpView mvpView) {
super.attachView(mvpView);
}
@Override
public void detachView() {
super.detachView();
if (mSubscription != null) mSubscription.unsubscribe();
}
public void createLoansAccount(LoansPayload loansPayload) {
checkViewAttached();
getMvpView().showProgressbar(true);
mSubscription.add(mDataManagerLoan.createLoansAccount(loansPayload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Loans>() {
@Override
public void onCompleted() {
getMvpView().showProgressbar(false);
}
@Override
public void onError(Throwable e) {
getMvpView().showProgressbar(false);
getMvpView().showMessage(R.string.generic_failure_message);
}
@Override
public void onNext(Loans loans) {
getMvpView().showProgressbar(false);
getMvpView().showMessage(R.string.loan_creation_success);
}
}));
}
public void createGroupLoanAccount(GroupLoanPayload loansPayload) {
checkViewAttached();
getMvpView().showProgressbar(true);
mSubscription.add(mDataManager.createGroupLoansAccount(loansPayload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Loans>() {
@Override
public void onCompleted() {
getMvpView().showProgressbar(false);
}
@Override
public void onError(Throwable e) {
getMvpView().showProgressbar(false);
getMvpView().showMessage(R.string.generic_failure_message);
}
@Override
public void onNext(Loans loans) {
getMvpView().showProgressbar(false);
getMvpView().showMessage(R.string.loan_creation_success);
}
})
);
}
public void createClient(ClientPayload clientPayload) {
checkViewAttached();
getMvpView().showProgressbar(true);
mSubscription.add(dataManagerClient.createClient(clientPayload)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Client>() {
@Override
public void onCompleted() {
getMvpView().showProgressbar(false);
}
@Override
public void onError(Throwable e) {
getMvpView().showProgressbar(false);
getMvpView().showMessage(MFErrorParser.errorMessage(e));
}
@Override
public void onNext(Client client) {
getMvpView().showProgressbar(false);
getMvpView().showClientCreatedSuccessfully(client);
}
}));
}
}
| mpl-2.0 |
CecileBONIN/Silverpeas-Core | web-core/src/main/java/com/silverpeas/accesscontrol/PublicationAccessController.java | 5856 | /**
* 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.accesscontrol;
import java.util.Collection;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;
import org.silverpeas.core.admin.OrganisationController;
import org.silverpeas.core.admin.OrganisationControllerFactory;
import com.silverpeas.util.ComponentHelper;
import com.silverpeas.util.StringUtil;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.SilverpeasRole;
import com.stratelia.webactiv.util.EJBUtilitaire;
import com.stratelia.webactiv.util.JNDINames;
import com.stratelia.webactiv.util.node.model.NodePK;
import com.stratelia.webactiv.util.publication.control.PublicationBm;
import com.stratelia.webactiv.util.publication.model.PublicationDetail;
import com.stratelia.webactiv.util.publication.model.PublicationPK;
/**
* Check the access to a publication for a user.
* @author neysseric
*/
@Named
public class PublicationAccessController extends AbstractAccessController<PublicationPK> {
@Inject
private NodeAccessController accessController;
@Inject
private OrganisationController controller;
public PublicationAccessController() {
}
/**
* For test only.
* @param accessController
*/
PublicationAccessController(NodeAccessController accessController) {
this.accessController = accessController;
}
@Override
public boolean isUserAuthorized(String userId, PublicationPK object,
final AccessControlContext context) {
boolean authorized = true;
boolean isRoleVerificationRequired = true;
boolean sharingOperation = context.getOperations().contains(AccessControlOperation.sharing);
// Verifying sharing is possible
if (sharingOperation) {
authorized =
StringUtil.getBooleanValue(getOrganisationController().getComponentParameterValue(
object.getInstanceId(), "usePublicationSharing"));
isRoleVerificationRequired = authorized;
}
if (isRoleVerificationRequired &&
ComponentHelper.getInstance().isThemeTracker(object.getInstanceId())) {
String foreignId = object.getId();
try {
foreignId = getActualForeignId(foreignId, object.getInstanceId());
} catch (Exception e) {
SilverTrace.error("accesscontrol", getClass().getSimpleName() + ".isUserAuthorized()",
"root.NO_EX_MESSAGE", e);
return false;
}
try {
Collection<NodePK> nodes = getPublicationBm().getAllFatherPK(new PublicationPK(foreignId,
object.getInstanceId()));
for (NodePK nodePk : nodes) {
if (sharingOperation) {
Set<SilverpeasRole> userRoles = getNodeAccessController().getUserRoles(context, userId, nodePk);
SilverpeasRole greaterUserRole = SilverpeasRole.getGreaterFrom(userRoles);
return greaterUserRole.isGreaterThanOrEquals(SilverpeasRole.admin);
} else {
if (getNodeAccessController().isUserAuthorized(userId, nodePk)) {
return true;
}
}
}
} catch (Exception ex) {
SilverTrace.error("accesscontrol", getClass().getSimpleName() + ".isUserAuthorized()",
"root.NO_EX_MESSAGE", ex);
return false;
}
return false;
}
return authorized;
}
protected PublicationBm getPublicationBm() throws Exception {
return EJBUtilitaire.getEJBObjectRef(JNDINames.PUBLICATIONBM_EJBHOME, PublicationBm.class);
}
/**
* Return the 'real' id of the publication to which this file is attached to. In case of a clone
* publication we need the cloneId (that is the original publication).
* @param foreignId
* @param instanceId
* @return
* @throws Exception
*/
private String getActualForeignId(String foreignId, String instanceId) throws Exception {
PublicationDetail pubDetail = getPublicationBm().getDetail(new PublicationPK(foreignId,
instanceId));
if (!pubDetail.isValid() && pubDetail.haveGotClone()) {
return pubDetail.getCloneId();
}
return foreignId;
}
/**
* Gets a controller of access on the nodes of a publication.
* @return a NodeAccessController instance.
*/
protected NodeAccessController getNodeAccessController() {
if (accessController == null) {
accessController = new NodeAccessController();
}
return accessController;
}
/**
* Gets the organization controller used for performing its task.
* @return an organization controller instance.
*/
private OrganisationController getOrganisationController() {
if (controller == null) {
controller = OrganisationControllerFactory.getOrganisationController();
}
return controller;
}
} | agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-accessiweb2.2/src/test/java/org/asqatasun/rules/accessiweb22/Aw22Rule03022Test.java | 3499 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.accessiweb22;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.rules.accessiweb22.test.Aw22RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 3.2.2 of the referential Accessiweb 2.2.
*
* @author jkowalczyk
*/
public class Aw22Rule03022Test extends Aw22RuleImplementationTestCase {
/**
* Default constructor
*/
public Aw22Rule03022Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.asqatasun.rules.accessiweb22.Aw22Rule03022");
}
@Override
protected void setUpWebResourceMap() {
// getWebResourceMap().put("AW22.Test.3.2.2-1Passed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule03022/AW22.Test.3.2.2-1Passed-01.html"));
// getWebResourceMap().put("AW22.Test.3.2.2-2Failed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule03022/AW22.Test.3.2.2-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.3.2.2-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule03022/AW22.Test.3.2.2-3NMI-01.html"));
// getWebResourceMap().put("AW22.Test.3.2.2-4NA-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule03022/AW22.Test.3.2.2-4NA-01.html"));
}
@Override
protected void setProcess() {
// assertEquals(TestSolution.PASSED,
// processPageTest("AW22.Test.3.2.2-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// processPageTest("AW22.Test.3.2.2-2Failed-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
processPageTest("AW22.Test.3.2.2-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// processPageTest("AW22.Test.3.2.2-4NA-01").getValue());
}
@Override
protected void setConsolidate() {
// assertEquals(TestSolution.PASSED,
// consolidate("AW22.Test.3.2.2-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// consolidate("AW22.Test.3.2.2-2Failed-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("AW22.Test.3.2.2-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// consolidate("AW22.Test.3.2.2-4NA-01").getValue());
}
}
| agpl-3.0 |
opensourceBIM/bimql | BimQL/src/nl/wietmazairac/bimql/get/attribute/GetAttributeSubIfcSweptAreaSolid.java | 2569 | package nl.wietmazairac.bimql.get.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 BIMserver.org
*
* 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 {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.ArrayList;
import org.bimserver.models.ifc2x3tc1.IfcSweptAreaSolid;
public class GetAttributeSubIfcSweptAreaSolid {
// fields
private Object object;
private String string;
// constructors
public GetAttributeSubIfcSweptAreaSolid(Object object, String string) {
this.object = object;
this.string = string;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public ArrayList<Object> getResult() {
ArrayList<Object> resultList = new ArrayList<Object>();
if (string.equals("SweptArea")) {
resultList.add(((IfcSweptAreaSolid) object).getSweptArea());
//1IfcProfileDef
}
else if (string.equals("Position")) {
resultList.add(((IfcSweptAreaSolid) object).getPosition());
//1IfcAxis2Placement3D
}
else if (string.equals("Dim")) {
resultList.add(((IfcSweptAreaSolid) object).getDim());
//2int
}
else if (string.equals("StyledByItem")) {
//3xxx
for (int i = 0; i < ((IfcSweptAreaSolid) object).getStyledByItem().size(); i++) {
resultList.add(((IfcSweptAreaSolid) object).getStyledByItem().get(i));
}
//3EList
}
else if (string.equals("LayerAssignments")) {
//3xxx
for (int i = 0; i < ((IfcSweptAreaSolid) object).getLayerAssignments().size(); i++) {
resultList.add(((IfcSweptAreaSolid) object).getLayerAssignments().get(i));
}
//3EList
}
else {
}
return resultList;
}
}
| agpl-3.0 |
MCPhoton/Photon-MC1.8 | src/org/mcphoton/entity/MetadataInputStream.java | 3933 | /*
* Copyright (C) 2015 ElectronWill
*
* 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.mcphoton.entity;
import java.io.IOException;
import java.util.List;
import org.mcphoton.item.AppliedEnchantment;
import org.mcphoton.item.EnchantmentType;
import org.mcphoton.item.ItemStack;
import org.mcphoton.item.ItemType;
import org.mcphoton.util.Location;
import org.mcphoton.util.Rotation;
import com.electronwill.collections.IndexMap;
import com.electronwill.nbt.NBTParser;
import com.electronwill.nbt.TagCompound;
import com.electronwill.streams.EasyInputStream;
/**
* An outputstream for reading entity's metadata.
*
* @see http://wiki.vg/Entities#Entity_Metadata_Format
* @author ElectronWill
*/
public final class MetadataInputStream {
private final EasyInputStream in;
private final IndexMap<Object> data = new IndexMap<>();
public MetadataInputStream(EasyInputStream in) {
this.in = in;
}
public void read() throws IOException {
while (in.available() > 0) {
final byte identifier = in.readByte();
if (identifier == 127) {
break;
}
int index = identifier & 0x1F;
int type = identifier >> 5;
final Object value;
switch (type) {
case 0:
value = in.readByte();
break;
case 1:
value = in.readShort();
break;
case 2:
value = in.readInt();
break;
case 3:
value = in.readFloat();
break;
case 4:
value = in.readString();
break;
case 5:
short typeId = in.readShort();
byte count = in.readByte();
short damage = in.readShort();
boolean hasNbt = in.readBoolean();
ItemType item = null;// TODO ItemType.getItem(typeId);
ItemStack stack = null;// TODO item.createStack(count, damage);
if (hasNbt) {
NBTParser parser = new NBTParser(in);
TagCompound nbt = parser.parse();
List<TagCompound> compounds = (List) nbt.get("ench");
for (TagCompound tc : compounds) {
short enchantId = (short) tc.get("id");
short enchantLevel = (short) tc.get("lvl");
AppliedEnchantment enchant = new AppliedEnchantment(stack, EnchantmentType.get(enchantId), enchantLevel);
stack.addEnchantment(enchant);
}
}
value = stack;
break;
case 6:
int x = in.readInt(), y = in.readInt(), z = in.readInt();
value = new Location(null, x, y, z);
break;
case 7:
float pitch = in.readFloat(), yaw = in.readFloat(), roll = in.readFloat();
value = new Rotation(pitch, yaw, roll);
break;
default:
// Invalid type!!
value = null;
break;
}
data.put(index, value);
}
}
public Object get(int index) {
return data.get(index);
}
public byte getByte(int index) {
return (byte) data.get(index);
}
public short getShort(int index) {
return (short) data.get(index);
}
public int getInt(int index) {
return (int) data.get(index);
}
public float getFloat(int index) {
return (float) data.get(index);
}
public String getString(int index) {
return (String) data.get(index);
}
public Location getLocation(int index) {
return (Location) data.get(index);
}
public Rotation getRotation(int index) {
return (Rotation) data.get(index);
}
public ItemStack getSlot(int index) {
return (ItemStack) data.get(index);
}
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-core/src/main/java/edu/arizona/kfs/sys/identity/UaEmployeeDerivedRoleTypeServiceImpl.java | 10840 | package edu.arizona.kfs.sys.identity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coreservice.api.parameter.Parameter;
import org.kuali.kfs.coreservice.framework.parameter.ParameterConstants;
import org.kuali.kfs.coreservice.framework.parameter.ParameterService;
import edu.arizona.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.identity.EmployeeDerivedRoleTypeServiceImpl;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.kim.api.identity.affiliation.EntityAffiliation;
import org.kuali.rice.kim.api.identity.entity.EntityDefault;
import edu.arizona.kfs.sys.UaKFSConstants;
public class UaEmployeeDerivedRoleTypeServiceImpl extends EmployeeDerivedRoleTypeServiceImpl {
/**
* The basic role that grants users access to KFS. It gives users the
* ability to initiate most documents and use inquiries and search screens.
*/
private static final String ROLE_54_TITLE = KFSConstants.SysKimApiConstants.KFS_USER_ROLE_NAME;
/**
* A role that uses the Affiliation Type and Employee Status on a Principal
* record to determine if a user is an active faculty or staff employee.
* These users can initiate some KFS-PURAP documents and inquire into
* certain KFS screens, including Balance Inquiry screens.
*/
private static final String ROLE_32_TITLE = KFSConstants.SysKimApiConstants.ACTIVE_FACULTY_OR_STAFF_KIM_ROLE_NAME;
/**
* This role requires a Principal to have role 32 and the 'Professional'
* designation. The professional designation is determined by a Principal
* have one or more active affiliations found in the EDS_PROFESSIONAL_AFFS
* parameter. These users are allowed to be Account Supervisors or Account
* Managers on Accounts.
*/
private static final String ROLE_33_TITLE = KFSConstants.SysKimApiConstants.ACTIVE_PROFESSIONAL_EMPLOYEE_KIM_ROLE_NAME;
/**
* To be granted role 93, a Principal must have role 32 and role 54. These
* users are allowed to be fiscal Officers on Accounts.
*/
private static final String ROLE_93_TITLE = KFSConstants.SysKimApiConstants.ACTIVE_EMPLOYEE_AND_KFS_USER_KIM_ROLE_NAME;
/**
* To be granted role 94, a Principal must have role 33 and role 54. These
* users are allowed to be fiscal Officers on Accounts.
*/
private static final String ROLE_94_TITLE = KFSConstants.SysKimApiConstants.ACTIVE_PROFESSIONAL_EMPLOYEE_AND_KFS_USER_KIM_ROLE_NAME;
/**
* This role is a non-derived role that mimics role 32, and is used for
* individuals that need KFS base access but do not qualify for role 32,
* e.g. 'DCC: Independant Contractors' do not qualify for role 32, but some
* still need KFS access.
*/
private static final String ROLE_11173_TITLE = UaKFSConstants.BASE_FINANCIAL_SYSTEM_USER_KIM_ROLE_NAME;
// UA KFS7 upgrade
private static final String EDS_RESPECTED_AND_ORDERED_AFFS = "EDS_RESPECTED_AND_ORDERED_AFFS";
private static final String EDS_ORDERED_ACTIVE_STATUS_INDICATORS = "EDS_ORDERED_ACTIVE_STATUS_INDICATORS";
private static final String EDS_PROFESSIONAL_AFFS = "EDS_PROFESSIONAL_AFFS";
private static final String EDS_RESTRICTED_EMPLOYEE_TYPES = "EDS_RESTRICTED_EMPLOYEE_TYPES";
private ParameterService parameterService;
@Override
public boolean hasDerivedRole(String principalId, List<String> groupIds, String namespaceCode, String roleName, Map<String, String> qualification) {
boolean retval = false;
// Nothing to go off of, reject
if (StringUtils.isNotBlank(roleName) && StringUtils.isNotBlank(principalId)) {
// Work through our cases
EntityDefault entity = getIdentityService().getEntityDefaultByPrincipalId(principalId);
if (entity == null || entity.getEmployment() == null) {
retval = false;
} else if (hasRestrictedEmployeeType(entity)) {
retval = false;
} else if (roleName.equals(ROLE_32_TITLE)) {
// Note: this will return true if the person has role 11173
retval = hasRole32(entity, principalId);
} else if (roleName.equals(ROLE_33_TITLE)) {
retval = hasRole33(entity, principalId);
} else if (roleName.equals(ROLE_93_TITLE)) {
retval = hasRole93(entity, principalId);
} else if (roleName.equals(ROLE_94_TITLE)) {
retval = hasRole94(entity, principalId);
}
}
return retval;
}
private boolean hasRole32(EntityDefault entity, String principalId) {
// Role 32: has a respected EDS affiliation, and an active status,
// *or* has role 11173. Role 11173 is the manually assigned role
// for when we need to override role 32 requirments, e.g. our
// KATT DCC's are of the unrespected type 000975, and would not
// have KFS access, so we can just assign this role, and they're in
return (hasRespectedAffiliation(entity) && hasActiveStatus(entity)) || hasRole(principalId, ROLE_11173_TITLE);
}
private boolean hasRole33(EntityDefault entity, String principalId) {
// Role 33: has role 32, and has a designated 'professional' affiliation
return hasRole32(entity, principalId) && hasProfessionalDesignation(entity);
}
private boolean hasRole93(EntityDefault entity, String principalId) {
// Role 93: has role 32 and 54
return hasRole32(entity, principalId) && hasRole54(principalId);
}
private boolean hasRole94(EntityDefault entity, String principalId) {
// Role 94: has roles 33 and 54
return hasRole33(entity, principalId) && hasRole54(principalId);
}
private boolean hasRole54(String principalId) {
return hasRole(principalId, ROLE_54_TITLE);
}
/*
* Verify with role service that principal has role
*/
private boolean hasRole(String principalId, String roleName) {
String namespaceCode = KFSConstants.CoreModuleNamespaces.KFS;
List<String> roleIds = new ArrayList<String>(1);
String roleId = getRoleService().getRoleIdByNamespaceCodeAndName(namespaceCode, roleName);
roleIds.add(roleId);
return getRoleService().principalHasRole(principalId, roleIds, null);
}
/*
* Verify principal is active. To be active, an employee record must have
* its active flag set true *and* its active indicator must be in the
* defined set of active indicators identified in the KFS param
* 'EDS_EMPLOYEE_ACTIVE_INDICATORS'.
*
* These two variables are set by the class EdsPrincipalDaoImpl using
* information collected from an EDS interface.
*/
private boolean hasActiveStatus(EntityDefault entity) {
// Compare status code against KFS params
Set<String> activeIndicators = getValueSetForParameter(EDS_ORDERED_ACTIVE_STATUS_INDICATORS);
String statusCode = entity.getEmployment().getEmployeeStatus().getCode();
boolean statusCodeIsActive = activeIndicators.contains(statusCode);
// Get status flag (is redundant w/ statusCode comparison, do it to be
// safe)
boolean statusFlagIsActive = entity.getEmployment().isActive();
// Return combo of the two
return statusCodeIsActive && statusFlagIsActive;
}
/**
* An active affiliation is set on an employee by EdsPrincipalDaoImpl from
* an EDS interface. The set of active affiliations are defined in two KFS
* parameters: 1. EDS_EMPLOYEE_ACTIVE_AFFILIATIONS 2.
* EDS_DCC_ACTIVE_AFFILIATIONS
*/
private boolean hasRespectedAffiliation(EntityDefault entity) {
// Ensure they have at least one affiliation
List<EntityAffiliation> affInfoList = entity.getAffiliations();
if (affInfoList == null || affInfoList.size() == 0) {
return false;
}
// Collect all of our affiliations from KFS params
Set<String> respectedAffStrings = getValueSetForParameter(EDS_RESPECTED_AND_ORDERED_AFFS);
// Do actual comparison
for (EntityAffiliation affInfo : affInfoList) {
String affString = affInfo.getAffiliationType().getCode();
if (respectedAffStrings.contains(affString)) {
return true;
}
}
return false;
}
/**
* The 'professional' designation of a user is determined by the user's
* affiliation. The affiliations designated as 'professional' are defined in
* the KFS param 'EDS_PROFESSIONAL_AFFILIATIONS'.
*/
private boolean hasProfessionalDesignation(EntityDefault entity) {
// Collect all of our affiliations from KFS params
Set<String> allProfessionalAffiliations = getValueSetForParameter(EDS_PROFESSIONAL_AFFS);
// Ensure they have at least one affiliation
List<EntityAffiliation> affInfoList = entity.getAffiliations();
if (affInfoList == null || affInfoList.size() == 0) {
return false;
}
// Do actual comparison
for (EntityAffiliation affInfo : affInfoList) {
if (allProfessionalAffiliations.contains(affInfo.getAffiliationType().getCode())) {
return true;
}
}
return false;
}
/**
* Restrict employees from access if their employee type code is in the
* restricted list. The list of resticted emplyees types live in the kfs
* 'EDS_RESTRICTED_EMPLOYEE_TYPES' param. As of release 58, the codes
* included 'J' and 'U', which are highschool student workers, and workers
* of the 'unknown' type.
*/
private boolean hasRestrictedEmployeeType(EntityDefault entity) {
String employeeType = entity.getEmployment().getEmployeeType().getCode();
Set<String> restrictedEmployeeTypes = getValueSetForParameter(EDS_RESTRICTED_EMPLOYEE_TYPES);
return restrictedEmployeeTypes.contains(employeeType);
}
/**
* Method to obtain a set of values associated with a KFS paramater key.
*/
private Set<String> getValueSetForParameter(String parameterKey) {
String listAsCommaString = getStringForParameter(parameterKey);
String[] listAsArray = listAsCommaString.split(KFSConstants.MULTI_VALUE_SEPERATION_CHARACTER);
Set<String> resultSet = new HashSet<String>();
for (String result : listAsArray) {
resultSet.add(result);
}
return resultSet;
}
private String getStringForParameter(String parameterKey) {
String namespaceCode = KFSConstants.ParameterNamespaces.KFS;
String detailTypeCode = ParameterConstants.LOOKUP_COMPONENT;
String parameter = getParameterService().getParameterValueAsString(namespaceCode, detailTypeCode, parameterKey);
if (StringUtils.isBlank(parameter)) {
String message = String.format("ParameterService returned null for parameterKey: '%s', namespaceCode: '%s', detailTypeCode: '%s'", parameterKey, namespaceCode, detailTypeCode);
throw new RuntimeException(message);
}
return parameter;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
}
| agpl-3.0 |
flaviohenso/projeto-JSF2 | src/main/java/com/flavio/servlet/ProdutoComplete.java | 1390 | /**
* projeto-web : 11 de ago de 2017
*/
package com.flavio.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.flavio.service.ProdutoService;
import com.google.gson.Gson;
/**
* @author flavio
*
*/
@WebServlet(name="autoCompleteProduto", urlPatterns="/compras/autoCompleteProduto")
public class ProdutoComplete extends HttpServlet{
private static final long serialVersionUID = 1L;
@Inject
private ProdutoService produtoService;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
try {
String term = request.getParameter("query");
System.out.println("Data from ajax call ");
ArrayList<String> list = produtoService.autoComplete(term);
String searchList = new Gson().toJson(list);
response.getWriter().write(searchList);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| agpl-3.0 |
semantic-web-software/dynagent | Tools/src/dynagent/tools/parsers/uni/auxiliar/TClaseAdvanced.java | 2089 | package dynagent.tools.parsers.uni.auxiliar;
//ELIMINAR DE AQUI CUANDO NO HAYA QUE PROBAR MAS
//FraN
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.naming.NamingException;
import dynagent.common.basicobjects.TClase;
import dynagent.server.database.dao.DAOManager;
import dynagent.server.database.dao.IDAO;
import dynagent.server.database.dao.TClaseDAO;
public class TClaseAdvanced {
private LinkedList tablaClases=null;
private IDAO idao;
public TClaseAdvanced() throws SQLException, NamingException{
idao = DAOManager.getInstance().getDAO("Clases");
idao.open();
TClaseDAO clasdao = (TClaseDAO)idao.getDAO();
if(clasdao==null)
System.out.println("classdao=null");
tablaClases = clasdao.getAll();
idao.close();
}
public LinkedList getTablaClases(){
return tablaClases;
}
public void setTablaClases(LinkedList l){
this.tablaClases = l;
}
public IDAO getIDAO(){
return idao;
}
public void setIDAO(IDAO idao){
this.idao = idao;
}
public String getNameById(int idto){
for(int i = 0; i< tablaClases.size();i++){
TClase clase = (TClase) tablaClases.get(i);
if(clase.getIDTO() == idto)
return clase.getName();
}
return null;
}
public int getIdByName(String s){
for(int i = 0; i< tablaClases.size();i++){
TClase clase = (TClase) tablaClases.get(i);
if(clase.getName().equals(s))
return clase.getIDTO();
}
return -1;
}
public ArrayList getClasesDB(){
ArrayList l = new ArrayList();
for(int i = 0; i< tablaClases.size(); i++){
TClase tclase = (TClase) tablaClases.get(i);
Clase clase = new Clase();
int idto = tclase.getIDTO();
String name = tclase.getName();
clase.setIdto(idto);
clase.setName(name);
l.add(clase);
}
return l;
}
public void insertNewClass(int idto, String name) throws SQLException{
TClase nClas = new TClase();
nClas.setIDTO(idto);
nClas.setName(name);
TClaseDAO nClasDAO = new TClaseDAO();
nClasDAO.insert(nClas);
}
public void close() throws SQLException{
idao.close();
}
}
| agpl-3.0 |
hogi/kunagi | src/test/java/scrum/client/wiki/WikiTest.java | 7144 | package scrum.client.wiki;
import org.testng.Assert;
import org.testng.annotations.Test;
public class WikiTest extends Assert {
@Test
public void table() {
assertEquals(toHtml("{|a|}"), "\n<table class='data-table'>\n<tr> <td>a</td> </tr>\n</table>\n");
assertEquals(toHtml("{|\n|a\n|b\n|-\n|c\n|d\n\n|}"),
"\n<table class='data-table'>\n<tr> <td>a</td> <td>b</td> </tr>\n<tr> <td>c</td> <td>d</td> </tr>\n</table>\n");
assertEquals(toHtml("{|\n|a||b\n|-\n|c||d\n|}"),
"\n<table class='data-table'>\n<tr> <td>a</td> <td>b</td> </tr>\n<tr> <td>c</td> <td>d</td> </tr>\n</table>\n");
}
@Test
public void tableWithHeaders() {
assertEquals(toHtml("{|\n!a\n!b\n|-\n|c\n|d\n\n|}"),
"\n<table class='data-table'>\n<tr> <th>a</th> <th>b</th> </tr>\n<tr> <td>c</td> <td>d</td> </tr>\n</table>\n");
assertEquals(toHtml("{|\n!a!!b\n|-\n!c||d\n|}"),
"\n<table class='data-table'>\n<tr> <th>a</th> <th>b</th> </tr>\n<tr> <th>c</th> <td>d</td> </tr>\n</table>\n");
}
@Test
public void localImg() {
Assert.assertEquals(toHtml("[[Image:fle1]]"), "<a href='fle1.html'><img src=\"fle1\"></a>");
Assert.assertEquals(toHtml("[[Image:fle1|thumb]]"),
"<a href='fle1.html'><img src=\"fle1\" width=\"100px\" align=\"right\"></a>");
Assert.assertEquals(toHtml("[[Image:fle1|thumb|left]]"),
"<a href='fle1.html'><img src=\"fle1\" width=\"100px\" align=\"left\"></a>");
}
@Test
public void externalImg() {
Assert.assertEquals(toHtml("[[Image:http://servisto.de/image.png]]"),
"<a href=\"http://servisto.de/image.png\" target=\"_blank\"><img src=\"http://servisto.de/image.png\"></a>");
}
@Test
public void toc() {
Assert.assertEquals(toHtml("TOC\n= 1 =\n== 1.1 ==\n= 2 ="),
"<ul class=\"toc\"><li>1</li><ul><li>1.1</li></ul><li>2</li></ul><h1>1</h1><h2>1.1</h2><h1>2</h1>");
}
@Test
public void emphAndStrong() {
Assert.assertEquals(toHtml("'''''emph and strong'''''"), "<strong><em>emph and strong</em></strong>");
Assert.assertEquals(toHtml("this is '''strong'''"), "this is <strong>strong</strong>");
Assert.assertEquals(toHtml("this is ''emph''"), "this is <em>emph</em>");
Assert.assertEquals(toHtml("''''''''''"), "''''''''''");
Assert.assertEquals(toHtml("'''''test"), "'''''test");
}
@Test
public void entityReference() {
Assert.assertTrue(toHtml("tsk15 is completed").contains("<a "));
Assert.assertTrue(toHtml("[[Wiki]] is cool").contains("<a "));
Assert.assertTrue(toHtml("[[Wiki|Custom Text]] is cool").contains(">Custom Text</a>"));
Assert.assertTrue(toHtml("tsk15!").contains("<a "));
Assert.assertTrue(toHtml("(tsk15!), :-)").contains("<a "));
}
@Test
public void link() {
Assert.assertEquals(toHtml("link www.servisto.de here"),
"link <a href=\"http://www.servisto.de\" target=\"_blank\">servisto.de</a> here");
Assert.assertEquals(toHtml("http://www.servisto.de"),
"<a href=\"http://www.servisto.de\" target=\"_blank\">servisto.de</a>");
Assert.assertEquals(toHtml("link [www.servisto.de Servisto] here"),
"link <a href=\"http://www.servisto.de\" target=\"_blank\">Servisto</a> here");
}
@Test
public void itemList() {
Assert.assertEquals(toHtml("* item"), "<ul><li>item</li></ul>");
Assert.assertEquals(toHtml("# item"), "<ol><li>item</li></ol>");
Assert.assertEquals(toHtml("* item\nxyz"), "<ul><li>item<br>xyz</li></ul>");
Assert.assertEquals(toHtml("* item 1\n* item 2"), "<ul><li>item 1</li><li>item 2</li></ul>");
}
@Test
public void nestedItemList() {
Assert.assertEquals(toHtml("* item\n # subitem"), "<ul><li>item<ol><li>subitem</li></ol></li></ul>");
Assert.assertEquals(toHtml("* item\n # subitem\n # subitem"),
"<ul><li>item<ol><li>subitem</li><li>subitem</li></ol></li></ul>");
Assert.assertEquals(toHtml("* item\n # subitem\n * subsubitem"),
"<ul><li>item<ol><li>subitem<ul><li>subsubitem</li></ul></li></ol></li></ul>");
}
@Test
public void preformated() {
Assert.assertEquals(toHtml(" preformated"), "<div class=\"codeBlock\"><pre> preformated</pre></div>");
Assert.assertEquals(toHtml("\tpreformated"), "<div class=\"codeBlock\"><pre> preformated</pre></div>");
Assert.assertEquals(toHtml(" line 1\n line 2"), "<div class=\"codeBlock\"><pre> line 1\n line 2</pre></div>");
}
@Test
public void code() {
Assert.assertEquals(toHtml("here is <code>code</code>."), "here is <code>code</code>.");
Assert.assertEquals(toHtml("here is <code>multiword code</code>."), "here is <code>multiword code</code>.");
Assert.assertEquals(toHtml("here is <code>multiline\ncode</code>."),
"<p>here is <div class=\"codeBlock\"><code>multiline<br>code</code></div>.</p>");
Assert.assertEquals(toHtml("simple line\n\n<code>code</code>"), "<p>simple line</p><p><code>code</code></p>");
Assert.assertEquals(toHtml("<code>\n# enum\n# enum\n</code>"),
"<p><div class=\"codeBlock\"><code># enum<br># enum<br></code></div></p>");
Assert.assertEquals(toHtml("<code>a\n\nb</code>"),
"<p><div class=\"codeBlock\"><code>a<br><br>b</code></div></p>");
}
@Test
public void paragraph() {
Assert.assertEquals(toHtml("a b"), "a b");
Assert.assertEquals(toHtml("a\nb"), "<p>a<br>b</p>");
Assert.assertEquals(toHtml("a\r\nb"), "<p>a<br>b</p>");
Assert.assertEquals(toHtml("a\n\nb"), "<p>a</p><p>b</p>");
Assert.assertEquals(toHtml("a\n\n\n"), "<p>a</p>");
}
@Test
public void header() {
Assert.assertEquals(toHtml("= header ="), "<h1>header</h1>");
Assert.assertEquals(toHtml("= ="), "= =");
Assert.assertEquals(toHtml("= header = dummy"), "= header = dummy");
Assert.assertEquals(toHtml("== header =="), "<h2>header</h2>");
Assert.assertEquals(toHtml("== =="), "== ==");
Assert.assertEquals(toHtml("== header == dummy"), "== header == dummy");
Assert.assertEquals(toHtml("=== header ==="), "<h3>header</h3>");
Assert.assertEquals(toHtml("==== header ===="), "<h4>header</h4>");
}
@Test
public void specialChars() {
Assert.assertEquals(toHtml("ü ä ß"), "ü ä ß");
Assert.assertEquals(toHtml("& #"), "& #");
Assert.assertEquals(toHtml("< >"), "< >");
}
@Test
public void simple() {
Assert.assertEquals(toHtml("hello world"), "hello world");
}
@Test
public void complete() {
String html = toHtml("= header 1 =\nmy first paragraph\nstill first\n\nsecond paragraph\n\n\n\nthird paragraph\n\n== header 2 ==");
// System.out.println("\n-----\n" + html + "\n-----\n");
Assert.assertEquals(
html,
"<h1>header 1</h1><p>my first paragraph<br>still first</p><p>second paragraph</p><p>third paragraph</p><h2>header 2</h2>");
}
private static String toHtml(String wiki) {
WikiParser parser = new WikiParser(wiki);
WikiModel model = parser.parse(true);
return model.toHtml(new TestHtmlContext());
}
static class TestHtmlContext implements HtmlContext {
@Override
public String getEntityReferenceHrefOrOnclickAParameter(String reference) {
return "href='" + reference + ".html'";
}
@Override
public String getDownloadUrlByReference(String reference) {
return reference;
}
@Override
public String getEntityLabelByReference(String reference) {
return null;
}
}
}
| agpl-3.0 |
jasolangi/jasolangi.github.io | modules/help/src/main/java/org/openlmis/help/Repository/mapper/HelpContentMapper.java | 1676 | package org.openlmis.help.Repository.mapper;
import org.apache.ibatis.annotations.*;
import org.openlmis.help.domain.HelpContent;
import org.openlmis.help.domain.HelpTopic;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by seifu on 10/20/2014.
*/
@Deprecated
@Repository
public interface HelpContentMapper {
@Insert({"INSERT INTO elmis_help",
"(helpTopicId, name, htmlcontent, imagelink, createddate, createdby, modifiedby, modifieddate) ",
"VALUES(#{helpTopic.id}, #{name}, #{htmlContent}, #{imageLink}, #{createdDate}, #{createdBy}, #{modifiedBy}, #{modifiedDate})"})
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
void insert(HelpContent helpContent);
/*
*/
@Select("SELECT eh.* FROM elmis_help eh INNER JOIN elmis_help_topic et on eh.helpTopicId=et.id ")
@Results({
@Result(column = "helpTopicId", property = "helpTopic.id")
})
List<HelpContent> getHelpContentList();
/*
*/
@Select("SELECT * FROM elmis_help where helptopicid = #{id} ")
List<HelpContent> getHelpTopcicContentList(@Param(value = "id") Long id);
/*
*/
@Select("SELECT * FROM elmis_help where id = #{id} ")
HelpContent get(@Param(value = "id") Long id);
@Update("UPDATE elmis_help" +
" SET name= #{name}," +
" modifiedby=#{modifiedBy}, " +
"htmlcontent=#{htmlContent}, " +
"imagelink=#{imageLink}, " +
"modifieddate=#{modifiedDate}," +
" helptopicid=#{helpTopic.id}" +
" WHERE id=#{id};")
void update(HelpContent helpContent);
}
| agpl-3.0 |
ivanovlev/Gadgetbridge | app/src/main/java/nodomain/freeyourgadget/gadgetbridge/activities/ControlCenter.java | 18708 | package nodomain.freeyourgadget.gadgetbridge.activities;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import de.cketti.library.changelog.ChangeLog;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.activities.charts.ChartsActivity;
import nodomain.freeyourgadget.gadgetbridge.adapter.GBDeviceAdapter;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceManager;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
public class ControlCenter extends GBActivity {
private static final Logger LOG = LoggerFactory.getLogger(ControlCenter.class);
private TextView hintTextView;
private FloatingActionButton fab;
private ImageView background;
private SwipeRefreshLayout swipeLayout;
private GBDeviceAdapter mGBDeviceAdapter;
private DeviceManager deviceManager;
/**
* Temporary field for the context menu
*/
private GBDevice selectedDevice;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case GBApplication.ACTION_QUIT:
finish();
break;
case DeviceManager.ACTION_DEVICES_CHANGED:
refreshPairedDevices();
GBDevice selectedDevice = deviceManager.getSelectedDevice();
if (selectedDevice != null) {
refreshBusyState(selectedDevice);
enableSwipeRefresh(selectedDevice);
}
break;
}
}
};
private void refreshBusyState(GBDevice dev) {
if (dev != null && dev.isBusy()) {
swipeLayout.setRefreshing(true);
} else {
boolean wasBusy = swipeLayout.isRefreshing();
if (wasBusy) {
swipeLayout.setRefreshing(false);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controlcenter);
deviceManager = ((GBApplication)getApplication()).getDeviceManager();
hintTextView = (TextView) findViewById(R.id.hintTextView);
ListView deviceListView = (ListView) findViewById(R.id.deviceListView);
fab = (FloatingActionButton) findViewById(R.id.fab);
background = (ImageView) findViewById(R.id.no_items_bg);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchDiscoveryActivity();
}
});
final List<GBDevice> deviceList = deviceManager.getDevices();
mGBDeviceAdapter = new GBDeviceAdapter(this, deviceList);
deviceListView.setAdapter(this.mGBDeviceAdapter);
deviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
GBDevice gbDevice = mGBDeviceAdapter.getItem(position);
if (gbDevice.isInitialized()) {
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(gbDevice);
Class<? extends Activity> primaryActivity = coordinator.getPrimaryActivity();
if (primaryActivity != null) {
Intent startIntent = new Intent(ControlCenter.this, primaryActivity);
startIntent.putExtra(GBDevice.EXTRA_DEVICE, gbDevice);
startActivity(startIntent);
}
} else {
GBApplication.deviceService().connect(gbDevice);
}
}
});
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.controlcenter_swipe_layout);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
fetchActivityData();
}
});
registerForContextMenu(deviceListView);
IntentFilter filterLocal = new IntentFilter();
filterLocal.addAction(GBApplication.ACTION_QUIT);
filterLocal.addAction(DeviceManager.ACTION_DEVICES_CHANGED);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filterLocal);
refreshPairedDevices();
/*
* Ask for permission to intercept notifications on first run.
*/
Prefs prefs = GBApplication.getPrefs();
if (prefs.getBoolean("firstrun", true)) {
prefs.getPreferences().edit().putBoolean("firstrun", false).apply();
Intent enableIntent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(enableIntent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkAndRequestPermissions();
}
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
cl.getLogDialog().show();
}
GBApplication.deviceService().start();
enableSwipeRefresh(deviceManager.getSelectedDevice());
if (GB.isBluetoothEnabled() && deviceList.isEmpty() && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
startActivity(new Intent(this, DiscoveryActivity.class));
} else {
GBApplication.deviceService().requestDeviceInfo();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
selectedDevice = mGBDeviceAdapter.getItem(acmi.position);
if (selectedDevice != null && selectedDevice.isBusy()) {
// no context menu when device is busy
return;
}
getMenuInflater().inflate(R.menu.controlcenter_context, menu);
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(selectedDevice);
if (!coordinator.supportsActivityDataFetching()) {
menu.removeItem(R.id.controlcenter_fetch_activity_data);
}
if (!coordinator.supportsScreenshots()) {
menu.removeItem(R.id.controlcenter_take_screenshot);
}
if (!coordinator.supportsAlarmConfiguration()) {
menu.removeItem(R.id.controlcenter_configure_alarms);
}
if (!coordinator.supportsActivityTracking()) {
menu.removeItem(R.id.controlcenter_start_sleepmonitor);
}
if (selectedDevice.getState() == GBDevice.State.NOT_CONNECTED) {
menu.removeItem(R.id.controlcenter_disconnect);
}
if (!selectedDevice.isInitialized()) {
menu.removeItem(R.id.controlcenter_find_device);
menu.removeItem(R.id.controlcenter_fetch_activity_data);
menu.removeItem(R.id.controlcenter_configure_alarms);
menu.removeItem(R.id.controlcenter_take_screenshot);
}
menu.setHeaderTitle(selectedDevice.getName());
}
private void enableSwipeRefresh(GBDevice device) {
if (device == null) {
swipeLayout.setEnabled(false);
} else {
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(device);
boolean enable = coordinator.allowFetchActivityData(device);
swipeLayout.setEnabled(enable);
}
}
private void fetchActivityData() {
GBDevice selectedDevice = deviceManager.getSelectedDevice();
if (selectedDevice == null) {
return;
}
if (selectedDevice.isInitialized()) {
GBApplication.deviceService().onFetchActivityData();
} else {
swipeLayout.setRefreshing(false);
GB.toast(this, getString(R.string.device_not_connected), Toast.LENGTH_SHORT, GB.ERROR);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.controlcenter_start_sleepmonitor:
if (selectedDevice != null) {
Intent startIntent;
startIntent = new Intent(ControlCenter.this, ChartsActivity.class);
startIntent.putExtra(GBDevice.EXTRA_DEVICE, selectedDevice);
startActivity(startIntent);
}
return true;
case R.id.controlcenter_fetch_activity_data:
fetchActivityData();
return true;
case R.id.controlcenter_disconnect:
if (selectedDevice != null) {
selectedDevice = null;
GBApplication.deviceService().disconnect();
}
return true;
case R.id.controlcenter_find_device:
if (selectedDevice != null) {
findDevice(true);
ProgressDialog.show(
this,
getString(R.string.control_center_find_lost_device),
getString(R.string.control_center_cancel_to_stop_vibration),
true, true,
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
findDevice(false);
}
});
}
return true;
case R.id.controlcenter_configure_alarms:
if (selectedDevice != null) {
Intent startIntent;
startIntent = new Intent(ControlCenter.this, ConfigureAlarms.class);
startIntent.putExtra(GBDevice.EXTRA_DEVICE, selectedDevice);
startActivity(startIntent);
}
return true;
case R.id.controlcenter_take_screenshot:
if (selectedDevice != null) {
GBApplication.deviceService().onScreenshotReq();
}
return true;
case R.id.controlcenter_delete_device:
if (selectedDevice != null) {
confirmDeleteDevice(selectedDevice);
}
return true;
default:
return super.onContextItemSelected(item);
}
}
private void findDevice(boolean start) {
GBApplication.deviceService().onFindDevice(start);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
case R.id.action_debug:
Intent debugIntent = new Intent(this, DebugActivity.class);
startActivity(debugIntent);
return true;
case R.id.action_db_management:
Intent dbIntent = new Intent(this, DbManagementActivity.class);
startActivity(dbIntent);
return true;
case R.id.action_quit:
GBApplication.quit();
return true;
}
return super.onOptionsItemSelected(item);
}
private void launchDiscoveryActivity() {
startActivity(new Intent(this, DiscoveryActivity.class));
}
private void confirmDeleteDevice(final GBDevice gbDevice) {
new AlertDialog.Builder(this)
.setCancelable(true)
.setTitle(getString(R.string.controlcenter_delete_device_name, gbDevice.getName()))
.setMessage(R.string.controlcenter_delete_device_dialogmessage)
.setPositiveButton(R.string.Delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(gbDevice);
if (coordinator != null) {
coordinator.deleteDevice(selectedDevice);
}
DeviceHelper.getInstance().removeBond(selectedDevice);
} catch (Exception ex) {
GB.toast(ControlCenter.this, "Error deleting device: " + ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
} finally {
selectedDevice = null;
Intent refreshIntent = new Intent(DeviceManager.ACTION_REFRESH_DEVICELIST);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(refreshIntent);
}
}
})
.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onDestroy();
}
private void refreshPairedDevices() {
List<GBDevice> deviceList = deviceManager.getDevices();
GBDevice connectedDevice = null;
for (GBDevice device : deviceList) {
if (device.isConnected() || device.isConnecting()) {
connectedDevice = device;
break;
}
}
if (deviceList.isEmpty()) {
background.setVisibility(View.VISIBLE);
} else {
background.setVisibility(View.INVISIBLE);
}
if (connectedDevice != null) {
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(connectedDevice);
hintTextView.setText(coordinator.getTapString());
} else if (!deviceList.isEmpty()) {
hintTextView.setText(R.string.tap_a_device_to_connect);
}
mGBDeviceAdapter.notifyDataSetChanged();
}
@TargetApi(Build.VERSION_CODES.M)
private void checkAndRequestPermissions() {
List<String> wantedPermissions = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.BLUETOOTH);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.BLUETOOTH_ADMIN);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_CONTACTS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.CALL_PHONE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_PHONE_STATE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_SMS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.SEND_SMS);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_DENIED)
wantedPermissions.add(Manifest.permission.READ_CALENDAR);
if (ContextCompat.checkSelfPermission(this, "com.fsck.k9.permission.READ_MESSAGES") == PackageManager.PERMISSION_DENIED)
wantedPermissions.add("com.fsck.k9.permission.READ_MESSAGES");
if (!wantedPermissions.isEmpty())
ActivityCompat.requestPermissions(this, wantedPermissions.toArray(new String[wantedPermissions.size()]), 0);
}
}
| agpl-3.0 |
rapidminer/rapidminer-studio | src/main/java/com/rapidminer/operator/learner/igss/IGSSResult.java | 5248 | /**
* 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.learner.igss;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.ResultObjectAdapter;
import com.rapidminer.operator.learner.igss.hypothesis.Hypothesis;
import com.rapidminer.tools.Tools;
import java.util.Iterator;
import java.util.LinkedList;
/**
* This class stores all results found by the IGSS algorithm. It contains method to calculate the
* prior probabilities and the diversity in the results of the predictions.
*
* @author Dirk Dach
*/
public class IGSSResult extends ResultObjectAdapter {
private static final long serialVersionUID = -3021620651938759878L;
/** The list of results. */
private LinkedList<Result> results;
/** The default probability of the positive class */
private double[] priors;
public IGSSResult(ExampleSet eSet) {
this.priors = getPriors(eSet);
results = new LinkedList<Result>();
}
/** Adds a result. */
public void addResult(Result r) {
this.results.addLast(r);
}
/** Returns a list of all stored results. */
public LinkedList<Result> getResults() {
return this.results;
}
/** Returns the default probability of the example set the object was constructed with. */
public double[] getPriors() {
return this.priors;
}
/** Returns the default probability of the given example set. */
public static double[] getPriors(ExampleSet exampleSet) {
Iterator<Example> reader = exampleSet.iterator();
double totalWeight = 0.0d;
double totalPositiveWeight = 0.0d;
while (reader.hasNext()) {
Example e = reader.next();
totalWeight += e.getWeight();
if ((int) e.getLabel() == Hypothesis.POSITIVE_CLASS) {
totalPositiveWeight += e.getWeight();
}
}
double[] result = new double[2];
result[Hypothesis.POSITIVE_CLASS] = totalPositiveWeight / totalWeight;
result[Hypothesis.NEGATIVE_CLASS] = 1.0d - result[Hypothesis.POSITIVE_CLASS];
return result;
}
/** Calculates the diversity in the predictions of the results for the given example set. */
public static double calculateDiversity(ExampleSet exampleSet, LinkedList<Result> theResults) {
Iterator<Example> reader = exampleSet.iterator();
int[][] predictionMatrix = new int[exampleSet.size()][2];
for (int i = 0; reader.hasNext(); i++) { // all examples
Example e = reader.next();
for (Result res : theResults) {// all results
Hypothesis hypo = res.getHypothesis(); // get hypothesis
if (hypo.applicable(e)) {
predictionMatrix[i][hypo.getPrediction()]++;
} else {
predictionMatrix[i][1 - hypo.getPrediction()]++;
}
}
}
double sum1 = 0.0d;
for (int i = 0; i < predictionMatrix.length; i++) {
if (predictionMatrix[i][0] != 0 && predictionMatrix[i][1] != 0) { // avoid Double.NaN
// for p0=0 or p1=0
double p0 = (double) predictionMatrix[i][0] / (double) theResults.size();
double p1 = (double) predictionMatrix[i][1] / (double) theResults.size();
sum1 = sum1 + ((-1) * p0 * log2(p0)) + ((-1) * p1 * log2(p1));
}
}
double result = sum1 / predictionMatrix.length;
return result;
}
/** Returns a String-representation of the results in this object. */
@Override
public String toString() {
LinkedList<Result> includedResultsForDiversityCalculation = new LinkedList<Result>();
StringBuffer result = new StringBuffer("(Rule, Utility)" + Tools.getLineSeparator());
Iterator<Result> it = this.results.iterator();
double cumulativeWeight = 0.0d;
for (int i = 1; it.hasNext(); i++) {
result.append(i + ") ");
Result r = it.next();
includedResultsForDiversityCalculation.addLast(r);
cumulativeWeight = cumulativeWeight + r.getTotalWeight();
result.append(r.getHypothesis().toString() + ", " + r.getUtility() + Tools.getLineSeparator());
}
result.append("total necessary example weight: " + cumulativeWeight + Tools.getLineSeparator());
result.append("a priori probability: " + this.priors[Hypothesis.POSITIVE_CLASS] + Tools.getLineSeparator());
return result.toString();
}
/** Returns the logarithm to base 2. */
public static double log2(double arg) {
return Math.log(arg) / Math.log(2);
}
public String getExtension() {
return "gss";
}
public String getFileDescription() {
return "IGSS results";
}
}
| agpl-3.0 |
ging/isabel | components/gateway/GAPI/src/isabel/gw/isabel_client/simulator2/Client.java | 4419 | /*
* ISABEL: A group collaboration tool for the Internet
* Copyright (C) 2009 Agora System S.A.
*
* This file is part of Isabel.
*
* Isabel is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Isabel 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
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with Isabel. If not, see <http://www.gnu.org/licenses/>.
*/
package isabel.gw.isabel_client.simulator2;
import isabel.gw.FlowInfo;
import isabel.gw.IsabelClient;
import isabel.gw.MemberInfo;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class Client {
/**
* Logs
*/
private Logger mylogger;
/**
* The IsabelClient object which connect with the isabel session.
*/
IsabelClient ic;
/**
* Widget where traces are displayed.
*/
private JTextArea traces;
/**
* Scroll panel to used with traces.
*/
JScrollPane jsp;
/**
* Constructor
*/
Client(String nickname, String addr, String payloads) {
mylogger = Logger.getLogger("isabel.gw.isabel_client.simulato2.Client");
mylogger.info("Created the " + nickname + " client.");
makeGUI(nickname);
Thread.yield();
ic = IsabelClient.create();
trace("IsabelClient Created");
Vector<FlowInfo> flowList = new Vector<FlowInfo>();
StringTokenizer st = new StringTokenizer(payloads);
while (st.hasMoreTokens()) {
String spt = st.nextToken();
try {
int pt = Integer.parseInt(spt);
FlowInfo fi = new FlowInfo(pt, 10, 20, -1);
flowList.add(fi);
} catch (NumberFormatException nfe) {
System.err.println("Invalid payload type: " + spt);
}
}
MemberInfo mi = new MemberInfo(0, nickname, addr, flowList);
trace("Calling IsabelClient.connect(" + nickname + "," + addr + "," + flowList
+ ")");
ic.connect(mi);
}
/**
* Disconnect
*/
void disconnect() {
trace("Calling IsabelClient.disconnect()");
ic.disconnect();
}
/**
* Create the gui.
*/
void makeGUI(String title) {
JFrame jf = new JFrame("Client " + title);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Title
JLabel jl = new JLabel("<html><font size=+1>Client "+title+"</font>",
SwingConstants.CENTER);
jf.getContentPane().add(BorderLayout.NORTH, jl);
// Traces:
traces = new JTextArea();
jsp = new JScrollPane(traces);
jsp.setPreferredSize(new Dimension(320, 200));
jf.getContentPane().add(BorderLayout.CENTER, jsp);
// Bottom panel
JPanel jpb = new JPanel();
jpb.setLayout(new FlowLayout());
jf.getContentPane().add(BorderLayout.SOUTH, jpb);
// Disconnect:
JButton jdiscc = new JButton("Disconnect");
jdiscc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
disconnect();
}
});
jpb.add(jdiscc);
// Question:
JButton jques = new JButton("Question");
jques.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
trace("Calling IsabelClient.question()");
ic.question();
}
});
jpb.add(jques);
// Mute:
JButton jmute = new JButton("Mute");
jmute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
trace("Calling IsabelClient.setParameter(Audio_Capture,FALSE)");
ic.setParameter("Audio_Capture",new Boolean(false));
}
});
jpb.add(jmute);
// Make visible:
jf.pack();
jf.setVisible(true);
}
/**
* Write a new trace
*/
void trace(String msg) {
traces.append(msg + "\n");
JScrollBar jsb = jsp.getVerticalScrollBar();
jsb.setValue(jsb.getMaximum());
Thread.yield();
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/studio/concurrency/internal/ExecutionExceptionHandling.java | 4890 | /**
* 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.studio.concurrency.internal;
import java.util.List;
import java.util.concurrent.ExecutionException;
import com.rapidminer.Process;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.PortUserError;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.Port;
/**
* Helper class for exception handling when using {@link ConcurrencyExecutionService}.
* <p>
* Note that this part of the API is only temporary and might be removed in future versions again.
* </p>
*
* @author Sebastian Land
* @since 7.4
* @see ConcurrencyExecutionServiceProvider Provider to get the concurrency execution service
*/
public enum ExecutionExceptionHandling {
/** the singleton instance */
INSTANCE;
/**
* Tries to get the underlying cause of an {@link ExecutionException} which occurred while using
* {@link ConcurrencyExecutionServiceProvider}.
*
* @param e
* the exception which occurred during execution via
* {@link ConcurrencyExecutionService} methods.
* @param process
* the process in which the exception occurred
* @return the {@link UserError} or {@link OperatorException} that caused the execution
* exception.
* @throws OperatorException
* if the execution exception cannot be processed.
* @throws RuntimeException
* if the cause of the exception was a runtime exception
* @throws Error
* if the cause of the exception was an error
*/
public OperatorException processExecutionException(ExecutionException e, Process process)
throws OperatorException, RuntimeException, Error {
// unpack stacked execution exceptions
Throwable cause = e.getCause();
while (cause != null && cause != cause.getCause() && cause instanceof ExecutionException) {
cause = cause.getCause();
}
if (cause != null) {
// unpack runtime exceptions if necessary
Throwable innerCause = cause;
while (innerCause != null && innerCause != innerCause.getCause() && innerCause instanceof RuntimeException) {
// we'll assume the cause is the actual nested exception
innerCause = innerCause.getCause();
}
// if the inner cause is an instance of an operator exception
// we'll handle this exception as root cause
if (innerCause instanceof OperatorException) {
cause = innerCause;
}
// try to re-map the operator and port to the original process
if (cause instanceof UserError) {
UserError error = (UserError) cause;
Operator sourceOperator = error.getOperator();
if (process != null && sourceOperator != null) {
error.setOperator(process.getOperator(sourceOperator.getName()));
}
if (sourceOperator != null && cause instanceof PortUserError) {
PortUserError portError = (PortUserError) error;
List<InputPort> inputPorts = sourceOperator.getInputPorts().getAllPorts();
Port errorPort = portError.getPort();
boolean portFound = false;
for (int i = 0; i < inputPorts.size(); i++) {
if (inputPorts.get(i).equals(errorPort)) {
portError.setPort(error.getOperator().getInputPorts().getAllPorts().get(i));
portFound = true;
break;
}
}
if (!portFound) {
List<OutputPort> outputPorts = sourceOperator.getOutputPorts().getAllPorts();
for (int i = 0; i < outputPorts.size(); i++) {
if (outputPorts.get(i).equals(errorPort)) {
portError.setPort(error.getOperator().getOutputPorts().getAllPorts().get(i));
break;
}
}
}
}
return error;
} else if (cause instanceof OperatorException) {
return (OperatorException) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
}
return new OperatorException("There seems to be an unknown problem", cause);
}
}
| agpl-3.0 |
clintonhealthaccess/lmis-moz-mobile | app/src/main/java/org/openlmis/core/persistence/migrations/AddServiceItemTable.java | 534 | package org.openlmis.core.persistence.migrations;
import org.openlmis.core.persistence.Migration;
public class AddServiceItemTable extends Migration {
@Override
public void up() {
execSQL("create table `service_items` "
+ "(`formItem_id` BIGINT , "
+ "`service_id` BIGINT,"
+ "`amount` BIGINT,"
+ "`id` INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "`createdAt` VARCHAR NOT NULL, "
+ "`updatedAt` VARCHAR NOT NULL)");
}
}
| agpl-3.0 |
akuz/readrz-public | rz-www-search/src/main/java/com/readrz/www/builders/BuildPeriodsMenu.java | 1503 | package com.readrz.www.builders;
import com.readrz.data.Period;
import com.readrz.www.RzPar;
import com.readrz.www.UrlBuilder;
import com.readrz.www.objects.WwwMenu;
import com.readrz.www.objects.WwwMenuItem;
public final class BuildPeriodsMenu {
public static final WwwMenu createLoading(Period period, Period topPeriod) {
WwwMenu periodsMenu = new WwwMenu(period.getName(), null);
if (period.equals(topPeriod) == false) {
periodsMenu.setIsActive(true);
}
return periodsMenu;
}
public static final WwwMenu createWithAvailablePeriods(
UrlBuilder baseUrl, String setParameterName,
Period selectedPeriod, Period defaultPeriod) {
WwwMenu periodsMenu = new WwwMenu(selectedPeriod.getName(), null);
if (selectedPeriod.equals(defaultPeriod) == false) {
periodsMenu.setIsActive(true);
}
for (int i=0; i<RzPar.availableGroupingPeriods.size(); i++) {
Period availablePeriod = RzPar.availableGroupingPeriods.get(i);
UrlBuilder periodUrl = baseUrl.clone();
periodUrl.remove(RzPar.parPeriod);
periodUrl.update(setParameterName, availablePeriod.getAbbr());
WwwMenuItem periodMenuItem = new WwwMenuItem(
availablePeriod.getName(),
null,
periodUrl);
if (availablePeriod.equals(defaultPeriod) == false) {
periodMenuItem.setTurnsMenuOn(true);
}
periodsMenu.addItem(periodMenuItem);
if (availablePeriod.equals(selectedPeriod)) {
periodMenuItem.setIsActive(true);
}
}
return periodsMenu;
}
}
| agpl-3.0 |
domkowald/tagrecommender | src/processing/MalletCalculator.java | 16684 | /*
TagRecommender:
A framework to implement and evaluate algorithms for the recommendation
of tags.
Copyright (C) 2013 Dominik Kowald
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 processing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import com.google.common.base.Stopwatch;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
import common.DoubleMapComparator;
import common.UserData;
import common.Utilities;
import cc.mallet.pipe.Array2FeatureVector;
import cc.mallet.pipe.CharSequence2TokenSequence;
import cc.mallet.pipe.CharSequenceArray2TokenSequence;
import cc.mallet.pipe.CharSequenceLowercase;
import cc.mallet.pipe.Pipe;
import cc.mallet.pipe.PrintInputAndTarget;
import cc.mallet.pipe.SerialPipes;
import cc.mallet.pipe.StringList2FeatureSequence;
import cc.mallet.pipe.TokenSequence2FeatureSequence;
import cc.mallet.pipe.TokenSequenceLowercase;
import cc.mallet.topics.ParallelTopicModel;
import cc.mallet.types.Alphabet;
import cc.mallet.types.FeatureSequence;
import cc.mallet.types.IDSorter;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.TokenSequence;
import file.PredictionFileWriter;
import file.BookmarkReader;
import file.BookmarkSplitter;
public class MalletCalculator {
private final static int MAX_RECOMMENDATIONS = 10;
private final static int MAX_TERMS = 100;
private final static int NUM_THREADS = 10;
private final static int NUM_ITERATIONS = 2000;
private final static double ALPHA = 0.01;
private final static double BETA = 0.01;
private final static double TOPIC_THRESHOLD = 0.001;
private int numTopics;
private List<Map<Integer, Integer>> maps;
private InstanceList instances;
private List<Map<Integer, Double>> docList;
private List<Map<Integer, Double>> topicList;
public MalletCalculator(List<Map<Integer, Integer>> maps, int numTopics) {
this.numTopics = numTopics;
this.maps = maps;
initializeDataStructures();
}
private void initializeDataStructures() {
this.instances = new InstanceList(new StringList2FeatureSequence());
for (Map<Integer, Integer> map : this.maps) {
List<String> tags = new ArrayList<String>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
for (int i = 0; i < entry.getValue(); i++) {
tags.add(entry.getKey().toString());
}
}
Instance inst = new Instance(tags, null, null, null);
inst.setData(tags);
this.instances.addThruPipe(inst);
}
}
private List<Map<Integer, Double>> getMaxTopicsByDocs(ParallelTopicModel LDA, int maxTopicsPerDoc) {
List<Map<Integer, Double>> docList = new ArrayList<Map<Integer, Double>>();
int numDocs = this.instances.size();
for (int doc = 0; doc < numDocs; ++doc) {
Map<Integer, Double> topicList = new LinkedHashMap<Integer, Double>();
double[] topicProbs = LDA.getTopicProbabilities(doc);
//double probSum = 0.0;
for (int topic = 0; topic < topicProbs.length && topic < maxTopicsPerDoc; topic++) {
//if (topicProbs[topic] > 0.01) { // TODO
topicList.put(topic, topicProbs[topic]);
//probSum += topicProbs[topic];
//}
}
//System.out.println("Topic Sum: " + probSum);
Map<Integer, Double> sortedTopicList = new TreeMap<Integer, Double>(new DoubleMapComparator(topicList));
sortedTopicList.putAll(topicList);
docList.add(sortedTopicList);
}
return docList;
}
private List<Map<Integer, Double>> getMaxTermsByTopics(ParallelTopicModel LDA, int limit) {
Alphabet alphabet = LDA.getAlphabet();
List<Map<Integer, Double>> topicList = new ArrayList<Map<Integer, Double>>();
int numTopics = LDA.getNumTopics();
List<TreeSet<IDSorter>> sortedWords = LDA.getSortedWords();
for (int topic = 0; topic < numTopics; ++topic) {
Map<Integer, Double> termList = new LinkedHashMap<Integer, Double>();
TreeSet<IDSorter> topicWords = sortedWords.get(topic);
//int i = 0;
double weightSum = 0.0;
for (IDSorter entry : topicWords) {
if (entry.getWeight() > 0.0) { // TODO
//if (i++ < limit) { // TODO
int tag = Integer.parseInt(alphabet.lookupObject(entry.getID()).toString());
termList.put(tag, entry.getWeight());
weightSum += entry.getWeight();
//} else {
// break;
//}
}
}
// relative values
//double relSum = 0.0;
for (Map.Entry<Integer, Double> entry : termList.entrySet()) {
//relSum += (entry.getValue() / weightSum);
entry.setValue(entry.getValue() / weightSum);
}
//System.out.println("RelSum: " + relSum);
topicList.add(termList);
}
return topicList;
}
public void predictValuesProbs() {
ParallelTopicModel LDA = new ParallelTopicModel(this.numTopics, ALPHA * this.numTopics, BETA); // TODO
LDA.addInstances(this.instances);
LDA.setNumThreads(1);
LDA.setNumIterations(NUM_ITERATIONS);
LDA.setRandomSeed(43);
try {
LDA.estimate();
} catch (Exception e) {
e.printStackTrace();
}
this.docList = getMaxTopicsByDocs(LDA, this.numTopics);
System.out.println("Fetched Doc-List");
this.topicList = getMaxTermsByTopics(LDA, MAX_TERMS);
System.out.println("Fetched Topic-List");
}
public Map<Integer, Double> getValueProbsForID(int id, boolean topicCreation) {
Map<Integer, Double> terms = null;
if (id < this.docList.size()) {
terms = new LinkedHashMap<Integer, Double>();
Map<Integer, Double> docVals = this.docList.get(id);
for (Map.Entry<Integer, Double> topic : docVals.entrySet()) { // look at each assigned topic
Set<Entry<Integer, Double>> entrySet = this.topicList.get(topic.getKey()).entrySet();
double topicProb = topic.getValue();
for (Map.Entry<Integer, Double> entry : entrySet) { // and its terms
if (topicCreation) {
if (topicProb > TOPIC_THRESHOLD) {
terms.put(entry.getKey(), topicProb);
break; // only use first tag as topic-name with the topic probability
}
} else {
double wordProb = entry.getValue();
Double val = terms.get(entry.getKey());
terms.put(entry.getKey(), val == null ? wordProb * topicProb : val + wordProb * topicProb);
}
}
}
}
return terms;
}
// Statics -------------------------------------------------------------------------------------------------------------------------
private static List<Double> getDenoms(List<Map<Integer, Double>> maps) {
List<Double> denoms = new ArrayList<Double>();
for (Map<Integer, Double> map : maps) {
double denom = 0.0;
for (Map.Entry<Integer, Double> entry : map.entrySet()) {
denom += Math.exp(entry.getValue());
}
denoms.add(denom);
}
return denoms;
}
private static Map<Integer, Double> getRankedTagList(BookmarkReader reader, Map<Integer, Double> userMap, double userDenomVal,
Map<Integer, Double> resMap, double resDenomVal, boolean sorting, boolean smoothing, boolean topicCreation) {
Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>();
if (userMap != null) {
for (Map.Entry<Integer, Double> entry : userMap.entrySet()) {
resultMap.put(entry.getKey(), entry.getValue().doubleValue());
}
}
if (resMap != null) {
for (Map.Entry<Integer, Double> entry : resMap.entrySet()) {
double resVal = entry.getValue().doubleValue();
Double val = resultMap.get(entry.getKey());
resultMap.put(entry.getKey(), val == null ? resVal : val.doubleValue() + resVal);
}
}
if (sorting) {
Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap));
sortedResultMap.putAll(resultMap);
Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(MAX_RECOMMENDATIONS);
int i = 0;
for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) {
if (i++ < MAX_RECOMMENDATIONS) {
returnMap.put(entry.getKey(), entry.getValue());
} else {
break;
}
}
return returnMap;
}
return resultMap;
/*
double size = (double)reader.getTagAssignmentsCount();
double tagSize = (double)reader.getTags().size();
Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>();
for (int i = 0; i < tagSize; i++) {
double pt = (double)reader.getTagCounts().get(i) / size;
Double userVal = 0.0;
if (userMap != null && userMap.containsKey(i)) {
userVal = userMap.get(i);//Math.exp(userMap.get(i)) / userDenomVal;
}
Double resVal = 0.0;
if (resMap != null && resMap.containsKey(i)) {
resVal = resMap.get(i);//Math.exp(resMap.get(i)) / resDenomVal;
}
if (userVal > 0.0 || resVal > 0.0) { // TODO
if (smoothing) {
resultMap.put(i, Utilities.getSmoothedTagValue(userVal, userDenomVal, resVal, resDenomVal, pt));
} else {
resultMap.put(i, userVal + resVal);
}
}
}
if (sorting) {
Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap));
sortedResultMap.putAll(resultMap);
if (topicCreation) {
return sortedResultMap;
} else { // otherwise filter
Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(MAX_RECOMMENDATIONS);
int i = 0;
for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) {
if (i++ < MAX_RECOMMENDATIONS) {
returnMap.put(entry.getKey(), entry.getValue());
} else {
break;
}
}
return returnMap;
}
}
return resultMap;
*/
}
private static String timeString;
public static List<Map<Integer, Double>> startLdaCreation(BookmarkReader reader, int sampleSize, boolean sorting, int numTopics, boolean userBased, boolean resBased, boolean topicCreation, boolean smoothing) {
timeString = "";
int size = reader.getUserLines().size();
int trainSize = size - sampleSize;
Stopwatch timer = new Stopwatch();
timer.start();
MalletCalculator userCalc = null;
List<Map<Integer, Integer>> userMaps = null;
//List<Double> userDenoms = null;
if (userBased) {
userMaps = Utilities.getUserMaps(reader.getUserLines().subList(0, trainSize));
userCalc = new MalletCalculator(userMaps, numTopics);
userCalc.predictValuesProbs();
//userDenoms = getDenoms(userPredictionValues);
System.out.println("User-Training finished");
}
MalletCalculator resCalc = null;
List<Map<Integer, Integer>> resMaps = null;
//List<Double> resDenoms = null;
if (resBased) {
resMaps = Utilities.getResMaps(reader.getUserLines().subList(0, trainSize));
resCalc = new MalletCalculator(resMaps, numTopics);
resCalc.predictValuesProbs();
//resDenoms = getDenoms(resPredictionValues);
System.out.println("Res-Training finished");
}
List<Map<Integer, Double>> results = new ArrayList<Map<Integer, Double>>();
if (trainSize == size) {
trainSize = 0;
}
timer.stop();
long trainingTime = timer.elapsed(TimeUnit.MILLISECONDS);
timer = new Stopwatch();
timer.start();
for (int i = trainSize; i < size; i++) { // the test set
UserData data = reader.getUserLines().get(i);
int userID = data.getUserID();
int resID = data.getWikiID();
//Map<Integer, Integer> userMap = null;
//if (userBased && userMaps != null && userID < userMaps.size()) {
// userMap = userMaps.get(userID);
//}
//Map<Integer, Integer> resMap = null;
//if (resBased && resMaps != null && resID < resMaps.size()) {
// resMap = resMaps.get(resID);
//}
double userTagCount = 0.0;//Utilities.getMapCount(userMap);
double resTagCount = 0.0;//Utilities.getMapCount(resMap);
/*
double userDenomVal = 0.0;
if (userDenoms != null && userID < userDenoms.size()) {
userDenomVal = userDenoms.get(userID);
}
double resDenomVal = 0.0;
if (resDenoms != null && resID < resDenoms.size()) {
resDenomVal = resDenoms.get(resID);
}
*/
Map<Integer, Double> userPredMap = null;
if (userCalc != null) {
userPredMap = userCalc.getValueProbsForID(userID, topicCreation);
}
Map<Integer, Double> resPredMap = null;
if (resCalc != null) {
resPredMap = resCalc.getValueProbsForID(resID, topicCreation);
}
Map<Integer, Double> map = getRankedTagList(reader, userPredMap, userTagCount, resPredMap, resTagCount, sorting, smoothing, topicCreation);
results.add(map);
}
timer.stop();
long testTime = timer.elapsed(TimeUnit.MILLISECONDS);
timeString += ("Full training time: " + trainingTime + "\n");
timeString += ("Full test time: " + testTime + "\n");
timeString += ("Average test time: " + testTime / (double)sampleSize) + "\n";
timeString += ("Total time: " + (trainingTime + testTime) + "\n");
return results;
}
public static void predictSample(String filename, int trainSize, int sampleSize, int numTopics, boolean userBased, boolean resBased) {
BookmarkReader reader = new BookmarkReader(trainSize, false);
reader.readFile(filename);
List<Map<Integer, Double>> ldaValues = startLdaCreation(reader, sampleSize, true, numTopics, userBased, resBased, false, true);
List<int[]> predictionValues = new ArrayList<int[]>();
for (int i = 0; i < ldaValues.size(); i++) {
Map<Integer, Double> ldaVal = ldaValues.get(i);
predictionValues.add(Ints.toArray(ldaVal.keySet()));
}
reader.setUserLines(reader.getUserLines().subList(trainSize, reader.getUserLines().size()));
PredictionFileWriter writer = new PredictionFileWriter(reader, predictionValues);
writer.writeFile(filename + "_lda_" + numTopics);
Utilities.writeStringToFile("./data/metrics/" + filename + "_lda_" + numTopics + "_TIME.txt", timeString);
}
public static void createSample(String filename, int sampleSize, short numTopics, boolean userBased, boolean resBased) {
String outputFile = new String(filename) + "_lda_" + numTopics;
filename += "_res";
outputFile += "_res";
BookmarkReader reader = new BookmarkReader(0, false);
reader.readFile(filename);
int trainSize = reader.getUserLines().size() - sampleSize;
List<Map<Integer, Double>> ldaValues = startLdaCreation(reader, 0, true, numTopics, userBased, resBased, true, true);
List<int[]> predictionValues = new ArrayList<int[]>();
// TODO: make argument for the probValues
List<double[]> probValues = new ArrayList<double[]>();
for (int i = 0; i < ldaValues.size(); i++) {
Map<Integer, Double> ldaVal = ldaValues.get(i);
predictionValues.add(Ints.toArray(ldaVal.keySet()));
probValues.add(Doubles.toArray(ldaVal.values()));
/*
int[] values = new int[MAX_RECOMMENDATIONS];
int j = 0;
for (Integer val : ldaVal.keySet()) {
if (j < MAX_RECOMMENDATIONS) {
values[j++] = val;
} else {
break;
}
}
predictionValues.add(values);
*/
}
List<UserData> trainUserSample = reader.getUserLines().subList(0, trainSize);
List<UserData> testUserSample = reader.getUserLines().subList(trainSize, trainSize + sampleSize);
List<UserData> userSample = reader.getUserLines().subList(0, trainSize + sampleSize);
BookmarkSplitter.writeWikiSample(reader, trainUserSample, outputFile + "_train", predictionValues);
BookmarkSplitter.writeWikiSample(reader, testUserSample, outputFile + "_test", predictionValues);
BookmarkSplitter.writeWikiSample(reader, userSample, outputFile, predictionValues);
}
}
| agpl-3.0 |
SilverDav/Silverpeas-Core | core-services/workflow/src/main/java/org/silverpeas/core/workflow/api/ProcessModelManager.java | 4463 | /*
* 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.workflow.api;
import org.silverpeas.core.workflow.api.model.ProcessModel;
import java.util.List;
/**
* The workflow engine services related to process model management.
*/
public interface ProcessModelManager {
/**
* List all the ProcessModels that are stored in the process model directory Retrieves all the
* files in the directory tree below the process model directory.
* @return list of strings containing ProcesModel XML descriptor filenames with relative paths.
* @throws WorkflowException when something goes wrong
*/
List<String> listProcessModels() throws WorkflowException;
/**
* Get a ProcessModel from its modelId. Retrieves the xml descriptor filename from the model Id
* and load abstract process model information in ProcessModel object
* @param modelId model id
* @return ProcessModel object
* @throws WorkflowException when something goes wrong
*/
ProcessModel getProcessModel(String modelId) throws WorkflowException;
/**
* Create a ProcessModel from xml descriptor filename. Generate an id for this model and load
* abstract process model information in ProcessModel object
* @param fileName xml descriptor filename.
* @param peasId Id of processManager instance (peas).
* @return ProcessModel object
* @throws WorkflowException when something goes wrong
*/
ProcessModel createProcessModel(String fileName, String peasId)
throws WorkflowException;
/**
* Create a new ProcessModel descriptor that is not yet saved in a XML file.
* @return ProcessModel object
* @throws WorkflowException when something goes wrong
*/
ProcessModel createProcessModelDescriptor() throws WorkflowException;
/**
* Delete a ProcessModel with given model id
* @param instanceId component instance identifier
* @throws WorkflowException when something goes wrong
*/
void deleteProcessModel(String instanceId) throws WorkflowException;
/**
* Delete a ProcessModelDescriptor XML with given path
* @param strProcessModelFileName the relative path and file name of the process file
* @throws WorkflowException when something goes wrong or the file cannot be found
*/
void deleteProcessModelDescriptor(String strProcessModelFileName)
throws WorkflowException;
/**
* Get the directory where are stored the models
*/
String getProcessModelDir();
/**
* load a process model definition from xml file to java objects
* @param processFileName the xml file name that contains process model definition
* @return a ProcessModel object
* @throws WorkflowException when something goes wrong or the file cannot be found
*/
ProcessModel loadProcessModel(String processFileName) throws WorkflowException;
/**
* Get all the "process manager" peas ids
*/
String[] getAllPeasIds() throws WorkflowException;
/**
* Saves a process model definition from java objects to an XML file
* @param processFileName the xml file name that contains process model definition
* @param process A processModel object to be saved
* @throws WorkflowException when something goes wrong
*/
void saveProcessModel(ProcessModel process, String processFileName)
throws WorkflowException;
void clearProcessModelCache() throws WorkflowException;
} | agpl-3.0 |
pythoncat1024/SwipeItemLayout | SwipeItemLayout.java | 16742 |
import android.content.Context;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.python.cat.animatorbutton.BuildConfig;
import java.util.ArrayList;
import java.util.List;
import static com.python.cat.animatebutton.view.SwipeItemLayout.State.Center;
import static com.python.cat.animatebutton.view.SwipeItemLayout.State.Right;
/**
* packageName: com.python.cat.animatebutton.view
* Created on 2017/5/6.
* 右边有菜单的item
*
* @author cat
*/
public class SwipeItemLayout extends FrameLayout {
@SuppressWarnings("FieldCanBeLocal")
private int mHeight;
private int mWidth;
private ViewDragHelper mDragHelper;
private List<ItemPos> mItemSet;
private OnOpenStatedListener mViewStateListener;
private DragCallback mDragCallBack;
public SwipeItemLayout(Context context) {
this(context, null);
}
public SwipeItemLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeItemLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// setOrientation(HORIZONTAL); // 验证说明ok
initDragHelper();
}
private void initDragHelper() {
mDragCallBack = new DragCallback();
mDragHelper = ViewDragHelper.create(this, 1, mDragCallBack);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// LogUtils.w("on measure....");
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// LogUtils.w("on finish inflate....");
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.mWidth = w;
this.mHeight = h;
int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
// LogUtils.i("touchSlop = %d", touchSlop);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// super.onLayout(changed, left, top, right, bottom);
layoutChildren(0, 0);
// LogUtils.w("on layout.........");
}
private void layoutChildren(int dx, int dy) {
mItemSet = new ArrayList<>();
mItemSet.clear();
int childCount = getChildCount();
int cl, ct, cr, cb;
int tempX = 0;
boolean isFirstView;
for (int i = 0; i < childCount; i++) {
isFirstView = i == 0;
View child = getChildAt(i);
MarginLayoutParams params = getChildLayoutParams(child);
cl = tempX + params.leftMargin + dx;
ct = params.topMargin + get().getPaddingTop() + dy;
if (isFirstView) {
// first view
cl += get().getPaddingLeft();
}
cr = cl + getChildWidth(child);
cb = ct + getChildHeight(child);
tempX += cr + params.rightMargin;
//noinspection unused
int bX = getChildWidth(child)
+ params.leftMargin + params.rightMargin
+ getPaddingLeft() + getPaddingRight();
// 当子View完全填充时, ax == bx
// LogUtils.w("index ---ax= " + aX + " , bx=" + bX);
// LogUtils.w("index = %d, left= %d, top= %d, right=%d, bottom=%d", cl, ct, cr, cb);
child.layout(cl, ct, cr, cb);
ItemPos it = new ItemPos(i, cl, ct, cr, cb);
mItemSet.add(it);
}
}
private class ItemPos {
int index;
int left;
int top;
int right;
int bottom;
ItemPos(int index, int left, int top, int right, int bottom) {
this.index = index;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return mDragHelper.shouldInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
private class DragCallback extends ViewDragHelper.Callback {
State mCurrentOpen = Center; // default is center
ScrollState scrollState = new ScrollState();
@IntRange(from = 0, to = 2)
private int mDragState = ViewDragHelper.STATE_IDLE; // default is idle
class ScrollState {
static final int LEFT = -1;
static final int RIGHT = 1;
int scrollDirection; // Left or Right
@Override
public String toString() {
return "ScrollState{" +
"scrollDirection=" + scrollDirection +
'}';
}
}
@Override
public int getViewHorizontalDragRange(View child) {
int dx = getMeasuredWidth() - child.getMeasuredWidth();
// LogUtils.w("dx = " + dx);
return dx;
}
@Override
public boolean tryCaptureView(View child, int pointerId) {
return true;
}
/**
* @param left 父容器的左侧,到child的左侧的距离
*/
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
// LogUtils.w("clampH : " + left + " , " + dx + " , " + child);
getParent().requestDisallowInterceptTouchEvent(true); // 不给外层布局上下滑动
View childAt1 = getChildAt(1);
// 滑动第一个view
if (child == getChildAt(0)) {
// left [getPaddingLeft() + getChildLayoutParams(child).leftMargin,
int maxL = getPaddingLeft() + getChildLayoutParams(child).leftMargin;
if (left > maxL) {
// 向右 ok
left = maxL;
} else {
// 向左 ok
int min = mWidth - getChildWidthWithMargin(child) - getChildWidthWithMargin(childAt1);
if (left < min) {
left = min;
}
}
}
// 滑动第二个view
else if (child == getChildAt(1)) {
int max = mItemSet.get(1).left;
int min = mWidth - getChildWidthWithMargin(child) - getPaddingRight();
if (left > max) {
// 向右 ok
left = max;
} else if (left < min) {
// 向左 ok
left = min;
}
}
if (dx > 0) {
scrollState.scrollDirection = ScrollState.RIGHT;
} else if (dx < 0) {
scrollState.scrollDirection = ScrollState.LEFT;
}
return left;
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
// LogUtils.w("onViewPositionChanged : " + left + " , " + top + " , " + dx + " , " + dy);
View childAt0 = getChildAt(0);
View childAt1 = getChildAt(1);
if (changedView == childAt0) {
ItemPos it = mItemSet.get(1);
int moveX = left - mItemSet.get(0).left;
childAt1.layout(it.left + moveX, it.top, it.right + moveX, it.bottom + dy);
} else if (changedView == childAt1) {
ItemPos it = mItemSet.get(0);
int moveX = left - mItemSet.get(1).left;
childAt0.layout(it.left + moveX, it.top, it.right + moveX, it.bottom + dy);
}
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
// 继续保持margin与padding
return getPaddingTop() + getChildLayoutParams(child).topMargin;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
this.mDragState = state;
// LogUtils.e("ViewDragState == " + state);
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
View childAt0 = getChildAt(0);
View childAt1 = getChildAt(1);
int a = getPaddingLeft();
int d = getChildLayoutParams(childAt0).leftMargin;
int L = getChildAt(0).getLeft();
int k = getChildWidth(childAt1);
if (BuildConfig.DEBUG) {
int b = getWidth();
int c = getPaddingRight();
int e = getChildLayoutParams(childAt0).rightMargin;
int f = getChildWidthWithMargin(childAt0);
int g = getChildWidth(childAt0);
int h = getChildLayoutParams(childAt1).leftMargin;
int i = getChildLayoutParams(childAt1).rightMargin;
int j = getChildWidthWithMargin(childAt1);
// LogUtils.e("release: " + a + " , " + b + " , "
// + c + " , " + d + " , " + e + " , "
// + f + " , " + g + " , " + h + " , "
// + i + " , " + j + " , " + k + " , "
// + L);
// // L == -34 , d==e==26 , a==c==80 , ---> k/2 == 140
// LogUtils.e("L-d-a = " + (L - d - a) + " k/2 = " + k / 2); // 中点真难找啊..
}
State temp = this.mCurrentOpen;
// LogUtils.e(scrollState);
int left = L - d - a;
int change; // 释放临界值:不要放中间,放1/4处就好了
int absLeft = Math.abs(left);
if (scrollState.scrollDirection == ScrollState.LEFT) {
// 左滑
change = k / 4;
if (absLeft > change) {
// 左滑到底
openRight(childAt0, childAt1);
} else {
// 右滑到底
openCenter(childAt0, childAt1);
}
// LogUtils.e("left = " + left + " absLeft = " + absLeft + " change = " + change);
} else if (scrollState.scrollDirection == ScrollState.RIGHT) {
// 右滑
change = k * 3 / 4;
if (absLeft > change) {
// 左滑到底
openRight(childAt0, childAt1);
this.mCurrentOpen = Right;
} else {
// 右滑到底
openCenter(childAt0, childAt1);
this.mCurrentOpen = Center;
}
// LogUtils.e("left = " + left + " absLeft = " + absLeft + " change = " + change);
}
// LogUtils.e("xv = " + xvel + " , yv = " + yvel);
// xvel<0 -->右滑 >0 左滑 | 缓慢滑就 == 0
// LogUtils.e("temp = " + temp + " , state = " + mCurrentOpen);
if (mViewStateListener != null) {
mViewStateListener.onViewOpen(temp != this.mCurrentOpen, this.mCurrentOpen);
}
invalidate();
}
// ####################################
private void openCenter(View childAt0, View childAt1) {
mDragHelper.smoothSlideViewTo(childAt0, mItemSet.get(0).left, mItemSet.get(0).top);
mDragHelper.smoothSlideViewTo(childAt1, mItemSet.get(1).left, mItemSet.get(1).top);
this.mCurrentOpen = Center;
}
private void openRight(View childAt0, View childAt1) {
mDragHelper.smoothSlideViewTo(childAt0,
mItemSet.get(0).left - getChildWidthWithMargin(childAt1),
mItemSet.get(0).top);
mDragHelper.smoothSlideViewTo(childAt1,
mItemSet.get(1).left - getChildWidthWithMargin(childAt1),
mItemSet.get(1).top);
this.mCurrentOpen = Right;
}
}
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
public void setOnViewStatedChangedListener(OnOpenStatedListener listener) {
this.mViewStateListener = listener;
}
public interface OnOpenStatedListener {
@SuppressWarnings("unused")
void onViewOpen(boolean changed, State state);
}
@SuppressWarnings("unused")
public enum State {
Left, Center, Right,
}
@SuppressWarnings("unused")
public State getOpenState() {
return mDragCallBack.mCurrentOpen;
}
@SuppressWarnings("unused")
public int getDragState() {
return mDragCallBack.mDragState;
}
public State openRight() {
mDragCallBack.openRight(getChildAt(0), getChildAt(1));
return mDragCallBack.mCurrentOpen;
}
public State openCenter() {
mDragCallBack.openCenter(getChildAt(0), getChildAt(1));
return mDragCallBack.mCurrentOpen;
}
@SuppressWarnings("unused")
public State changeState() {
switch (getOpenState()) {
case Center:
openRight();
break;
case Right:
openCenter();
break;
}
return mDragCallBack.mCurrentOpen;
}
// ######################---##########################
private MarginLayoutParams getChildLayoutParams(@NonNull View child) {
ViewGroup.LayoutParams pa = child.getLayoutParams();
if (pa instanceof MarginLayoutParams) {
return (MarginLayoutParams) pa;
} else {
throw new RuntimeException(pa == null ? null : pa.toString());
}
}
private int getChildWidth(@NonNull View child) {
return child.getMeasuredWidth();
}
private int getChildHeight(@NonNull View child) {
return child.getMeasuredHeight();
}
private int getChildWidthWithMargin(@NonNull View child) {
MarginLayoutParams params = getChildLayoutParams(child);
return getChildWidth(child) + params.leftMargin + params.rightMargin;
}
@SuppressWarnings("unused")
private int getChildHeightWithMargin(@NonNull View child) {
MarginLayoutParams params = getChildLayoutParams(child);
return getChildWidth(child) + params.topMargin + params.bottomMargin;
}
private ViewGroup get() {
return this;
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | lib-core/src/main/java/com/stratelia/silverpeas/genericPanel/PanelSearchToken.java | 2007 | /**
* 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/>.
*/
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent)
---*/
package com.stratelia.silverpeas.genericPanel;
abstract public class PanelSearchToken {
static public final int TYPE_UNKNOWN = -1;
static public final int TYPE_TEXT = 0;
static public final int TYPE_LINK = 1;
static public final int TYPE_EDIT = 2;
static public final int TYPE_COMBO = 3;
public boolean m_ReadOnly = false;
public int m_Type = TYPE_UNKNOWN;
public String m_Label = "";
public int m_Index = 0;
public String getHTMLDisplay() {
StringBuffer sb = new StringBuffer();
sb.append("<tr>\n<td nowrap><span class=\"txtlibform\">");
sb.append(m_Label);
sb.append(" : </span></td>\n<td nowrap>");
sb.append(getHTMLSpecific());
sb.append("\n</td>\n</tr>");
return sb.toString();
}
public String getHTMLSpecific() {
return "";
}
}
| agpl-3.0 |
paulmartel/voltdb | src/frontend/org/voltdb/utils/CallableNoThrow.java | 934 | /* This file is part of VoltDB.
* Copyright (C) 2008-2016 VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.utils;
/**
* Callable interface that doesn't throw an Exception. Saves installing the exception handler.
*
*/
public interface CallableNoThrow<T> {
public T call();
}
| agpl-3.0 |
medsob/Tanaguru | rules/accessiweb2.1/src/main/java/org/tanaguru/rules/accessiweb21/Aw21Rule01061.java | 1987 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* 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/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.accessiweb21;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.rules.accessiweb21.detection.AbstractTagDetectionPageRuleImplementation;
/**
* Implementation of the rule 1.6.1 of the referential Accessiweb 2.1.
* <br/>
* For more details about the implementation, refer to <a href="http://www.tanaguru.org/en/content/aw21-rule-1-6-1">the rule 1.6.1 design page.</a>
* @see <a href="http://www.braillenet.org/accessibilite/referentiel-aw21-en/index.php#test-1-6-1"> 1.6.1 rule specification</a>
*
* @author jkowalczyk
*/
public class Aw21Rule01061 extends AbstractTagDetectionPageRuleImplementation {
public static final String MESSAGE_CODE = "ManualCheckOnElements";
private static final String TAG_DETECTION_XPATH_EXPR ="//IMG[not(ancestor::A)]";
/**
* Default constructor
*/
public Aw21Rule01061 () {
super();
setMessageCode(MESSAGE_CODE);
setSelectionExpression(TAG_DETECTION_XPATH_EXPR);
setDetectedSolution(TestSolution.NEED_MORE_INFO);
setNotDetectedSolution(TestSolution.NOT_APPLICABLE);
setIsRemarkCreatedOnDetection(true);
}
} | agpl-3.0 |
RestComm/jss7 | cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/service/gprs/primitive/InitiatingEntity.java | 1854 | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* 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.service.gprs.primitive;
/**
*
InitiatingEntity ::= ENUMERATED { mobileStation (0), sgsn (1), hlr (2), ggsn (3) }
*
*
* @author sergey vetyutnev
*
*/
public enum InitiatingEntity {
mobileStation(0), sgsn(1), hlr(2), ggsn(3);
private int code;
private InitiatingEntity(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static InitiatingEntity getInstance(int code) {
switch (code) {
case 0:
return InitiatingEntity.mobileStation;
case 1:
return InitiatingEntity.sgsn;
case 2:
return InitiatingEntity.hlr;
case 3:
return InitiatingEntity.ggsn;
default:
return null;
}
}
}
| agpl-3.0 |
sturesy/client | src/src-main/sturesy/settings/websettings/NewLectureController.java | 5217 | /*
* StuReSy - Student Response System
* Copyright (C) 2012-2014 StuReSy-Team
*
* 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 sturesy.settings.websettings;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.Collection;
import javax.swing.JOptionPane;
import sturesy.core.Localize;
import sturesy.core.ui.MessageWindow;
import sturesy.items.LectureID;
import sturesy.util.Settings;
public class NewLectureController
{
private NewLectureUI _ui;
private Collection<LectureID> _lectureIDs;
private Settings _settings;
public NewLectureController(Collection<LectureID> lectureIds)
{
_settings = Settings.getInstance();
_ui = new NewLectureUI();
_lectureIDs = lectureIds;
registerListeners();
}
public void show(Component relativeToComponent)
{
_ui.show(relativeToComponent);
}
private void cancelAction()
{
closeWindow();
}
/**
* Closes this Dialog
*/
private void closeWindow()
{
WindowEvent wev = new WindowEvent(_ui.getDialog(), WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
}
/**
* Stores the Password in the Settings
*/
private void storePassword()
{
String password = new String(_ui.getPasswortTextFieldText());
String idtext = _ui.getIdTextFieldText();
String serveradress = _settings.getString(Settings.SERVERADDRESS);
LectureID toadd = new LectureID(idtext, password, serveradress);
LectureID duplicate = findDuplicateFor(toadd);
if (duplicate != null)
{
int result = JOptionPane.showConfirmDialog(_ui.getDialog(),
Localize.getString("message.websettings.duplicate", idtext),
Localize.getString("label.lecture.duplicate.id"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION)
{
_lectureIDs.remove(duplicate);
_lectureIDs.add(toadd);
}
}
else
{
_lectureIDs.add(toadd);
}
}
private LectureID findDuplicateFor(LectureID tofind)
{
for (LectureID id : _lectureIDs)
{
if (id.getLectureID().equals(tofind.getLectureID()) && id.getHost().equals(tofind.getHost()))
{
// LectureID == LectureID
// Host == Host
return id;
}
}
return null;
}
private void confirmAction()
{
char[] passwordTextFieldText = _ui.getPasswortTextFieldText();
String password = new String(passwordTextFieldText);
String id = _ui.getIdTextFieldText();
if (id.length() != 0 && password.length() != 0)
{
String host = _settings.getString(Settings.SERVERADDRESS);
if (host == null || !host.matches("https?://.*"))
{
MessageWindow.showMessageWindowError(Localize.getString("error.lectureid.no.host"), 1500);
return;
}
storePassword();
closeWindow();
}
else
{ // Password or ID empty
if (id.length() == 0)
{
MessageWindow.showMessageWindowError(Localize.getString("error.lectureid.empty"), 1500);
}
else
{
MessageWindow.showMessageWindowError(Localize.getString("error.password.empty"), 1500);
}
}
}
public void registerListeners()
{
_ui.getConfirmButton().addActionListener(e -> confirmAction());
_ui.getCancelButton().addActionListener(e -> cancelAction());
KeyAdapter enterKeyAdapter = new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
confirmAction();
}
else if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
cancelAction();
}
}
};
_ui.getIdTextfield().addKeyListener(enterKeyAdapter);
_ui.getPasswordTextfield().addKeyListener(enterKeyAdapter);
}
}
| agpl-3.0 |
gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/xowa/addons/bldrs/centrals/cmds/Xobc_cmd_itm.java | 681 | package gplx.xowa.addons.bldrs.centrals.cmds; import gplx.*; import gplx.xowa.*; import gplx.xowa.addons.*; import gplx.xowa.addons.bldrs.*; import gplx.xowa.addons.bldrs.centrals.*;
import gplx.core.progs.*; import gplx.core.gfobjs.*;
public interface Xobc_cmd_itm extends Gfo_prog_ui, Gfo_invk {
int Task_id();
int Step_id();
int Cmd_id();
String Cmd_type(); // "xowa.core.http_download"
String Cmd_name(); // "download"
boolean Cmd_suspendable(); // "true"
String Cmd_uid(); // for thread_pool_mgr: "0:0:0"
void Cmd_cleanup();
String Cmd_fallback();
void Cmd_clear();
Gfobj_nde Save_to(Gfobj_nde nde);
void Load_checkpoint();
}
| agpl-3.0 |
sudduth/Aardin | Core/CoreImpl/src/test/java/org/aardin/core/tests/unit/dao/MessageLayoutDAOTest.java | 3838 | package org.aardin.core.tests.unit.dao;
import javax.annotation.Resource;
import org.aardin.common.exceptions.ValidationException;
import org.aardin.common.model.Partition;
import org.aardin.common.model.base.PartitionedId;
import org.aardin.core.dao.IMessageLayoutDAO;
import org.aardin.core.model.DeviceClass;
import org.aardin.core.model.MessageLayout;
import org.aardin.core.model.Phase;
import org.aardin.core.tests.unit.CoreServiceTestConfig;
import org.hibernate.Session;
import org.hibernate.stat.Statistics;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ContextConfiguration(classes=CoreServiceTestConfig.class, loader=AnnotationConfigContextLoader.class)
@Transactional
public class MessageLayoutDAOTest
extends AbstractTransactionalTestNGSpringContextTests {
@Resource
private IMessageLayoutDAO messageLayoutDao;
/**
* Output Hibernate statistics.
*/
@AfterMethod
public void batch_output_hibernate_statistics() {
Statistics s = ((Session) messageLayoutDao.getEntityManager().getDelegate()).getSessionFactory().getStatistics();
s.logSummary();
s.clear();
}
/**
* Verify the database rolled back correctly.
*/
@BeforeMethod
public void verify_data(){
Statistics s = ((Session) messageLayoutDao.getEntityManager().getDelegate()).getSessionFactory().getStatistics();
s.setStatisticsEnabled(true);
assertEquals(super.countRowsInTable("core_nt_msg_los"), 6);
}
@Test
public void testCrud() throws ValidationException {
// Fetch.
String id = "ml1";
Partition partition = new Partition();
partition.setId("p1");
partition.setCode("partition1");
PartitionedId partitionedId = new PartitionedId(partition, id);
MessageLayout ml = messageLayoutDao.find(partitionedId);
assertEquals(ml.getPartitionedId().getId(), id);
assertEquals(ml.getPhase(), Phase.ACTIVE);
assertEquals(ml.getDeviceClasses().size(), 1);
DeviceClass dc = (DeviceClass) ml.getDeviceClasses().toArray()[0];
assertEquals(dc.getId(), "dc1");
assertEquals(dc.getCode(), "default");
// Create a new one
MessageLayout mlNew = new MessageLayout();
mlNew.setBody("The new message");
List<MessageLayout> messageLayouts = messageLayoutDao.findAll("partition1");
assertEquals(messageLayouts.size(), 6);
PartitionedId newPartitionedId = new PartitionedId(partition, "newone");
mlNew.setPartitionedId(newPartitionedId);
mlNew.setPhase(Phase.TERMINATE);
Set<DeviceClass> deviceClasses = new HashSet<>();
dc = new DeviceClass();
dc.setId("dc5");
dc.setName("im");
dc.setCode("IM");
deviceClasses.add(dc);
mlNew.setDeviceClasses(deviceClasses);
mlNew.setBody("Termination");
mlNew.setSubject("Subject: Termination");
messageLayoutDao.persist(mlNew);
mlNew = messageLayoutDao.find(newPartitionedId);
assertEquals(mlNew.getBody(), "Termination");
assertNotNull(mlNew.getPartitionedId().getId());
messageLayouts = messageLayoutDao.findAll("partition1");
assertEquals(messageLayouts.size(), 7);
// Remove
messageLayoutDao.remove(mlNew);
// Find all
messageLayouts = messageLayoutDao.findAll("partition1");
assertEquals(messageLayouts.size(), 6);
// Find by String partitionCode, DeviceClass deviceClass, Phase phase
ml = messageLayoutDao.getMessageLayout("partition1", dc, Phase.ACTIVE);
assertEquals(ml.getPhase(), Phase.ACTIVE);
}
} | agpl-3.0 |
cinquin/mutinack | src/contrib/net/sf/picard/reference/ReferenceSequenceFile.java | 3113 | /*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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 OR COPYRIGHT HOLDERS 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 contrib.net.sf.picard.reference;
import contrib.net.sf.samtools.SAMSequenceDictionary;
/**
* An interface for working with files of reference sequences regardless of the file format
* being used.
*
* @author Tim Fennell
*/
public interface ReferenceSequenceFile {
/**
* Must return a sequence dictionary with at least the following fields completed
* for each sequence: name, length.
*
* @return a list of sequence records representing the sequences in this reference file
*/
SAMSequenceDictionary getSequenceDictionary();
/**
* Retrieves the next whole sequences from the file.
* @return a ReferenceSequence or null if at the end of the file
*/
ReferenceSequence nextSequence();
/**
* Resets the ReferenceSequenceFile so that the next call to nextSequence() will return
* the first sequence in the file.
*/
void reset();
/**
* @return true if getSequence and getSubsequenceAt methods are allowed.
*/
boolean isIndexed();
/**
* Retrieves the complete sequence described by this contig.
* @param contig contig whose data should be returned.
* @return The full sequence associated with this contig.
* @throws UnsupportedOperationException if !sIndexed.
*/
ReferenceSequence getSequence(String contig);
/**
* Gets the subsequence of the contig in the range [start,stop]
* @param contig Contig whose subsequence to retrieve.
* @param start inclusive, 1-based start of region.
* @param stop inclusive, 1-based stop of region.
* @return The partial reference sequence associated with this range.
* @throws UnsupportedOperationException if !sIndexed.
*/
ReferenceSequence getSubsequenceAt(String contig, long start, long stop);
/**
* @return Reference name, file name, or something other human-readable representation.
*/
@Override
String toString();
}
| agpl-3.0 |
cm-is-dog/rapidminer-studio-core | src/main/java/com/rapidminer/operator/ports/quickfix/RelativizeRepositoryLocationQuickfix.java | 2556 | /**
* 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.operator.ports.quickfix;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.UserError;
import com.rapidminer.repository.RepositoryLocation;
/**
* Replaces an absolute reference to a repository entry by an entry resolved relative to the current
* process.
*
* @author Simon Fischer
*/
public class RelativizeRepositoryLocationQuickfix extends AbstractQuickFix {
private String key;
private Operator operator;
/**
* Instantiates a new Relativize repository location quickfix.
*
* @param operator the operator
* @param key the key
* @param value the value
*/
public RelativizeRepositoryLocationQuickfix(Operator operator, String key, String value) {
super(10, false, "relativize_repository_location", key, value);
this.key = key;
this.operator = operator;
}
@Override
public void apply() {
RepositoryLocation absLoc;
try {
absLoc = operator.getParameterAsRepositoryLocation(key);
final RepositoryLocation processLoc = operator.getProcess().getRepositoryLocation() != null
? operator.getProcess().getRepositoryLocation().parent() : null;
if (processLoc == null) {
SwingTools.showVerySimpleErrorMessage("quickfix_failed", "Process is not stored in repository.");
} else {
String relative = absLoc.makeRelative(processLoc);
operator.setParameter(key, relative);
}
} catch (UserError e) {
// Should not happen. Parameter should be set, otherwise we would not have created this
// prefix.
SwingTools.showVerySimpleErrorMessage("quickfix_failed", e.toString());
}
}
}
| agpl-3.0 |
kaltura/KalturaGeneratedAPIClientsAndroid | KalturaClient/src/main/java/com/kaltura/client/types/JobData.java | 2559 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 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.types;
import android.os.Parcel;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.types.ObjectBase;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(JobData.Tokenizer.class)
public class JobData extends ObjectBase {
public interface Tokenizer extends ObjectBase.Tokenizer {
}
public JobData() {
super();
}
public JobData(JsonObject jsonObject) throws APIException {
super(jsonObject);
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaJobData");
return kparams;
}
public static final Creator<JobData> CREATOR = new Creator<JobData>() {
@Override
public JobData createFromParcel(Parcel source) {
return new JobData(source);
}
@Override
public JobData[] newArray(int size) {
return new JobData[size];
}
};
public JobData(Parcel in) {
super(in);
}
}
| agpl-3.0 |
shanghaiscott/joid | src/com/swdouglass/joid/server/HibernateUserManagerImpl.java | 2071 | /*
* Copyright 2009 Scott Douglass <scott@swdouglass.com>
* Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.swdouglass.joid.server;
import com.swdouglass.joid.util.HibernateUtil;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* Implements a persistent {@link UserManager} with
* <a href="http://www.hibernate.org/">Hibernate</a>.
*
* @author scott
*/
public class HibernateUserManagerImpl extends MemoryUserManagerImpl implements UserManager {
private final static Log log = LogFactory.getLog(HibernateUserManagerImpl.class);
@Override
public User getUser(String username) {
User user = null;
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
String s = "from User as a where a.username=:username";
Query q = session.createQuery(s);
q.setParameter("username", username);
List l = q.list();
if (l.size() > 1) {
log.warn("Non-unique username: " + username);
}
tx.commit();
HibernateUtil.closeSession();
if (l.size() == 0) {
log.debug("Found no such username: " + username);
} else {
user = (User) l.get(0);
}
return user;
}
@Override
public void save(User user) {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
HibernateUtil.closeSession();
}
}
| agpl-3.0 |
sozialemedienprojekt/ces-game | src/main/java/de/hub/cses/ces/service/persistence/BalanceFacade.java | 1840 | /*
* 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 de.hub.cses.ces.service.persistence;
/*
* #%L
* CES-Game
* %%
* Copyright (C) 2015 Humboldt-Universität zu Berlin,
* Department of Computer Science,
* Research Group "Computer Science Education / Computer Science and Society"
* Sebastian Gross <sebastian.gross@hu-berlin.de>
* Sven Strickroth <sven.strickroth@hu-berlin.de>
* %%
* 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 Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import de.hub.cses.ces.entity.company.accounting.Balance;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Sebastian Gross <sebastian.gross@hu-berlin.de>
*/
@Stateless
public class BalanceFacade extends AbstractFacade<Balance> {
@PersistenceContext(unitName = "de.hub.cses.ces.PersistenceUnit")
private EntityManager em;
/**
*
*/
public BalanceFacade() {
super(Balance.class);
}
/**
*
* @return
*/
@Override
protected EntityManager getEntityManager() {
return em;
}
}
| agpl-3.0 |
jshort/coner | dropwizard-app/src/main/java/org/coner/boundary/HandicapGroupSetHibernateAddPayloadBoundary.java | 990 | package org.coner.boundary;
import javax.inject.Inject;
import org.coner.core.domain.payload.HandicapGroupSetAddPayload;
import org.coner.hibernate.entity.HandicapGroupSetHibernateEntity;
import org.coner.util.merger.ObjectMerger;
import org.coner.util.merger.ReflectionPayloadJavaBeanMerger;
import org.coner.util.merger.UnsupportedOperationMerger;
public class HandicapGroupSetHibernateAddPayloadBoundary extends AbstractBoundary<
HandicapGroupSetHibernateEntity,
HandicapGroupSetAddPayload> {
@Inject
public HandicapGroupSetHibernateAddPayloadBoundary() {
}
@Override
protected ObjectMerger<HandicapGroupSetHibernateEntity, HandicapGroupSetAddPayload> buildLocalToRemoteMerger() {
return new UnsupportedOperationMerger<>();
}
@Override
protected ObjectMerger<HandicapGroupSetAddPayload, HandicapGroupSetHibernateEntity> buildRemoteToLocalMerger() {
return ReflectionPayloadJavaBeanMerger.payloadToJavaBean();
}
}
| agpl-3.0 |
jletellier/DataHubSystem | core/src/main/java/fr/gael/dhus/spring/security/CookieKey.java | 1105 | /*
* Data Hub Service (DHuS) - For Space data distribution.
* Copyright (C) 2013,2014,2015 GAEL Systems
*
* This file is part of DHuS software sources.
*
* 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 fr.gael.dhus.spring.security;
public class CookieKey
{
public static final String AUTHENTICATION_COOKIE_NAME = "dhusAuth";
public static final String VALIDITY_COOKIE_NAME = "dhusValidity";
public static final String INTEGRITY_COOKIE_NAME = "dhusIntegrity";
}
| agpl-3.0 |
diederikd/DeBrug | languages/Gegevens/source_gen/Gegevens/editor/Tabel_tabel_Editor.java | 783 | package Gegevens.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.DefaultNodeEditor;
import java.util.Collection;
import java.util.Arrays;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
public class Tabel_tabel_Editor extends DefaultNodeEditor {
private Collection<String> myContextHints = Arrays.asList(new String[]{"Gegevens.editor.Gegevens.tabel"});
@Override
@NotNull
public Collection<String> getContextHints() {
return myContextHints;
}
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return new Tabel_tabel_EditorBuilder_a(editorContext, node).createCell();
}
}
| agpl-3.0 |
opencadc/dal | cadc-sia/src/main/java/ca/nrc/cadc/sia2/SiaValidator.java | 4145 | /*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2020. (c) 2020.
* 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/>.
*
************************************************************************
*/
package ca.nrc.cadc.sia2;
/**
*
* @author pdowler
* @deprecated use SiaParamValidator
*/
@Deprecated
public class SiaValidator extends SiaParamValidator {
public SiaValidator() {
}
}
| agpl-3.0 |
kamax-io/matrix-appservice-email | src/main/java/io/kamax/matrix/bridge/email/model/email/_EmailManager.java | 994 | /*
* matrix-appservice-email - Matrix Bridge to E-mail
* Copyright (C) 2017 Kamax Sarl
*
* https://www.kamax.io/
*
* 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 io.kamax.matrix.bridge.email.model.email;
public interface _EmailManager {
String getKey(String email, String threadId);
_EmailEndPoint getEndpoint(String email, String threadId);
}
| agpl-3.0 |
sturesy/client | src/src-main/sturesy/core/ui/loaddialog/TreeListPair.java | 3271 | /*
* StuReSy - Student Response System
* Copyright (C) 2012-2014 StuReSy-Team
*
* 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 sturesy.core.ui.loaddialog;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JPanel;
import org.apache.commons.collections.CollectionUtils;
import sturesy.core.ui.filetree.FileTreeController;
public class TreeListPair extends SubsettedListPairObservable
{
private TreeListPairUI _ui;
/**
* The controller handling the file tree on the left
*/
private FileTreeController _fileTree;
/**
* the list model which has the content of the right table. This list model
* will be changed on actions on the left table.
*/
private DefaultListModel _contentListModel;
public TreeListPair()
{
_fileTree = new FileTreeController();
_contentListModel = new DefaultListModel();
_ui = new TreeListPairUI(_fileTree.getPanel(), _contentListModel);
registerListeners();
}
public void setNewSourceTreeRoot(String path)
{
System.out.println("setting");
_fileTree.setNewDirectory(path);
_fileTree.setSelectedIndex(0);
}
public void setNewContentListContent(List<String> newContent)
{
_contentListModel.clear();
if (CollectionUtils.isNotEmpty(newContent))
{
for (String newElement : newContent)
{
_contentListModel.addElement(newElement);
}
setFirstContentListEntrySelected();
}
}
private void setFirstContentListEntrySelected()
{
_ui.setContentListEntrySelected(0);
}
public JPanel getPanel()
{
return _ui.getPanel();
}
public boolean hasSelectedEntries()
{
return _fileTree.isNodeSelected() && _ui.isContentListItemSelected();
}
public String getContentListItem()
{
return _ui.getContentListItem();
}
public String getSourceListElement()
{
return _fileTree.getLastSelectedFile().getAbsolutePath();
}
public void setNewSourceListContent(String directory)
{
_fileTree.setNewDirectory(directory);
}
private void registerListeners()
{
_fileTree.registerListener(folder -> informSourceListChanged(true));
_ui.getContentList().addKeyListener(new KeyAdapter()
{
public void keyReleased(KeyEvent keyEvent)
{
informContentListKeyEvent(keyEvent.getKeyCode());
}
});
}
}
| agpl-3.0 |
Contargo/iris | src/main/java/net/contargo/iris/routing/osrm/Osrm4QueryStrategy.java | 3291 | package net.contargo.iris.routing.osrm;
import net.contargo.iris.GeoLocation;
import net.contargo.iris.routing.RoutingException;
import net.contargo.iris.routing.RoutingQueryResult;
import net.contargo.iris.routing.RoutingQueryStrategy;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import static net.contargo.iris.routing.RoutingQueryResult.STATUS_NO_ROUTE;
/**
* An OSRM specific implementation of {@code RoutingServiceQueryStrategy} suitable for querying an OSRM version 4
* routing service.
*
* @author Sven Mueller - mueller@synyx.de
* @author Tobias Schneider - schneider@synyx.de
* @author David Schilling - schilling@synyx.de
*/
public class Osrm4QueryStrategy implements RoutingQueryStrategy {
private static final String Q_QUESTIONMARK = "?";
private static final String Q_EQUALS = "=";
private static final String Q_AMPERSAND = "&";
private static final String Q_COMMA = ",";
private static final String Q_LOCATION = "loc";
private static final String Q_ZOOM = "z";
private static final String Q_GEOMETRY = "geometry";
private static final String Q_INSTRUCTIONS = "instructions";
private static final String Q_ALTERNATIVE = "alt";
private final String baseUrl;
private final RestTemplate osrmRestClient;
public Osrm4QueryStrategy(RestTemplate osrmRestClient, String baseUrl) {
this.osrmRestClient = osrmRestClient;
this.baseUrl = baseUrl;
}
@Override
public RoutingQueryResult route(GeoLocation start, GeoLocation destination) {
try {
return createOSRMQueryResult(routeRequest(start, destination));
} catch (RestClientException e) {
throw new RoutingException("Error querying OSRM service: ", e);
}
}
@Override
public RoutingQueryResult route(GeoLocation start, GeoLocation destination, OSRMProfile profile) {
throw new UnsupportedOperationException("Osrm4QueryStrategy does not support profiles");
}
private OSRM4Response routeRequest(GeoLocation start, GeoLocation destination) {
return osrmRestClient.getForEntity(createOSRMQueryString(start, destination), OSRM4Response.class).getBody();
}
private String createOSRMQueryString(GeoLocation start, GeoLocation destination) {
return baseUrl + Q_QUESTIONMARK + Q_LOCATION + Q_EQUALS + start.getLatitude() + Q_COMMA + start.getLongitude()
+ Q_AMPERSAND + Q_LOCATION + Q_EQUALS + destination.getLatitude() + Q_COMMA + destination.getLongitude()
+ Q_AMPERSAND + Q_ZOOM + Q_EQUALS + 0 + Q_AMPERSAND + Q_GEOMETRY + Q_EQUALS + false + Q_AMPERSAND
+ Q_INSTRUCTIONS + Q_EQUALS + true + Q_AMPERSAND + Q_ALTERNATIVE + Q_EQUALS + false;
}
private RoutingQueryResult createOSRMQueryResult(OSRM4Response response) {
double totalDistance = 0d;
double totalTime = 0d;
int status = response.getStatus();
if (status != STATUS_NO_ROUTE) {
totalDistance = response.getRoute_summary().getTotal_distance();
totalTime = response.getRoute_summary().getTotalTime();
}
return new RoutingQueryResult(status, totalDistance, totalTime, response.getToll());
}
}
| agpl-3.0 |
educorzo/Siabra-Platform-Spring-Hibernate | siabra/src/main/java/com/ecorzo/siabra/repository/PerfilDAO.java | 145 | package com.ecorzo.siabra.repository;
import com.ecorzo.siabra.domain.Perfil;
public interface PerfilDAO extends GenericDAO<Perfil,String>{
}
| agpl-3.0 |
elki-project/elki | elki-index-mtree/src/main/java/elki/index/tree/metrical/mtreevariants/mktrees/mktab/MkTabTreeFactory.java | 2652 | /*
* This file is part of ELKI:
* Environment for Developing KDD-Applications Supported by Index-Structures
*
* Copyright (C) 2019
* ELKI Development Team
*
* 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 elki.index.tree.metrical.mtreevariants.mktrees.mktab;
import elki.database.relation.Relation;
import elki.index.tree.metrical.mtreevariants.mktrees.AbstractMkTreeUnifiedFactory;
import elki.index.tree.metrical.mtreevariants.mktrees.MkTreeSettings;
import elki.persistent.PageFile;
import elki.persistent.PageFileFactory;
import elki.utilities.ClassGenericsUtil;
/**
* Factory for MkTabTrees
*
* @author Erich Schubert
* @since 0.4.0
*
* @stereotype factory
* @navassoc - create - MkTabTreeIndex
*
* @param <O> Object type
*/
public class MkTabTreeFactory<O> extends AbstractMkTreeUnifiedFactory<O, MkTabTreeNode<O>, MkTabEntry, MkTreeSettings<O, MkTabTreeNode<O>, MkTabEntry>> {
/**
* Constructor.
*
* @param pageFileFactory Data storage
* @param settings Tree settings
*/
public MkTabTreeFactory(PageFileFactory<?> pageFileFactory, MkTreeSettings<O, MkTabTreeNode<O>, MkTabEntry> settings) {
super(pageFileFactory, settings);
}
@Override
public MkTabTreeIndex<O> instantiate(Relation<O> relation) {
PageFile<MkTabTreeNode<O>> pagefile = makePageFile(getNodeClass());
return new MkTabTreeIndex<>(relation, pagefile, settings);
}
protected Class<MkTabTreeNode<O>> getNodeClass() {
return ClassGenericsUtil.uglyCastIntoSubclass(MkTabTreeNode.class);
}
/**
* Parameterization class.
*
* @author Erich Schubert
*/
public static class Par<O> extends AbstractMkTreeUnifiedFactory.Par<O, MkTabTreeNode<O>, MkTabEntry, MkTreeSettings<O, MkTabTreeNode<O>, MkTabEntry>> {
@Override
public MkTabTreeFactory<O> make() {
return new MkTabTreeFactory<>(pageFileFactory, settings);
}
@Override
protected MkTreeSettings<O, MkTabTreeNode<O>, MkTabEntry> makeSettings() {
return new MkTreeSettings<>();
}
}
}
| agpl-3.0 |
bisq-network/exchange | cli/src/main/java/bisq/cli/TableFormat.java | 8019 | /*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.cli;
import bisq.proto.grpc.AddressBalanceInfo;
import bisq.proto.grpc.BalancesInfo;
import bisq.proto.grpc.BsqBalanceInfo;
import bisq.proto.grpc.BtcBalanceInfo;
import protobuf.PaymentAccount;
import com.google.common.annotations.VisibleForTesting;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;
import static bisq.cli.ColumnHeaderConstants.*;
import static bisq.cli.CurrencyFormat.formatBsq;
import static bisq.cli.CurrencyFormat.formatSatoshis;
import static com.google.common.base.Strings.padEnd;
import static java.lang.String.format;
import static java.util.Collections.max;
import static java.util.Comparator.comparing;
import static java.util.TimeZone.getTimeZone;
@Deprecated
@VisibleForTesting
public class TableFormat {
static final TimeZone TZ_UTC = getTimeZone("UTC");
static final SimpleDateFormat DATE_FORMAT_ISO_8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public static String formatAddressBalanceTbl(List<AddressBalanceInfo> addressBalanceInfo) {
String headerFormatString = COL_HEADER_ADDRESS + COL_HEADER_DELIMITER
+ COL_HEADER_AVAILABLE_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_CONFIRMATIONS + COL_HEADER_DELIMITER
+ COL_HEADER_IS_USED_ADDRESS + COL_HEADER_DELIMITER + "\n";
String headerLine = format(headerFormatString, "BTC");
String colDataFormat = "%-" + COL_HEADER_ADDRESS.length() + "s" // lt justify
+ " %" + (COL_HEADER_AVAILABLE_BALANCE.length() - 1) + "s" // rt justify
+ " %" + COL_HEADER_CONFIRMATIONS.length() + "d" // rt justify
+ " %-" + COL_HEADER_IS_USED_ADDRESS.length() + "s"; // lt justify
return headerLine
+ addressBalanceInfo.stream()
.map(info -> format(colDataFormat,
info.getAddress(),
formatSatoshis(info.getBalance()),
info.getNumConfirmations(),
info.getIsAddressUnused() ? "NO" : "YES"))
.collect(Collectors.joining("\n"));
}
public static String formatBalancesTbls(BalancesInfo balancesInfo) {
return "BTC" + "\n"
+ formatBtcBalanceInfoTbl(balancesInfo.getBtc()) + "\n"
+ "BSQ" + "\n"
+ formatBsqBalanceInfoTbl(balancesInfo.getBsq());
}
public static String formatBsqBalanceInfoTbl(BsqBalanceInfo bsqBalanceInfo) {
String headerLine = COL_HEADER_AVAILABLE_CONFIRMED_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_UNVERIFIED_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_UNCONFIRMED_CHANGE_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_LOCKED_FOR_VOTING_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_LOCKUP_BONDS_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_UNLOCKING_BONDS_BALANCE + COL_HEADER_DELIMITER + "\n";
String colDataFormat = "%" + COL_HEADER_AVAILABLE_CONFIRMED_BALANCE.length() + "s" // rt justify
+ " %" + (COL_HEADER_UNVERIFIED_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_UNCONFIRMED_CHANGE_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_LOCKED_FOR_VOTING_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_LOCKUP_BONDS_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_UNLOCKING_BONDS_BALANCE.length() + 1) + "s"; // rt justify
return headerLine + format(colDataFormat,
formatBsq(bsqBalanceInfo.getAvailableConfirmedBalance()),
formatBsq(bsqBalanceInfo.getUnverifiedBalance()),
formatBsq(bsqBalanceInfo.getUnconfirmedChangeBalance()),
formatBsq(bsqBalanceInfo.getLockedForVotingBalance()),
formatBsq(bsqBalanceInfo.getLockupBondsBalance()),
formatBsq(bsqBalanceInfo.getUnlockingBondsBalance()));
}
public static String formatBtcBalanceInfoTbl(BtcBalanceInfo btcBalanceInfo) {
String headerLine = COL_HEADER_AVAILABLE_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_RESERVED_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_TOTAL_AVAILABLE_BALANCE + COL_HEADER_DELIMITER
+ COL_HEADER_LOCKED_BALANCE + COL_HEADER_DELIMITER + "\n";
String colDataFormat = "%" + COL_HEADER_AVAILABLE_BALANCE.length() + "s" // rt justify
+ " %" + (COL_HEADER_RESERVED_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_TOTAL_AVAILABLE_BALANCE.length() + 1) + "s" // rt justify
+ " %" + (COL_HEADER_LOCKED_BALANCE.length() + 1) + "s"; // rt justify
return headerLine + format(colDataFormat,
formatSatoshis(btcBalanceInfo.getAvailableBalance()),
formatSatoshis(btcBalanceInfo.getReservedBalance()),
formatSatoshis(btcBalanceInfo.getTotalAvailableBalance()),
formatSatoshis(btcBalanceInfo.getLockedBalance()));
}
public static String formatPaymentAcctTbl(List<PaymentAccount> paymentAccounts) {
// Some column values might be longer than header, so we need to calculate them.
int nameColWidth = getLongestColumnSize(
COL_HEADER_NAME.length(),
paymentAccounts.stream().map(PaymentAccount::getAccountName)
.collect(Collectors.toList()));
int paymentMethodColWidth = getLongestColumnSize(
COL_HEADER_PAYMENT_METHOD.length(),
paymentAccounts.stream().map(a -> a.getPaymentMethod().getId())
.collect(Collectors.toList()));
String headerLine = padEnd(COL_HEADER_NAME, nameColWidth, ' ') + COL_HEADER_DELIMITER
+ COL_HEADER_CURRENCY + COL_HEADER_DELIMITER
+ padEnd(COL_HEADER_PAYMENT_METHOD, paymentMethodColWidth, ' ') + COL_HEADER_DELIMITER
+ COL_HEADER_UUID + COL_HEADER_DELIMITER + "\n";
String colDataFormat = "%-" + nameColWidth + "s" // left justify
+ " %-" + COL_HEADER_CURRENCY.length() + "s" // left justify
+ " %-" + paymentMethodColWidth + "s" // left justify
+ " %-" + COL_HEADER_UUID.length() + "s"; // left justify
return headerLine
+ paymentAccounts.stream()
.map(a -> format(colDataFormat,
a.getAccountName(),
a.getSelectedTradeCurrency().getCode(),
a.getPaymentMethod().getId(),
a.getId()))
.collect(Collectors.joining("\n"));
}
// Return size of the longest string value, or the header.len, whichever is greater.
static int getLongestColumnSize(int headerLength, List<String> strings) {
int longest = max(strings, comparing(String::length)).length();
return Math.max(longest, headerLength);
}
static String formatTimestamp(long timestamp) {
DATE_FORMAT_ISO_8601.setTimeZone(TZ_UTC);
return DATE_FORMAT_ISO_8601.format(new Date(timestamp));
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/service/DocumentPersistService.java | 18039 | package com.x.cms.assemble.control.service;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.cms.assemble.control.DocumentDataHelper;
import com.x.cms.assemble.control.factory.ProjectionFactory;
import com.x.cms.assemble.control.jaxrs.document.ActionPersistBatchModifyData.WiDataChange;
import com.x.cms.assemble.control.jaxrs.document.ActionPersistBatchModifyData.Wo;
import com.x.cms.assemble.control.jaxrs.permission.element.PermissionInfo;
import com.x.cms.core.entity.CategoryInfo;
import com.x.cms.core.entity.Document;
import com.x.cms.core.entity.Document_;
import com.x.cms.core.entity.Projection;
import com.x.cms.core.entity.content.Data;
import com.x.query.core.entity.Item;
import org.apache.commons.collections4.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* 对文档信息进行持久化服务类
* @author sword
*/
public class DocumentPersistService {
private static Logger logger = LoggerFactory.getLogger(DocumentPersistService.class);
private static ReentrantLock lock = new ReentrantLock();
private DocumentInfoService documentInfoService = new DocumentInfoService();
private PermissionOperateService permissionService = new PermissionOperateService();
public Document save( Document document, JsonElement jsonElement, String projection) throws Exception {
if( document == null ){
throw new Exception("document is null!");
}
if (ListTools.isNotEmpty(document.getPictureList())) {
document.setHasIndexPic(true);
if(document.getPictureList().size() > 3){
document.setIndexPics(StringUtils.join(document.getPictureList().subList(0, 2), ","));
}else{
document.setIndexPics(StringUtils.join(document.getPictureList(), ","));
}
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
document.setModifyTime( new Date());
document.setSequenceAppAlias( document.getAppAlias() + document.getId() );
document.setSequenceCategoryAlias( document.getCategoryAlias() + document.getId() );
if( document.getTitle().length() > 30 ) {
document.setSequenceTitle( document.getTitle().substring(0, 30) + document.getId() );
}else {
document.setSequenceTitle( document.getTitle() + document.getId() );
}
if( document.getCreatorPerson().length() > 50 ) {
document.setSequenceCreatorPerson( document.getCreatorPerson().substring(0, 50) + document.getId() );
}else {
document.setSequenceCreatorPerson( document.getCreatorPerson() + document.getId() );
}
if( document.getCreatorUnitName().length() > 50 ) {
document.setSequenceCreatorUnitName( document.getCreatorUnitName().substring(0, 50) + document.getId() );
}else {
document.setSequenceCreatorUnitName( document.getCreatorUnitName() + document.getId() );
}
document = documentInfoService.save( emc, document );
//如果有数据信息,则保存数据信息
DocumentDataHelper documentDataHelper = new DocumentDataHelper( emc, document );
if( jsonElement != null ) {
documentDataHelper.update( jsonElement );
}
emc.commit();
Data data = documentDataHelper.get();
this.doProjection(emc, projection, data, document);
data.setDocument( document );
documentDataHelper.update( data );
emc.commit();
return document;
} catch ( Exception e ) {
throw e;
}
}
public void doProjection(EntityManagerContainer emc, String projection, Data data, Document document) throws Exception {
if(StringUtils.isNotBlank(projection) && XGsonBuilder.isJsonArray(projection)){
emc.beginTransaction( Document.class );
List<Projection> projections = XGsonBuilder.instance().fromJson(projection,
new TypeToken<List<Projection>>(){}.getType());
ProjectionFactory.projectionDocument(projections, data, document);
}
}
/**
* 根据文档信息更新数据内容中的文档信息内容
* @param document
* @return
* @throws Exception
*/
public Document refreshDocInfoData( Document document ) throws Exception {
if( document == null ){
throw new Exception("document is null!");
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
document = documentInfoService.save( emc, document );
//如果有数据信息,则保存数据信息
DocumentDataHelper documentDataHelper = new DocumentDataHelper( emc, document );
Data data = documentDataHelper.get();
data.setDocument( document );
documentDataHelper.update(data);
emc.commit();
return document;
} catch ( Exception e ) {
throw e;
}
}
void fill(Item o, Document document) {
/** 将DateItem与Document放在同一个分区 */
o.setDistributeFactor(document.getDistributeFactor());
o.setBundle(document.getId());
o.setItemCategory(ItemCategory.cms);
}
/**
* 变更一个文档的分类信息
* @param document
* @param categoryInfo
* @throws Exception
*/
public Boolean changeCategory( Document document, CategoryInfo categoryInfo) throws Exception {
if( document == null ){
throw new Exception("document is empty!");
}
if( categoryInfo == null ){
throw new Exception("categoryInfo is empty!");
}
Data data = null;
DocumentDataHelper documentDataHelper = null;
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
emc.beginTransaction( Document.class );
emc.beginTransaction( Item.class );
document = emc.find( document.getId(), Document.class );
//更新document分类相关信息
document.setAppId( categoryInfo.getAppId() );
document.setAppName( categoryInfo.getAppName() );
document.setCategoryId( categoryInfo.getId() );
document.setCategoryName( categoryInfo.getCategoryName() );
document.setCategoryAlias( categoryInfo.getCategoryAlias() );
document.setForm( categoryInfo.getReadFormId() );
document.setFormName( categoryInfo.getReadFormName() );
document.setModifyTime( new Date());
document.setSequenceAppAlias( document.getAppAlias() + document.getId() );
document.setSequenceCategoryAlias( document.getCategoryAlias() + document.getId() );
if( document.getTitle().length() > 30 ) {
document.setSequenceTitle( document.getTitle().substring(0, 30) + document.getId() );
}else {
document.setSequenceTitle( document.getTitle() + document.getId() );
}
if( document.getCreatorPerson().length() > 50 ) {
document.setSequenceCreatorPerson( document.getCreatorPerson().substring(0, 50) + document.getId() );
}else {
document.setSequenceCreatorPerson( document.getCreatorPerson() + document.getId() );
}
if( document.getCreatorUnitName().length() > 50 ) {
document.setSequenceCreatorUnitName( document.getCreatorUnitName().substring(0, 50) + document.getId() );
}else {
document.setSequenceCreatorUnitName( document.getCreatorUnitName() + document.getId() );
}
emc.check( document, CheckPersistType.all );
//更新数据里的document对象信息
documentDataHelper = new DocumentDataHelper( emc, document );
data = documentDataHelper.get();
data.setDocument( document );
documentDataHelper.update( data );
emc.commit();
return true;
} catch ( Exception e ) {
throw e;
}
}
public Wo changeData(List<String> docIds, List<WiDataChange> dataChanges) throws Exception {
if( ListTools.isEmpty( docIds )){
throw new Exception("docIds is empty!");
}
if( ListTools.isEmpty( dataChanges )){
throw new Exception("dataChanges is empty!");
}
Wo wo = new Wo();
Data data = null;
Document document_entity = null;
DocumentDataHelper documentDataHelper = null;
for( String docId : docIds ) {
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
emc.beginTransaction( Document.class );
emc.beginTransaction( Item.class );
document_entity = emc.find( docId, Document.class );
document_entity.setModifyTime( new Date());
documentDataHelper = new DocumentDataHelper( emc, document_entity );
data = documentDataHelper.get();
for( WiDataChange dataChange : dataChanges ) {
if( "Integer".equals(dataChange.getDataType() )) {
data.put( dataChange.getDataPath(), dataChange.getDataInteger());
}else if( "String".equals(dataChange.getDataType() )) {
data.put( dataChange.getDataPath(), dataChange.getDataString());
}else if( "Date".equals(dataChange.getDataType() )) {
data.put( dataChange.getDataPath(), dataChange.getDataDate());
}else if( "Boolean".equals(dataChange.getDataType() )) {
data.put( dataChange.getDataPath(), dataChange.getDataBoolean());
}else {
data.put( dataChange.getDataPath(), dataChange.getDataString());
}
}
data.setDocument( document_entity );
documentDataHelper.update( data );
emc.commit();
wo.increaseSuccess_count(1);
} catch ( Exception e ) {
wo.appendErorrId(docId);
wo.increaseError_count(1);
e.printStackTrace();
}
}
return wo;
}
public Boolean inReview(String documentId) throws Exception {
if( StringUtils.isEmpty( documentId ) ){
throw new Exception("documentId is empty!");
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
return documentInfoService.inReview( emc, documentId );
} catch ( Exception e ) {
throw e;
}
}
public void topDocument(String id) throws Exception {
if( StringUtils.isEmpty( id ) ){
throw new Exception("id is empty!");
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
Document document = emc.find( id, Document.class );
if( document != null ) {
// emc.beginTransaction( Item.class );
emc.beginTransaction( Document.class );
document.setIsTop( true );
DocumentDataHelper documentDataHelper = new DocumentDataHelper( emc, document );
Data data = documentDataHelper.get();
data.setDocument( document );
documentDataHelper.update( data );
emc.commit();
}
} catch ( Exception e ) {
throw e;
}
}
public void unTopDocument(String id) throws Exception {
if( StringUtils.isEmpty( id ) ){
throw new Exception("id is empty!");
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
Document document = emc.find( id, Document.class );
if( document != null ) {
emc.beginTransaction( Document.class );
document.setIsTop( false );
DocumentDataHelper documentDataHelper = new DocumentDataHelper( emc, document );
Data data = documentDataHelper.get();
data.setDocument( document );
documentDataHelper.update( data );
emc.commit();
}
} catch ( Exception e ) {
throw e;
}
}
/**
* 删除指定ID的文档
* @param docId
* @throws Exception
*/
public void delete( String docId ) throws Exception {
if( StringUtils.isEmpty( docId ) ){
throw new Exception("docId is empty!");
}
try ( EntityManagerContainer emc = EntityManagerContainerFactory.instance().create() ) {
documentInfoService.delete(emc, docId);
} catch ( Exception e ) {
throw e;
}
}
/**
* 根据读者作者列表更新文档所有的权限信息
* @param docId
* @param readerList
* @param authorList
* @throws Exception
*/
public Document refreshDocumentPermission( String docId, List<PermissionInfo> readerList, List<PermissionInfo> authorList ) throws Exception {
if( StringUtils.isEmpty( docId ) ){
throw new Exception("docId is empty!");
}
Document document = permissionService.refreshDocumentPermission( docId, readerList, authorList);
new CmsBatchOperationPersistService().addOperation(
CmsBatchOperationProcessService.OPT_OBJ_DOCUMENT,
CmsBatchOperationProcessService.OPT_TYPE_PERMISSION, docId, docId, "刷新文档权限:ID=" + docId );
return document;
}
/**
* 根据组织好的权限信息列表更新指定文档的权限信息
* @param docId
* @param permissionList
* @throws Exception
*/
public void refreshDocumentPermission( String docId, List<PermissionInfo> permissionList ) throws Exception {
if( StringUtils.isEmpty( docId ) ){
throw new Exception("docId is empty!");
}
permissionService.refreshDocumentPermission(docId, permissionList);
}
/**
* 重新计算所有的文档的权限和review信息
*/
public void refreshAllDocumentPermission(boolean flag) throws Exception {
try {
if(lock.tryLock()) {
AppInfoServiceAdv appInfoService = new AppInfoServiceAdv();
DocumentQueryService documentQueryService = new DocumentQueryService();
List<String> appIds = appInfoService.listAllIds("信息");
if (ListTools.isNotEmpty(appIds)) {
for (String appId : appIds) {
//查询指定App中所有的文档Id
List<String> documentIds = documentQueryService.listIdsByAppId(appId, "信息", 50000);
logger.info("刷新应用{}的数据共{}条",appId,documentIds.size());
if (ListTools.isNotEmpty(documentIds)) {
int count = 0;
for (List<String> partDocIds : ListTools.batch(documentIds, 4)){
count = count + 4;
List<CompletableFuture<Void>> futures = new TreeList<>();
for (String documentId : partDocIds) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ReviewService reviewService = new ReviewService();
boolean fullRead = reviewService.refreshDocumentReview(emc, documentId);
Document document = emc.find(documentId, Document.class);
emc.beginTransaction(Document.class);
document.setIsAllRead(fullRead);
emc.commit();
} catch (Exception e) {
logger.warn("刷新文档权限异常1:{}", e.getMessage());
}
});
futures.add(future);
}
if(!flag){
Calendar cal = DateUtils.toCalendar(new Date());
if(cal.get(Calendar.HOUR_OF_DAY)>6){
lock.unlock();
return;
}
}
for (CompletableFuture<Void> future : futures) {
try {
future.get(200, TimeUnit.SECONDS);
} catch (Exception e) {
logger.warn("刷新文档权限异常2:{}",e.getMessage());
}
}
futures.clear();
if(flag && count > 199 && count % 200 == 0){
logger.info("应用文档权限已刷新{}个",count);
}
}
}
}
CacheManager.notify(Document.class);
}
lock.unlock();
}
} catch (Exception e) {
lock.unlock();
logger.error(e);
}
}
public boolean refreshDocumentPermissionByCategory(String categoryId) {
boolean flag = false;
try {
if(lock.tryLock()) {
List<String> documentIds = null;
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
EntityManager em = emc.get( Document.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<Document> root = cq.from( Document.class );
Predicate p = cb.equal(root.get( Document_.categoryId ), categoryId );
p = cb.and( p, cb.equal( root.get( Document_.documentType), "信息"));
cq.select( root.get( Document_.id) ).where(p);
documentIds = em.createQuery( cq ).getResultList();
}
if (ListTools.isNotEmpty(documentIds)) {
logger.info("刷新分类{}的数据共{}条",categoryId,documentIds.size());
int count = 0;
for (List<String> partDocIds : ListTools.batch(documentIds, 10)){
count = count + 10;
List<CompletableFuture<Void>> futures = new TreeList<>();
for (String documentId : partDocIds) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ReviewService reviewService = new ReviewService();
boolean fullRead = reviewService.refreshDocumentReview(emc, documentId);
Document document = emc.find(documentId, Document.class);
emc.beginTransaction(Document.class);
document.setIsAllRead(fullRead);
emc.commit();
} catch (Exception e) {
logger.warn("刷新文档权限异常1:{}", e.getMessage());
}
});
futures.add(future);
}
for (CompletableFuture<Void> future : futures) {
try {
future.get(200, TimeUnit.SECONDS);
} catch (Exception e) {
logger.warn("刷新文档权限异常2:{}",e.getMessage());
}
}
futures.clear();
if(count > 99 && count % 100 == 0){
logger.info("分类文档权限已刷新{}个",count);
}
}
}
CacheManager.notify(Document.class);
lock.unlock();
flag = true;
logger.info("完成分类{}的权限刷新", categoryId);
}else{
logger.info("有分类正在刷新权限中,请稍后....");
}
} catch (Exception e) {
lock.unlock();
logger.error(e);
}
return flag;
}
}
| agpl-3.0 |
AsherBond/MondocosmOS | glob3/igolibs/libs/jCharts-0.7.5/src/org/jCharts/chartData/interfaces/IPieChartDataSet.java | 3250 | /***********************************************************************************************
* File Info: $Id: IPieChartDataSet.java,v 1.2 2002/10/14 20:52:04 nathaniel_auvil Exp $
* Copyright (C) 2001
* Author: Nathaniel G. Auvil
* Contributor(s):
*
* Copyright 2002 (C) Nathaniel G. Auvil. All Rights Reserved.
*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "jCharts" or "Nathaniel G. Auvil" must not be used to
* endorse or promote products derived from this Software without
* prior written permission of Nathaniel G. Auvil. For written
* permission, please contact nathaniel_auvil@users.sourceforge.net
*
* 4. Products derived from this Software may not be called "jCharts"
* nor may "jCharts" appear in their names without prior written
* permission of Nathaniel G. Auvil. jCharts is a registered
* trademark of Nathaniel G. Auvil.
*
* 5. Due credit should be given to the jCharts Project
* (http://jcharts.sourceforge.net/).
*
* THIS SOFTWARE IS PROVIDED BY Nathaniel G. Auvil AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* jCharts OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************************/
package org.jCharts.chartData.interfaces;
public interface IPieChartDataSet extends IDataSet
{
/******************************************************************************************
* Returns the value in the data set at the specified position.
*
* @param index
* @return double
*******************************************************************************************/
public double getValue( int index );
/******************************************************************************************
* Returns the chart title.
*
* @return String the chart title. If this returns NULL, no title will be displayed.
******************************************************************************************/
public String getChartTitle();
}
| agpl-3.0 |
DanielYao/tigase-server | src/main/java/tigase/server/sreceiver/sysmon/CPUMonitor.java | 13343 | /*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2012 "Artur Hefczyc" <artur.hefczyc@tigase.org>
*
* 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, version 3 of the License.
*
* 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. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.server.sreceiver.sysmon;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.server.Packet;
import tigase.stats.StatisticsList;
import tigase.sys.TigaseRuntime;
import tigase.xmpp.JID;
/**
* Created: Dec 10, 2008 12:27:15 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class CPUMonitor extends AbstractMonitor {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger(CPUMonitor.class.getName());
private int historySize = 100;
private long prevUptime = TigaseRuntime.getTigaseRuntime().getUptime();;
private long prevCputime = TigaseRuntime.getTigaseRuntime().getProcessCPUTime();
// private long lastCpuUsage = 0;
// private long lastCpuChecked = 0;
private float[] cpuUsage = new float[historySize];
private int cpuUsageIdx = 0;
private double[] loadAverage = new double[historySize];
private int loadAverageIdx = 0;
private ThreadMXBean thBean = null;
private OperatingSystemMXBean osBean = null;
private NumberFormat format = NumberFormat.getNumberInstance();
private Map<Long, ThreadData> threads =
new ConcurrentHashMap<Long, ThreadData>();
private int deadLockedThreadsNo = 0;
private String checkForDeadLock() {
long[] tids = thBean.findDeadlockedThreads();
if (tids != null && tids.length > 0) {
deadLockedThreadsNo = tids.length;
StringBuilder sb = new StringBuilder();
sb.append("Locked threads " + tids.length + ":\n");
Set<Long> tidSet = new LinkedHashSet<Long>();
for (long tid : tids) {
tidSet.add(tid);
}
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
while (rootGroup.getParent() != null)
rootGroup = rootGroup.getParent();
int allThreadsCount = thBean.getThreadCount();
Thread[] allThreads = new Thread[allThreadsCount];
rootGroup.enumerate(allThreads, true);
for (Thread thread : allThreads) {
if (tidSet.contains(thread.getId())) {
ThreadInfo threadInfo = thBean.getThreadInfo(thread.getId());
sb.append("Locked thread [" + thread.getId() + "] " +
threadInfo.getThreadName() + " on " +
threadInfo.getLockInfo().toString() +
", locked synchronizers: " +
Arrays.toString(threadInfo.getLockedSynchronizers()) +
", locked monitors: " +
Arrays.toString(threadInfo.getLockedMonitors()) +
" by [" + threadInfo.getLockOwnerId() + "] " +
threadInfo.getLockOwnerName()).append('\n');
StackTraceElement[] ste = thread.getStackTrace();
for (StackTraceElement stackTraceElement : ste) {
sb.append(" " + stackTraceElement.toString()).append('\n');
}
}
}
return sb.toString();
}
return null;
}
private enum command {
maxthread(" - Returns information about the most active thread."),
mth(" - Short version of the command above."),
allthreads(" [ex] - display all threads information, with 'ex' parameters it prints extended information.");
private String helpText = null;
private command(String helpText) {
this.helpText = helpText;
}
public String getHelp() {
return helpText;
}
};
private String getStackTrace(Map<Thread,StackTraceElement[]> map, long id) {
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
if (entry.getKey().getId() == id) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement stelem : entry.getValue()) {
sb.append(stelem.toString() + "\n");
}
return sb.toString();
}
}
return null;
}
private String getThreadInfo(long thid, boolean stack) {
ThreadInfo ti = thBean.getThreadInfo(thid);
if (ti != null) {
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
StringBuilder sb =
new StringBuilder("Thread: " + ti.getThreadName() +
", ID: " + ti.getThreadId());
ThreadData td = threads.get(thid);
if (td != null) {
sb.append(", CPU usage: " + format.format(td.cpuUse) + "%\n");
}
if (stack) {
sb.append(ti.toString());
sb.append(getStackTrace(map, thid));
}
return sb.toString();
} else {
return "ThreadInfo is null...";
}
}
@Override
public String runCommand(String[] com) {
command comm = command.valueOf(com[0].substring(2));
switch (comm) {
case mth:
case maxthread:
if (com.length > 1) {
try {
long thid = Long.parseLong(com[1]);
return getThreadInfo(thid, true);
} catch (Exception e) {
return "Incorrect Thread ID";
}
}
List<ThreadData> sorted = sortThreadCPUUse();
if (sorted.size() > 0) {
return getThreadInfo(sorted.get(0).id, true);
} else {
return "No max threads info yet.";
}
case allthreads:
boolean extend = false;
if (com.length > 1 && com[1].equals("ex")) {
extend = true;
}
StringBuilder sb = new StringBuilder("All threads information:\n");
for (long thid : thBean.getAllThreadIds()) {
sb.append(getThreadInfo(thid, extend));
}
return sb.toString();
}
return null;
}
private List<ThreadData> sortThreadCPUUse() {
ArrayList<ThreadData> list =
new ArrayList<ThreadData>(threads.values());
Collections.sort(list, new Comparator<ThreadData>() {
@Override
public int compare(ThreadData o1, ThreadData o2) {
if (o1.cpuUse < o2.cpuUse) {
return 1;
}
if (o1.cpuUse > o2.cpuUse) {
return -1;
}
return 0;
}
});
return list;
}
@Override
public String commandsHelp() {
StringBuilder sb = new StringBuilder();
for (command comm : command.values()) {
sb.append("//" + comm.name() + comm.getHelp() + "\n");
}
return sb.toString();
}
@Override
public boolean isMonitorCommand(String com) {
if (com != null) {
for (command comm: command.values()) {
if (com.startsWith("//" + comm.toString())) {
return true;
}
}
}
return false;
}
@Override
public void init(JID jid, float treshold, SystemMonitorTask smTask) {
super.init(jid, treshold, smTask);
thBean = ManagementFactory.getThreadMXBean();
osBean = ManagementFactory.getOperatingSystemMXBean();
format.setMaximumFractionDigits(1);
// if (format instanceof DecimalFormat) {
// DecimalFormat decf = (DecimalFormat)format;
// decf.applyPattern(decf.toPattern()+"%");
// }
if (thBean.isCurrentThreadCpuTimeSupported()) {
thBean.setThreadCpuTimeEnabled(true);
} else {
log.warning("Current thread CPU Time is NOT supported.");
}
if (thBean.isThreadContentionMonitoringSupported()) {
thBean.setThreadContentionMonitoringEnabled(true);
} else {
log.warning("Thread contention monitoring is NOT supported.");
}
}
@Override
public void check10Secs(Queue<Packet> results) {
long currUptime = TigaseRuntime.getTigaseRuntime().getUptime();
long currCputime = TigaseRuntime.getTigaseRuntime().getProcessCPUTime();
float cpuUse = calcCPUUse(prevUptime, currUptime, prevCputime, currCputime,
TigaseRuntime.getTigaseRuntime().getCPUsNumber());
prevUptime = currUptime;
prevCputime = currCputime;
cpuUsageIdx = setValueInArr(cpuUsage, cpuUsageIdx, cpuUse);
loadAverageIdx = setValueInArr(loadAverage, loadAverageIdx,
osBean.getSystemLoadAverage());
float thresh = treshold * 100;
if ((cpuUse > thresh) && (recentCpu(6) > thresh)) {
prepareWarning("High CPU usage, current: " + format.format(cpuUse) +
"%, last minute: " +
format.format(recentCpu(6)) + "%", results, this);
} else {
if (cpuUse < (thresh * 0.75)) {
prepareCalmDown("CPU usage is now low again, current: " +
format.format(cpuUse) + "%, last minute: " +
format.format(recentCpu(6)) + "%", results, this);
}
}
String result = checkForDeadLock();
if (result != null) {
System.out.println("Dead-locked threads:\n" + result);
prepareWarning("Dead-locked threads:\n" + result, results, this);
}
updateThreadCPUUse();
}
private double recentCpu(int histCheck) {
double recentCpu = 0;
int start = cpuUsageIdx - histCheck;
if (start < 0) {
start = cpuUsage.length - start;
}
for (int i = 0; i < histCheck; i++) {
int idx = (start + i) % cpuUsage.length;
recentCpu += cpuUsage[idx];
}
return recentCpu / histCheck;
}
@Override
public String getState() {
int idx = cpuUsageIdx-1;
if (idx < 0) {
idx = cpuUsage.length-1;
}
NumberFormat formd = NumberFormat.getNumberInstance();
formd.setMaximumFractionDigits(4);
return "Current CPU usage is: " + format.format(cpuUsage[idx]) +
"%, Last minute CPU usage is: " + format.format(recentCpu(6)) +
"%, Load average is: " + formd.format(loadAverage[idx]) + "\n";
}
@Override
public void destroy() {
// Nothing to destroy
}
private static final String CPU_MON = "cpu-mon";
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(CPU_MON, "Deadlocked threads no", deadLockedThreadsNo, Level.INFO);
List<ThreadData> sorted = sortThreadCPUUse();
if (sorted.size() > 0) {
ThreadData td = sorted.get(0);
list.add(CPU_MON, "1st max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.INFO);
}
if (sorted.size() > 1) {
ThreadData td = sorted.get(1);
list.add(CPU_MON, "2nd max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.FINE);
}
if (sorted.size() > 2) {
ThreadData td = sorted.get(2);
list.add(CPU_MON, "3rd max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.FINE);
}
if (sorted.size() > 3) {
ThreadData td = sorted.get(3);
list.add(CPU_MON, "4th max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.FINER);
}
if (sorted.size() > 4) {
ThreadData td = sorted.get(4);
list.add(CPU_MON, "5th max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.FINER);
}
if (sorted.size() > 5) {
ThreadData td = sorted.get(5);
list.add(CPU_MON, "6th max CPU thread",
td.name + ": " + format.format(td.cpuUse) + "%", Level.FINEST);
}
}
public float calcCPUUse(long prevUptime, long currUptime, long prevCputime,
long currCputime, int cpus) {
long elapsedTime = currUptime - prevUptime;
long elapsedCpu = currCputime - prevCputime;
return Math.min(99.99F, elapsedCpu / (elapsedTime * 10000F * cpus));
}
private void updateThreadCPUUse() {
long currUptime = TigaseRuntime.getTigaseRuntime().getUptime();
long[] allIds = thBean.getAllThreadIds();
for (long l : allIds) {
ThreadData td = threads.get(l);
if (td == null) {
ThreadInfo ti = thBean.getThreadInfo(l);
if (ti != null) {
td = new ThreadData();
td.id = l;
td.name = ti.getThreadName();
td.prevCputime = thBean.getThreadCpuTime(l);
td.prevUptime = currUptime;
threads.put(l, td);
} else {
log.finer("ThreadInfo null for thread: " + l);
}
} else {
long currCputime = thBean.getThreadCpuTime(l);
if ((currCputime) > 0) {
td.cpuUse = calcCPUUse(td.prevUptime, currUptime, td.prevCputime,
currCputime, 1);
// System.out.println(td.name + " - td.prevUptime: " + td.prevUptime +
// ", currUptime: " + currUptime +
// ", td.prevCputime: " + td.prevCputime +
// ", currCputime: " + currCputime +
// ", td.cpuUse: " + td.cpuUse);
}
td.prevCputime = currCputime;
td.prevUptime = currUptime;
}
}
}
private class ThreadData {
long id = 0;
String name = "";
float cpuUse = 0F;
long prevUptime = 0;
long prevCputime = 0;
}
}
| agpl-3.0 |
darksideprogramming/LineFit | LineFit WS/LineFit/src/linefit/SpreadSheetAdapter.java | 9763 | /* Copyright (C) 2013 Covenant College Physics Department
*
* 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 License for more details.
*
* You should have received a copy of the GNU Affero General License along with this program. If not, see
* http://www.gnu.org/licenses/. */
package linefit;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
// Maybe add mouse functionality like in:
// http://stackoverflow.com/questions/22622973/jtable-copy-and-paste-using-clipboard-and-abstractaction
/** ExcelAdapter enables Copy-Paste Clipboard functionality on JTables. The clipboard data format used by the adapter is
* compatible with the clipboard format used by Excel. This provides for clipboard interoperability between enabled
* JTables and Excel.
*
* This code is based on the ExcelAdapter from JavaWorld and is used per their (IDG) copyright policy as of 2015 and has
* since been modified by Covenant College Students to work with other platforms
*
* http://www.javaworld.com/article/2077579/learn-java/java-tip-77--enable-copy-and-paste-functionality-between-swing-s-jtables-and-excel.html
*
* Allowed use of source code from http://www.javaworld.com/about/copyright.html on 2/16/2015 copied below for
* convenience: Permissions Content derived from JavaWorld may be reproduced in print or displayed online and
* distributed, for free, in limited quantities for nonprofit, educational purposes with proper attribution. IDG retains
* the copyright for any such use. Any use of whole or partial JavaWorld content intended to endorse a product or for
* other commercial use must be approved by a JavaWorld editor. Requests will be acted on quickly. For any commercial
* reproduction of JavaWorld content, print or online, you must purchase a reprint.
*
* @author Ashok Banerjee, Jignesh Mehta and Keith Rice
* @version 1.1
* @since <0.98.0 */
public class SpreadSheetAdapter implements ActionListener
{
private Clipboard clipboard;
private JTable tableActedOn;
/** Creates the Adapter based on the JTable that it listens to in order to add copy, paste, etc. functionalities too
*
* @param tableToListenOn The table that this will listen to */
public SpreadSheetAdapter(JTable tableToListenOn)
{
tableActedOn = tableToListenOn;
// Set up the keystrokes to use for the commands so it activates the listener
KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
false);
KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
false);
KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
false);
KeyStroke selectAll = KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask(), false);
KeyStroke delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false);
// Now register them to the listener
tableActedOn.registerKeyboardAction(this, "copy", copy, JComponent.WHEN_FOCUSED);
tableActedOn.registerKeyboardAction(this, "cut", cut, JComponent.WHEN_FOCUSED);
tableActedOn.registerKeyboardAction(this, "paste", paste, JComponent.WHEN_FOCUSED);
tableActedOn.registerKeyboardAction(this, "all", selectAll, JComponent.WHEN_FOCUSED);
tableActedOn.registerKeyboardAction(this, "delete", delete, JComponent.WHEN_FOCUSED);
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
/** Copies the data so that it is in the standard spreadsheet format */
public void copy()
{
// Check to ensure we have selected only a contiguous block of cells
int numberOfColumns = tableActedOn.getSelectedColumnCount();
int numberOfRows = tableActedOn.getSelectedRowCount();
int[] rowsselected = tableActedOn.getSelectedRows();
int[] colsselected = tableActedOn.getSelectedColumns();
if (!((numberOfRows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] &&
numberOfRows == rowsselected.length) && (numberOfColumns - 1 == colsselected[colsselected.length - 1] -
colsselected[0] && numberOfColumns == colsselected.length)))
{
JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection",
JOptionPane.ERROR_MESSAGE);
return;
}
StringBuffer copiedCellsAsStrings = new StringBuffer();
for (int currentRow = 0; currentRow < numberOfRows; currentRow++)
{
for (int currentColumn = 0; currentColumn < numberOfColumns; currentColumn++)
{
copiedCellsAsStrings.append(tableActedOn.getValueAt(rowsselected[currentRow],
colsselected[currentColumn]));
if (currentColumn < numberOfColumns - 1)
{
copiedCellsAsStrings.append("\t");
}
}
copiedCellsAsStrings.append("\n");
}
StringSelection selectedCellsAsString = new StringSelection(copiedCellsAsStrings.toString());
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selectedCellsAsString, selectedCellsAsString);
}
/** Pastes the data from our clipboard into our table */
public void paste()
{
int startRow = (tableActedOn.getSelectedRows())[0];
int startCol = (tableActedOn.getSelectedColumns())[0];
try
{
String trstring = (String) (clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor));
System.out.println("String is:\n" + trstring);
String newLine;
if (CheckOS.isMacOSX())
{
newLine = "\r\n";
}
else
{
newLine = "\n";
}
StringTokenizer st1 = new StringTokenizer(trstring, newLine);
boolean firstTime = true;
for (int i = 0; st1.hasMoreTokens(); i++)
{
String rowstring = st1.nextToken();
System.out.println("String at row " + i + " is " + rowstring);
StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
for (int j = 0; st2.hasMoreTokens(); j++)
{
String value = (String) st2.nextToken();
int sRi = startRow + i, sCj = startCol + j; // debugging
System.out.println("String at row " + sRi + " and column " + sCj + " is " + value);
// we keep track of the first value because it does wonky things on macs and wont take it
if (firstTime)
{
if (startRow != 0 && startCol != 0)
{
tableActedOn.editCellAt(0, 0);
}
else
{
tableActedOn.editCellAt(1, 1);
}
}
if (startRow + i < tableActedOn.getRowCount() && startCol + j < tableActedOn.getColumnCount())
{
tableActedOn.setValueAt(value, startRow + i, startCol + j);
}
if (firstTime)
{
tableActedOn.editCellAt(startRow, startCol);
firstTime = false;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/** Deletes all the selected data and sets it to null so we don't read it as data */
public void delete()
{
int rows[] = tableActedOn.getSelectedRows();
int columns[] = tableActedOn.getSelectedColumns();
for (int i = 0; i < rows.length; i++)
{
for (int j = 0; j < columns.length; j++)
{
tableActedOn.setValueAt(null, rows[i], columns[j]);
}
}
}
/** The action listener that is triggered when one of our defined keystrokes are pressed which then calls an
* appropriate function to do the work */
public void actionPerformed(ActionEvent e)
{
switch (e.getActionCommand())
{
case "copy":
copy();
break;
case "cut":
{
copy();
delete();
break;
}
case "paste":
paste();
break;
case "all":
tableActedOn.selectAll();
break;
case "delete":
delete();
break;
}
}
}
| agpl-3.0 |
clintonhealthaccess/lmis-moz-mobile | app/src/main/java/org/openlmis/core/view/fragment/BaseReportFragment.java | 3097 | package org.openlmis.core.view.fragment;
import android.os.Bundle;
import org.openlmis.core.R;
import org.openlmis.core.presenter.BaseReportPresenter;
import org.openlmis.core.presenter.Presenter;
import org.openlmis.core.view.widget.ActionPanelView;
import org.openlmis.core.view.widget.SignatureDialog;
import roboguice.inject.InjectView;
import rx.Subscription;
import rx.functions.Action1;
public abstract class BaseReportFragment extends BaseFragment {
@InjectView(R.id.action_panel)
ActionPanelView actionPanelView;
BaseReportPresenter presenter;
protected abstract BaseReportPresenter injectPresenter();
@Override
public Presenter initPresenter() {
return presenter;
}
@Override
public void onCreate(Bundle savedInstanceState) {
presenter = injectPresenter();
super.onCreate(savedInstanceState);
}
protected void finish() {
getActivity().finish();
}
public void onBackPressed() {
if (presenter.isDraft()) {
showConfirmDialog();
} else {
finish();
}
}
private void showConfirmDialog() {
SimpleDialogFragment dialogFragment = SimpleDialogFragment.newInstance(
null,
getString(R.string.msg_back_confirm),
getString(R.string.btn_positive),
getString(R.string.btn_negative),
"back_confirm_dialog");
dialogFragment.show(getActivity().getFragmentManager(), "back_confirm_dialog");
dialogFragment.setCallBackListener(new SimpleDialogFragment.MsgDialogCallBack() {
@Override
public void positiveClick(String tag) {
presenter.deleteDraft();
finish();
}
@Override
public void negativeClick(String tag) {
}
});
}
public void showSignDialog() {
SignatureDialog signatureDialog = new SignatureDialog();
String signatureDialogTitle = getSignatureDialogTitle();
signatureDialog.setArguments(SignatureDialog.getBundleToMe(signatureDialogTitle));
signatureDialog.setDelegate(signatureDialogDelegate);
signatureDialog.show(this.getFragmentManager());
}
protected abstract String getSignatureDialogTitle();
protected SignatureDialog.DialogDelegate signatureDialogDelegate = new SignatureDialog.DialogDelegate() {
public void onSign(String sign) {
Subscription subscription = presenter.getOnSignObservable(sign).subscribe(getOnSignedAction());
subscriptions.add(subscription);
}
};
protected abstract Action1<? super Void> getOnSignedAction();
public void showMessageNotifyDialog() {
SimpleDialogFragment notifyDialog = SimpleDialogFragment.newInstance(null,
getNotifyDialogMsg(), null, getString(R.string.btn_continue), "showMessageNotifyDialog");
notifyDialog.show(getActivity().getFragmentManager(), "showMessageNotifyDialog");
}
protected abstract String getNotifyDialogMsg();
}
| agpl-3.0 |
cm-is-dog/rapidminer-studio-core | src/main/java/com/rapidminer/operator/EnabledOperatorView.java | 2538 | /**
* 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.operator;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
/**
* An unmodifyable view of a collection of Operators that hides disabled operators.
*
* @author Simon Fischer
*/
public class EnabledOperatorView extends AbstractList<Operator> {
private Collection<Operator> base;
/**
* Instantiates a new Enabled operator view.
*
* @param base the base
*/
public EnabledOperatorView(Collection<Operator> base) {
super();
this.base = base;
}
@Override
public Iterator<Operator> iterator() {
return new Iterator<Operator>() {
private Operator next;
private Iterator<Operator> baseIterator = base.iterator();
@Override
public boolean hasNext() {
if (next != null) {
return true;
}
while (baseIterator.hasNext()) {
next = baseIterator.next();
if (next.isEnabled()) {
return true;
}
}
next = null;
return false;
}
@Override
public Operator next() {
hasNext();
Operator result = next;
next = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Unmodifyable view!");
}
};
}
@Override
public int size() {
int size = 0;
Iterator<Operator> i = iterator();
while (i.hasNext()) {
i.next();
size++;
}
return size;
}
@Override
public Operator get(int index) {
int n = 0;
Iterator<Operator> i = iterator();
while (i.hasNext()) {
Operator next = i.next();
if (n == index) {
return next;
}
n++;
}
return null;
}
}
| agpl-3.0 |
Skelril/Aurora | src/main/java/com/skelril/aurora/economic/store/ItemPricePair.java | 2113 | /*
* Copyright (c) 2014 Wyatt Childers.
*
* This file is part of Aurora.
*
* Aurora 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.
*
* Aurora 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 Aurora. If not, see <http://www.gnu.org/licenses/>.
*/
package com.skelril.aurora.economic.store;
public class ItemPricePair implements Comparable<ItemPricePair> {
private String name;
private double price;
private boolean disableBuy, disableSell;
public ItemPricePair(String name, double price, boolean disableBuy, boolean disableSell) {
this.name = name;
this.price = price;
this.disableBuy = disableBuy;
this.disableSell = disableSell;
}
public String getName() {
return name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public double getSellPrice() {
double sellPrice = price > 100000 ? price * .92 : price * .80;
return sellPrice < .01 ? 0 : sellPrice;
}
public boolean isEnabled() {
return isBuyable() || isSellable();
}
public boolean isBuyable() {
return !disableBuy;
}
public boolean isSellable() {
return !disableSell;
}
@Override
public int compareTo(ItemPricePair record) {
if (record == null) return -1;
if (this.getPrice() == record.getPrice()) {
int c = String.CASE_INSENSITIVE_ORDER.compare(this.getName(), record.getName());
return c == 0 ? 1 : c;
}
return this.getPrice() > record.getPrice() ? 1 : -1;
}
}
| agpl-3.0 |
diederikd/DeBrug | languages/ObjectiefRecht/source_gen/ObjectiefRecht/editor/ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.java | 49106 | package ObjectiefRecht.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import de.slisson.mps.editor.multiline.cellProviders.MultilineCellProvider;
import Datum.editor.GN_StyleSheet.NameStyleClass;
import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.openapi.editor.cells.CellActionType;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSmart;
import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo;
import jetbrains.mps.openapi.editor.menus.transformation.SNodeLocation;
import org.jetbrains.mps.openapi.language.SReferenceLink;
import jetbrains.mps.lang.editor.cellProviders.SReferenceCellProvider;
import jetbrains.mps.util.Computable;
import jetbrains.mps.editor.runtime.impl.CellUtil;
import jetbrains.mps.nodeEditor.cellMenu.SReferenceSubstituteInfo;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.AttributeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import java.util.Objects;
import jetbrains.mps.lang.core.behavior.LinkAttribute__BehaviorDescriptor;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.openapi.editor.update.AttributeKind;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo;
import jetbrains.mps.nodeEditor.cells.EditorCell_Property;
import jetbrains.mps.nodeEditor.cells.SPropertyAccessor;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteEasily;
import jetbrains.mps.nodeEditor.cellActions.CellAction_DeleteNode;
import jetbrains.mps.nodeEditor.cellMenu.SPropertySubstituteInfo;
import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSPropertyOrNode;
import Datum.editor.GN_StyleSheet.SubjectStyleClass;
import Datum.editor.GN_StyleSheet.OnderwerpStyleClass;
/*package*/ class ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_vcx8b9_a();
}
private EditorCell createCollection_vcx8b9_a() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_vcx8b9_a");
editorCell.setBig(true);
editorCell.setCellContext(getCellFactory().getCellContext());
editorCell.addEditorCell(createConstant_vcx8b9_a0());
editorCell.addEditorCell(createComponent_vcx8b9_b0());
editorCell.addEditorCell(createMultiline_vcx8b9_c0_0());
editorCell.addEditorCell(createConstant_vcx8b9_d0());
editorCell.addEditorCell(createConstant_vcx8b9_e0());
editorCell.addEditorCell(createRefNode_vcx8b9_f0());
editorCell.addEditorCell(createConstant_vcx8b9_g0());
editorCell.addEditorCell(createConstant_vcx8b9_h0());
editorCell.addEditorCell(createComponent_vcx8b9_i0());
editorCell.addEditorCell(createConstant_vcx8b9_j0());
editorCell.addEditorCell(createConstant_vcx8b9_k0());
editorCell.addEditorCell(createRefCell_vcx8b9_l0());
editorCell.addEditorCell(createConstant_vcx8b9_m0());
editorCell.addEditorCell(createConstant_vcx8b9_n0());
editorCell.addEditorCell(createRefCell_vcx8b9_o0());
editorCell.addEditorCell(createConstant_vcx8b9_p0());
editorCell.addEditorCell(createConstant_vcx8b9_q0());
editorCell.addEditorCell(createRefCell_vcx8b9_r0());
editorCell.addEditorCell(createConstant_vcx8b9_s0());
editorCell.addEditorCell(createConstant_vcx8b9_t0());
editorCell.addEditorCell(createRefCell_vcx8b9_u0());
editorCell.addEditorCell(createConstant_vcx8b9_v0());
editorCell.addEditorCell(createRefNode_vcx8b9_w0());
editorCell.addEditorCell(createConstant_vcx8b9_x0());
editorCell.addEditorCell(createConstant_vcx8b9_y0());
editorCell.addEditorCell(createConstant_vcx8b9_z0());
editorCell.addEditorCell(createConstant_vcx8b9_ab0());
editorCell.addEditorCell(createRefNode_vcx8b9_bb0());
editorCell.addEditorCell(createConstant_vcx8b9_cb0());
editorCell.addEditorCell(createConstant_vcx8b9_db0());
editorCell.addEditorCell(createRefNode_vcx8b9_eb0());
editorCell.addEditorCell(createConstant_vcx8b9_fb0());
if (nodeCondition_vcx8b9_a23a()) {
editorCell.addEditorCell(createCollection_vcx8b9_gb0());
}
editorCell.addEditorCell(createConstant_vcx8b9_hb0());
return editorCell;
}
private boolean nodeCondition_vcx8b9_a23a() {
SNode context;
context = (SNode) SNodeOperations.getParent(myNode);
return SPropertyOperations.getBoolean(context, MetaAdapterFactory.getProperty(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d02L, 0xc9f8f37229dca04L, "toonopmerkingen"));
}
private EditorCell createConstant_vcx8b9_a0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "legal relation");
editorCell.setCellId("Constant_vcx8b9_a0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createComponent_vcx8b9_b0() {
EditorCell editorCell = getCellFactory().createEditorComponentCell(myNode, "ObjectiefRecht.editor.ConceptNummer");
return editorCell;
}
private EditorCell createMultiline_vcx8b9_c0(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new MultilineCellProvider(node, editorContext);
provider.setRole("name");
provider.setNoTargetText("<no name>");
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_name");
Style style = new StyleImpl();
new NameStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
if (attributeConcept != null) {
return getUpdateSession().updateAttributeCell(provider.getRoleAttributeKind(), editorCell, attributeConcept);
} else
return editorCell;
}
private EditorCell createMultiline_vcx8b9_c0_0() {
return createMultiline_vcx8b9_c0(getEditorContext(), myNode);
}
private EditorCell createConstant_vcx8b9_d0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "source");
editorCell.setCellId("Constant_vcx8b9_d0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_e0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_e0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_vcx8b9_f0() {
SingleRoleCellProvider provider = new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.bronSingleRoleHandler_vcx8b9_f0(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x4916e0625cee85caL, "bron"), getEditorContext());
return provider.createCell();
}
private static class bronSingleRoleHandler_vcx8b9_f0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public bronSingleRoleHandler_vcx8b9_f0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x4916e0625cee85caL, "bron"), child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x4916e0625cee85caL, "bron"), child));
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo(new SChildSubstituteInfo(editorCell));
}
if (editorCell.getRole() == null) {
editorCell.setRole("bron");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x4916e0625cee85caL, "bron")));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_bron");
installCellInfo(null, editorCell);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no bron>";
}
}
private EditorCell createConstant_vcx8b9_g0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "type");
editorCell.setCellId("Constant_vcx8b9_g0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_h0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_h0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createComponent_vcx8b9_i0() {
EditorCell editorCell = getCellFactory().createEditorComponentCell(myNode, "jetbrains.mps.lang.core.editor.alias");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
return editorCell;
}
private EditorCell createConstant_vcx8b9_j0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "obligation to");
editorCell.setCellId("Constant_vcx8b9_j0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_k0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_k0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_vcx8b9_l0() {
final SReferenceLink referenceLink = MetaAdapterFactory.getReferenceLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d96L, 0x3bfdb51c6ba54be5L, "verplichtingTot");
SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) {
protected EditorCell createReferenceCell(final SNode targetNode) {
EditorCell cell = getUpdateSession().updateReferencedNodeCell(new Computable<EditorCell>() {
public EditorCell compute() {
return new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.Inline_Builder_vcx8b9_a11a(getEditorContext(), getNode(), targetNode).createCell();
}
}, targetNode, "verplichtingTot");
CellUtil.setupIDeprecatableStyles(targetNode, cell);
setSemanticNodeToCells(cell, getNode());
installDeleteActions_notnull(cell);
return cell;
}
};
provider.setNoTargetText("<no verplichtingTot>");
EditorCell editorCell = provider.createCell();
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("verplichtingTot");
}
editorCell.setSubstituteInfo(new SReferenceSubstituteInfo(editorCell, referenceLink));
Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute"));
Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink);
}
});
if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell);
} else
return editorCell;
}
/*package*/ static class Inline_Builder_vcx8b9_a11a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
private SNode myReferencingNode;
/*package*/ Inline_Builder_vcx8b9_a11a(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) {
super(context);
myReferencingNode = referencingNode;
myNode = node;
}
/*package*/ EditorCell createCell() {
return createProperty_vcx8b9_a0l0();
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
private EditorCell createProperty_vcx8b9_a0l0() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, true, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteEasily(myNode, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteEasily(myNode, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name_1");
Style style = new StyleImpl();
new NameStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
}
private EditorCell createConstant_vcx8b9_m0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "legal subject with right");
editorCell.setCellId("Constant_vcx8b9_m0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_ON_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_n0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_n0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_vcx8b9_o0() {
final SReferenceLink referenceLink = MetaAdapterFactory.getReferenceLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x611073d615228d2dL, "rechtssubjectMetRecht");
SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) {
protected EditorCell createReferenceCell(final SNode targetNode) {
EditorCell cell = getUpdateSession().updateReferencedNodeCell(new Computable<EditorCell>() {
public EditorCell compute() {
return new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.Inline_Builder_vcx8b9_a41a(getEditorContext(), getNode(), targetNode).createCell();
}
}, targetNode, "rechtssubjectMetRecht");
CellUtil.setupIDeprecatableStyles(targetNode, cell);
setSemanticNodeToCells(cell, getNode());
installDeleteActions_notnull(cell);
return cell;
}
};
provider.setNoTargetText("<no rechtssubjectMetRecht>");
EditorCell editorCell = provider.createCell();
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("rechtssubjectMetRecht");
}
editorCell.setSubstituteInfo(new SReferenceSubstituteInfo(editorCell, referenceLink));
Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute"));
Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink);
}
});
if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell);
} else
return editorCell;
}
/*package*/ static class Inline_Builder_vcx8b9_a41a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
private SNode myReferencingNode;
/*package*/ Inline_Builder_vcx8b9_a41a(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) {
super(context);
myReferencingNode = referencingNode;
myNode = node;
}
/*package*/ EditorCell createCell() {
return createProperty_vcx8b9_a0o0();
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
private EditorCell createProperty_vcx8b9_a0o0() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name_2");
Style style = new StyleImpl();
new SubjectStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
}
private EditorCell createConstant_vcx8b9_p0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "legal subject with duty");
editorCell.setCellId("Constant_vcx8b9_p0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_ON_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_q0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_q0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_vcx8b9_r0() {
final SReferenceLink referenceLink = MetaAdapterFactory.getReferenceLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x611073d615228d2eL, "rechtssubjectMetPlicht");
SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) {
protected EditorCell createReferenceCell(final SNode targetNode) {
EditorCell cell = getUpdateSession().updateReferencedNodeCell(new Computable<EditorCell>() {
public EditorCell compute() {
return new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.Inline_Builder_vcx8b9_a71a(getEditorContext(), getNode(), targetNode).createCell();
}
}, targetNode, "rechtssubjectMetPlicht");
CellUtil.setupIDeprecatableStyles(targetNode, cell);
setSemanticNodeToCells(cell, getNode());
installDeleteActions_notnull(cell);
return cell;
}
};
provider.setNoTargetText("<no rechtssubjectMetPlicht>");
EditorCell editorCell = provider.createCell();
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("rechtssubjectMetPlicht");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SReferenceSubstituteInfo(editorCell, referenceLink));
Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute"));
Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink);
}
});
if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell);
} else
return editorCell;
}
/*package*/ static class Inline_Builder_vcx8b9_a71a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
private SNode myReferencingNode;
/*package*/ Inline_Builder_vcx8b9_a71a(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) {
super(context);
myReferencingNode = referencingNode;
myNode = node;
}
/*package*/ EditorCell createCell() {
return createProperty_vcx8b9_a0r0();
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
private EditorCell createProperty_vcx8b9_a0r0() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name_3");
Style style = new StyleImpl();
new SubjectStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
}
private EditorCell createConstant_vcx8b9_s0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "subject matter");
editorCell.setCellId("Constant_vcx8b9_s0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_ON_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_t0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_t0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefCell_vcx8b9_u0() {
final SReferenceLink referenceLink = MetaAdapterFactory.getReferenceLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x218d2fe3c8aff5f6L, "onderwerp");
SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) {
protected EditorCell createReferenceCell(final SNode targetNode) {
EditorCell cell = getUpdateSession().updateReferencedNodeCell(new Computable<EditorCell>() {
public EditorCell compute() {
return new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.Inline_Builder_vcx8b9_a02a(getEditorContext(), getNode(), targetNode).createCell();
}
}, targetNode, "onderwerp");
CellUtil.setupIDeprecatableStyles(targetNode, cell);
setSemanticNodeToCells(cell, getNode());
installDeleteActions_notnull(cell);
return cell;
}
};
provider.setNoTargetText("<no onderwerp>");
EditorCell editorCell = provider.createCell();
if (editorCell.getRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setRole("onderwerp");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SReferenceSubstituteInfo(editorCell, referenceLink));
Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute"));
Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink);
}
});
if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell);
} else
return editorCell;
}
/*package*/ static class Inline_Builder_vcx8b9_a02a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
private SNode myReferencingNode;
/*package*/ Inline_Builder_vcx8b9_a02a(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) {
super(context);
myReferencingNode = referencingNode;
myNode = node;
}
/*package*/ EditorCell createCell() {
return createProperty_vcx8b9_a0u0();
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
private EditorCell createProperty_vcx8b9_a0u0() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name_4");
Style style = new StyleImpl();
new OnderwerpStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
}
private EditorCell createConstant_vcx8b9_v0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_vcx8b9_v0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_vcx8b9_w0() {
SingleRoleCellProvider provider = new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.voorwaardenSingleRoleHandler_vcx8b9_w0(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x25be3715c7b32639L, "voorwaarden"), getEditorContext());
return provider.createCell();
}
private static class voorwaardenSingleRoleHandler_vcx8b9_w0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public voorwaardenSingleRoleHandler_vcx8b9_w0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x25be3715c7b32639L, "voorwaarden"), child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x25be3715c7b32639L, "voorwaarden"), child));
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo(new SChildSubstituteInfo(editorCell));
}
if (editorCell.getRole() == null) {
editorCell.setRole("voorwaarden");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
style.set(StyleAttributes.INDENT_LAYOUT_ON_NEW_LINE, true);
editorCell.getStyle().putAll(style);
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x25be3715c7b32639L, "voorwaarden")));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_voorwaarden");
installCellInfo(null, editorCell);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no voorwaarden>";
}
}
private EditorCell createConstant_vcx8b9_x0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_vcx8b9_x0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_y0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_vcx8b9_y0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_z0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "valid from");
editorCell.setCellId("Constant_vcx8b9_z0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_ab0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_ab0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_vcx8b9_bb0() {
SingleRoleCellProvider provider = new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.GeldigVanSingleRoleHandler_vcx8b9_bb0(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c109781917eL, "GeldigVan"), getEditorContext());
return provider.createCell();
}
private static class GeldigVanSingleRoleHandler_vcx8b9_bb0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public GeldigVanSingleRoleHandler_vcx8b9_bb0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c109781917eL, "GeldigVan"), child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c109781917eL, "GeldigVan"), child));
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo(new SChildSubstituteInfo(editorCell));
}
if (editorCell.getRole() == null) {
editorCell.setRole("GeldigVan");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c109781917eL, "GeldigVan")));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_GeldigVan");
installCellInfo(null, editorCell);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no GeldigVan>";
}
}
private EditorCell createConstant_vcx8b9_cb0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "valid to");
editorCell.setCellId("Constant_vcx8b9_cb0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_db0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_db0");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_vcx8b9_eb0() {
SingleRoleCellProvider provider = new ZwakkeAanspraakZwakkePlicht_EN_EditorBuilder_a.GeldigTotSingleRoleHandler_vcx8b9_eb0(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c1097819187L, "GeldigTot"), getEditorContext());
return provider.createCell();
}
private static class GeldigTotSingleRoleHandler_vcx8b9_eb0 extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public GeldigTotSingleRoleHandler_vcx8b9_eb0(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c1097819187L, "GeldigTot"), child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c1097819187L, "GeldigTot"), child));
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo(new SChildSubstituteInfo(editorCell));
}
if (editorCell.getRole() == null) {
editorCell.setRole("GeldigTot");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0dL, 0x3b480c1097819187L, "GeldigTot")));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_GeldigTot");
installCellInfo(null, editorCell);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no GeldigTot>";
}
}
private EditorCell createConstant_vcx8b9_fb0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_vcx8b9_fb0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createCollection_vcx8b9_gb0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_vcx8b9_gb0");
editorCell.addEditorCell(createConstant_vcx8b9_a23a());
editorCell.addEditorCell(createConstant_vcx8b9_b23a());
editorCell.addEditorCell(createMultiline_vcx8b9_c23a_0());
return editorCell;
}
private EditorCell createConstant_vcx8b9_a23a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "comments");
editorCell.setCellId("Constant_vcx8b9_a23a");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_vcx8b9_b23a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, ":");
editorCell.setCellId("Constant_vcx8b9_b23a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createMultiline_vcx8b9_c23a(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new MultilineCellProvider(node, editorContext);
provider.setRole("opmerkingen");
provider.setNoTargetText("<no opmerkingen>");
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_opmerkingen");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
if (attributeConcept != null) {
return getUpdateSession().updateAttributeCell(provider.getRoleAttributeKind(), editorCell, attributeConcept);
} else
return editorCell;
}
private EditorCell createMultiline_vcx8b9_c23a_0() {
return createMultiline_vcx8b9_c23a(getEditorContext(), myNode);
}
private EditorCell createConstant_vcx8b9_hb0() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_vcx8b9_hb0");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
}
| agpl-3.0 |
RestComm/jss7 | tools/simulator/gui/src/main/java/org/restcomm/protocols/ss7/tools/simulatorgui/TestingForm.java | 14133 | /*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* 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.tools.simulatorgui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.util.Vector;
import javax.management.Notification;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import org.restcomm.protocols.ss7.tools.simulator.management.TesterHostInterface;
import org.restcomm.protocols.ss7.tools.simulator.management.TesterHostMBean;
/**
*
* @author sergey vetyutnev
*
*/
public class TestingForm extends JDialog {
private static final long serialVersionUID = -3725574796168603069L;
private DefaultTableModel model = new DefaultTableModel();
private EventForm eventForm;
private SimulatorGuiForm mainForm;
private javax.swing.Timer tm;
private JPanel panel;
protected TesterHostMBean host;
private JTextField tbL1State;
private JTable tNotif;
private JButton btStart;
private JButton btStop;
private JButton btRefresh;
private JPanel panel_b;
protected JPanel panel_c;
private JPanel panel_a_1;
private JLabel lblLState_1;
private JPanel panel_a_but;
private JPanel panel_a;
private JScrollPane scrollPane;
private JLabel lblLState;
private JTextField tbL2State;
private JLabel lblLState_2;
private JTextField tbL3State;
private JLabel lblTestingState;
private JLabel lbTestState;
private JButton btnOpenEventWindow;
private JPanel panel_1;
private JPanel panel_2;
private JPanel panel_3;
public TestingForm(JFrame owner) {
super(owner, true);
setModal(false);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (getDefaultCloseOperation() == JDialog.DO_NOTHING_ON_CLOSE) {
JOptionPane.showMessageDialog(getJFrame(), "Before exiting you must Stop the testing process");
} else {
closingWindow();
}
}
});
setBounds(100, 100, 772, 677);
panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 1, 0, 0));
panel_a = new JPanel();
panel.add(panel_a);
panel_a.setLayout(new BorderLayout(0, 0));
panel_a_1 = new JPanel();
panel_a.add(panel_a_1);
panel_a_1.setLayout(new BoxLayout(panel_a_1, BoxLayout.Y_AXIS));
panel_2 = new JPanel();
panel_a_1.add(panel_2);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[] { 0, 0, 0 };
gbl_panel_2.rowHeights = new int[] { 0, 0, 0, 0 };
gbl_panel_2.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
gbl_panel_2.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
panel_2.setLayout(gbl_panel_2);
lblLState_1 = new JLabel("L1 state");
GridBagConstraints gbc_lblLState_1 = new GridBagConstraints();
gbc_lblLState_1.insets = new Insets(0, 0, 5, 5);
gbc_lblLState_1.gridx = 0;
gbc_lblLState_1.gridy = 0;
panel_2.add(lblLState_1, gbc_lblLState_1);
tbL1State = new JTextField();
GridBagConstraints gbc_tbL1State = new GridBagConstraints();
gbc_tbL1State.fill = GridBagConstraints.HORIZONTAL;
gbc_tbL1State.insets = new Insets(0, 0, 5, 0);
gbc_tbL1State.gridx = 1;
gbc_tbL1State.gridy = 0;
panel_2.add(tbL1State, gbc_tbL1State);
tbL1State.setMinimumSize(new Dimension(100, 20));
tbL1State.setPreferredSize(new Dimension(400, 20));
tbL1State.setEditable(false);
tbL1State.setColumns(10);
lblLState = new JLabel("L2 state");
GridBagConstraints gbc_lblLState = new GridBagConstraints();
gbc_lblLState.insets = new Insets(0, 0, 5, 5);
gbc_lblLState.gridx = 0;
gbc_lblLState.gridy = 1;
panel_2.add(lblLState, gbc_lblLState);
tbL2State = new JTextField();
GridBagConstraints gbc_tbL2State = new GridBagConstraints();
gbc_tbL2State.fill = GridBagConstraints.HORIZONTAL;
gbc_tbL2State.insets = new Insets(0, 0, 5, 0);
gbc_tbL2State.gridx = 1;
gbc_tbL2State.gridy = 1;
panel_2.add(tbL2State, gbc_tbL2State);
tbL2State.setPreferredSize(new Dimension(400, 20));
tbL2State.setMinimumSize(new Dimension(100, 20));
tbL2State.setEditable(false);
tbL2State.setColumns(10);
lblLState_2 = new JLabel("L3 state");
GridBagConstraints gbc_lblLState_2 = new GridBagConstraints();
gbc_lblLState_2.insets = new Insets(0, 0, 0, 5);
gbc_lblLState_2.gridx = 0;
gbc_lblLState_2.gridy = 2;
panel_2.add(lblLState_2, gbc_lblLState_2);
tbL3State = new JTextField();
GridBagConstraints gbc_tbL3State = new GridBagConstraints();
gbc_tbL3State.fill = GridBagConstraints.HORIZONTAL;
gbc_tbL3State.gridx = 1;
gbc_tbL3State.gridy = 2;
panel_2.add(tbL3State, gbc_tbL3State);
tbL3State.setPreferredSize(new Dimension(400, 20));
tbL3State.setMinimumSize(new Dimension(100, 20));
tbL3State.setEditable(false);
tbL3State.setColumns(10);
panel_3 = new JPanel();
panel_a_1.add(panel_3);
GridBagLayout gbl_panel_3 = new GridBagLayout();
gbl_panel_3.columnWidths = new int[] { 0, 0, 0 };
gbl_panel_3.rowHeights = new int[] { 0, 0 };
gbl_panel_3.columnWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
gbl_panel_3.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
panel_3.setLayout(gbl_panel_3);
lblTestingState = new JLabel("Testing state");
GridBagConstraints gbc_lblTestingState = new GridBagConstraints();
gbc_lblTestingState.insets = new Insets(0, 0, 0, 5);
gbc_lblTestingState.gridx = 0;
gbc_lblTestingState.gridy = 0;
panel_3.add(lblTestingState, gbc_lblTestingState);
lbTestState = new JLabel("-");
GridBagConstraints gbc_lbTestState = new GridBagConstraints();
gbc_lbTestState.gridx = 1;
gbc_lbTestState.gridy = 0;
panel_3.add(lbTestState, gbc_lbTestState);
panel_a_but = new JPanel();
panel_a.add(panel_a_but, BorderLayout.SOUTH);
btStart = new JButton("Start");
panel_a_but.add(btStart);
btStop = new JButton("Stop");
panel_a_but.add(btStop);
btStop.setEnabled(false);
btRefresh = new JButton("Refresh state");
panel_a_but.add(btRefresh);
btnOpenEventWindow = new JButton("Open event window");
btnOpenEventWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openEventWindow();
}
});
panel_a_but.add(btnOpenEventWindow);
btRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
refreshState();
}
});
btStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
host.stop();
} catch (Throwable e1) {
JOptionPane.showMessageDialog(getJFrame(), "Exception: " + e1.toString());
}
btStart.setEnabled(true);
btStop.setEnabled(false);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
});
btStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btStart.setEnabled(false);
btStop.setEnabled(true);
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
try {
host.start();
} catch (Throwable e1) {
JOptionPane.showMessageDialog(getJFrame(), "Exception: " + e1.toString());
}
}
});
panel_b = new JPanel();
panel.add(panel_b);
panel_b.setLayout(new GridLayout(1, 1, 0, 0));
tNotif = new JTable();
tNotif.setFillsViewportHeight(true);
tNotif.setBorder(new LineBorder(new Color(0, 0, 0)));
tNotif.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tNotif.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "TimeStamp", "Source", "Message", "UserData" }) {
Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class };
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
boolean[] columnEditables = new boolean[] { false, false, false, false };
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
tNotif.getColumnModel().getColumn(0).setPreferredWidth(46);
tNotif.getColumnModel().getColumn(1).setPreferredWidth(89);
tNotif.getColumnModel().getColumn(2).setPreferredWidth(221);
tNotif.getColumnModel().getColumn(3).setPreferredWidth(254);
scrollPane = new JScrollPane(tNotif);
panel_b.add(scrollPane);
model = (DefaultTableModel) tNotif.getModel();
tNotif.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
if (eventForm == null)
return;
// ����� ������� ������ �������
setEventMsg();
}
});
panel_c = new JPanel();
panel.add(panel_c);
panel_c.setLayout(new BorderLayout(0, 0));
panel_1 = new JPanel();
panel_c.add(panel_1, BorderLayout.CENTER);
}
private void setEventMsg() {
ListSelectionModel l = tNotif.getSelectionModel();
if (!l.isSelectionEmpty()) {
int index = l.getMinSelectionIndex();
String s1 = (String) model.getValueAt(index, 0);
String s2 = (String) model.getValueAt(index, 1);
String s3 = (String) model.getValueAt(index, 2);
String s4 = (String) model.getValueAt(index, 3);
eventForm.setData(s1, s2, s3, s4);
}
}
public void setData(SimulatorGuiForm mainForm, final TesterHostMBean host) {
this.host = host;
this.mainForm = mainForm;
this.tm = new javax.swing.Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
refreshState();
}
});
this.tm.start();
}
private JDialog getJFrame() {
return this;
}
public void refreshState() {
// if (this.host instanceof TesterHostImpl) {
// TesterHostImpl thost = (TesterHostImpl)host;
// thost.execute();
// }
if (this.host instanceof TesterHostInterface) {
TesterHostInterface thost = (TesterHostInterface) host;
thost.execute();
}
tbL1State.setText(this.host.getL1State());
tbL2State.setText(this.host.getL2State());
tbL3State.setText(this.host.getL3State());
lbTestState.setText(this.host.getTestTaskState());
}
public void sendNotif(Notification notif) {
Date d1 = new Date(notif.getTimeStamp());
String s1 = d1.toLocaleString();
Vector newRow = new Vector();
newRow.add(s1);
newRow.add(notif.getType());
newRow.add(notif.getMessage());
newRow.add(notif.getUserData());
model.getDataVector().add(0, newRow);
model.newRowsAdded(new TableModelEvent(model));
}
public void eventFormClose() {
this.eventForm = null;
}
private void openEventWindow() {
if (this.eventForm != null)
return;
this.eventForm = new EventForm(this);
this.eventForm.setVisible(true);
setEventMsg();
}
private void closingWindow() {
this.mainForm.testingFormClose();
}
}
| agpl-3.0 |
camunda/camunda-bpm-workbench | api/debug-service-websocket/src/main/java/org/camunda/bpm/debugger/server/protocol/dto/ProcessDefinitionDto.java | 2108 | /* Licensed under the Apache License, Version 2.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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.debugger.server.protocol.dto;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.repository.ProcessDefinition;
/**
* @author Daniel Meyer
*
*/
public class ProcessDefinitionDto {
protected String id;
protected String key;
protected String name;
protected int version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) {
ProcessDefinitionDto processDefinitionDto = new ProcessDefinitionDto();
processDefinitionDto.setId(definition.getId());
processDefinitionDto.setKey(definition.getKey());
processDefinitionDto.setName(definition.getName());
processDefinitionDto.setVersion(definition.getVersion());
return processDefinitionDto;
}
public static List<ProcessDefinitionDto> fromList(List<ProcessDefinition> definition) {
List<ProcessDefinitionDto> resultList = new ArrayList<ProcessDefinitionDto>();
for (ProcessDefinition processDefinition : definition) {
resultList.add(fromProcessDefinition(processDefinition));
}
return resultList;
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcLightFixture.java | 3937 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* 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.bimserver.models.ifc4;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* 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 {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public interface IfcLightFixture extends IfcFlowTerminal {
/**
* Returns the value of the '<em><b>Predefined Type</b></em>' attribute.
* The literals are from the enumeration {@link org.bimserver.models.ifc4.IfcLightFixtureTypeEnum}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Predefined Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Predefined Type</em>' attribute.
* @see org.bimserver.models.ifc4.IfcLightFixtureTypeEnum
* @see #isSetPredefinedType()
* @see #unsetPredefinedType()
* @see #setPredefinedType(IfcLightFixtureTypeEnum)
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcLightFixture_PredefinedType()
* @model unsettable="true"
* @generated
*/
IfcLightFixtureTypeEnum getPredefinedType();
/**
* Sets the value of the '{@link org.bimserver.models.ifc4.IfcLightFixture#getPredefinedType <em>Predefined Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Predefined Type</em>' attribute.
* @see org.bimserver.models.ifc4.IfcLightFixtureTypeEnum
* @see #isSetPredefinedType()
* @see #unsetPredefinedType()
* @see #getPredefinedType()
* @generated
*/
void setPredefinedType(IfcLightFixtureTypeEnum value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc4.IfcLightFixture#getPredefinedType <em>Predefined Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetPredefinedType()
* @see #getPredefinedType()
* @see #setPredefinedType(IfcLightFixtureTypeEnum)
* @generated
*/
void unsetPredefinedType();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc4.IfcLightFixture#getPredefinedType <em>Predefined Type</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Predefined Type</em>' attribute is set.
* @see #unsetPredefinedType()
* @see #getPredefinedType()
* @see #setPredefinedType(IfcLightFixtureTypeEnum)
* @generated
*/
boolean isSetPredefinedType();
} // IfcLightFixture
| agpl-3.0 |
TheLanguageArchive/FLAP | core/src/main/java/nl/mpi/flap/plugin/PluginArbilTable.java | 956 | /*
* Copyright (C) 2012 Max Planck Institute for Psycholinguistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.flap.plugin;
/**
* Created on : Nov 7, 2012, 3:42:54 PM
*
* @author Peter Withers <peter.withers@mpi.nl>
*/
public interface PluginArbilTable {
}
| agpl-3.0 |
rkfg/jbot | src/main/java/me/rkfg/xmpp/bot/plugins/doto/json/Player2.java | 7606 | package me.rkfg.xmpp.bot.plugins.doto.json;
import com.fasterxml.jackson.annotation.*;
import java.util.HashMap;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"player_slot",
"account_id",
"hero_id",
"kills",
"death",
"assists",
"last_hits",
"denies",
"gold",
"level",
"gold_per_min",
"xp_per_min",
"ultimate_state",
"ultimate_cooldown",
"item0",
"item1",
"item2",
"item3",
"item4",
"item5",
"respawn_timer",
"position_x",
"position_y",
"net_worth"
})
public class Player2 {
@JsonProperty("player_slot")
private Integer playerSlot;
@JsonProperty("account_id")
private String accountId;
@JsonProperty("hero_id")
private String heroId;
@JsonProperty("kills")
private Integer kills;
@JsonProperty("death")
private Integer death;
@JsonProperty("assists")
private Integer assists;
@JsonProperty("last_hits")
private Integer lastHits;
@JsonProperty("denies")
private Integer denies;
@JsonProperty("gold")
private Integer gold;
@JsonProperty("level")
private Integer level;
@JsonProperty("gold_per_min")
private Integer goldPerMin;
@JsonProperty("xp_per_min")
private Integer xpPerMin;
@JsonProperty("ultimate_state")
private Integer ultimateState;
@JsonProperty("ultimate_cooldown")
private Integer ultimateCooldown;
@JsonProperty("item0")
private Integer item0;
@JsonProperty("item1")
private Integer item1;
@JsonProperty("item2")
private Integer item2;
@JsonProperty("item3")
private Integer item3;
@JsonProperty("item4")
private Integer item4;
@JsonProperty("item5")
private Integer item5;
@JsonProperty("respawn_timer")
private Integer respawnTimer;
@JsonProperty("position_x")
private Double positionX;
@JsonProperty("position_y")
private Double positionY;
@JsonProperty("net_worth")
private Integer netWorth;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<>();
@JsonProperty("player_slot")
public Integer getPlayerSlot() {
return playerSlot;
}
@JsonProperty("player_slot")
public void setPlayerSlot(Integer playerSlot) {
this.playerSlot = playerSlot;
}
@JsonProperty("account_id")
public String getAccountId() {
return accountId;
}
@JsonProperty("account_id")
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@JsonProperty("hero_id")
public String getHeroId() {
return heroId;
}
@JsonProperty("hero_id")
public void setHeroId(String heroId) {
this.heroId = heroId;
}
@JsonProperty("kills")
public Integer getKills() {
return kills;
}
@JsonProperty("kills")
public void setKills(Integer kills) {
this.kills = kills;
}
@JsonProperty("death")
public Integer getDeath() {
return death;
}
@JsonProperty("death")
public void setDeath(Integer death) {
this.death = death;
}
@JsonProperty("assists")
public Integer getAssists() {
return assists;
}
@JsonProperty("assists")
public void setAssists(Integer assists) {
this.assists = assists;
}
@JsonProperty("last_hits")
public Integer getLastHits() {
return lastHits;
}
@JsonProperty("last_hits")
public void setLastHits(Integer lastHits) {
this.lastHits = lastHits;
}
@JsonProperty("denies")
public Integer getDenies() {
return denies;
}
@JsonProperty("denies")
public void setDenies(Integer denies) {
this.denies = denies;
}
@JsonProperty("gold")
public Integer getGold() {
return gold;
}
@JsonProperty("gold")
public void setGold(Integer gold) {
this.gold = gold;
}
@JsonProperty("level")
public Integer getLevel() {
return level;
}
@JsonProperty("level")
public void setLevel(Integer level) {
this.level = level;
}
@JsonProperty("gold_per_min")
public Integer getGoldPerMin() {
return goldPerMin;
}
@JsonProperty("gold_per_min")
public void setGoldPerMin(Integer goldPerMin) {
this.goldPerMin = goldPerMin;
}
@JsonProperty("xp_per_min")
public Integer getXpPerMin() {
return xpPerMin;
}
@JsonProperty("xp_per_min")
public void setXpPerMin(Integer xpPerMin) {
this.xpPerMin = xpPerMin;
}
@JsonProperty("ultimate_state")
public Integer getUltimateState() {
return ultimateState;
}
@JsonProperty("ultimate_state")
public void setUltimateState(Integer ultimateState) {
this.ultimateState = ultimateState;
}
@JsonProperty("ultimate_cooldown")
public Integer getUltimateCooldown() {
return ultimateCooldown;
}
@JsonProperty("ultimate_cooldown")
public void setUltimateCooldown(Integer ultimateCooldown) {
this.ultimateCooldown = ultimateCooldown;
}
@JsonProperty("item0")
public Integer getItem0() {
return item0;
}
@JsonProperty("item0")
public void setItem0(Integer item0) {
this.item0 = item0;
}
@JsonProperty("item1")
public Integer getItem1() {
return item1;
}
@JsonProperty("item1")
public void setItem1(Integer item1) {
this.item1 = item1;
}
@JsonProperty("item2")
public Integer getItem2() {
return item2;
}
@JsonProperty("item2")
public void setItem2(Integer item2) {
this.item2 = item2;
}
@JsonProperty("item3")
public Integer getItem3() {
return item3;
}
@JsonProperty("item3")
public void setItem3(Integer item3) {
this.item3 = item3;
}
@JsonProperty("item4")
public Integer getItem4() {
return item4;
}
@JsonProperty("item4")
public void setItem4(Integer item4) {
this.item4 = item4;
}
@JsonProperty("item5")
public Integer getItem5() {
return item5;
}
@JsonProperty("item5")
public void setItem5(Integer item5) {
this.item5 = item5;
}
@JsonProperty("respawn_timer")
public Integer getRespawnTimer() {
return respawnTimer;
}
@JsonProperty("respawn_timer")
public void setRespawnTimer(Integer respawnTimer) {
this.respawnTimer = respawnTimer;
}
@JsonProperty("position_x")
public Double getPositionX() {
return positionX;
}
@JsonProperty("position_x")
public void setPositionX(Double positionX) {
this.positionX = positionX;
}
@JsonProperty("position_y")
public Double getPositionY() {
return positionY;
}
@JsonProperty("position_y")
public void setPositionY(Double positionY) {
this.positionY = positionY;
}
@JsonProperty("net_worth")
public Integer getNetWorth() {
return netWorth;
}
@JsonProperty("net_worth")
public void setNetWorth(Integer netWorth) {
this.netWorth = netWorth;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
} | agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/tools/expression/internal/function/conversion/StringToNumerical.java | 4655 | /**
* 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.tools.expression.internal.function.conversion;
import java.util.concurrent.Callable;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.expression.DoubleCallable;
import com.rapidminer.tools.expression.ExpressionEvaluator;
import com.rapidminer.tools.expression.ExpressionParsingException;
import com.rapidminer.tools.expression.ExpressionType;
import com.rapidminer.tools.expression.FunctionDescription;
import com.rapidminer.tools.expression.FunctionInputException;
import com.rapidminer.tools.expression.internal.SimpleExpressionEvaluator;
import com.rapidminer.tools.expression.internal.function.AbstractFunction;
/**
*
* A {@link Function} parsing a string to a number.
*
* @author Marcel Seifert
*
*/
public class StringToNumerical extends AbstractFunction {
/**
* {@link NumericalToString} converts infinitys to a symbol, determined by
* {@link Tools.FORMAT_SYMBOLS}. Use those strings to allow to recognize them when converting
* back.
*/
private static final String POSITIVE_INFINITY_STRING = Tools.FORMAT_SYMBOLS.getInfinity();
private static final String NEGATIVE_INFINITY_STRING = Tools.FORMAT_SYMBOLS.getMinusSign()
+ Tools.FORMAT_SYMBOLS.getInfinity();
/**
* Constructs an AbstractFunction with {@link FunctionDescription} generated from the arguments
* and the function name generated from the description.
*/
public StringToNumerical() {
super("conversion.parse", 1, Ontology.NUMERICAL);
}
@Override
public ExpressionEvaluator compute(ExpressionEvaluator... inputEvaluators) {
if (inputEvaluators.length != 1) {
throw new FunctionInputException("expression_parser.function_wrong_input", getFunctionName(), 1,
inputEvaluators.length);
}
ExpressionType type = getResultType(inputEvaluators);
ExpressionEvaluator input = inputEvaluators[0];
return new SimpleExpressionEvaluator(makeDoubleCallable(input), type, isResultConstant(inputEvaluators));
}
/**
* Builds a DoubleCallable from one String input argument
*
* @param inputEvaluator
* the input
* @return the resulting callable<String>
*/
protected DoubleCallable makeDoubleCallable(final ExpressionEvaluator inputEvaluator) {
final Callable<String> func = inputEvaluator.getStringFunction();
try {
if (inputEvaluator.isConstant()) {
final double result = compute(func.call());
return new DoubleCallable() {
@Override
public double call() throws Exception {
return result;
}
};
} else {
return new DoubleCallable() {
@Override
public double call() throws Exception {
return compute(func.call());
}
};
}
} catch (ExpressionParsingException e) {
throw e;
} catch (Exception e) {
throw new ExpressionParsingException(e);
}
}
/**
* Computes the result for one input String value.
*
* @param value
* the string to parse
*
* @return the result of the computation.
*/
protected double compute(String value) {
if (value != null) {
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
// check if the value is positive or negative infinity as coming from {@link
// NumericalToString}
if (POSITIVE_INFINITY_STRING.equals(value)) {
return Double.POSITIVE_INFINITY;
} else if (NEGATIVE_INFINITY_STRING.equals(value)) {
return Double.NEGATIVE_INFINITY;
}
return Double.NaN;
}
}
return Double.NaN;
}
@Override
protected ExpressionType computeType(ExpressionType... inputTypes) {
ExpressionType input = inputTypes[0];
if (input == ExpressionType.STRING) {
return ExpressionType.DOUBLE;
} else {
throw new FunctionInputException("expression_parser.function_wrong_type", getFunctionName(), "nominal");
}
}
}
| agpl-3.0 |
britzke/rennspur | src/main/java/de/rennspur/model/Countries.java | 2795 | package de.rennspur.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence maxOccurs="unbounded">
* <element name="country">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="code" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
* <element name="a2code" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="a3code" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="since" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
* <element name="note" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"country"
})
@XmlRootElement(name = "countries")
public class Countries {
@XmlElement(required = true)
protected List<Country> country;
/**
* Gets the value of the country property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the country property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCountry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Countries.Country }
*
*
*/
public List<Country> getCountry() {
if (country == null) {
country = new ArrayList<Country>();
}
return this.country;
}
}
| agpl-3.0 |
cm-is-dog/rapidminer-studio-core | src/main/java/com/rapidminer/gui/renderer/models/KernelModelPlotRenderer.java | 1564 | /**
* 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.gui.renderer.models;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.datatable.DataTableKernelModelAdapter;
import com.rapidminer.gui.renderer.AbstractDataTablePlotterRenderer;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.learner.functions.kernel.KernelModel;
/**
* A renderer for the plot view of kernel models.
*
* @author Ingo Mierswa
*/
public class KernelModelPlotRenderer extends AbstractDataTablePlotterRenderer {
@Override
public DataTable getDataTable(Object renderable, IOContainer ioContainer) {
KernelModel kernelModel = (KernelModel) renderable;
return new DataTableKernelModelAdapter(kernelModel);
}
}
| agpl-3.0 |
zeineb/scheduling | scheduler/scheduler-examples/src/main/java/org/ow2/proactive/scheduler/examples/S3ConnectorDownloader.java | 8555 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: 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 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/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.scheduler.examples;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3URI;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.MultipleFileDownload;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
/**
* Import file(s) from an S3 server using the Import_from_S3 task.
* This task can be launched with parameters.
*
* @author The ProActive Team
*/
public class S3ConnectorDownloader extends JavaExecutable {
private String s3LocalRelativePath;
private String s3Url;
private String bucketName = null;
private String s3RemoteRelativePath = null;
private String host = null;
private String scheme;
private String accessKey;
private String secretKey;
private static final String S3_LOCAL_RELATIVE_PATH = "s3LocalRelativePath";
private static final String S3_URI = "s3Url";
/**
* @see JavaExecutable#init(Map)
*/
@Override
public void init(Map<String, Serializable> args) throws Exception {
if (args.containsKey(S3_URI) && !args.get(S3_URI).toString().isEmpty()) {
s3Url = args.get(S3_URI).toString();
parseAmazonS3URI(s3Url);
} else {
throw new IllegalArgumentException("You have to specify a valid s3URI. Empty value is not allowed.");
}
if (args.containsKey(S3_LOCAL_RELATIVE_PATH) && !args.get(S3_LOCAL_RELATIVE_PATH).toString().isEmpty()) {
s3LocalRelativePath = args.get(S3_LOCAL_RELATIVE_PATH).toString();
} else {
//Default value is getLocalSpace() because it will always be writable and moreover can be used to transfer files to another data space (global, user)
s3LocalRelativePath = getLocalSpace();
}
accessKey = getThirdPartyCredential("S3_ACCESS_KEY");
secretKey = getThirdPartyCredential("S3_SECRET_KEY");
if (accessKey == null || secretKey == null) {
throw new IllegalArgumentException("You first need to add your Access Key ID and Secret Access Key (S3_ACCESS_KEY, S3_SECRET_KEY) to the third party credentials");
}
}
/**
* @see JavaExecutable#execute(TaskResult[])
*/
@Override
public Serializable execute(TaskResult... results) throws IOException {
boolean s3PathIsPrefix = (s3RemoteRelativePath.lastIndexOf('/') == s3RemoteRelativePath.length() - 1);
File f = new File(s3LocalRelativePath);
createDirIfNotExists(f, s3PathIsPrefix);
AmazonS3 amazonS3 = S3ConnectorUtils.getS3Client(accessKey, secretKey, scheme, host);
// Assume that the path exists, do the download.
if (s3PathIsPrefix) {
downloadDir(bucketName, s3RemoteRelativePath, s3LocalRelativePath, false, amazonS3);
return (Serializable) SchedulerExamplesUtils.listDirectoryContents(f, new ArrayList<>());
} else {
s3LocalRelativePath = Paths.get(s3LocalRelativePath, Paths.get(s3Url).getFileName().toString()).toString();
downloadFile(bucketName, s3RemoteRelativePath, s3LocalRelativePath, false, amazonS3);
return (Serializable) Arrays.asList(s3LocalRelativePath);
}
}
/**
* Download a list of files from S3. <br>
* Requires a bucket name. <br>
* Requires a key prefix. <br>
*
* @param bucketName
* @param keyPrefix
* @param dirPath
* @param pause
* @param s3Client
*/
private void downloadDir(String bucketName, String keyPrefix, String dirPath, boolean pause, AmazonS3 s3Client) {
getOut().println("downloading to directory: " + dirPath + (pause ? " (pause)" : ""));
TransferManager transferManager = TransferManagerBuilder.standard().withS3Client(s3Client).build();
try {
MultipleFileDownload xfer = transferManager.downloadDirectory(bucketName, keyPrefix, new File(dirPath));
// loop with Transfer.isDone()
SchedulerExamplesUtils.showTransferProgress(xfer);
// or block with Transfer.waitForCompletion()
SchedulerExamplesUtils.waitForCompletion(xfer);
} catch (AmazonServiceException e) {
getErr().println(e.getMessage());
System.exit(1);
} finally {
transferManager.shutdownNow();
}
}
/**
* Download a file from S3. <br>
* Requires a bucket name. <br>
* Requires a key prefix. <br>
*
* @param bucketName
* @param keyName
* @param filePath
* @param pause
* @param s3Client
*/
private void downloadFile(String bucketName, String keyName, String filePath, boolean pause, AmazonS3 s3Client) {
getOut().println("Downloading to file: " + filePath + (pause ? " (pause)" : ""));
File f = new File(filePath);
TransferManager xferMgr = TransferManagerBuilder.standard().withS3Client(s3Client).build();
try {
Download xfer = xferMgr.download(bucketName, keyName, f);
// loop with Transfer.isDone()
SchedulerExamplesUtils.showTransferProgress(xfer);
// or block with Transfer.waitForCompletion()
SchedulerExamplesUtils.waitForCompletion(xfer);
} catch (AmazonServiceException e) {
getErr().println(e.getMessage());
System.exit(1);
} finally {
xferMgr.shutdownNow();
}
}
/**
* Parse an Amazon S3 Uri to extract four elements: scheme, host, bucket name and key name.
*
* @param s3Uri
*/
private void parseAmazonS3URI(String s3Uri) {
AmazonS3URI amazonS3URI = new AmazonS3URI(s3Uri);
if ((scheme = amazonS3URI.getURI().getScheme()) == null) {
throw new IllegalArgumentException("You have to specify a valid scheme in the provided s3 uri. Empty value is not allowed.");
}
if ((host = amazonS3URI.getURI().getHost()) == null) {
throw new IllegalArgumentException("You have to specify a valid host in the provided s3 uri. Empty value is not allowed.");
}
if ((bucketName = amazonS3URI.getBucket()) == null) {
throw new IllegalArgumentException("You have to specify a valid bucket name in the provided s3 uri. Empty value is not allowed.");
}
if ((s3RemoteRelativePath = amazonS3URI.getKey()) == null) {
throw new IllegalArgumentException("You have to specify a valid key name in the provided s3 uri. Empty value is not allowed.");
}
}
private void createDirIfNotExists(File f, boolean s3PathIsPrefix) {
// If the path already exists, print a warning.
if (f.exists()) {
getOut().println("The local path already exists");
if (s3PathIsPrefix) {
try {
f.mkdir();
} catch (Exception e) {
getOut().println("Couldn't create destination directory!");
System.exit(1);
}
}
}
}
}
| agpl-3.0 |
aborg0/rapidminer-studio | doc/doc/TexTaglet.java | 362 | /**
* Copyright (C) 2001-2019 RapidMiner GmbH
*/
package com.rapidminer.doc;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
/**
* Creates the LaTeX code from a html taglet.
*
* @author Simon Fischer
*/
public interface TexTaglet extends Taglet {
public String toTex(Tag tag);
public String toTex(Tag[] tag);
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/features/weighting/ChiSquaredWeighting.java | 6098 | /**
* 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.operator.features.weighting;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.AttributeWeights;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.Tools;
import com.rapidminer.operator.OperatorCapability;
import com.rapidminer.operator.OperatorCreationException;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.preprocessing.discretization.BinDiscretization;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeInt;
import com.rapidminer.tools.OperatorService;
import com.rapidminer.tools.math.ContingencyTableTools;
/**
* This operator calculates the relevance of a feature by computing for each attribute of the input
* example set the value of the chi-squared statistic with respect to the class attribute.
*
* @author Ingo Mierswa
*/
public class ChiSquaredWeighting extends AbstractWeighting {
private static final int PROGRESS_UPDATE_STEPS = 1_000_000;
public ChiSquaredWeighting(OperatorDescription description) {
super(description, true);
}
@Override
protected AttributeWeights calculateWeights(ExampleSet exampleSet) throws OperatorException {
Tools.hasNominalLabels(exampleSet, getOperatorClassName());
Attribute label = exampleSet.getAttributes().getLabel();
BinDiscretization discretization = null;
try {
discretization = OperatorService.createOperator(BinDiscretization.class);
} catch (OperatorCreationException e) {
throw new UserError(this, 904, "Discretization", e.getMessage());
}
int numberOfBins = getParameterAsInt(BinDiscretization.PARAMETER_NUMBER_OF_BINS);
discretization.setParameter(BinDiscretization.PARAMETER_NUMBER_OF_BINS, numberOfBins + "");
exampleSet = discretization.doWork(exampleSet);
int maximumNumberOfNominalValues = 0;
for (Attribute attribute : exampleSet.getAttributes()) {
if (attribute.isNominal()) {
maximumNumberOfNominalValues = Math.max(maximumNumberOfNominalValues, attribute.getMapping().size());
}
}
if (numberOfBins < maximumNumberOfNominalValues) {
getLogger().warning("Number of bins too small, was " + numberOfBins
+ ". Set to maximum number of occurring nominal values (" + maximumNumberOfNominalValues + ")");
numberOfBins = maximumNumberOfNominalValues;
}
// init
double[][][] counters = new double[exampleSet.getAttributes().size()][numberOfBins][label.getMapping().size()];
Attribute weightAttribute = exampleSet.getAttributes().getWeight();
// count
double[] temporaryCounters = new double[label.getMapping().size()];
for (Example example : exampleSet) {
double weight = 1.0d;
if (weightAttribute != null) {
weight = example.getValue(weightAttribute);
}
int labelIndex = (int) example.getLabel();
temporaryCounters[labelIndex] += weight;
}
for (int k = 0; k < counters.length; k++) {
for (int i = 0; i < temporaryCounters.length; i++) {
counters[k][0][i] = temporaryCounters[i];
}
}
// attribute counts
getProgress().setTotal(100);
long progressCounter = 0;
double totalProgress = exampleSet.size() * exampleSet.getAttributes().size();
int attributeCounter = 0;
for (Attribute attribute : exampleSet.getAttributes()) {
for (Example example : exampleSet) {
int labelIndex = (int) example.getLabel();
double weight = 1.0d;
if (weightAttribute != null) {
weight = example.getValue(weightAttribute);
}
int attributeIndex = (int) example.getValue(attribute);
counters[attributeCounter][attributeIndex][labelIndex] += weight;
counters[attributeCounter][0][labelIndex] -= weight;
if (++progressCounter % PROGRESS_UPDATE_STEPS == 0) {
getProgress().setCompleted((int) (100 * (progressCounter / totalProgress)));
}
}
attributeCounter++;
}
// calculate the actual chi-squared values and assign them to weights
AttributeWeights weights = new AttributeWeights(exampleSet);
attributeCounter = 0;
for (Attribute attribute : exampleSet.getAttributes()) {
double weight = ContingencyTableTools
.getChiSquaredStatistics(ContingencyTableTools.deleteEmpty(counters[attributeCounter]), false);
weights.setWeight(attribute.getName(), weight);
attributeCounter++;
}
return weights;
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeInt(BinDiscretization.PARAMETER_NUMBER_OF_BINS,
"The number of bins used for discretization of numerical attributes before the chi squared test can be performed.",
2, Integer.MAX_VALUE, 10));
return types;
}
@Override
public boolean supportsCapability(OperatorCapability capability) {
switch (capability) {
case BINOMINAL_ATTRIBUTES:
case POLYNOMINAL_ATTRIBUTES:
case NUMERICAL_ATTRIBUTES:
case BINOMINAL_LABEL:
case POLYNOMINAL_LABEL:
return true;
default:
return false;
}
}
}
| agpl-3.0 |
paulmartel/voltdb | tests/frontend/org/voltdb/IndexOrderPlayground.java | 3006 | /* This file is part of VoltDB.
* Copyright (C) 2008-2016 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;
import junit.framework.TestCase;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.compiler.VoltProjectBuilder;
public class IndexOrderPlayground extends TestCase {
public void testCompile() throws Exception {
String simpleSchema =
"create table table1 (" +
"column1 bigint not null," +
"column2 bigint not null," +
"constraint idx_table1_TREE_pk primary key (column1, column2));\n" +
"create index idx_table1_hash on table1 (column1);\n" +
"create table table2 (" +
"column1 bigint not null," +
"column2 bigint not null," +
"constraint idx_table2_TREE_pk primary key (column1, column2));\n" +
"create index idx_table2_tree on table2 (column1);\n" +
"create table table3 (" +
"column1 bigint not null," +
"column2 bigint not null," +
"constraint idx_table3_TREE_pk primary key (column1, column2));\n";
VoltProjectBuilder builder = new VoltProjectBuilder();
builder.addLiteralSchema(simpleSchema);
builder.addPartitionInfo("table1", "column1");
builder.addPartitionInfo("table2", "column1");
builder.addPartitionInfo("table3", "column1");
builder.addStmtProcedure("SelectT1", "select * from table1 where column1 = ? and column2 = ?;", "table1.column1:0");
builder.addStmtProcedure("SelectT2", "select * from table2 where column1 = ? and column2 = ?;", "table1.column1:0");
builder.addStmtProcedure("SelectT3", "select * from table3 where column1 = ? and column2 = ?;", "table1.column1:0");
boolean success = builder.compile(Configuration.getPathToCatalogForTest("indexordertest.jar"), 1, 1, 0);
assertTrue(success);
}
}
| agpl-3.0 |
paulmartel/voltdb | src/frontend/org/voltdb/compiler/AdHocPlannerWork.java | 7378 | /* This file is part of VoltDB.
* Copyright (C) 2008-2016 VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.compiler;
import org.voltcore.network.Connection;
import org.voltdb.AuthSystem;
import org.voltdb.CatalogContext;
import org.voltdb.ClientInterface.ExplainMode;
import org.voltdb.client.BatchTimeoutOverrideType;
import org.voltdb.client.ProcedureInvocationType;
public class AdHocPlannerWork extends AsyncCompilerWork {
private static final long serialVersionUID = -6567283432846270119L;
final String sqlBatchText;
final String[] sqlStatements;
final Object[] userParamSet;
final CatalogContext catalogContext;
final boolean inferPartitioning;
// The user partition key is usually null
// -- otherwise, it contains one element to support @AdHocSpForTest and
// ad hoc statements queued within single-partition stored procs.
final Object[] userPartitionKey;
public final ExplainMode explainMode;
public final int m_batchTimeout;
public AdHocPlannerWork(long replySiteId, long clientHandle, long connectionId,
boolean adminConnection, Connection clientConnection,
String sqlBatchText, String[] sqlStatements,
Object[] userParamSet, CatalogContext context, ExplainMode explainMode,
boolean inferPartitioning, Object[] userPartitionKey,
String invocationName, ProcedureInvocationType type,
long originalTxnId, long originalUniqueId, int batchTimeout,
boolean onReplica, boolean useAdhocDDL,
AsyncCompilerWorkCompletionHandler completionHandler, AuthSystem.AuthUser user)
{
super(replySiteId, false, clientHandle, connectionId,
clientConnection == null ? "" : clientConnection.getHostnameAndIPAndPort(),
adminConnection, clientConnection, invocationName, type,
originalTxnId, originalUniqueId, onReplica, useAdhocDDL,
completionHandler, user);
this.sqlBatchText = sqlBatchText;
this.sqlStatements = sqlStatements;
this.userParamSet = userParamSet;
this.catalogContext = context;
this.explainMode = explainMode;
this.inferPartitioning = inferPartitioning;
this.userPartitionKey = userPartitionKey;
this.m_batchTimeout = batchTimeout;
}
/**
* A mutated clone method, allowing override of completionHandler and
* clearing of (obsolete) catalogContext
*/
public static AdHocPlannerWork rework(AdHocPlannerWork orig,
AsyncCompilerWorkCompletionHandler completionHandler) {
return new AdHocPlannerWork(orig.replySiteId,
orig.clientHandle,
orig.connectionId,
orig.adminConnection,
(Connection) orig.clientData,
orig.sqlBatchText,
orig.sqlStatements,
orig.userParamSet,
null /* context */,
orig.explainMode,
orig.inferPartitioning,
orig.userPartitionKey,
orig.invocationName,
orig.invocationType,
orig.originalTxnId,
orig.originalUniqueId,
orig.m_batchTimeout,
orig.onReplica,
orig.useAdhocDDL,
completionHandler,
orig.user);
}
/**
* Special factory of a mostly mocked up instance for calling from inside a stored proc.
* It's also convenient for simple tests that need to mock up a quick planner request to
* test related parts of the system.
*/
public static AdHocPlannerWork makeStoredProcAdHocPlannerWork(long replySiteId,
String sql, Object[] userParams, boolean singlePartition, CatalogContext context,
AsyncCompilerWorkCompletionHandler completionHandler)
{
return makeStoredProcAdHocPlannerWork(replySiteId, sql, userParams, singlePartition, context, completionHandler, false);
}
public static AdHocPlannerWork makeStoredProcAdHocPlannerWork(long replySiteId,
String sql, Object[] userParams, boolean singlePartition, CatalogContext context,
AsyncCompilerWorkCompletionHandler completionHandler,
boolean isAdmin)
{
return new AdHocPlannerWork(replySiteId, 0, 0, isAdmin, null,
sql, new String[] { sql },
userParams, context, ExplainMode.NONE,
// ??? The settings passed here for the single partition stored proc caller
// denote that the partitioning has already been done so something like the planner
// code path for @AdHocSpForTest is called for.
// The plan is required to be single-partition regardless of its internal logic
// -- EXCEPT that writes to replicated tables are strictly forbdden -- and there
// should be no correlation inferred or assumed between the partitioning and the
// statement's constants or parameters.
false, (singlePartition ? new Object[1] /*any vector element will do, even null*/ : null),
"@AdHoc_RW_MP", ProcedureInvocationType.ORIGINAL, 0, 0, BatchTimeoutOverrideType.NO_TIMEOUT,
false, false, // don't allow adhoc DDL in this path
completionHandler, new AuthSystem.AuthDisabledUser());
}
@Override
public String toString() {
String retval = super.toString();
if (userParamSet == null || (userParamSet.length == 0)) {
retval += "\n user params: empty";
} else {
int i = 0;
for (Object param : userParamSet) {
i++;
retval += String.format("\n user param[%d]: %s",
i, (param == null ? "null" : param.toString()));
}
}
if (userPartitionKey == null) {
retval += "\n user partitioning: none";
} else {
retval += "\n user partitioning: " +
(userPartitionKey[0] == null ? "null" : userPartitionKey[0].toString());
}
assert(sqlStatements != null);
if (sqlStatements.length == 0) {
retval += "\n sql: empty";
} else {
int i = 0;
for (String sql : sqlStatements) {
i++;
retval += String.format("\n sql[%d]: %s", i, sql);
}
}
return retval;
}
public int getStatementCount()
{
return (this.sqlStatements != null ? this.sqlStatements.length : 0);
}
public int getParameterCount()
{
return (this.userParamSet != null ? this.userParamSet.length : 0);
}
}
| agpl-3.0 |
aishangzoulu/mygames | src/main/java/com/raymond/core/generic/GenericEnum.java | 322 | package com.raymond.core.generic;
/**
* 所有自定义枚举类型实现该接口
*
* @author chen_zx
*
**/
public interface GenericEnum {
/**
* value: 为保存在数据库中的值
*/
public String getValue();
/**
* text : 为前端显示值
*/
public String getText();
}
| agpl-3.0 |
Skelril/Aurora | src/main/java/com/skelril/aurora/economic/store/mysql/MySQLMarketTransactionDatabase.java | 5130 | /*
* Copyright (c) 2014 Wyatt Childers.
*
* This file is part of Aurora.
*
* Aurora 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.
*
* Aurora 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 Aurora. If not, see <http://www.gnu.org/licenses/>.
*/
package com.skelril.aurora.economic.store.mysql;
import com.skelril.aurora.data.MySQLHandle;
import com.skelril.aurora.data.MySQLPreparedStatement;
import com.skelril.aurora.economic.store.ItemTransaction;
import com.skelril.aurora.economic.store.MarketTransactionDatabase;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class MySQLMarketTransactionDatabase implements MarketTransactionDatabase {
private Queue<MySQLPreparedStatement> queue = new LinkedList<>();
@Override
public boolean load() {
try (Connection connection = MySQLHandle.getConnection()) {
String tranSQL = "CREATE TABLE IF NOT EXISTS `market-transactions` (" +
"`id` INT NOT NULL AUTO_INCREMENT," +
"`date` DATETIME NOT NULL," +
"`player` INT NOT NULL," +
"`item` INT NOT NULL," +
"`amount` INT NOT NULL," +
"PRIMARY KEY (`id`)" +
") ENGINE=MyISAM;";
try (PreparedStatement statement = connection.prepareStatement(tranSQL)) {
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean save() {
if (queue.isEmpty()) return true;
try (Connection connection = MySQLHandle.getConnection()) {
connection.setAutoCommit(false);
while (!queue.isEmpty()) {
MySQLPreparedStatement row = queue.poll();
row.setConnection(connection);
row.executeStatements();
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public void logTransaction(String playerName, String itemName, int amount) {
try {
int playerID = MySQLHandle.getPlayerId(playerName);
int itemID = MySQLItemStoreDatabase.getItemID(itemName);
ItemTransactionStatement transaction = new ItemTransactionStatement(playerID, itemID, amount);
try (Connection connection = MySQLHandle.getConnection()) {
transaction.setConnection(connection);
transaction.executeStatements();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<ItemTransaction> getTransactions() {
return getTransactions(null, null);
}
@Override
public List<ItemTransaction> getTransactions(String itemName, String playerName) {
List<ItemTransaction> transactions = new ArrayList<>();
try (Connection connection = MySQLHandle.getConnection()) {
String sql = "SELECT `lb-players`.`playername`, `market-items`.`name`, `market-transactions`.`amount` "
+ "FROM `market-transactions`"
+ "INNER JOIN `lb-players` ON `market-transactions`.`player` = `lb-players`.`playerid`"
+ "INNER JOIN `market-items` ON `market-items`.`id` = `market-transactions`.`item`";
if (itemName != null) {
sql += "WHERE `market-items`.`name` = \'" + itemName + "\'";
}
if (playerName != null) {
if (itemName != null) sql += "AND";
else sql += "WHERE";
sql += "`lb-players`.`playername` = \'" + playerName + "\'";
}
sql += "ORDER BY `market-transactions`.`date` DESC";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
try (ResultSet results = statement.executeQuery()) {
while (results.next()) {
transactions.add(new ItemTransaction(
results.getString(1),
results.getString(2),
results.getInt(3)
));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return transactions;
}
}
| agpl-3.0 |
dhosa/yamcs | yamcs-core/src/main/java/org/yamcs/archive/FSEventDecoder.java | 6330 | package org.yamcs.archive;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hornetq.api.core.HornetQException;
import org.hornetq.api.core.SimpleString;
import org.slf4j.Logger;
import org.yamcs.ConfigurationException;
import org.yamcs.ThreadSafe;
import org.yamcs.YConfiguration;
import org.yamcs.YamcsServer;
import org.yamcs.api.YamcsApiException;
import org.yamcs.api.YamcsClient;
import org.yamcs.api.YamcsSession;
import org.yamcs.protobuf.Yamcs.Event;
import org.yamcs.protobuf.Yamcs.ProtoDataType;
import org.yamcs.usoctools.PayloadModel;
import org.yamcs.usoctools.XtceUtil;
import org.yamcs.utils.CcsdsPacket;
import org.yamcs.utils.YObjectLoader;
import org.yamcs.xtce.MdbMappings;
import org.yamcs.xtceproc.XtceDbFactory;
import org.yamcs.yarch.Stream;
import org.yamcs.yarch.StreamSubscriber;
import org.yamcs.yarch.Tuple;
import org.yamcs.yarch.YarchDatabase;
import com.google.common.util.concurrent.AbstractService;
/**
* This class decodes Flight Segment Events.
* @author nm
*
*/
@ThreadSafe
public class FSEventDecoder extends AbstractService implements StreamSubscriber{
String instance;
Map<String,PayloadModel> opsnameToPayloadModel =new HashMap<String,PayloadModel>();
private final Logger log;
public YamcsClient msgClient;
final SimpleString realtimeAddress, dumpAddress; //addresses where to send realtime and dump events
final Stream realtimeTmStream, dumpTmStream; //TM packets come from here
XtceUtil xtceutil;
YamcsSession yamcsSession;
public FSEventDecoder(String instance) throws ConfigurationException {
log=YamcsServer.getLogger(this.getClass(), instance);
YConfiguration conf=YConfiguration.getConfiguration("yamcs."+instance);
YObjectLoader<PayloadModel> objLoader=new YObjectLoader<PayloadModel>();
List<Object> decoders=conf.getList("eventDecoders");
try {
for(Object d:decoders) {
PayloadModel payloadModel;
if(d instanceof String) {
log.debug("Adding decoder "+d);
payloadModel = objLoader.loadObject((String)d, instance);
} else if(d instanceof Map<?,?>) {
Map<?, ?> m = (Map<?, ?>) d;
String className = YConfiguration.getString(m, "class");
Object args = m.get("args");
payloadModel = objLoader.loadObject(className, instance, args);
} else {
throw new ConfigurationException("Event decoders have to be specified either by className or by {class: className, args: arguments} map");
}
for (String opsname:payloadModel.getEventPacketsOpsnames()) {
opsnameToPayloadModel.put(opsname, payloadModel);
}
log.debug("Added payload model "+d+" for payload"+payloadModel.getPayloadName());
}
YarchDatabase dict=YarchDatabase.getInstance(instance);
realtimeTmStream=dict.getStream(XtceTmRecorder.REALTIME_TM_STREAM_NAME);
if(realtimeTmStream==null) throw new ConfigurationException("There is no stream named "+XtceTmRecorder.REALTIME_TM_STREAM_NAME);
dumpTmStream=dict.getStream(XtceTmRecorder.DUMP_TM_STREAM_NAME);
if(dumpTmStream==null) throw new ConfigurationException("There is no stream named "+XtceTmRecorder.DUMP_TM_STREAM_NAME);
realtimeAddress=new SimpleString(instance+".events_realtime");
dumpAddress=new SimpleString(instance+".events_dump");
yamcsSession = YamcsSession.newBuilder().build();
msgClient = yamcsSession.newClientBuilder().setDataProducer(true).build();
} catch (HornetQException e) {
throw new ConfigurationException(e.toString());
} catch (YamcsApiException e) {
throw new ConfigurationException(e.getMessage(),e);
} catch (IOException e) {
throw new ConfigurationException(e.toString());
}
xtceutil=XtceUtil.getInstance(XtceDbFactory.getInstance(instance));
realtimeTmStream.addSubscriber(this);
dumpTmStream.addSubscriber(this);
}
/**
* do nothing, we are just waiting for tuples to come
*/
@Override
protected void doStart() {
notifyStarted();
}
@Override
public void onTuple(Stream stream, Tuple t) {
byte[] packet=(byte[])t.getColumn("packet");
long rectime=(Long)t.getColumn("rectime");
if(stream==realtimeTmStream) {
processPacket(rectime, packet,realtimeAddress);
} else {
processPacket(rectime, packet, dumpAddress);
}
}
@Override
public void streamClosed(Stream stream) {//shouldn't happen
}
public void processPacket(long rectime, byte[] packet, SimpleString address) {
CcsdsPacket ccsdsPacket = new CcsdsPacket(packet);
ByteBuffer bb=ByteBuffer.wrap(packet);
int packetId=ccsdsPacket.getPacketID();
int apid=CcsdsPacket.getAPID(bb);
String opsName=xtceutil.getPacketNameByApidPacketid(apid, packetId, MdbMappings.MDB_OPSNAME);
if(opsName==null) opsName=xtceutil.getPacketNameByPacketId(packetId, MdbMappings.MDB_OPSNAME);
if(opsName==null) {
log.info("Cannot find an opsname for packetId " +packetId);
return;
}
PayloadModel payloadModel=opsnameToPayloadModel.get(opsName);
if(payloadModel==null) {
return;
}
Collection<Event> events=payloadModel.decode(rectime, packet);
if(events!=null) {
try {
for(Event ev:events) {
msgClient.sendData(address, ProtoDataType.EVENT, ev);
}
} catch (HornetQException e) {
log.warn("Exception when sending event: ", e);
}
}
}
@Override
protected void doStop() {
try {
yamcsSession.close();
} catch (HornetQException e) {
log.error("Error when closing the yamcsSession", e);
}
notifyStopped();
}
}
| agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Core | web-core/src/main/java/org/silverpeas/look/web/DisplayUserContextEntity.java | 2671 | /*
* 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 recieved 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 org.silverpeas.look.web;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.silverpeas.look.LookHelper;
import com.silverpeas.personalization.UserMenuDisplay;
import com.silverpeas.personalization.UserPreferences;
/**
* The user display context entity represents display settings of the current user
* @author Yohann Chastagnier
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DisplayUserContextEntity extends AbstractLookEntity<DisplayUserContextEntity> {
private static final long serialVersionUID = -1135190036189814798L;
@XmlElement
private UserMenuDisplay userMenuDisplay;
@XmlElement
private String language;
/**
* Creates user display context entity.
* @param lookHelper
* @param userPreferences
* @return
*/
public static DisplayUserContextEntity createFrom(final LookHelper lookHelper,
final UserPreferences userPreferences) {
return new DisplayUserContextEntity(lookHelper, userPreferences);
}
/**
* Instantiating a new web entity from the corresponding data
* @param lookHelper
* @param userPreferences
*/
private DisplayUserContextEntity(final LookHelper lookHelper,
final UserPreferences userPreferences) {
userMenuDisplay = lookHelper.getDisplayUserMenu();
language = userPreferences.getLanguage();
}
protected DisplayUserContextEntity() {
}
}
| agpl-3.0 |
heniancheng/FRODO | src/frodo2/benchmarks/auctions/cats/Auction.java | 3264 | /*
FRODO: a FRamework for Open/Distributed Optimization
Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek
FRODO 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.
FRODO 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/>.
How to contact the authors:
<http://frodo2.sourceforge.net/>
*/
package frodo2.benchmarks.auctions.cats;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents an auction generated by the CATS program
*
* @author Andreas Schaedeli
*
*/
public class Auction {
/**List containing all the goods sold in this auction*/
private List<Good> goodsList;
/**List containing all the bids placed in this auction*/
private List<Bid> bidsList;
/**List containing all the bidders of this auction*/
private List<Bidder> biddersList;
/**
* The constructor first initializes all the lists used in this class. Then, it calls a method to create as many goods as desired and places them in
* the corresponding list.
*
* @param nbGoods Number of goods sold in this auction
*/
public Auction(int nbGoods) {
goodsList = new ArrayList<Good>(nbGoods);
bidsList = new ArrayList<Bid>();
biddersList = new ArrayList<Bidder>();
Bidder.NEXT_ID = 0;
createGoodsList(nbGoods);
}
/**
* This method adds a bid to the auction. A bid needs to be added in several places: First of all, to the bids list. Then, to the bids list of the
* corresponding bidder. And finally, to the bids lists of the goods contained in the bid
*
* @param bid Bid to add to the auction
*/
public void addBid(Bid bid) {
bidsList.add(bid);
bid.getBidder().addBid(bid);
for(Good good : bid.getGoodsList()) {
good.addBid(bid);
}
}
/**
* This method adds a new Bidder to the list of bidders in this auction
*
* @param bidder Bidder to add to the auction
*/
public void addBidder(Bidder bidder) {
biddersList.add(bidder);
}
/**
* @param goodID ID of the good to be returned
* @return Good object with the given ID
*/
public Good getGood(int goodID) {
return goodsList.get(goodID);
}
/**
* @return List of goods offered in this auction
*/
public List<Good> getGoods() {
return goodsList;
}
/**
* @return List of bids placed in this auction
*/
public List<Bid> getBids() {
return bidsList;
}
/**
* @return List of all bidders in this auction
*/
public List<Bidder> getBidders() {
return biddersList;
}
/**
* This method creates The desired number of goods having IDs from 0 to (nbGoods - 1) and adds them to the goodsList
*
* @param nbGoods Number of goods to create
*/
private void createGoodsList(int nbGoods) {
for(int i = 0; i < nbGoods; i++) {
goodsList.add(new Good(i));
}
}
}
| agpl-3.0 |
martinbaker/euclideanspace | com.euclideanspace.spad/src-gen/com/euclideanspace/spad/editor/RemExpression.java | 3236 | /**
*/
package com.euclideanspace.spad.editor;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Rem Expression</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.euclideanspace.spad.editor.RemExpression#getLeft <em>Left</em>}</li>
* <li>{@link com.euclideanspace.spad.editor.RemExpression#getOp <em>Op</em>}</li>
* <li>{@link com.euclideanspace.spad.editor.RemExpression#getRight <em>Right</em>}</li>
* </ul>
* </p>
*
* @see com.euclideanspace.spad.editor.EditorPackage#getRemExpression()
* @model
* @generated
*/
public interface RemExpression extends Expr
{
/**
* Returns the value of the '<em><b>Left</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Left</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Left</em>' containment reference.
* @see #setLeft(Expr)
* @see com.euclideanspace.spad.editor.EditorPackage#getRemExpression_Left()
* @model containment="true"
* @generated
*/
Expr getLeft();
/**
* Sets the value of the '{@link com.euclideanspace.spad.editor.RemExpression#getLeft <em>Left</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Left</em>' containment reference.
* @see #getLeft()
* @generated
*/
void setLeft(Expr value);
/**
* Returns the value of the '<em><b>Op</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Op</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Op</em>' attribute.
* @see #setOp(String)
* @see com.euclideanspace.spad.editor.EditorPackage#getRemExpression_Op()
* @model
* @generated
*/
String getOp();
/**
* Sets the value of the '{@link com.euclideanspace.spad.editor.RemExpression#getOp <em>Op</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Op</em>' attribute.
* @see #getOp()
* @generated
*/
void setOp(String value);
/**
* Returns the value of the '<em><b>Right</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Right</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Right</em>' containment reference.
* @see #setRight(Expr)
* @see com.euclideanspace.spad.editor.EditorPackage#getRemExpression_Right()
* @model containment="true"
* @generated
*/
Expr getRight();
/**
* Sets the value of the '{@link com.euclideanspace.spad.editor.RemExpression#getRight <em>Right</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Right</em>' containment reference.
* @see #getRight()
* @generated
*/
void setRight(Expr value);
} // RemExpression
| agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa2.2/src/main/java/org/asqatasun/rules/rgaa22/Rgaa22Rule09071.java | 2726 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* 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/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa22;
import org.asqatasun.ruleimplementation.AbstractPageRuleWithSelectorAndCheckerImplementation;
import org.asqatasun.rules.elementchecker.pertinence.TextPertinenceChecker;
import org.asqatasun.rules.elementselector.SimpleElementSelector;
import static org.asqatasun.rules.keystore.HtmlElementStore.TEXT_ELEMENT2;
import static org.asqatasun.rules.keystore.HtmlElementStore.TITLE_ELEMENT;
import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_TITLE_PERTINENCE_MSG;
import static org.asqatasun.rules.keystore.RemarkMessageStore.NOT_PERTINENT_TITLE_MSG;
/**
* Implementation of the rule 9.7 of the referential RGAA 2.2.
* <br/>
* For more details about the implementation, refer to <a href="http://www.old-dot-org.org/en/content/rgaa22-rule-9-7">the rule 9.7 design page.</a>
* @see <a href="http://rgaa.net/Pertinence-du-titre-de-la-page.html"> 9.7 rule specification </a>
*
* @author jkowalczyk
*/
public class Rgaa22Rule09071 extends AbstractPageRuleWithSelectorAndCheckerImplementation {
/* Title blacklisted nomenclature */
private static final String TITLE_BLACKLIST_NOM = "UnexplicitPageTitle";
/**
* Default constructor
*/
public Rgaa22Rule09071 () {
super(
new SimpleElementSelector(TITLE_ELEMENT),
new TextPertinenceChecker(
// check emptiness
true,
// no comparison with other attribute
null,
// blacklist nomenclature name
TITLE_BLACKLIST_NOM,
// not pertinent message
NOT_PERTINENT_TITLE_MSG,
// manual check message
CHECK_TITLE_PERTINENCE_MSG,
// evidence elements
TEXT_ELEMENT2
)
);
}
}
| agpl-3.0 |
TelefonicaED/liferaylms-portlet | docroot/WEB-INF/src/com/liferay/lms/service/http/ModuleResultServiceSoap.java | 2268 | /**
* 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.http;
/**
* <p>
* This class provides a SOAP utility for the
* {@link com.liferay.lms.service.ModuleResultServiceUtil} service utility. The
* static methods of this class calls the same methods of the service utility.
* However, the signatures are different because it is difficult for SOAP to
* support certain types.
* </p>
*
* <p>
* ServiceBuilder follows certain rules in translating the methods. For example,
* if the method in the service utility returns a {@link java.util.List}, that
* is translated to an array of {@link com.liferay.lms.model.ModuleResultSoap}.
* If the method in the service utility returns a
* {@link com.liferay.lms.model.ModuleResult}, that is translated to a
* {@link com.liferay.lms.model.ModuleResultSoap}. Methods that SOAP cannot
* safely wire are skipped.
* </p>
*
* <p>
* The benefits of using the SOAP utility is that it is cross platform
* compatible. SOAP allows different languages like Java, .NET, C++, PHP, and
* even Perl, to call the generated services. One drawback of SOAP is that it is
* slow because it needs to serialize all calls into a text format (XML).
* </p>
*
* <p>
* You can see a list of services at
* http://localhost:8080/api/secure/axis. Set the property
* <b>axis.servlet.hosts.allowed</b> in portal.properties to configure
* security.
* </p>
*
* <p>
* The SOAP utility is only generated for remote services.
* </p>
*
* @author TLS
* @see ModuleResultServiceHttp
* @see com.liferay.lms.model.ModuleResultSoap
* @see com.liferay.lms.service.ModuleResultServiceUtil
* @generated
*/
public class ModuleResultServiceSoap {
} | agpl-3.0 |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/profile/ProfileFragment.java | 27291 | package im.actor.sdk.controllers.profile;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.ArrayList;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import im.actor.core.entity.Peer;
import im.actor.core.viewmodel.UserEmail;
import im.actor.core.viewmodel.UserPhone;
import im.actor.core.viewmodel.UserVM;
import im.actor.runtime.mvvm.Value;
import im.actor.runtime.mvvm.ValueChangedListener;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.R;
import im.actor.sdk.controllers.BaseFragment;
import im.actor.sdk.controllers.Intents;
import im.actor.sdk.controllers.compose.ComposeActivity;
import im.actor.sdk.controllers.fragment.preview.ViewAvatarActivity;
import im.actor.sdk.util.Screen;
import im.actor.sdk.util.ViewUtils;
import im.actor.sdk.view.avatar.AvatarView;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
import static im.actor.sdk.util.ActorSDKMessenger.users;
public class ProfileFragment extends BaseFragment {
public static int SOUND_PICKER_REQUEST_CODE = 122;
public static final String EXTRA_UID = "uid";
private View recordFieldWithIcon;
public static ProfileFragment create(int uid) {
Bundle bundle = new Bundle();
bundle.putInt(EXTRA_UID, uid);
ProfileFragment res = new ProfileFragment();
res.setArguments(bundle);
return res;
}
private AvatarView avatarView;
private int uid;
public ProfileFragment() {
setRootFragment(true);
setHomeAsUp(true);
setTitle(null);
}
@Override
public void onConfigureActionBar(ActionBar actionBar) {
super.onConfigureActionBar(actionBar);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
uid = getArguments().getInt(EXTRA_UID);
final UserVM user = users().get(uid);
ArrayList<UserPhone> phones = user.getPhones().get();
ArrayList<UserEmail> emails = user.getEmails().get();
String about = user.getAbout().get();
final String userName = user.getNick().get();
final View res = inflater.inflate(R.layout.fragment_profile, container, false);
//
// Style Background
//
res.findViewById(R.id.container).setBackgroundColor(style.getMainBackgroundColor());
res.findViewById(R.id.avatarContainer).setBackgroundColor(style.getToolBarColor());
//
// User Avatar
//
avatarView = (AvatarView) res.findViewById(R.id.avatar);
avatarView.init(Screen.dp(48), 22);
avatarView.bind(user.getAvatar().get(), user.getName().get(), user.getId());
avatarView.setOnClickListener(v -> {
startActivity(ViewAvatarActivity.viewAvatar(user.getId(), getActivity()));
});
//
// User Name
//
TextView nameText = (TextView) res.findViewById(R.id.name);
nameText.setTextColor(style.getProfileTitleColor());
bind(nameText, user.getName());
//
// User Last Seen
//
TextView lastSeen = (TextView) res.findViewById(R.id.lastSeen);
lastSeen.setTextColor(style.getProfileSubtitleColor());
bind(lastSeen, user);
//
// Fab
//
FloatingActionButton fab = (FloatingActionButton) res.findViewById(R.id.fab);
fab.setBackgroundTintList(new ColorStateList(new int[][]{
new int[]{android.R.attr.state_pressed},
StateSet.WILD_CARD,
}, new int[]{
ActorSDK.sharedActor().style.getFabPressedColor(),
ActorSDK.sharedActor().style.getFabColor(),
}));
fab.setRippleColor(ActorSDK.sharedActor().style.getFabPressedColor());
fab.setOnClickListener(v -> startActivity(new Intent(getActivity(), ComposeActivity.class)));
//
// Remove Contact
//
final View removeContact = res.findViewById(R.id.addContact);
final TextView addContactTitle = (TextView) removeContact.findViewById(R.id.addContactTitle);
addContactTitle.setText(getString(R.string.profile_contacts_added));
addContactTitle.setTextColor(style.getTextPrimaryColor());
removeContact.setOnClickListener(v -> {
execute(ActorSDK.sharedActor().getMessenger().removeContact(user.getId()));
});
bind(user.isContact(), (isContact, valueModel) -> {
if (isContact) {
removeContact.setVisibility(View.VISIBLE);
//fab
fab.setImageResource(R.drawable.ic_message_white_24dp);
fab.setOnClickListener(view -> startActivity(Intents.openPrivateDialog(user.getId(), true, getActivity())));
} else {
removeContact.setVisibility(View.GONE);
//fab
fab.setImageResource(R.drawable.ic_person_add_white_24dp);
fab.setOnClickListener(view -> execute(ActorSDK.sharedActor().getMessenger().addContact(user.getId())));
}
});
//
// New Message
//
View newMessageView = res.findViewById(R.id.newMessage);
ImageView newMessageIcon = (ImageView) newMessageView.findViewById(R.id.newMessageIcon);
TextView newMessageTitle = (TextView) newMessageView.findViewById(R.id.newMessageText);
{
Drawable drawable = getResources().getDrawable(R.drawable.ic_chat_black_24dp);
drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
newMessageIcon.setImageDrawable(drawable);
newMessageTitle.setTextColor(style.getTextPrimaryColor());
}
newMessageView.setOnClickListener(v -> {
startActivity(Intents.openPrivateDialog(user.getId(), true, getActivity()));
});
//
// Voice Call
//
View voiceCallDivider = res.findViewById(R.id.voiceCallDivider);
View voiceCallView = res.findViewById(R.id.voiceCall);
if (ActorSDK.sharedActor().isCallsEnabled() && !user.isBot()) {
ImageView voiceViewIcon = (ImageView) voiceCallView.findViewById(R.id.actionIcon);
TextView voiceViewTitle = (TextView) voiceCallView.findViewById(R.id.actionText);
Drawable drawable = getResources().getDrawable(R.drawable.ic_phone_white_24dp);
drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
voiceViewIcon.setImageDrawable(drawable);
voiceViewTitle.setTextColor(style.getTextPrimaryColor());
voiceCallView.setOnClickListener(v -> {
execute(ActorSDK.sharedActor().getMessenger().doCall(user.getId()));
});
} else {
voiceCallView.setVisibility(View.GONE);
voiceCallDivider.setVisibility(View.GONE);
}
//
// Video Call
//
View videoCallDivider = res.findViewById(R.id.videoCallDivider);
View videoCallView = res.findViewById(R.id.videoCall);
if (ActorSDK.sharedActor().isCallsEnabled() && !user.isBot()) {
ImageView voiceViewIcon = (ImageView) videoCallView.findViewById(R.id.videoCallIcon);
TextView voiceViewTitle = (TextView) videoCallView.findViewById(R.id.videoCallText);
Drawable drawable = getResources().getDrawable(R.drawable.ic_videocam_white_24dp);
drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
voiceViewIcon.setImageDrawable(drawable);
voiceViewTitle.setTextColor(style.getTextPrimaryColor());
videoCallView.setOnClickListener(v -> {
execute(ActorSDK.sharedActor().getMessenger().doVideoCall(user.getId()));
});
} else {
videoCallView.setVisibility(View.GONE);
videoCallDivider.setVisibility(View.GONE);
}
//
// Contact Information
//
final LinearLayout contactsContainer = (LinearLayout) res.findViewById(R.id.contactsContainer);
String aboutString = user.getAbout().get();
boolean isFirstContact = aboutString == null || aboutString.isEmpty();
//
// About
//
bind(user.getAbout(), new ValueChangedListener<String>() {
private View userAboutRecord;
@Override
public void onChanged(final String newUserAbout, Value<String> valueModel) {
if (newUserAbout != null && newUserAbout.length() > 0) {
if (userAboutRecord == null) {
userAboutRecord = buildRecordBig(newUserAbout,
R.drawable.ic_info_outline_black_24dp,
true,
false,
inflater, contactsContainer);
} else {
((TextView) userAboutRecord.findViewById(R.id.value)).setText(newUserAbout);
}
if (recordFieldWithIcon != null) {
recordFieldWithIcon.findViewById(R.id.recordIcon).setVisibility(View.INVISIBLE);
}
}
}
});
if (!ActorSDK.sharedActor().isOnClientPrivacyEnabled() || user.isInPhoneBook().get()) {
//
// Phones
//
for (int i = 0; i < phones.size(); i++) {
final UserPhone userPhone = phones.get(i);
// Formatting Phone Number
String _phoneNumber;
try {
Phonenumber.PhoneNumber number = PhoneNumberUtil.getInstance().parse("+" + userPhone.getPhone(), "us");
_phoneNumber = PhoneNumberUtil.getInstance().format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
} catch (NumberParseException e) {
e.printStackTrace();
_phoneNumber = "+" + userPhone.getPhone();
}
final String phoneNumber = _phoneNumber;
String phoneTitle = userPhone.getTitle();
// "Mobile phone" is default value for non specified title
// Trying to localize this
if (phoneTitle.toLowerCase().equals("mobile phone")) {
phoneTitle = getString(R.string.settings_mobile_phone);
}
View view = buildRecord(phoneTitle,
phoneNumber,
R.drawable.ic_import_contacts_black_24dp,
isFirstContact,
false,
inflater, contactsContainer);
if (isFirstContact) {
recordFieldWithIcon = view;
}
view.setOnClickListener(v -> {
new AlertDialog.Builder(getActivity())
.setItems(new CharSequence[]{
getString(R.string.phone_menu_call).replace("{0}", phoneNumber),
getString(R.string.phone_menu_sms).replace("{0}", phoneNumber),
getString(R.string.phone_menu_share).replace("{0}", phoneNumber),
getString(R.string.phone_menu_copy)
}, (dialog, which) -> {
if (which == 0) {
startActivity(new Intent(Intent.ACTION_DIAL)
.setData(Uri.parse("tel:+" + userPhone.getPhone())));
} else if (which == 1) {
startActivity(new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("sms:+" + userPhone.getPhone())));
} else if (which == 2) {
startActivity(new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, getString(R.string.settings_share_text)
.replace("{0}", phoneNumber)
.replace("{1}", user.getName().get())));
} else if (which == 3) {
ClipboardManager clipboard =
(ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Phone number", phoneNumber);
clipboard.setPrimaryClip(clip);
Snackbar.make(res, R.string.toast_phone_copied, Snackbar.LENGTH_SHORT)
.show();
}
})
.show()
.setCanceledOnTouchOutside(true);
});
view.setOnLongClickListener(v -> {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Phone number", "+" + userPhone.getPhone());
clipboard.setPrimaryClip(clip);
Snackbar.make(res, R.string.toast_phone_copied, Snackbar.LENGTH_SHORT)
.show();
return true;
});
isFirstContact = false;
}
//
// Emails
//
for (int i = 0; i < emails.size(); i++) {
final UserEmail userEmail = emails.get(i);
View view = buildRecord(userEmail.getTitle(),
userEmail.getEmail(),
R.drawable.ic_import_contacts_black_24dp,
isFirstContact,
false,
inflater, contactsContainer);
if (isFirstContact) {
recordFieldWithIcon = view;
}
view.setOnClickListener(v -> {
new AlertDialog.Builder(getActivity())
.setItems(new CharSequence[]{
getString(R.string.email_menu_email).replace("{0}", userEmail.getEmail()),
getString(R.string.phone_menu_copy)
}, (dialog, which) -> {
if (which == 0) {
startActivity(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", userEmail.getEmail(), null)));
} else if (which == 1) {
ClipboardManager clipboard =
(ClipboardManager) getActivity()
.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Email", userEmail.getEmail());
clipboard.setPrimaryClip(clip);
Snackbar.make(res, R.string.toast_email_copied, Snackbar.LENGTH_SHORT)
.show();
}
})
.show()
.setCanceledOnTouchOutside(true);
});
view.setOnLongClickListener(v -> {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Email", "+" + userEmail.getEmail());
clipboard.setPrimaryClip(clip);
Snackbar.make(res, R.string.toast_email_copied, Snackbar.LENGTH_SHORT)
.show();
return true;
});
isFirstContact = false;
}
}
//
// Username
//
final boolean finalIsFirstContact = isFirstContact;
bind(user.getNick(), new ValueChangedListener<String>() {
private View userNameRecord;
@Override
public void onChanged(final String newUserName, Value<String> valueModel) {
if (newUserName != null && newUserName.length() > 0) {
if (userNameRecord == null) {
userNameRecord = buildRecord(getString(R.string.nickname), "@" + newUserName,
R.drawable.ic_import_contacts_black_24dp,
finalIsFirstContact,
false,
inflater, contactsContainer);
} else {
((TextView) userNameRecord.findViewById(R.id.value)).setText(newUserName);
}
userNameRecord.setOnLongClickListener(v -> {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Username", newUserName);
clipboard.setPrimaryClip(clip);
Snackbar.make(res, R.string.toast_nickname_copied, Snackbar.LENGTH_SHORT)
.show();
return true;
});
if (finalIsFirstContact) {
recordFieldWithIcon = userNameRecord;
}
}
}
});
//
// Settings
//
{
//
// Notifications
//
View notificationContainer = res.findViewById(R.id.notificationsCont);
View notificationPickerContainer = res.findViewById(R.id.notificationsPickerCont);
((TextView) notificationContainer.findViewById(R.id.settings_notifications_title)).setTextColor(style.getTextPrimaryColor());
final SwitchCompat notificationEnable = (SwitchCompat) res.findViewById(R.id.enableNotifications);
Peer peer = Peer.user(user.getId());
notificationEnable.setChecked(messenger().isNotificationsEnabled(peer));
if (messenger().isNotificationsEnabled(peer)) {
ViewUtils.showView(notificationPickerContainer, false);
} else {
ViewUtils.goneView(notificationPickerContainer, false);
}
notificationEnable.setOnCheckedChangeListener((buttonView, isChecked) -> {
messenger().changeNotificationsEnabled(Peer.user(user.getId()), isChecked);
if (isChecked) {
ViewUtils.showView(notificationPickerContainer, false);
} else {
ViewUtils.goneView(notificationPickerContainer, false);
}
});
notificationContainer.setOnClickListener(v -> notificationEnable.setChecked(!notificationEnable.isChecked()));
ImageView iconView = (ImageView) res.findViewById(R.id.settings_notification_icon);
Drawable drawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_list_black_24dp));
drawable.mutate();
DrawableCompat.setTint(drawable, style.getSettingsIconColor());
iconView.setImageDrawable(drawable);
((TextView) notificationPickerContainer.findViewById(R.id.settings_notifications_picker_title)).setTextColor(style.getTextPrimaryColor());
notificationPickerContainer.setOnClickListener(view -> {
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Uri currentSound = null;
String defaultPath = null;
Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
String path = messenger().getPreferences().getString("userNotificationSound_" + uid);
if (path == null) {
path = defaultPath;
}
if (path != null && !path.equals("none")) {
if (path.equals(defaultPath)) {
currentSound = defaultUri;
} else {
currentSound = Uri.parse(path);
}
}
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
startActivityForResult(intent, SOUND_PICKER_REQUEST_CODE);
});
//
// Block
//
View blockContainer = res.findViewById(R.id.blockCont);
final TextView blockTitle = (TextView) blockContainer.findViewById(R.id.settings_block_title);
blockTitle.setTextColor(style.getTextPrimaryColor());
bind(user.getIsBlocked(), (val, valueModel) -> {
blockTitle.setText(val ? R.string.profile_settings_unblock : R.string.profile_settings_block);
});
blockContainer.setOnClickListener(v -> {
if (!user.getIsBlocked().get()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.profile_settings_block_confirm).replace("{user}", user.getName().get()))
.setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
execute(messenger().blockUser(user.getId()));
dialog.dismiss();
})
.setNegativeButton(R.string.dialog_cancel, (dialog, which) -> {
dialog.dismiss();
})
.show();
} else {
execute(messenger().unblockUser(user.getId()));
}
});
ImageView blockIconView = (ImageView) res.findViewById(R.id.settings_block_icon);
Drawable blockDrawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_block_white_24dp));
drawable.mutate();
DrawableCompat.setTint(blockDrawable, style.getSettingsIconColor());
blockIconView.setImageDrawable(blockDrawable);
}
//
// Scroll Coordinate
//
final ScrollView scrollView = ((ScrollView) res.findViewById(R.id.scrollContainer));
scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> updateBar(scrollView.getScrollY()));
updateBar(scrollView.getScrollY());
return res;
}
private void checkInfiIcon() {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SOUND_PICKER_REQUEST_CODE) {
Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (ringtone != null) {
messenger().getPreferences().putString("userNotificationSound_" + uid, ringtone.toString());
} else {
messenger().getPreferences().putString("userNotificationSound_" + uid, "none");
}
}
}
@Override
public void onResume() {
super.onResume();
messenger().onProfileOpen(uid);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.profile_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getActivity().finish();
return true;
} else if (item.getItemId() == R.id.edit) {
startActivity(Intents.editUserName(uid, getActivity()));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
private void updateBar(int offset) {
ActionBar bar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (bar != null) {
int fullColor = style.getToolBarColor();
if (Math.abs(offset) > Screen.dp(248 - 56)) {
bar.setBackgroundDrawable(new ColorDrawable(fullColor));
} else {
float alpha = Math.abs(offset) / (float) Screen.dp(248 - 56);
bar.setBackgroundDrawable(new ColorDrawable(Color.argb(
(int) (255 * alpha),
Color.red(fullColor),
Color.green(fullColor),
Color.blue(fullColor)
)));
}
}
}
@Override
public void onPause() {
super.onPause();
messenger().onProfileClosed(uid);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (avatarView != null) {
avatarView.unbind();
avatarView = null;
}
}
}
| agpl-3.0 |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/zuzhijiagou/ZzjgFragment.java | 24121 | package im.actor.sdk.controllers.zuzhijiagou;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import im.actor.core.viewmodel.UserVM;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.R;
import im.actor.sdk.controllers.BaseFragment;
import im.actor.sdk.controllers.Intents;
import im.actor.sdk.controllers.root.Node;
import im.actor.sdk.controllers.zuzhijiagou.TreeDanWeiAdapter;
import im.actor.sdk.controllers.search.GlobalSearchDefaultFragment;
import im.actor.sdk.controllers.zuzhijiagou.topBar.TopBarAdapter;
import im.actor.sdk.controllers.zuzhijiagou.topBar.TopBarItemDecoration;
import im.actor.sdk.controllers.zuzhijiagou.topBar.TreeBarBean;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
import static im.actor.sdk.util.ActorSDKMessenger.users;
/**
* Created by huchengjie on 2017/9/21.
*/
public class ZzjgFragment extends BaseFragment {
private Node rootNode;
private View emptyView;
RecyclerView topBarRecyclerView;
ListView dwcollection;
// ListView bmcollection;
// ListView rycollection;
// TextView zuZhiTitleText;
// ImageView backImage;
LinearLayout zuzhijiagou_lay;
int treeSize = 0;//0表示单位层级,1表示部门层级,2表示人员层级
HashMap<String, HashMap<String, List<Node>>> bmMap = new HashMap<String, HashMap<String, List<Node>>>();
HashMap<String, HashMap<String, HashMap<String, List<Node>>>> ryMap = new HashMap<>();
public ZzjgFragment() {
setRootFragment(true);
setHomeAsUp(true);
setTitle("组织架构");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return onCreateContactsView(R.layout.fragment_base_zuzhijiagou, inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public RecyclerView.Adapter adapter;
TopBarAdapter baradapter;
protected View onCreateContactsView(int layoutId, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View res = inflater.inflate(layoutId, container, false);
topBarRecyclerView = (RecyclerView) res.findViewById(R.id.zuzhijiagou_topbar);
topBarRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
List<TreeBarBean> bars = new ArrayList<TreeBarBean>();
baradapter = new TopBarAdapter(getContext(), bars);
baradapter.setOnItemClickLitener(new TopBarAdapter.OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
TreeBarBean barBean = baradapter.getBars().get(position);
if (position == baradapter.getItemCount() - 1)
return;
Node root = new Node("", "-1");
TreeDanWeiAdapter danWeiAdapter = (TreeDanWeiAdapter) dwcollection.getAdapter();
List<Node> nodes = new ArrayList<>();
nodes.addAll(barBean.getNodes());
root.setChildren(nodes);
danWeiAdapter.setRoot(root);
danWeiAdapter.notifyDataSetChanged();
treeSize = barBean.getTreeSize();
int count = baradapter.getItemCount() - 1;
for (int i = count; i > position; i--) {
baradapter.getBars().remove(i);
}
baradapter.notifyDataSetChanged();
}
});
topBarRecyclerView.setAdapter(baradapter);
topBarRecyclerView.addItemDecoration(new TopBarItemDecoration(getContext()));
dwcollection = (ListView) res.findViewById(R.id.zuzhijiagou_dw);
// bmcollection = (ListView) res.findViewById(R.id.zuzhijiagou_bm);
// rycollection = (ListView) res.findViewById(R.id.zuzhijiagou_ry);
zuzhijiagou_lay = (LinearLayout) res.findViewById(R.id.zuzhijiagou_title_lay);
ZzjgData(ActorSDK.getZjjgData());
res.findViewById(R.id.zuzhijiagou_dw).setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
emptyView = res.findViewById(R.id.emptyCollection);
if (emptyView != null) {
emptyView.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
emptyView.findViewById(R.id.empty_collection_bg).setBackgroundColor(ActorSDK.sharedActor().style.getMainColor());
((TextView) emptyView.findViewById(R.id.empty_collection_text)).setTextColor(ActorSDK.sharedActor().style.getMainColor());
} else {
emptyView = res.findViewById(R.id.empty_collection_text);
if (emptyView != null && emptyView instanceof TextView) {
((TextView) emptyView.findViewById(R.id.empty_collection_text)).setTextColor(ActorSDK.sharedActor().style.getMainColor());
}
}
// setAnimationsEnabled(false);
// View headerPadding = new View(getActivity());
// headerPadding.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
// headerPadding.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, useCompactVersion ? 0 : ActorSDK.sharedActor().style.getContactsMainPaddingTop()));
// addHeaderView(headerPadding);
//
// addFootersAndHeaders();
if (emptyView != null) {
dwcollection.setEmptyView(emptyView);
// if (messenger().getAppState().getIsContactsEmpty().get()) {
// emptyView.setVisibility(View.VISIBLE);
// } else {
// emptyView.setVisibility(View.GONE);
// }
}
// bind(messenger().getAppState().getIsContactsEmpty(), new ValueChangedListener<Boolean>() {
// @Override
// public void onChanged(Boolean val, Value<Boolean> Value) {
// if (emptyView != null) {
// if (val) {
// emptyView.setVisibility(View.VISIBLE);
// } else {
// emptyView.setVisibility(View.GONE);
// }
// }
// }
// });
// emptyView.setVisibility(View.GONE);
res.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
return res;
}
// protected RecyclerView.Adapter onCreateAdapter(Node node, Activity activity) {
// return new ZzjgAdapter(rootNode, activity, false, new OnItemClickedListener<Contact>() {
// @Override
// public void onClicked(Contact item) {
// onItemClicked(item);
// }
//
// @Override
// public boolean onLongClicked(Contact item) {
// return onItemLongClicked(item);
// }
// });
// }
protected void configureRecyclerView(RecyclerView recyclerView) {
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setRecycleChildrenOnDetach(false);
linearLayoutManager.setSmoothScrollbarEnabled(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHorizontalScrollBarEnabled(false);
recyclerView.setVerticalScrollBarEnabled(true);
}
public void setAnimationsEnabled(boolean isEnabled) {
if (isEnabled) {
// DefaultItemAnimator itemAnimator = new DefaultItemAnimator();
// // CustomItemAnimator itemAnimator = new CustomItemAnimator();
// itemAnimator.setSupportsChangeAnimations(false);
// itemAnimator.setMoveDuration(200);
// itemAnimator.setAddDuration(150);
// itemAnimator.setRemoveDuration(200);
// dwcollection.setItemAnimator(itemAnimator);
dwcollection.setVisibility(View.VISIBLE);
} else {
dwcollection.setVisibility(View.GONE);
}
}
public void ZzjgData(JSONObject json) {
JSONArray yh_array = null;
try {
if (json == null) {
return;
}
dwcollection.setVisibility(View.VISIBLE);
// bmcollection.setVisibility(View.GONE);
// rycollection.setVisibility(View.GONE);
zuzhijiagou_lay.setVisibility(View.VISIBLE);
yh_array = json.getJSONArray("yh_data");
System.out.println(yh_array.toString());
List<Node> yhList = getListNode(yh_array, new String[]{"iGIMID", "xm", "wzh", null, "dwid", "bmid"});
// yhList = getAdapterRoot(yhList).getChildren();
ryMap = new HashMap<>();
for (int i = 0; i < yhList.size(); i++) {
Node node = yhList.get(i);
node.setRy(true);
JSONObject ryJson = node.getJson();
String zwmc = ryJson.getString("zwmc").trim();
if (zwmc.length() > 0) {
zwmc = "(" + zwmc + ")";
}
node.setText(node.getText() + zwmc);
String dwid = node.getDwid();
String bmid = node.getBmid();
String szk = node.getSzk();
HashMap<String, HashMap<String, List<Node>>> maps = new HashMap<>();
if (ryMap.get(szk) != null)
maps = ryMap.get(szk);
HashMap<String, List<Node>> mapDws = new HashMap<>();
if (maps.get(dwid) != null)
mapDws = maps.get(dwid);
List<Node> ryLists = new ArrayList<Node>();
if (mapDws.get(bmid) != null)
ryLists = mapDws.get(bmid);
ryLists.add(node);
mapDws.put(bmid, ryLists);
maps.put(dwid, mapDws);
ryMap.put(szk, maps);
}
JSONArray dw_array = json.getJSONArray("dw_data");
List<Node> dwList = getListNode(dw_array, new String[]{"id", "mc", "wzh", "egDel"});
Collections.sort(dwList);
dwList = getAdapterRoot(dwList).getChildren();
JSONArray bm_array = json.getJSONArray("bm_data");
List<Node> bmList = getListNode(bm_array, new String[]{"id", "mc", "wzh", "fid", "dwid"});
// bmList = getAdapterRoot(bmList).getChildren();
bmMap = new HashMap<>();
for (int i = 0; i < bmList.size(); i++) {
Node node = bmList.get(i);
System.out.println(node.toString());
String dwid = node.getDwid();
if (dwid == null && node.getFid() != null) {
dwid = getDwid(bmList, node.getFid());
node.setDwid(dwid);
}
String szk = node.getSzk();
List<Node> bmNodes = new ArrayList<Node>();
HashMap<String, List<Node>> mapSzks = new HashMap<>();
if (bmMap.get(szk) != null) {
mapSzks = bmMap.get(szk);
}
// if (ryMap.get(dwid) != null &&
// ryMap.get(dwid).get(node.getValue()) != null) {
// node.setChildren(ryMap.get(dwid).get(node.getValue()));
// }
if (mapSzks.get(dwid) != null) {
bmNodes = mapSzks.get(dwid);
}
if (ryMap.get(szk).get(dwid) != null) {
List<Node> ryNodes = ryMap.get(szk).get(dwid).get(node.getValue());
if (ryNodes != null) {
node.setChildrenSize(ryNodes.size());
} else {
// System.out.println("iGem:" + node.getText() + "setChildrenSize:0");
node.setChildrenSize(0);
}
}
bmNodes.add(node);
System.out.println("EgTool---" + node.getText() + "---" + node.getValue() + "----" + node.getDwid() + "---" + bmNodes.size());
mapSzks.put(dwid, bmNodes);
bmMap.put(szk, mapSzks);
}
for (String szk : bmMap.keySet()) {
HashMap<String, List<Node>> valueMap = bmMap.get(szk);
for (String dwid : valueMap.keySet()) {
List<Node> list = valueMap.get(dwid);
if (list != null) {
Collections.sort(list);
list = getAdapterRoot(list).getChildren();
}
for (Node node : list) {
if (node.getChildrenSize() == 0 && node.getChildren() != null) {
node.setChildrenSize(node.getChildren().size());
// System.out.println("iGem:" + node.getText() + ":node.getChildren().size():" + node.getChildren().size());
}
}
bmMap.get(szk).put(dwid, list);
}
}
// for (HashMap<String, List<Node>> valueMap : bmMap.values()) {
// for (List<Node> list : valueMap.values()){
// if (list != null) {
// Collections.sort(list);
// list = getAdapterRoot(list).getChildren();
// }
//// bmMap.get()
// for (Node node: list) {
// if(node.getChildrenSize() == 0&&node.getChildren() !=null){
// node.setChildrenSize(node.getChildren().size());
// System.out.println("iGem:"+node.getText()+":node.getChildren().size():"+node.getChildren().size());
// }
// }
// }
// }
// for (int i = 0; i < dwList.size(); i++) {
// Node node = dwList.get(i);
// String dwid = node.getValue();
// node.setChildren(bmMap.get(dwid));
// }
rootNode = new Node("", "-1");
List<Node> dwNodes = new ArrayList<>();
dwNodes.addAll(dwList);
rootNode.setChildren(dwNodes);
if (rootNode == null || rootNode.getChildren() == null || rootNode.getChildren().size() == 0) {
dwcollection.setVisibility(View.INVISIBLE);
} else {
dwcollection.setVisibility(View.VISIBLE);
}
List<Node> bars = new ArrayList<>();
bars.addAll(dwList);
baradapter.getBars().add(new TreeBarBean("单位", bars, treeSize));
baradapter.notifyItemInserted(0);
TreeDanWeiAdapter danWeiAdapter = (TreeDanWeiAdapter) dwcollection.getAdapter();
Node dwNode = new Node("", "-1");
dwNode.setChildren(dwList);
if (danWeiAdapter == null) {
danWeiAdapter = new TreeDanWeiAdapter(getContext(), dwNode);
dwcollection.setAdapter(danWeiAdapter);
} else {
danWeiAdapter.setRoot(dwNode);
danWeiAdapter.notifyDataSetChanged();
}
dwcollection.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TreeDanWeiAdapter danWeiAdapter = (TreeDanWeiAdapter) dwcollection.getAdapter();
Node node = (Node) danWeiAdapter.getItem(i);
Node root = new Node("", "-1");
TreeBarBean barBean = new TreeBarBean();
barBean.setText(node.getText());
List<Node> nodes = new ArrayList<>();
List<Node> bars = new ArrayList<>();
List<Node> nrNodes = new ArrayList<>();
int isRY = 0;
if (node.isRy()) {
isRY = 1;
} else if (node.getChildren() != null && node.getChildren().size() > 0) {
nrNodes = node.getChildren();
try {
List<Node> ryNodes = ryMap.get(node.getSzk()).get(node.getDwid()).get(node.getValue());
if (ryNodes != null && ryNodes.size() > 0) {
if (!nrNodes.contains(ryNodes.get(0))) {
if (nrNodes != null)
Collections.sort(ryNodes);
nrNodes.addAll(0, ryNodes);
nrNodes.add(ryNodes.size(), new Node("进入人员列表", "-9999"));
}
}
} catch (Exception e) {
e.printStackTrace();
// System.out.println("iGem:" + e.getMessage());
}
} else if (treeSize == 0) {
//从单位进入部门。
treeSize = 1;
nrNodes = bmMap.get(node.getSzk()).get(node.getValue());
// if (bmNodes != null) {
// Collections.sort(bmNodes);
// bmNodes = getAdapterRoot(bmNodes).getChildren();
// }
} else if (treeSize == 1) {
//从部门进入人员
treeSize = 2;
nrNodes = ryMap.get(node.getSzk()).get(node.getDwid()).get(node.getValue());
if (nrNodes != null) {
Collections.sort(nrNodes);
} else {
nrNodes = new ArrayList<>();
}
}
if (isRY == 1) {
onItemClicked(Integer.parseInt(node.getValue()));
} else {
nodes.addAll(nrNodes);
bars.addAll(nrNodes);
barBean.setNodes(bars);
root.setChildren(nodes);
danWeiAdapter.setRoot(root);
danWeiAdapter.notifyDataSetChanged();
topBarChanged(barBean, treeSize);
}
}
});
dwcollection.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getDwid(List<Node> bmList, String fid) {
Optional optional = bmList.stream().filter(bm -> fid.equals(bm.getValue())).findFirst();
if (!optional.equals(Optional.empty())) {
Node fNode = (Node) optional.get();
String dwid = fNode.getDwid();
if (dwid == null) {
if (dwid == null && fNode.getFid() != null) {
String t = getDwid(bmList, fNode.getFid());
return t;
}
} else {
return dwid;
}
}
return null;
}
// 根据一个jsonArray生成一个无关系的list<Node>
public static List<Node> getListNode(JSONArray jsonArray, String[] jsonName) {
List<Node> nodes = new ArrayList<Node>();
for (int i = 0; i < jsonArray.length(); i++)// 第一层节点数据
{
try {
JSONObject jo = jsonArray.getJSONObject(i);
Node node = new Node(jo.getString(jsonName[1]).trim(), jo
.getString(jsonName[0]).trim());
// 顺序依次为id,mc,wzh,父id
if (jsonName[2] != null) {
String wzh = jo.getString(jsonName[2]).trim();
if ("".equals(wzh)) {
wzh = "9999";
} else if (wzh == null) {
wzh = "9999";
}
node.setWzh(wzh);
}
if (jsonName[3] != null) {
try {
if (jsonName[3].equals("egDel")) {
//单位数据fid是-1的干掉一层
String fid = jo.getString("fid");
if (fid.equals("-1")) {
continue;
}
} else {
node.setFid(jo.getString(jsonName[3]).trim());
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (jsonName.length > 4) {
node.setDwid(jo.getString(jsonName[4]).trim());
}
if (jsonName.length > 5) {
node.setBmid(jo.getString(jsonName[5]).trim());
}
// if (jsonName.length > 6) {
node.setSzk("ZGGF");
// }
if (node.getDwid() != null && node.getDwid().equals(node.getFid())) {
node.setFid("-1");
}
node.setJson(jo);
nodes.add(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
return nodes;
}
// 根据得到的list<Node>,在处理父子关系
public Node getAdapterRoot(List<Node> nodes) {
Node root = new Node("", "-1");
for (int i = 0; i < nodes.size(); i++) {
Node node = nodes.get(i);
if (node.getFid() == null || "-1".equals(node.getFid())) {
node.setFid("-1");
node.setParent(root);// 设置父节点
root.add(node);
} else {
for (int j = 0; j < nodes.size(); j++) {
Node nodePar = nodes.get(j);
if (nodePar.getValue().equals(node.getFid())) {
node.setParent(nodePar);// 设置父节点
nodePar.add(node);
break;
}
}
}
// if (node.getChildrenSize() == 0 && node.getChildren() != null) {
// node.setChildrenSize(node.getChildren().size());
//// System.out.println("iGem:" + node.getText() + ":node.getChildren().size():" + node.getChildren().size());
// }
}
return root;
}
private void topBarChanged(TreeBarBean bar, int treeSize) {
bar.setTreeSize(treeSize);
List<TreeBarBean> bars = baradapter.getBars();
bars.add(bar);
baradapter.notifyItemChanged(bars.size() - 2);
baradapter.notifyItemInserted(bars.size() - 1);
topBarRecyclerView.smoothScrollToPosition(bars.size() - 1);
}
public void onItemClicked(int uid) {
try {
UserVM userVM = users().get(uid);
getActivity().startActivity(Intents.openPrivateDialog(uid, true, getActivity()));
} catch (Exception e) {
// e.printStackTrace();
}
}
}
| agpl-3.0 |
julie-sullivan/phytomine | intermine/model/main/src/org/intermine/metadata/ReferenceDescriptor.java | 8049 | package org.intermine.metadata;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.apache.commons.lang.StringUtils;
/**
* Describes a field that references a single other class (i.e. not a collection
* of objects). getReverseReferenceDescriptor() allows one to work out the multiplicity
* of the association's other end.
*
* @author Richard Smith
*/
public class ReferenceDescriptor extends FieldDescriptor
{
protected final String referencedType;
protected ClassDescriptor referencedClassDesc;
protected final String reverseRefName; // can be reference, collection or null
protected ReferenceDescriptor reverseRefDesc;
private boolean modelSet = false;
/**
* Construct a ReferenceDescriptor. Requires the name of Class referenced and
* the field in the referenced class that refers back to this (will be null in
* a unidirectional relationship).
* @param name name of the field
* @param referencedType fully qualfied class name of another business object
* @param reverseRefName name of the field in remote object that refers back to this one
* @throws IllegalArgumentException if fields are null
*/
public ReferenceDescriptor(String name, String referencedType, String reverseRefName) {
super(name);
if (referencedType == null || "".equals(referencedType)) {
throw new IllegalArgumentException("A value must be provided for "
+ "the referenced type");
}
this.reverseRefName = reverseRefName;
this.referencedType = referencedType;
}
/**
* Returns a ClassDescriptor for the object referenced by this field.
* @return ClassDescriptor for the referenced object
* @throws IllegalStateException if model has not been set
*/
public ClassDescriptor getReferencedClassDescriptor() {
if (!modelSet) {
throw new IllegalStateException("This ReferenceDescriptor (" + getName()
+ ") is not yet part of a metadata Model");
}
return referencedClassDesc;
}
/**
* Gets the name of the reverse reference field.
* @return the name of the reverse reference field
*/
public String getReverseReferenceFieldName() {
return reverseRefName;
}
/**
* Returns the class name of the object referenced by this field.
* @return the class name of the object referenced
*/
public String getReferencedClassName() {
return referencedType;
}
/**
* Gets the field in the referenced object that refers back to this class.
* Note that this will be null in a unidirectional relationship,
* a ReferenceDescriptor in a 1:1 and a CollectionDescriptor in a 1:N.
* @return a FieldDescriptor referring back to this class.
* @throws IllegalStateException if model has not been set
*/
public ReferenceDescriptor getReverseReferenceDescriptor() {
if (!modelSet) {
throw new IllegalStateException("This ReferenceDescriptor (" + getName()
+ ") is not yet part of a metadata Model");
}
return reverseRefDesc;
}
/**
* sort out references from this class
* @throws MetaDataException if references not found
*/
protected void findReferencedDescriptor() throws MetaDataException {
// find ClassDescriptor for referenced class
if (cld.getModel().hasClassDescriptor(referencedType)) {
referencedClassDesc = cld.getModel().getClassDescriptorByName(referencedType);
} else {
throw new MetaDataException("Unable to find ClassDescriptor for '"
+ referencedType + "' in model while processing: " + cld.getName() + "."
+ name);
}
// find ReferenceDescriptor for the reverse reference
if (!StringUtils.isBlank(reverseRefName)) {
reverseRefDesc = referencedClassDesc.getReferenceDescriptorByName(reverseRefName);
if (reverseRefDesc == null) {
reverseRefDesc = referencedClassDesc
.getCollectionDescriptorByName(reverseRefName);
}
if (reverseRefDesc == null) {
throw new MetaDataException("Unable to find named reverse reference '"
+ reverseRefName + "' in class " + referencedClassDesc.getName()
+ " while processing: " + getClassDescriptor().getName() + "." + getName());
}
// Reverse references need to point to one another and have correct types
// NOTE these checks were added when models already exist that fail them, so we can't
// throw a MetaDataException, instead add problems to the model that are checked by
// the ModelMerger when creating new models.
if (reverseRefDesc.getReverseReferenceFieldName() != null) {
if (!reverseRefDesc.getReverseReferenceFieldName().equals(this.name)) {
modelSet = true;
throw new NonFatalMetaDataException("Reverse reference names do not match: "
+ reverseRefDesc.getReverseReferenceFieldName() + " and " + this.name
+ " (" + this.cld.getName() + ": " + this.toString() + ", "
+ referencedType + ": " + reverseRefDesc.toString() + ")");
}
if (!reverseRefDesc.referencedType.equals(this.cld.getName())) {
modelSet = true;
throw new NonFatalMetaDataException("Reverse reference types do not match: "
+ this.cld.getName() + ": " + this.toString() + ", "
+ referencedType + ": " + reverseRefDesc.toString());
}
}
}
modelSet = true;
}
/**
* {@inheritDoc}
*/
@Override
public int relationType() {
ReferenceDescriptor rd = getReverseReferenceDescriptor();
if ((rd == null) || (rd instanceof CollectionDescriptor)) {
return N_ONE_RELATION;
} else {
return ONE_ONE_RELATION;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof ReferenceDescriptor) {
ReferenceDescriptor ref = (ReferenceDescriptor) obj;
return name.equals(ref.name)
&& referencedType.equals(ref.referencedType)
&& Util.equals(reverseRefName, ref.reverseRefName);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 3 * name.hashCode()
+ 7 * referencedType.hashCode()
+ 11 * Util.hashCode(reverseRefName);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<reference name=\"" + name + "\" referenced-type=\""
+ referencedType.substring(referencedType.lastIndexOf(".") + 1) + "\"")
.append(reverseRefName != null ? " reverse-reference=\"" + reverseRefName + "\"" : "")
.append("/>");
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toJSONString() {
StringBuffer sb = new StringBuffer();
sb.append("{\"name\":\"" + name + "\","
+ "\"referencedType\":\""
+ referencedType.substring(referencedType.lastIndexOf(".") + 1) + "\"");
if (reverseRefName != null) {
sb.append(",\"reverseReference\":\"" + reverseRefName + "\"");
}
sb.append("}");
return sb.toString();
}
}
| lgpl-2.1 |
soultek101/projectzulu1.7.10 | src/main/java/com/stek101/projectzulu/common/blocks/BlockPalmTreeSapling.java | 8994 | package com.stek101.projectzulu.common.blocks;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBush;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.stek101.projectzulu.common.ProjectZulu_Core;
import com.stek101.projectzulu.common.api.BlockList;
public class BlockPalmTreeSapling extends BlockBush {
public BlockPalmTreeSapling() {
super(Material.plants);
float var3 = 0.4F;
this.setBlockBounds(0.5F - var3, 0.0F, 0.5F - var3, 0.5F + var3, var3 * 2.0F, 0.5F + var3);
this.setCreativeTab(ProjectZulu_Core.projectZuluCreativeTab);
}
/**
* Ticks the block if it's been scheduled
*/
@Override
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random) {
if (!par1World.isRemote) {
super.updateTick(par1World, par2, par3, par4, par5Random);
if (par1World.getBlockLightValue(par2, par3 + 1, par4) >= 9 && par5Random.nextInt(7) == 0) {
this.growTree(par1World, par2, par3, par4, par5Random);
}
}
}
/**
* Attempts to grow a sapling into a tree
*/
public void growTree(World par1World, int par2, int par3, int par4, Random par5Random) {
if (!par1World.isRemote && BlockList.palmTreeLeaves.isPresent() && BlockList.palmTreeLog.isPresent()) {
int height = par5Random.nextInt(3) + 4;
// Check if there is water nearby 9x9
// As loop finds water it incremement direction towards it,
// The favored direction at the end of the loop will be towards the side with more water
int favoredDirectionX = 0;
int favoredDirectionZ = 0;
for (int i = -4; i <= 4; i++) {
for (int k = -4; k <= 4; k++) {
for (int j = -4; j <= 4; j++) {
Block ID = par1World.getBlock(par2 + i, par3 + j, par4 + k);
if (ID == Blocks.flowing_water || ID == Blocks.water) {
// Add +/- 1 to favored Direcion indicating the direction water is in
if (i != 0) {
favoredDirectionX += i / Math.abs(i);
}
if (k != 0) {
favoredDirectionZ += k / Math.abs(k);
}
}
}
}
}
// TBD: If favoredDirectionX and Z are almost the same, greater than 2 and Rare chance, spawn multiple
// trees.
// Set FavoredDirection that is less to zero, as we don't want to grow a tree in that direction
if (Math.abs(favoredDirectionX) - Math.abs(favoredDirectionZ) >= 0) {
favoredDirectionZ = 0;
} else {
favoredDirectionX = 0;
}
// Temp variables used in placing log blocks, work wrt global coordinats of block
int localX = 0;
int localY = 0;
int localZ = 0;
// Adjusts the 'cost' of placing a block horizontally, higher means less horizontal variance
// Does not affect vertical, which is set by height
int horizontalFactor = par5Random.nextInt(10) + 20;
Block palmTreeLogID = BlockList.palmTreeLog.get();
while (localY <= height) {
// Place Log above by 1
localY++;
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
if (favoredDirectionX > 0) {
localX++;
favoredDirectionX = Math.max(favoredDirectionX - horizontalFactor, 0);
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
} else if (favoredDirectionX < 0) {
localX--;
favoredDirectionX = Math.min(favoredDirectionX + horizontalFactor, 0);
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
}
if (favoredDirectionZ > 0) {
localZ++;
favoredDirectionZ = Math.max(favoredDirectionZ - horizontalFactor, 0);
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
} else if (favoredDirectionZ < 0) {
localZ--;
favoredDirectionZ = Math.min(favoredDirectionZ + horizontalFactor, 0);
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
}
if (localY + 1 == height) {
localY++;
par1World.setBlock(par2 + localX, par3 + localY, par4 + localZ, palmTreeLogID);
localY++;
spawnLeaves(par1World, par2 + localX, par3 + localY, par4 + localZ, par5Random, height);
// Place block at original sapling locations
par1World.setBlock(par2, par3, par4, palmTreeLogID);
}
}
}
}
public void spawnLeaves(World par1World, int par2, int par3, int par4, Random par5Random, int height) {
Block palmTreeLeavesID = BlockList.palmTreeLeaves.get();
// TODO: Add more Leave Spawn Templates
if (height + 1 >= 7) {
par1World.setBlock(par2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 1, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 3, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 4, par3 - 1, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 1, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 3, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 3, par3 - 1, par4, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 - 1, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 - 2, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 - 3, palmTreeLeavesID);
par1World.setBlock(par2, par3 - 1, par4 - 3, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 + 1, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 + 2, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 + 3, palmTreeLeavesID);
par1World.setBlock(par2, par3 - 1, par4 + 3, palmTreeLeavesID);
} else {
par1World.setBlock(par2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 1, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 - 2, par3 - 1, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 1, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 2, par3, par4, palmTreeLeavesID);
par1World.setBlock(par2 + 2, par3 - 1, par4, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 - 1, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 - 2, palmTreeLeavesID);
par1World.setBlock(par2, par3 - 1, par4 - 2, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 + 1, palmTreeLeavesID);
par1World.setBlock(par2, par3, par4 + 2, palmTreeLeavesID);
par1World.setBlock(par2, par3 - 1, par4 + 2, palmTreeLeavesID);
}
}
@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer,
int par6, float par7, float par8, float par9) {
ItemStack itemstack = par5EntityPlayer.inventory.getCurrentItem();
if (itemstack != null && itemstack.getItem() == Items.dye) {
if (itemstack.getItemDamage() == 15) {
growTree(par1World, par2, par3, par4, par1World.rand);
if (!par5EntityPlayer.capabilities.isCreativeMode) {
itemstack.stackSize--;
}
}
}
super.onBlockActivated(par1World, par2, par3, par4, par5EntityPlayer, par6, par7, par8, par9);
return true;
}
@Override
protected boolean canPlaceBlockOn(Block block) {
return block == Blocks.sand || block == Blocks.dirt || block == Blocks.grass;
}
/**
* Determines the damage on the item the block drops. Used in cloth and wood.
*/
@Override
public int damageDropped(int par1) {
return par1;
}
}
| lgpl-2.1 |
CheeseL0ver/Ore-TTM | build/tmp/recompSrc/net/minecraft/network/play/server/S30PacketWindowItems.java | 2648 | package net.minecraft.network.play.server;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.io.IOException;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
public class S30PacketWindowItems extends Packet
{
private int field_148914_a;
private ItemStack[] field_148913_b;
private static final String __OBFID = "CL_00001294";
public S30PacketWindowItems() {}
public S30PacketWindowItems(int p_i45186_1_, List p_i45186_2_)
{
this.field_148914_a = p_i45186_1_;
this.field_148913_b = new ItemStack[p_i45186_2_.size()];
for (int j = 0; j < this.field_148913_b.length; ++j)
{
ItemStack itemstack = (ItemStack)p_i45186_2_.get(j);
this.field_148913_b[j] = itemstack == null ? null : itemstack.copy();
}
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer p_148837_1_) throws IOException
{
this.field_148914_a = p_148837_1_.readUnsignedByte();
short short1 = p_148837_1_.readShort();
this.field_148913_b = new ItemStack[short1];
for (int i = 0; i < short1; ++i)
{
this.field_148913_b[i] = p_148837_1_.readItemStackFromBuffer();
}
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer p_148840_1_) throws IOException
{
p_148840_1_.writeByte(this.field_148914_a);
p_148840_1_.writeShort(this.field_148913_b.length);
ItemStack[] aitemstack = this.field_148913_b;
int i = aitemstack.length;
for (int j = 0; j < i; ++j)
{
ItemStack itemstack = aitemstack[j];
p_148840_1_.writeItemStackToBuffer(itemstack);
}
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandlerPlayClient p_148833_1_)
{
p_148833_1_.handleWindowItems(this);
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandler p_148833_1_)
{
this.processPacket((INetHandlerPlayClient)p_148833_1_);
}
@SideOnly(Side.CLIENT)
public int func_148911_c()
{
return this.field_148914_a;
}
@SideOnly(Side.CLIENT)
public ItemStack[] func_148910_d()
{
return this.field_148913_b;
}
} | lgpl-2.1 |
windauer/exist | exist-core/src/main/java/org/exist/client/DialogCompleteWithResponse.java | 1084 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2012 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
package org.exist.client;
/**
*
* @author <a href="mailto:adam.retter@googlemail.com">Adam Retter</a>
*/
public interface DialogCompleteWithResponse<T> {
public void complete(final T response);
}
| lgpl-2.1 |
offn/Myrelease | jcommune-service/src/main/java/org/jtalks/jcommune/service/transactional/TransactionalTopicFetchService.java | 4745 | /**
* Copyright (C) 2011 JTalks.org Team
* 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.
* 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.jtalks.jcommune.service.transactional;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.jtalks.jcommune.model.dao.TopicDao;
import org.jtalks.jcommune.model.dao.search.TopicSearchDao;
import org.jtalks.jcommune.model.dto.JCommunePageRequest;
import org.jtalks.jcommune.model.entity.Branch;
import org.jtalks.jcommune.model.entity.Topic;
import org.jtalks.jcommune.service.TopicFetchService;
import org.jtalks.jcommune.service.UserService;
import org.jtalks.jcommune.service.exceptions.NotFoundException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.Collections;
/**
* Performs load operations on topic based on various
* conditions. Topic search operations are also performed here.
*/
public class TransactionalTopicFetchService extends AbstractTransactionalEntityService<Topic, TopicDao>
implements TopicFetchService {
private UserService userService;
private TopicSearchDao searchDao;
/**
* @param dao topic dao for database manipulations
* @param userService to get current user and his preferences
* @param searchDao for search index access
*/
public TransactionalTopicFetchService(TopicDao dao, UserService userService, TopicSearchDao searchDao) {
super(dao);
this.userService = userService;
this.searchDao = searchDao;
}
/**
* {@inheritDoc}
*/
@Override
public Topic get(Long id) throws NotFoundException {
Topic topic = super.get(id);
topic.setViews(topic.getViews() + 1);
this.getDao().saveOrUpdate(topic);
return topic;
}
/**
* {@inheritDoc}
*/
@Override
public Page<Topic> getRecentTopics(int page) {
int pageSize = userService.getCurrentUser().getPageSize();
JCommunePageRequest pageRequest = JCommunePageRequest.createWithPagingEnabled(page, pageSize);
DateTime date24HoursAgo = new DateTime().minusDays(1);
return this.getDao().getTopicsUpdatedSince(date24HoursAgo, pageRequest, userService.getCurrentUser());
}
/**
* {@inheritDoc}
*/
@Override
public Page<Topic> getUnansweredTopics(int page) {
int pageSize = userService.getCurrentUser().getPageSize();
JCommunePageRequest pageRequest = JCommunePageRequest.createWithPagingEnabled(page, pageSize);
return this.getDao().getUnansweredTopics(pageRequest, userService.getCurrentUser());
}
/**
* {@inheritDoc}
*/
@Override
public Page<Topic> getTopics(Branch branch, int page, boolean pagingEnabled) {
int pageSize = userService.getCurrentUser().getPageSize();
JCommunePageRequest pageRequest = new JCommunePageRequest(page, pageSize, pagingEnabled);
return getDao().getTopics(branch, pageRequest);
}
/**
* {@inheritDoc}
*/
@Override
public Page<Topic> searchByTitleAndContent(String phrase, int page) {
if (!StringUtils.isEmpty(phrase)) {
int pageSize = userService.getCurrentUser().getPageSize();
JCommunePageRequest pageRequest = JCommunePageRequest.createWithPagingEnabled(page, pageSize);
// hibernate search refuses to process long string throwing error
String normalizedPhrase = StringUtils.left(phrase, 50);
return searchDao.searchByTitleAndContent(normalizedPhrase, pageRequest);
}
return new PageImpl<Topic>(Collections.<Topic>emptyList());
}
/**
* {@inheritDoc}
*/
@Override
public void rebuildSearchIndex() {
searchDao.rebuildIndex();
}
/**
* {@inheritDoc}
*/
@PreAuthorize("hasPermission(#branchId, 'BRANCH', 'BranchPermission.VIEW_TOPICS')")
@Override
public void checkViewTopicPermission(Long branchId) {
}
}
| lgpl-2.1 |