repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Lebronbingcheng/git | Migong/Migong.java | 2683 | package Migong;
import java.util.ArrayList;
import java.util.List;
public class Migong {
int[][] mg;
int[][] edge;
Node[] array;
public Migong(int[][] mg){
this.mg = mg;
this.array = this.toNodeArray(mg);
this.edge = this.toEdgeArray(this.array, mg);
}
public void printMg(int[][] mg){
for(int i = 0; i < mg.length; i++){
for(int a = 0; a < mg[i].length; a++){
System.out.print(mg[i][a] + " ");
}
System.out.println();
}
}
public Node[] toNodeArray(int[][] mg){
List<Node> list = new ArrayList<Node>();
for(int i = 0 ; i < mg.length; i++){
for(int j = 0; j < mg[i].length; j++){
if(mg[i][j] == 0){
list.add(new Node(i,j));
}
}
}
Node[] array = new Node[list.size()];
for(int i = 0; i < array.length; i++){
array[i] = list.get(i);
}
return array;
}
public int[][] toEdgeArray(Node[] array, int[][] mg){
int[][] edgeArray = new int[array.length][array.length];
for(int a = 0; a < array.length; a++){
int x = array[a].x;
int y = array[a].y;
int[] edge = new int[4];
edge[0] = findNode(x+1, y, array);
edge[1] = findNode(x-1, y, array);
edge[2] = findNode(x, y+1, array);
edge[3] = findNode(x, y-1, array);
for(int ad : edge){
if(ad != -1){
edgeArray[a][ad] = 1;
}
}
}
return edgeArray;
}
public void depTravel(Node p, int[][] edge, Node[] array){
int test = 1;
for(int i = 0; i < array.length; i++){
test = test * array[i].visited;
}
if(test == 1){
return;
}
if(p.visited == 0){
p.visited = 1;
System.out.print("(" + p.x + "," + p.y + ")");
}
for(int i = 0 ; i < edge[findIndex(p,array)].length; i++){
if(edge[findIndex(p,array)][i] == 1 && array[i].visited != 1){
this.depTravel(array[i], edge, array);
}
}
}
List<Node> list = new ArrayList<Node>();
public List<Node> findPath(Node start, Node end){
for(int i = 0; i < edge[findIndex(start,array)].length; i++){
if(edge[findIndex(start, array)][findIndex(end, array)] == 1){
list.add(start);
list.add(end);
return list;
}
}
if(start.visited == 0){
start.visited = 1;
list.add(start);
}
for(int i = array.length-1; i > 0; i--){
if(edge[findIndex(start,array)][i] == 1 && array[i].visited != 1){
findPath(array[i], end);
break;
}
}
return list;
}
private int findNode(int x, int y, Node[] array){
for(int i = 0; i < array.length; i++){
if(array[i].x == x && array[i].y == y){
return i;
}
}
return -1;
}
private static int findIndex(Node p, Node[] array){
for(int i = 0; i < array.length; i++){
if(p.x == array[i].x && p.y == array[i].y){
return i;
}
}
return -1;
}
}
| gpl-2.0 |
aktion-hip/vif | org.hip.viffw/src/org/hip/kernel/bom/HomeManager.java | 1414 | /**
This package is part of the servlet framework used for the application VIF.
Copyright (C) 2001-2015, Benno Luthiger
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.hip.kernel.bom;
/** The HomeManager is responsible to instantiate homes. The singleton can be access by the global variable
* VSys.homeManager
*
* <PRE>
* PersonHome home = VSys.homeManager.getHome("org.hip.kernel.bom.PersonHome");
* Person person = home.findByPrimaryKey("M�ller");
*
* </PRE>
*
* @author Benno Luthiger */
public interface HomeManager {
/** Returns the specified Home.
*
* @return org.hip.kernel.bom.DomainObjectHome
* @param inHomeName java.lang.String */
Home getHome(String inHomeName);
}
| gpl-2.0 |
krutikk/LockApp | gen/com/krutik/unlock/R.java | 1579 | /* 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.krutik.unlock;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
public static final int off=0x7f020001;
public static final int widget_button=0x7f020002;
}
public static final class id {
public static final int about=0x7f070007;
public static final int disable_button=0x7f070003;
public static final int enable_button=0x7f070002;
public static final int off_button=0x7f070005;
public static final int screen=0x7f070000;
public static final int settings=0x7f070006;
public static final int textView1=0x7f070001;
public static final int widget_layout=0x7f070004;
}
public static final class layout {
public static final int lock_screen=0x7f030000;
public static final int main=0x7f030001;
public static final int settings=0x7f030002;
public static final int widget=0x7f030003;
}
public static final class menu {
public static final int main_screen_menu=0x7f060000;
}
public static final class string {
public static final int app_name=0x7f050000;
}
public static final class xml {
public static final int admin_turn_off=0x7f040000;
public static final int widget_info=0x7f040001;
}
}
| gpl-2.0 |
Furt/JMaNGOS | Tools/src/main/java/org/jmangos/tools/m2/Offsets.java | 13848 | package org.jmangos.tools.m2;
/**
*
* @author MinimaJack
*
*/
class Offsets {
/**
* Offset Name
*/
private int ofsName;
/**
* Offset GlobalSequences
*/
private int ofsGlobalSequences;
/**
* Offset Animations
*/
private int ofsAnimations;
/**
* Offset AnimationLookup
*/
private int ofsAnimationLookup;
/**
* Offset Bones
*/
private int ofsBones;
/**
* Offset KeyBoneLookup
*/
private int ofsKeyBoneLookup;
/**
* Offset Vertices
*/
private int ofsVertices;
/**
* Offset Colors
*/
private int ofsColors;
/**
* Offset Textures
*/
private int ofsTextures;
/**
* Offset Transparency
*/
private int ofsTransparency;
/**
* Offset TextureAnimations
*/
private int ofsTextureAnimations;
/**
* Offset TexReplace
*/
private int ofsTexReplace;
/**
* Offset RenderFlags
*/
private int ofsRenderFlags;
/**
* Offset BoneLookupTable
*/
private int ofsBoneLookupTable;
/**
* Offset TexLookup
*/
private int ofsTexLookup;
/**
* Offset TexUnits
*/
private int ofsTexUnits;
/**
* Offset BoundTriangles
*/
private int ofsBoundTriangles;
/**
* Offset BoundingVertices
*/
private int ofsBoundingVertices;
/**
* Offset BoundingNormals
*/
private int ofsBoundingNormals;
/**
* Offset Attachments
*/
private int ofsAttachments;
/**
* Offset AttachLookup
*/
private int ofsAttachLookup;
/**
* Offset Attachments2
*/
private int ofsAttachments2;
/**
* Offset Lights
*/
private int ofsLights;
/**
* Offset Cameras
*/
private int ofsCameras;
/**
* Offset CameraLookup
*/
private int ofsCameraLookup;
/**
* Offset RibbonEmitters
*/
private int ofsRibbonEmitters;
/**
* Offset ParticleEmitters
*/
private int ofsParticleEmitters;
/**
* Offset Unknown
*/
private int ofsUnknown;
/**
* Offset TransLookup
*/
private int ofsTransLookup;
/**
* @return the ofsName
*/
public final int getOfsName() {
return this.ofsName;
}
/**
* @param givenofsName
* the ofsName to set
*/
public final void setOfsName(final int givenofsName) {
this.ofsName = givenofsName;
}
/**
* @return the ofsGlobalSequences
*/
public final int getOfsGlobalSequences() {
return this.ofsGlobalSequences;
}
/**
* @param givenofsGlobalSequences
* the ofsGlobalSequences to set
*/
public final void setOfsGlobalSequences(final int givenofsGlobalSequences) {
this.ofsGlobalSequences = givenofsGlobalSequences;
}
/**
* @return the ofsAnimations
*/
public final int getOfsAnimations() {
return this.ofsAnimations;
}
/**
* @param givenofsAnimations
* the ofsAnimations to set
*/
public final void setOfsAnimations(final int givenofsAnimations) {
this.ofsAnimations = givenofsAnimations;
}
/**
* @return the ofsAnimationLookup
*/
public final int getOfsAnimationLookup() {
return this.ofsAnimationLookup;
}
/**
* @param givenofsAnimationLookup
* the ofsAnimationLookup to set
*/
public final void setOfsAnimationLookup(final int givenofsAnimationLookup) {
this.ofsAnimationLookup = givenofsAnimationLookup;
}
/**
* @return the ofsBones
*/
public final int getOfsBones() {
return this.ofsBones;
}
/**
* @param givenofsBones
* the ofsBones to set
*/
public final void setOfsBones(final int givenofsBones) {
this.ofsBones = givenofsBones;
}
/**
* @return the ofsKeyBoneLookup
*/
public final int getOfsKeyBoneLookup() {
return this.ofsKeyBoneLookup;
}
/**
* @param givenofsKeyBoneLookup
* the ofsKeyBoneLookup to set
*/
public final void setOfsKeyBoneLookup(final int givenofsKeyBoneLookup) {
this.ofsKeyBoneLookup = givenofsKeyBoneLookup;
}
/**
* @return the ofsVertices
*/
public final int getOfsVertices() {
return this.ofsVertices;
}
/**
* @param givenofsVertices
* the ofsVertices to set
*/
public final void setOfsVertices(final int givenofsVertices) {
this.ofsVertices = givenofsVertices;
}
/**
* @return the ofsColors
*/
public final int getOfsColors() {
return this.ofsColors;
}
/**
* @param givenofsColors
* the ofsColors to set
*/
public final void setOfsColors(final int givenofsColors) {
this.ofsColors = givenofsColors;
}
/**
* @return the ofsTextures
*/
public final int getOfsTextures() {
return this.ofsTextures;
}
/**
* @param givenofsTextures
* the ofsTextures to set
*/
public final void setOfsTextures(final int givenofsTextures) {
this.ofsTextures = givenofsTextures;
}
/**
* @return the ofsTransparency
*/
public final int getOfsTransparency() {
return this.ofsTransparency;
}
/**
* @param givenofsTransparency
* the ofsTransparency to set
*/
public final void setOfsTransparency(final int givenofsTransparency) {
this.ofsTransparency = givenofsTransparency;
}
/**
* @return the ofsTextureAnimations
*/
public final int getOfsTextureAnimations() {
return this.ofsTextureAnimations;
}
/**
* @param givenofsTextureAnimations
* the ofsTextureAnimations to set
*/
public final void setOfsTextureAnimations(final int givenofsTextureAnimations) {
this.ofsTextureAnimations = givenofsTextureAnimations;
}
/**
* @return the ofsTexReplace
*/
public final int getOfsTexReplace() {
return this.ofsTexReplace;
}
/**
* @param givenofsTexReplace
* the ofsTexReplace to set
*/
public final void setOfsTexReplace(final int givenofsTexReplace) {
this.ofsTexReplace = givenofsTexReplace;
}
/**
* @return the ofsRenderFlags
*/
public final int getOfsRenderFlags() {
return this.ofsRenderFlags;
}
/**
* @param givenofsRenderFlags
* the ofsRenderFlags to set
*/
public final void setOfsRenderFlags(final int givenofsRenderFlags) {
this.ofsRenderFlags = givenofsRenderFlags;
}
/**
* @return the ofsBoneLookupTable
*/
public final int getOfsBoneLookupTable() {
return this.ofsBoneLookupTable;
}
/**
* @param givenofsBoneLookupTable
* the ofsBoneLookupTable to set
*/
public final void setOfsBoneLookupTable(final int givenofsBoneLookupTable) {
this.ofsBoneLookupTable = givenofsBoneLookupTable;
}
/**
* @return the ofsTexLookup
*/
public final int getOfsTexLookup() {
return this.ofsTexLookup;
}
/**
* @param givenofsTexLookup
* the ofsTexLookup to set
*/
public final void setOfsTexLookup(final int givenofsTexLookup) {
this.ofsTexLookup = givenofsTexLookup;
}
/**
* @return the ofsTexUnits
*/
public final int getOfsTexUnits() {
return this.ofsTexUnits;
}
/**
* @param givenofsTexUnits
* the ofsTexUnits to set
*/
public final void setOfsTexUnits(final int givenofsTexUnits) {
this.ofsTexUnits = givenofsTexUnits;
}
/**
* @return the ofsBoundTriangles
*/
public final int getOfsBoundTriangles() {
return this.ofsBoundTriangles;
}
/**
* @param givenofsBoundTriangles
* the ofsBoundTriangles to set
*/
public final void setOfsBoundTriangles(final int givenofsBoundTriangles) {
this.ofsBoundTriangles = givenofsBoundTriangles;
}
/**
* @return the ofsBoundingVertices
*/
public final int getOfsBoundingVertices() {
return this.ofsBoundingVertices;
}
/**
* @param givenofsBoundingVertices
* the ofsBoundingVertices to set
*/
public final void setOfsBoundingVertices(final int givenofsBoundingVertices) {
this.ofsBoundingVertices = givenofsBoundingVertices;
}
/**
* @return the ofsBoundingNormals
*/
public final int getOfsBoundingNormals() {
return this.ofsBoundingNormals;
}
/**
* @param givenofsBoundingNormals
* the ofsBoundingNormals to set
*/
public final void setOfsBoundingNormals(final int givenofsBoundingNormals) {
this.ofsBoundingNormals = givenofsBoundingNormals;
}
/**
* @return the ofsAttachments
*/
public final int getOfsAttachments() {
return this.ofsAttachments;
}
/**
* @param givenofsAttachments
* the ofsAttachments to set
*/
public final void setOfsAttachments(final int givenofsAttachments) {
this.ofsAttachments = givenofsAttachments;
}
/**
* @return the ofsAttachLookup
*/
public final int getOfsAttachLookup() {
return this.ofsAttachLookup;
}
/**
* @param givenofsAttachLookup
* the ofsAttachLookup to set
*/
public final void setOfsAttachLookup(final int givenofsAttachLookup) {
this.ofsAttachLookup = givenofsAttachLookup;
}
/**
* @return the ofsAttachments2
*/
public final int getOfsAttachments2() {
return this.ofsAttachments2;
}
/**
* @param givenofsAttachments2
* the ofsAttachments2 to set
*/
public final void setOfsAttachments2(final int givenofsAttachments2) {
this.ofsAttachments2 = givenofsAttachments2;
}
/**
* @return the ofsLights
*/
public final int getOfsLights() {
return this.ofsLights;
}
/**
* @param givenofsLights
* the ofsLights to set
*/
public final void setOfsLights(final int givenofsLights) {
this.ofsLights = givenofsLights;
}
/**
* @return the ofsCameras
*/
public final int getOfsCameras() {
return this.ofsCameras;
}
/**
* @param givenofsCameras
* the ofsCameras to set
*/
public final void setOfsCameras(final int givenofsCameras) {
this.ofsCameras = givenofsCameras;
}
/**
* @return the ofsCameraLookup
*/
public final int getOfsCameraLookup() {
return this.ofsCameraLookup;
}
/**
* @param givenofsCameraLookup
* the ofsCameraLookup to set
*/
public final void setOfsCameraLookup(final int givenofsCameraLookup) {
this.ofsCameraLookup = givenofsCameraLookup;
}
/**
* @return the ofsRibbonEmitters
*/
public final int getOfsRibbonEmitters() {
return this.ofsRibbonEmitters;
}
/**
* @param givenofsRibbonEmitters
* the ofsRibbonEmitters to set
*/
public final void setOfsRibbonEmitters(final int givenofsRibbonEmitters) {
this.ofsRibbonEmitters = givenofsRibbonEmitters;
}
/**
* @return the ofsParticleEmitters
*/
public final int getOfsParticleEmitters() {
return this.ofsParticleEmitters;
}
/**
* @param givenofsParticleEmitters
* the ofsParticleEmitters to set
*/
public final void setOfsParticleEmitters(final int givenofsParticleEmitters) {
this.ofsParticleEmitters = givenofsParticleEmitters;
}
/**
* @return the ofsUnknown
*/
public final int getOfsUnknown() {
return this.ofsUnknown;
}
/**
* @param givenofsUnknown
* the ofsUnknown to set
*/
public final void setOfsUnknown(final int givenofsUnknown) {
this.ofsUnknown = givenofsUnknown;
}
/**
* @return the ofsTransLookup
*/
public final int getOfsTransLookup() {
return this.ofsTransLookup;
}
/**
* @param givenofsTransLookup
* the ofsTransLookup to set
*/
public final void setOfsTransLookup(final int givenofsTransLookup) {
this.ofsTransLookup = givenofsTransLookup;
}
}
| gpl-2.0 |
mprat/Terminus | Java/src/gameCode/Game.java | 34412 | package gameCode;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Game {
//private HashSet<Room> rooms;
private Room currentRoom;
private Item currentItem;
private ImageIcon currentIcon;
private Room dankRoom;
private Room tunnel;
private Room library;
private Room backRoom;
public Room rockyPath;
public Item boulder;
private Room artisanShop;
public Room clearing;
private Room brokenbridge;
private Item librarian;
private Room cage;
public Room farm;
public Room caveOfTrolls;
public Item hideousTroll;
public Item uglyTroll;
public Item uglierTroll;
private Item farmer;
private Item artisan;
private ArrayList<String> spellsLearned = new ArrayList<String>();
private boolean libquestcomplete = false;
private boolean rockinpath = true;
//private boolean madeAllGears = false;
private int numGearsMade = 0;
public String gearName;
private int cornCounter = 0;
private Item cryingMan;
private Item kidnappedChild;
public Room ominousPath;
public Item thornybrambles;
public boolean bridgesolved = false;
private boolean housequestcomplete = false;
public boolean bramblessolved = false;
private boolean awaitingPassword = false;
public boolean troll1gone = false;
public boolean troll2gone = false;
private Room house;
public Game(){
String introText = "Welcome! If you are new to the game, here are some tips: \n " +
"Look at your surroundings with the command \"ls\". \n " +
"Move to a new location with the command \"cd LOCATION\" \n" +
"You can backtrack with the command \"cd ..\". \n" +
"Interact with things in the world with the command \"less ITEM\" \n" +
"Go ahead, explore. We hope you enjoy what you find. Do ls as your first command.\n";
//this.rooms = new HashSet<Room>();
//HOME
Room home = new Room("Home", introText + "\n", "titlescreen");
home.addItem(new Item("Letter", introText, "item_manuscript"));
this.currentIcon = new ImageIcon("graphic/" + home.getIconText() + ".gif");
this.currentRoom = home;
//---------LEVEL 1----------------------
//WESTERN FOREST
Room westernForest = new Room("WesternForest", "You enter and travel deep into the forest. \n" +
"Eventually, the path leads to a clearing with a large impressive building. \n" +
"A sign on it reads: Spell Casting Academy: The Elite School of Magic.\n",
"loc_forest");
westernForest.addItem(new Item("Sign", "Spell Casting Academy: The Elite School of Magic \n" +
"Today Only: Free Introductory Lessons! Novices welcome! \n", "item_sign"));
//SPELL CASTING ACADEMY
Room spellCastingAcademy = new Room("SpellCastingAcademy", "The halls are filled the hustle and bustle " +
"of academy students scurrying to and from classes. " +
"The inside of the academy is as impressive as it is on the outside " +
"with a high ceiling and gothic arches, it seems even larger on the inside. \n",
"loc_academy");
spellCastingAcademy.addItem(new OnceItem("HurryingStudent", "You to speak to a hurrying student. " +
"The student runs into you and falls to the ground. " +
"The student quickly gets up and apologizes to you, asking if you are okay. " +
"You are sturdier than you look and you're undamaged." +
"\"I'm so sorry, I was in such a hurry that I didn't see you there... " +
"Say, I haven't seen you here before. You're new here aren't-cha?\" " +
"the student winks at you, \"Don't worry, there's tons of newbies around today, " +
"why don't you try checking out one of the free intro lessons? " +
"I'd show you where to go, but I gotta run to class. " +
"Just head into the Lessons hall and someone should help you out. See you around.\" " +
"The student runs past you. You notice that the student is pretty cute, " +
"and probably around your age. Unfortunately, the student disappears around " +
" a corner before you can ask for a name.\n", "item_student"));
//PRACTICE ROOM
Room practiceRoom = new Room("PracticeRoom", "The room is filled with practice dummies \n" +
"for students to practice their new spells on. \n", "loc_practiceroom");
practiceRoom.addItem(new Item("Instructions", "Welcome to the Practice Room. \n" +
"Here you will find practice dummies try your new spells on. \n" +
"Go ahead, give it a go! Practice dummies will respawn in their original \n" +
"location once you leave the Practice Room. If you don't know any spells yet, \n" +
"go back and check out some Lessons.\n", "item_manuscript"));
practiceRoom.addItem(new MoveableItem("PracticeDummy1", "It's a practice dummy\n", "item_dummy"));
practiceRoom.addItem(new MoveableItem("PracticeDummy2", "It's a practice dummy\n", "item_dummy"));
practiceRoom.addItem(new MoveableItem("PracticeDummy3", "It's a practice dummy\n", "item_dummy"));
practiceRoom.addItem(new MoveableItem("PracticeDummy4", "It's a practice dummy\n", "item_dummy"));
practiceRoom.addItem(new MoveableItem("PracticeDummy5", "It's a practice dummy\n", "item_dummy"));
practiceRoom.addCommand("mv");
//BOX
Box box = new Box("Box", "This box is too small for you to fit into.");
//MEADOW
Room northernMeadow = new Room("NorthernMeadow", "This is a beautiful green meadow. " +
"A plump but majestic pony prances happily about.\n", "loc_meadow");
northernMeadow.addItem(new Item("Pony", "You go up to the pony and attempt to ride it. " +
"It compiles and you ride the pony around in circles for a bit. " +
"It then grows tired of having you as a burden and knocks you off. " +
"He then looks towards the east as if suggesting that you head in that direction.\n", "item_fatpony"));
//EASTERN MOUNTAINS
Room easternMountains = new Room("EasternMountains", "You travel through a mountain path, " +
"which eventually leads you to the entrance of a cave. " +
"Sitting right outside this cave is an old man.", "loc_mountains");
easternMountains.addItem(new Item("OldMan", "You speak with the old man. " +
"He greets you warmly as if you were old friends. " +
"You feel at ease with him. Hello adventurer! Top of the morning to you! " +
"You seem like a young and energetic explorer. " +
"If you're brave enough, your destiny awaits within this cave." +
"That destiny will manifest itself as a portal. " +
"Enter this portal and begin the next chapter of your life. " +
"The old man sees the shock on your face and smiles comforting smile, " +
"\"I am but a fragile old man, and cannot accompany you through this cave, " +
"but what I can provide are a few simple spells that will help you along " +
"your way. Just read my old manuscripts and tryout those spells.\"", "item_mysteryman"));
easternMountains.addItem(new Item("OldManuscripts", "If you ever forget a spell just use \"help\" " +
"and a list of available spells will appear. If you need details " +
"on how to use a specific spell, use 'man' followed by spell command. " +
"For example, if you were interested in details on how to use the " +
"\"mv\" spell you would use: man mv\n", "item_manuscript"));
//LESSONS
Room lessons = new Room("Lessons", "You enter the Lessons hall ready and eager. \n" +
"It's much quieter here, as many of the lessons have already started. \n" +
" You quickly ushered into the Introductory Lesson, which already begun. \n" +
"You enter the class on the \"Move Spell.\"\n", "loc_classroom");
lessons.addItem(new Item("Professor", "The professor is difficult to understand, \n" +
"but you pick up just enough to learn 3 things: \n" +
"1. You can use 'mv' to move things in the world \n" +
"2. You have to indicate the object and the new location \n" +
"(i.e.: mv OBJECT NEWLOCATION) \n" +
"3. This spell will only work on certain objects, for example \n" +
"the PracticeDummy objects in the PracticeRoom \n" +
"You did not pay enough attention to learn which types of \n" +
"objects are unmovable. Oh well, experimenting was always more of \n" +
"your style anyways. But be careful!\n", "item_professor"));
//CAVE
Room cave = new Room("Cave", "It's your typical cave: dark and dank.\n", "loc_cave");
//DARK CORRIDOR
Room darkCorridor = new Room("DarkCorridor", "You travel through the dark corridor \n" +
"and find a small dank room at the end.\n", "loc_corridor");
//STAIRCASE
Room staircase = new Room("Staircase", "The rocky staircase leads you to a dead end \n" +
"and a sign indicating such.\n", "loc_stair");
staircase.addItem(new Item("Sign", "DEAD END\n", "item_sign"));
//DANK ROOM
dankRoom = new Room("DankRoom", "It's a musty dank room. A round boulder sits \n" +
"to the right side of the room.\n", "loc_darkroom");
dankRoom.addItem(new MoveableItem("Boulder", "You feel a slight breeze coming from behind the \n" +
"boulder. Maybe move it out of your way?\n", "item_boulder"));
dankRoom.addCommand("mv");
//SMALL HOLE
Box smallHole = new Box("SmallHole", "There's nothing exciting in the small hole, and it's pretty dirty. There's no real reason to go into the hole.");
//TUNNEL
tunnel = new Room("Tunnel", "It's quite moist in here. \n" +
"You notice a small furry movement in the corner of your vision. \n" +
"It's most likely a rat. A very large rat. Perhaps a mongoose. \n" +
"At the end of the tunnel you find a stone chamber.\n", "loc_tunnel");
tunnel.addItem(new Item("Rat", "Upon further inspection, you determine that the furry \n" +
"presence is in fact a rat...the size of a small dog. It bites you. \n" +
"You are very displeased.\n", "item_rat"));
//STONE CHAMBER
Room stoneChamber = new Room("StoneChamber", "The whole rooms glows a dim green light. \n" +
"The source of this light is a portal standing in the middle of the room. \n" +
"This is obviously the portal of which the old man spoke.\n", "loc_portalroom");
//PORTAL (to bring you to the next level
Room portal = new Room("Portal", "You have been transported through time...\n", "item_portal");
//link LEVEL 1 together
link(home, westernForest);
link(home, northernMeadow);
link(westernForest, spellCastingAcademy);
link(northernMeadow, easternMountains);
link(spellCastingAcademy, lessons);
link(spellCastingAcademy, practiceRoom);
link(easternMountains, cave);
link(cave, darkCorridor);
link(cave, staircase);
link(darkCorridor, dankRoom);
//link(dankRoom, tunnel); - this link is made when you move the boulder
link(dankRoom, smallHole);
link(tunnel, stoneChamber);
link(stoneChamber, portal);
//---------------END LEVEL 1-----------------
//---------------LEVEL 2---------------------
//TOWN SQUARE
Room townSquare = new Room("TownSquare", "You are in a sunny and spacious town square. \n" +
"There is a pedestal at the center of the cobblestone turnabout, but no statue on it. \n" +
"The architecture is charming, but everyone here seems nervous for some reason.\n", "loc_square");
townSquare.addItem(new Item("RandomCitizen1", "\"Excuse me,\" you begin. The man turns, startled. \n" +
"\"Oh, hello! Welcome to Terminus. You'll have to forgive me, but we're all a little \n" +
"on edge lately, what with the Dark Wizard spreading corruption all along the \n" +
"coast. You should be careful!\" \n", "item_citizen1"));
townSquare.addItem(new Item("RandomCitizen2", "The man looks up from his newspaper when he notices you staring. \n" +
"\"Have you read this?\" he exclaims, shaking the latest edition of \"The Last \n" +
"Word\" in your face. \"It says here the wizard's corruption has spread as far\n" +
"as Oston to the south, and New Console is completely unrecoverable! These are \n" +
"dangerous times,\" he mutters, shaking his head and turning back to his reading. \n", "item_citizen2"));
townSquare.addItem(new Item("DistraughtLady", "The woman is sobbing uncontrollably, her face in her hands.\n" +
"\"My baby,\" she cries, \"They kidnapped my baby! I just know that wizard had \n" +
"something to do with it.\"\n", "item_lady"));
//MARKETPLACE
Room marketplace = new Room("Marketplace", "You are in the marketplace.\n", "loc_market");
Item vendor = new Item("Vendor", "\" 'Ello there.\" The vendor smiles at you unpleasantly, \n" +
"revealing a mouth full of gold teeth. \"Well? Wot are you looking for?\"\n", "item_merchant");
vendor.setRMText("\"Ha! That spell doesn't work on everything, you know. I may have forgotten \n" +
"to mention that before I sold it to you...\"\n");
marketplace.addItem(vendor);
YNItem backpack = new YNItem("Backpack", "There's a beat-up looking backpack on the table with no price tag. Its cloth looks \n" +
"frayed, but sturdy. You glance quickly at the vendor, but his attention is elsewhere. \n" +
"Do you take the backpack? y\\n \n", "item_backpack", "You quickly snatch the backpack from the table. This could come in handy.\n" +
"From now on, you can put items into your backpack.\n",
"You decide to leave the backpack where it is for now.\n");
marketplace.addItem(backpack);
YNItem rmSpell = new YNItem("rmSpell", "There's a spell scroll on the table labeled \"Remove.\" \n" +
"Do you want to buy it for 15 gold pieces? y/n \n", "item_manuscript", "The vendor snatches the gold from your hand and then hands you the scroll,\n" +
"leering as he does so. \"Ah, yes, the rm spell,\" he muses. \"Simply say \"rm\" followed by the name of an item or person, \n" +
"and they will disappear from this plane... forever. D'you have the guts to use it, I wonder?\"\n" +
"You can now use the \"rm\" spell.\n", "Come back later.\n");
marketplace.addItem(rmSpell);
YNItem mkdirSpell = new YNItem("mkdirSpell", "There's a spell scroll on the table labeled \"Make dreams into reality.\" \n" +
"Do you want to buy it for 30 gold pieces? y\\n \n", "item_manuscript", "The vendor cackles. \"An ambitious one, eh? Very well. \n" +
"Just say \"mkdir\" followed by any name that pleases you, and you can create a new place \n" +
"that never existed there before. Ha! Not very useful, if y'ask me...\"\n" +
"You can now use the \"mkdir\" spell.\n", "You leave the mkdirSpell on the table\n");
marketplace.addItem(mkdirSpell);
//LIBRARY
library = new Room("Library", "The Library is dimly lit and smells like mildew. \n" +
"Still, it's warm in here and the soft green carpet makes it seem kind of cozy.\n", "loc_library");
library.addItem(new Item("TotallyRadSpellbook", "Legends speak of a great word of power that allows the speaker to perform \n" +
"any action on any item. \"Sudo\", as the ancients called it, conveys complete mastery over the elements. \n" +
"Unfortunately, or perhaps fortunately, the mystical password has been lost \n" +
"to the sands of time.\n", "item_radspellbook"));
library.addItem(new Item("PaperbackRomance", "You flip the paperback open to a random page. \n" +
"\"Oh, Horatio!\" Antonia exclaimed, her bosom heaving as Horatio deftly ripped the \n" +
"bodice from her lithe frame. Horatio gave an animalistic growl and he clasped her \n" +
"fingers in his strong hands and brought them to rest upon his swollen You close the \n" +
"book, disinterested, and place it back on the shelf. \n", "item_romancenovel"));
library.addItem(new GrepItem("HistoryOfTerminus", "It looks like an interesting book, but it's way too \n" +
"long and the print is too tiny.\n", "item_historybook", "DarkWizard", "...old tales tell of a dark wizard who will fragment the land...\n" +
"...only the world-maker can stop the dark wizard's virus from...\n" +
"...that the power of \"sudo\" may be the dark wizard's only weakness...\n"));
library.addItem(new Item("InconspicuousLever", "You spot an inconspicuous lever behind the shelves. Curious, you pull it, \n" +
"and a panel slides open to reveal a secret back room.\n", "item_lever"));
library.addCommand("grep");
//BACK ROOM
backRoom = new Room("BackRoom", "You find a mysterious back room. You find a librarian \n" +
"alone with a small elf. You hope you're not interrupting.", "loc_backroom");
backRoom.addItem(new Item("Grep", "The exceptionally ugly elf turns to you with a sour expression. \n" +
"\"Greeeeeep,\" he says sullenly.\n", "grep"));
librarian = new Item("Librarian", "\"Hm? Oh, hello. I apologize for the mess, but I'm very busy \n" +
"doing research on the dark wizard. Would you do me a favor? Go look up all \n" +
"references to DarkWizard in the History of Terminus. My assistant Grep \n" +
"can help you.\" \n" +
"Grep eyes you balefully. \"Greeepp.\" \"To search the contents of the book, just type \n" +
"\"grep PHRASE DOCUMENT\", where PHRASE is the phrase you want to search for,\n" +
"and DOCUMENT is the name of the book you want to search.\"\n", "item_librarian");
backRoom.addItem(librarian);
backRoom.addCommand("grep");
//ROCKY PATH
rockyPath = new Room("RockyPath", "The weed-choked path leads off into the fields. \n" +
"There is an enormous boulder blocking your way, however.\n", "loc_rockypath");
boulder = new Item("LargeBoulder", "It's much too big to move. \n", "item_boulder");
boulder.setRMText("The boulder disappears with a pop. The way is clear now.\n");
boulder.setRM(true);
rockyPath.addItem(boulder);
rockyPath.addCommand("rm");
//ARTISAN'S SHOP
artisanShop = new Room("ArtisanShop", "The walls of the shop are covered in clocks, \n" +
"all slightly out of sync. At the workbench, a woman in an enormous pair of goggles \n" +
"is wielding a blowtorch with frightening enthusiasm.\n", "loc_artisanshop");
Item strangeTrinket = new Item("StrangeTrinket", "It looks like a crystal of some sort. It's very beautiful.", "item_trinket");
strangeTrinket.setRMText("Didn't your mother ever teach you that it's rude to rease other people's \n" +
"things from their plane of existence?\n");
strangeTrinket.setMVText("You can't take that, it's not yours!\n");
artisanShop.addItem(strangeTrinket);
Item clockworkDragon = new Item("ClockworkDragon","A dragon the size of a small dog is frolicking about the room. \n" +
"You'd think it was real if it weren't for the wind-up key sticking out of its \n" +
"back.","item_clockdragon");
clockworkDragon.setRMText("Didn't your mother ever teach you that it's rude to erase other people's \n" +
"things from their plane of existence?\n");
clockworkDragon.setMVText("You can't take that, it's not yours!\n");
artisanShop.addItem(clockworkDragon);
artisan = new Item("Artisan", "The Artisan lifts up her goggles and peers at you in " +
"surprise. \"Are you the new assistant? You're late! ... \n You say you aren't my assistant? \n" +
"Well, that doesn't mean you can't make yourself useful. I need some gears, quickly! \n" +
"... \n" +
"You don't even know how to make things? Hmph. Some assistant you are. Just \n" +
"say \"touch ITEM\" alright? Where ITEM is the name of the thing you want to create. \n" +
"Now make me a Gear! Then come back.\"\n", "item_artisan");
artisanShop.addItem(artisan);
artisanShop.addCommand("touch");
//FARM
farm = new Room("Farm", "There was once a farm of some sort here, but now the fields are scorched and \n" +
"brown.\n", "loc_farm");
Item earOfCorn = new Item("EarOfCorn","The corn is sad and withered-looking.\n","item_corn");
earOfCorn.setRMText("rm: Why would you destroy a starving man's only food?\n");
farm.addItem(earOfCorn);
farmer = new Item("Farmer", "\"Ruined! I'm ruined! Look at these crops... almost nothing \n" +
"left! The wizard's minions were here last week... they destroyed everything. How \n" +
"will I feed my 10 children with just one ear of corn? Can you help me? \" \n", "");
farm.addItem(farmer);
farm.addCommand("cp");
//BROKEN BRIDGE
brokenbridge = new Room("BrokenBridge", "A creaky wooden bridges stretches across a chasm. But it's missing a \n" +
"Plank, and the gap is too far to jump. \n", "loc_bridge");
//beforeClearing = new Room("Clearing", "You can't cross the bridge until you've replaced the missing Plank.", "");
brokenbridge.addCommand("touch");
//CLEARING
clearing = new Room("Clearing", "There's a small grassy clearing here, with a man sitting on a \n" +
"stone and sobbing. Behind him is a pile of rubble. \n", "loc_clearing");
cryingMan = new Item("CryingMan", "\"You! You're a magic-user! I can tell, you've got that look. \n" +
"Come to finish the job, have you? Well, go ahead, do your worst there's nothing else you \n"+
"can take from me. Not since the rest of you were here a few days ago.\"\n"+
" \n"+
"\"What happened? You DARE to ask-- you know perfectly well what happened.\n"+
"Your friends, the wizard's minions, destroyed my house and kidnapped my poor \n"+
"daughter, that's what! My wife even went into town to look for help, and I haven't \n"+
"heard from her since!\"\n"+
" \n"+
"\"Hm? Well, I guess it's true that you don't look like one of the wizard's minions. Still, \n"+
"I don't trust you magicfolk. If you really are who you say you are, then prove your \n"+
"good intentions by making me a new House!\" \n", "item_man");
clearing.addItem(cryingMan);
house = new Room("House", "You made this house for the man. How thoughtful of you!", "");
//OMINOUS-LOOKING PATH
ominousPath = new Room("OminousLookingPath", "The path leads toward a dark cave. It's an ordinary cobblestone path, but for \n" +
"some reason it fills you with a sense of dread.\n", "loc_path");
thornybrambles = new Item("ThornyBrambles", "This thicket of brambles is covered with wicked-looking thorns. You \n" +
"can't go around it, and you definitely aren't about to go through it.\n", "");
thornybrambles.setMVText("You can't touch them because they are covered with thorns. Ouch!\n");
thornybrambles.setRMText("You speak the words of the Remove spell and the brambles glimmer a \n" +
"deep blue. The sparks rearrange themselves into a prompt: 'PASSWORD?' \n");
ominousPath.addItem(thornybrambles);
ominousPath.addCommand("rm");
//CAVE
//Room beforeCave = new Room("CaveOfDisgruntledTrolls", "A patch of thorny brambles is growing at the mouth of the cave, blocking your way.", "loc_cave");
caveOfTrolls = new Room("CaveOfDisgruntledTrolls", "The cave is dark and smells like... feet? Oh, right, it's probably the trolls. \n" +
"There's a scared-looking kid in a cage by the far wall.\n", "loc_cave");
uglyTroll = new Item("UglyTroll", "He looks mad, and really ugly.\n", "item_troll1");
uglyTroll.setRMText("The troll looks briefy surprised, then vanishes with an unpleasant squelching sound.\n");
caveOfTrolls.addItem(uglyTroll);
//beforeCave.addItem(uglyTroll);
uglierTroll = new Item("UglierTroll", "He looks mad, and really, really ugly.\n", "item_troll2");
uglierTroll.setRMText("The troll looks briefy surprised, then vanishes with an unpleasant \n" +
"squelching sound.\n");
caveOfTrolls.addItem(uglierTroll);
//beforeCave.addItem(uglierTroll);
/*hideousTroll = new MoveableItem("AbsolutelyHideousTroll", "You probably don't want to look at this guy. Oops, too late. \n", "item_supertroll");
hideousTroll.setRMText("The troll belches spectacularly, and you could swear he actually smirks. \n" +
"You won't get rid of him that easily, not without admin privileges.\n");
hideousTroll.setMVText("If you move him out of the cave, he'll terrorize \n" +
"the countryside. Also he will probably eat you. \n");*/
hideousTroll = new Item("AbsolutelyHideousTroll", "You probably don't want to look at this guy. Oops, too late. \n", "item_supertroll");
hideousTroll.setRMText("The troll belches spectacularly, and you could swear he actually smirks. \n" +
"You won't get rid of him that easily, not without admin privileges.\n");
hideousTroll.setMVText("If you move him out of the cave, he'll terrorize \n" +
"the countryside. Also he will probably eat you. \n");
caveOfTrolls.addItem(hideousTroll);
//beforeCave.addItem(hideousTroll);
caveOfTrolls.addCommand("rm");
caveOfTrolls.addCommand("mv");
//CAGE
cage = new Room("Cage", "There's a scared-looking kid in there.\n", "item_cage");
kidnappedChild = new Item("kidnappedChild", "You know it's kind of mean, but you can't help but think that that is one \n" +
"funny-looking kid.\n", "item_cagedboy");
kidnappedChild.setMVText("The kid looks around, dazed, surprised to find himself out of the cage. \n" +
"You smile at him and speak in a gentle voice. 'You should probably be getting home, \n" +
"little boy. Someone is there waiting for you.' \n" +
"'I'm a girl,' says the little girl smartly. Then she dashes past you, out of the cave, and \n" +
"runs up the ominous path towards home.\n");
cage.addItem(kidnappedChild);
//link level 2 together
link(townSquare, marketplace);
link(townSquare, library);
link(townSquare, rockyPath);
link(townSquare, artisanShop);
link(townSquare, brokenbridge);
//link(library, backRoom);
link(rockyPath, farm);
link(brokenbridge, clearing);
link(clearing, ominousPath);
link(ominousPath, caveOfTrolls);
link(caveOfTrolls, cage);
link(practiceRoom, box);
//link level 1 to level 2
link(portal, townSquare);
//---------------END LEVEL 2-----------------
this.currentRoom = home;
}
private void link(Room parent, Room child){
if (!(parent.getChildren().contains(child)))
parent.addChild(child);
child.setParent(parent);
}
public ArrayList<MoveableItem> getMoveableItems(){
ArrayList<MoveableItem> mov = new ArrayList<MoveableItem>();
for (Item i: this.getCurrentLessItems()){
if (i instanceof MoveableItem){
mov.add((MoveableItem)i);
}
}
return mov;
}
/*public Game(ArrayList<Room> rooms){
this.rooms = new HashSet<Room>(rooms);
}*/
public boolean changeRoom(String roomName){
for (Room r: this.currentRoom.getChildren()){
if (r.getName().equals(roomName))
{
this.currentRoom = r;
return true;
}
}
return false;
}
public ArrayList<String> getLocationNames()
{
ArrayList<String> locations = new ArrayList<String>();
for (Room r: this.currentRoom.getChildren())
locations.add(r.getName());
return locations;
}
public ArrayList<String> getItemNames()
{
ArrayList<String> items = new ArrayList<String>();
for (Item i: this.currentRoom.getItems())
items.add(i.getName());
return items;
}
public ArrayList<String> getCurrentLSList(){
ArrayList<String> lsList = new ArrayList<String>();
lsList.add("Locations:");
lsList.addAll(getLocationNames());
lsList.add("Items:");
lsList.addAll(getItemNames());
return lsList;
}
public ArrayList<Room> getCurrentCDRooms(){
return this.currentRoom.getChildren();
}
public ArrayList<? extends Item> getCurrentLessItems(){
return this.currentRoom.getItems();
}
public String getCurrentText() {
return this.currentRoom.getText();
}
public Room getCurrentRoom() {
return this.currentRoom;
}
public void changeRoom(Room r) {
this.currentRoom = r;
this.currentIcon = new ImageIcon("graphic/" + r.getIconText() + ".gif");
}
public ArrayList<Box> getBoxes() {
ArrayList<Box> boxes = new ArrayList<Box>();
for (Room r: this.currentRoom.getChildren()){
if (r instanceof Box)
boxes.add((Box)r);
}
return boxes;
}
public void resetAllBoxes(){
for (Box b: getBoxes())
b.resetItems();
}
public void move(MoveableItem itemToMove, Room box) {
box.addItem(itemToMove);
this.currentRoom.removeItem(itemToMove);
}
public void linkDankRoomToTunnel() {
link(dankRoom, tunnel);
}
public void linkLibraryToBackRoom(){
link(library, backRoom);
}
public Icon getCurrentIcon() {
return this.currentIcon;
}
public void setIcon(String imgName){
this.currentIcon = new ImageIcon("graphics/" + imgName + ".gif");
}
public Item getCurrentItem(){
return this.currentItem;
}
public void setCurrentItem(Item i){
this.currentItem = i;
}
public void unlink(){
dankRoom.removeChild(tunnel);
tunnel.removeParent(dankRoom);
library.removeChild(backRoom);
backRoom.removeParent(library);
}
/*public void linkClearingAndHouse(){
link(afterClearing, house);
}*/
public void libQuestCompleted(){
libquestcomplete = true;
}
public boolean isLibQuestFinished(){
return libquestcomplete;
}
public void setLibrarianPostQuestText(){
librarian.setText("\"Thank you, you've been most helpful! Here, take this for your troubles. It's the least I can do.\" The librarian hands you five gold pieces.");
}
public boolean isRockInPath(){
return rockinpath;
}
public void rockMovedFromPath(){
rockinpath = false;
}
public void setRockyPathText(){
rockyPath.setText("The weed-choked path leads off into the farm fields.");
//link(getRockyPath(), farm);
}
public void addGearToArtisanShop(String name){
artisanShop.addItem(new Item(name, "You made this gear.", "item_manuscript"));
}
public void setArtisanText(int num){
if (num == 1){
artisan.setText("\"Well that's lovely, thank you, but you can't expect me to make \n" +
"anything with just one gear! Can't you copy it? \n" +
"... \n" +
"*sigh* I can see you are going to need a lot of training. Just say \"cp ITEM \n" +
"NEWITEM\". ITEM's the name of the item that you want copy, and NEWITEM is the \n" +
"new name of the copy, got it? Then poof! You'll have shiny new item. I need five \n" +
"more gears so you'd better get started! Come back when you've made all five. \n");
} else if (num == 2){
artisan.setText("\"Ha, finished already? I guess you learn fast. Well, thanks for \n" +
"your assistance. Take this.\" The Artisan hands you some gold pieces.");
artisanShop.removeCommand("touch");
artisanShop.addCommand("cp");
} else if (num == 3){
artisan.setText("\"I need more gears!\"");
}
}
public int numGearsMade() {
return this.numGearsMade;
}
public void incrementNumGears(){
this.numGearsMade++;
}
public boolean hasLearned(String spell){
return spellsLearned.contains(spell);
}
public void learnSpell(String spell){
spellsLearned.add(spell);
}
public void setNewFarmerText(String txt){
farmer.setText(txt);
}
public void incrementCornCounter() {
cornCounter++;
}
public int getCornCounter() {
return cornCounter;
}
/*public void setRockyPath(Room rockyPath) {
this.rockyPath = rockyPath;
}
public Room getRockyPath() {
return rockyPath;
}*/
/*public void switchClearings(){
link(brokenbridge, afterClearing);
brokenbridge.setText("A creaky rope bridges stretches across a chasm.\n");
brokenbridge.removeChild(beforeClearing);
//beforeClearing.removeParent(brokenbridge);
}*/
public void fixBridge(){
bridgesolved=true;
brokenbridge.setText("A creaky rope bridges stretches across a chasm.\n");
}
/*public void makeHouseComplete(){
clearing.setText("There's a small grassy clearing here, with a man sitting on a stone and \n" +
"sobbing. Behind him is a small white house.\n");
}*/
public void setTrollText(boolean cage){
if (cage){
hideousTroll.setMVText("The troll vanishes with a pop and reappears \n" +
"inside of the cage. He scowls and then begins to chew on the kidnapped \n" +
"child's leg. \n");
} else {
hideousTroll.setMVText("The troll vanishes with a pop and reappears inside of the cage. He scowls and roars.\n");
}
}
public void completeHouseQuest(Room house){
housequestcomplete = true;
link(clearing, house);
clearing.setText("There's a small grassy clearing here, with a man sitting on a stone and " +
"sobbing. Behind him is a small white house.\n");
cryingMan.setText("\"Maybe you aren't so bad after all. If you really want "+
"to help, though, you'll go save my daughter! They took her that way, down that "+
"ominous-looking path. I heard one of them mutter the word 'brambles_b_gone' as "+
"they were leaving. It doesn't mean anything to me, but maybe it will help you on "+
"your journey.\" \n ");
}
public boolean houseQuestComplete(){
return housequestcomplete;
}
/*public Room getAfterClearing() {
return afterClearing;
}*/
/*public void setOminousPath(Room ominousPath) {
this.ominousPath = ominousPath;
}
public Room getOminousPath() {
return ominousPath;
}*/
/*public void setThornyBrambles(Item thornyBrambles) {
this.thornyBrambles = thornyBrambles;
}
public Item getThornyBrambles() {
return thornyBrambles;
}*/
public void setAwaitingPassword(boolean awaitingPassword) {
this.awaitingPassword = awaitingPassword;
}
public boolean isAwaitingPassword() {
return awaitingPassword;
}
public void setBramblessolved(boolean bramblessolved) {
this.bramblessolved = bramblessolved;
}
public boolean isBramblessolved() {
return bramblessolved;
}
public void moveTroll(){
caveOfTrolls.removeItem(hideousTroll);
cage.addItem(hideousTroll);
}
public void moveKid(){
cage.removeItem(kidnappedChild);
clearing.addItem(kidnappedChild);
kidnappedChild.setText("I am so glad to be away from those stinky trolls!");
kidnappedChild.setIconName("item_boy");
cryingMan.setText("Oh, thank goodness she's safe!");
clearing.setText("A man and his daughter are frolicking in front of a lovely house.");
}
}
| gpl-2.0 |
Pugduddly/enderX | src/main/java/com/jcraft/weirdx/Keymap_101.java | 10166 | /* -*-mode:java; c-basic-offset:2; -*- */
/* WeirdX - Guess.
*
* Copyright (C) 1999-2004 JCraft, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.jcraft.weirdx;
import java.io.*;
import java.awt.event.KeyEvent;
import java.net.*;
final class Keymap_101 extends Keymap{
private int[] _map={
0xff1b, 0x0,
0x31, 0x21,
0x32, 0x40,
0x33, 0x23,
0x34, 0x24,
0x35, 0x25,
0x36, 0x5e,
0x37, 0x26,
0x38, 0x2a,
0x39, 0x28,
0x30, 0x29,
0x2d, 0x5f,
0x3d, 0x2b,
0xff08, 0x0,
0xff09, 0xfe20,
0x71, 0x51,
0x77, 0x57,
0x65, 0x45,
0x72, 0x52,
0x74, 0x54,
0x79, 0x59,
0x75, 0x55,
0x69, 0x49,
0x6f, 0x4f,
0x70, 0x50,
0x5b, 0x7b,
0x5d, 0x7d,
0xff0d, 0x0,
0xffe3, 0x0,
0x61, 0x41,
0x73, 0x53,
0x64, 0x44,
0x66, 0x46,
0x67, 0x47,
0x68, 0x48,
0x6a, 0x4a,
0x6b, 0x4b,
0x6c, 0x4c,
0x3b, 0x3a,
0x27, 0x22,
0x60, 0x7e,
0xffe1, 0x0,
0x5c, 0x7c,
0x7a, 0x5a,
0x78, 0x58,
0x63, 0x43,
0x76, 0x56,
0x62, 0x42,
0x6e, 0x4e,
0x6d, 0x4d,
0x2c, 0x3c,
0x2e, 0x3e,
0x2f, 0x3f,
0xffe2, 0x0,
0xffaa, 0x0,
0xffe9, 0xffe7,
0x20, 0x0,
0xffe5, 0x0,
0xffbe, 0x0,
0xffbf, 0x0,
0xffc0, 0x0,
0xffc1, 0x0,
0xffc2, 0x0,
0xffc3, 0x0,
0xffc4, 0x0,
0xffc5, 0x0,
0xffc6, 0x0,
0xffc7, 0x0,
0xff7f, 0xfef9,
0xff14, 0x0,
0xff95, 0xffb7,
0xff97, 0xffb8,
0xff9a, 0xffb9,
0xffad, 0x0,
0xff96, 0xffb4,
0xff9d, 0xffb5,
0xff98, 0xffb6,
0xffab, 0x0,
0xff9c, 0xffb1,
0xff99, 0xffb2,
0xff9b, 0xffb3,
0xff9e, 0xffb0,
0xff9f, 0xffae,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0xffc8, 0x0,
0xffc9, 0x0,
0xff50, 0x0,
0xff52, 0x0,
0xff55, 0x0,
0xff51, 0x0,
0x0, 0x0,
0xff53, 0x0,
0xff57, 0x0,
0xff54, 0x0,
0xff56, 0x0,
0xff63, 0x0,
0xffff, 0x0,
0xff8d, 0x0,
0xffe4, 0x0,
0xff13, 0xff6b,
0xff61, 0xff62,
0xffaf, 0x0,
0xffea, 0xffe8,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0,
0x0, 0x0};
Keymap_101(){
start=9;
width=2;
count=109;
map=_map;
}
final int getCode(KeyEvent e){
if(e.isShiftDown()) state|=1;
if(e.isControlDown()) state|=4;
if(e.isAltDown()) state|=8;
int key=e.getKeyCode();
if(key!=0){
switch(key){
case KeyEvent.VK_A:
case KeyEvent.VK_B:
case KeyEvent.VK_C:
case KeyEvent.VK_D:
case KeyEvent.VK_E:
case KeyEvent.VK_F:
case KeyEvent.VK_G:
case KeyEvent.VK_H:
case KeyEvent.VK_I:
case KeyEvent.VK_J:
case KeyEvent.VK_K:
case KeyEvent.VK_L:
case KeyEvent.VK_M:
case KeyEvent.VK_N:
case KeyEvent.VK_O:
case KeyEvent.VK_P:
case KeyEvent.VK_Q:
case KeyEvent.VK_R:
case KeyEvent.VK_S:
case KeyEvent.VK_T:
case KeyEvent.VK_U:
case KeyEvent.VK_V:
case KeyEvent.VK_W:
case KeyEvent.VK_X:
case KeyEvent.VK_Y:
case KeyEvent.VK_Z:
key=key+0x20;
break;
case KeyEvent.VK_0:
case KeyEvent.VK_1:
case KeyEvent.VK_2:
case KeyEvent.VK_3:
case KeyEvent.VK_4:
case KeyEvent.VK_5:
case KeyEvent.VK_6:
case KeyEvent.VK_7:
case KeyEvent.VK_8:
case KeyEvent.VK_9:
break;
case KeyEvent.VK_ENTER:
key=0xff0d; break;
case KeyEvent.VK_BACK_SPACE:
key=0xff08; break;
case KeyEvent.VK_TAB:
key=0xff09; break;
// case KeyEvent.VK_CANCEL:
// key=0xff69;
// break;
// case KeyEvent.VK_CLEAR:
// key=0xff0b;
// break;
case KeyEvent.VK_COMMA:
case KeyEvent.VK_PERIOD:
case KeyEvent.VK_SLASH:
case KeyEvent.VK_SEMICOLON:
case KeyEvent.VK_EQUALS:
case KeyEvent.VK_OPEN_BRACKET:
case KeyEvent.VK_BACK_SLASH:
case KeyEvent.VK_CLOSE_BRACKET:
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_BACK_QUOTE:
key=0x60; break;
case KeyEvent.VK_QUOTE:
key=0x27; break;
case KeyEvent.VK_SHIFT:
key=0xffe1; break;
case KeyEvent.VK_CONTROL:
key=0xffe3; break;
case KeyEvent.VK_ALT:
key=0xffe9; break;
case KeyEvent.VK_PAUSE:
key=0xff13; break;
case KeyEvent.VK_CAPS_LOCK:
key=0xffe5; break;
case KeyEvent.VK_ESCAPE:
key=0xff1b; break;
case KeyEvent.VK_PAGE_UP:
key=0xff55; break;
case KeyEvent.VK_PAGE_DOWN:
key=0xff56; break;
case KeyEvent.VK_END:
key=0xff57; break;
case KeyEvent.VK_HOME:
key=0xff50; break;
case KeyEvent.VK_LEFT:
key=0xff51; break;
case KeyEvent.VK_UP:
key=0xff52; break;
case KeyEvent.VK_RIGHT:
key=0xff53; break;
case KeyEvent.VK_DOWN:
key=0xff54; break;
case KeyEvent.VK_NUMPAD0:
key=0xffb0; break;
case KeyEvent.VK_NUMPAD1:
key=0xffb1; break;
case KeyEvent.VK_NUMPAD2:
key=0xffb2; break;
case KeyEvent.VK_NUMPAD3:
key=0xffb3; break;
case KeyEvent.VK_NUMPAD4:
key=0xffb4; break;
case KeyEvent.VK_NUMPAD5:
key=0xffb5; break;
case KeyEvent.VK_NUMPAD6:
key=0xffb6; break;
case KeyEvent.VK_NUMPAD7:
key=0xffb7; break;
case KeyEvent.VK_NUMPAD8:
key=0xffb8; break;
case KeyEvent.VK_NUMPAD9:
key=0xffb9; break;
case KeyEvent.VK_MULTIPLY:
key=0xffaa; break;
case KeyEvent.VK_ADD:
key=0xffab; break;
case KeyEvent.VK_SEPARATER:
key=0xffac; break;
case KeyEvent.VK_SUBTRACT:
if(e.getKeyChar()=='_') key=0x5f;
else key=0xffad; break;
case KeyEvent.VK_DECIMAL:
key=0xffae; break;
case KeyEvent.VK_DIVIDE:
key=0xffaf; break;
case KeyEvent.VK_F1:
key=0xffbe; break;
case KeyEvent.VK_F2:
key=0xffbf; break;
case KeyEvent.VK_F3:
key=0xffc0; break;
case KeyEvent.VK_F4:
key=0xffc1; break;
case KeyEvent.VK_F5:
key=0xffc2; break;
case KeyEvent.VK_F6:
key=0xffc3; break;
case KeyEvent.VK_F7:
key=0xffc4; break;
case KeyEvent.VK_F8:
key=0xffc5; break;
case KeyEvent.VK_F9:
key=0xffc6; break;
case KeyEvent.VK_F10:
key=0xffc7; break;
case KeyEvent.VK_F11:
key=0xffc8; break;
case KeyEvent.VK_F12:
key=0xffc9; break;
case KeyEvent.VK_DELETE:
key=0xffff; break;
case KeyEvent.VK_NUM_LOCK:
key=0xff7f; break;
case KeyEvent.VK_SCROLL_LOCK:
key=0xff14; break;
case KeyEvent.VK_PRINTSCREEN:
key=0xff61; break;
case KeyEvent.VK_INSERT:
key=0xff63; break;
case KeyEvent.VK_HELP:
key=0xff6a; break;
case KeyEvent.VK_META:
key=0xffe7; break;
// case KeyEvent.VK_KP_UP:
// key=0xff97; break;
// case KeyEvent.VK_KP_DOWN:
// key=0xff99; break;
// case KeyEvent.VK_KP_LEFT:
// key=0xff96; break;
// case KeyEvent.VK_KP_RIGHT:
// key=0xff98; break;
/*
// For European keyboards
case KeyEvent.VK_DEAD_GRAVE:
case KeyEvent.VK_DEAD_ACUTE:
case KeyEvent.VK_DEAD_CIRCUMFLEX:
case KeyEvent.VK_DEAD_TILDE:
case KeyEvent.VK_DEAD_MACRON:
case KeyEvent.VK_DEAD_BREVE:
case KeyEvent.VK_DEAD_ABOVEDOT:
case KeyEvent.VK_DEAD_DIAERESIS:
case KeyEvent.VK_DEAD_ABOVERING:
case KeyEvent.VK_DEAD_DOUBLEACUTE:
case KeyEvent.VK_DEAD_CARON:
case KeyEvent.VK_DEAD_CEDILLA:
case KeyEvent.VK_DEAD_OGONEK:
case KeyEvent.VK_DEAD_IOTA:
case KeyEvent.VK_DEAD_VOICED_SOUND:
case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
case KeyEvent.VK_AMPERSAND:
case KeyEvent.VK_ASTERISK:
case KeyEvent.VK_QUOTEDBL:
case KeyEvent.VK_LESS:
case KeyEvent.VK_GREATER:
case KeyEvent.VK_BRACELEFT:
case KeyEvent.VK_BRACERIGHT:
// for Asian Keyboards
case KeyEvent.VK_FINAL:
case KeyEvent.VK_CONVERT:
case KeyEvent.VK_NONCONVERT:
case KeyEvent.VK_ACCEPT:
case KeyEvent.VK_MODECHANGE:
case KeyEvent.VK_KANA:
case KeyEvent.VK_KANJI:
// for Sun keyboards
case KeyEvent.VK_CUT:
case KeyEvent.VK_COPY:
case KeyEvent.VK_PASTE:
case KeyEvent.VK_UNDO:
case KeyEvent.VK_AGAIN:
case KeyEvent.VK_FIND:
case KeyEvent.VK_PROPS:
case KeyEvent.VK_STOP:
*/
default:
key=e.getKeyChar();
}
}
else{
key=e.getKeyChar();
}
int s=10;
if(km!=null){
int i=0;
int j=0;
s=km.start;
while(i<km.count*km.width){
if(km.map[i]==key)break;
i++;
j++;
if(j==km.width){
j=0;
s++;
}
}
}
return s;
}
/*
public static int getCode(int key){
if(key==KeyEvent.VK_BACK_SPACE){
key=0xff08;
}
else if(key==KeyEvent.VK_TAB){
key=0xff09;
}
else if(key==KeyEvent.VK_ENTER){
key=0xff0d;
}
else if(key==KeyEvent.VK_ESCAPE){
key=0xff1b;
}
else if(key==KeyEvent.VK_DELETE){
key=0xffff;
}
int s=10;
if(km!=null){
int i=0;
int j=0;
s=km.start;
while(i<km.count*km.width){
if(km.map[i]==key)break;
i++;
j++;
if(j==km.width){
j=0;
s++;
}
}
}
return s;
}
public static void main(String[] arg){
if(km!=null){
int i=0;
int j=0;
int s=km.start;
System.out.print(s+": ");
while(i<km.count*km.width){
System.out.print(km.map[i]+", ");
i++;
j++;
if(j==km.width){
j=0;
s++;
System.out.print("\n"+s+": ");
}
}
}
}
*/
}
| gpl-2.0 |
bartvbl/shooter | Shooter/src/reused/resources/loaders/obj/ModelPartType.java | 80 | package reused.resources.loaders.obj;
enum ModelPartType {
PHYSICAL, VIRTUAL
} | gpl-2.0 |
RealTimeWeb/datasets | datasets/java/business_dynamics/src/corgis/business_dynamics/domain/Record.java | 2877 | package corgis.business_dynamics.domain;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import corgis.business_dynamics.domain.Data;
/**
*
*/
public class Record {
private Data data;
// The state that this report was made for (full name, not the two letter abbreviation).
private String state;
// The year that this report was made for.
private Integer year;
/**
*
* @return Data
*/
public Data getData() {
return this.data;
}
/**
* The state that this report was made for (full name, not the two letter abbreviation).
* @return String
*/
public String getState() {
return this.state;
}
/**
* The year that this report was made for.
* @return Integer
*/
public Integer getYear() {
return this.year;
}
/**
* Creates a string based representation of this Record.
* @return String
*/
public String toString() {
return "Record[" +data+", "+state+", "+year+"]";
}
/**
* Internal constructor to create a Record from a representation.
* @param json_data The raw json data that will be parsed.
*/
public Record(JSONObject json_data) {
//System.out.println(json_data);
try {
// Data
this.data = new Data((JSONObject)json_data.get("Data"));
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Record; the field data was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Record; the field data had the wrong structure.");
e.printStackTrace();
}
try {
// State
this.state = (String)json_data.get("State");
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Record; the field state was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Record; the field state had the wrong structure.");
e.printStackTrace();
}
try {
// Year
this.year = ((Number)json_data.get("Year")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Record; the field year was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Record; the field year had the wrong structure.");
e.printStackTrace();
}
}
} | gpl-2.0 |
samousli/twitter-spot-the-fraud | src/TweetAnalytics/DBManager.java | 2708 | /*
* 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 TweetAnalytics;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import twitter4j.api.TweetsResources;
import com.mongodb.AggregationOptions;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoURI;
import com.mongodb.util.JSON;
/**
*
* @author avail
*/
public class DBManager {
private static DB db;
public DBManager() {
this("mongodb://localhost:28888");
}
public DBManager(String conStr) {
// create the database
try {
// make the initial connection to the mongoDB
@SuppressWarnings("deprecation")
Mongo tweetsMongoClient = new Mongo(new MongoURI(conStr));
db = tweetsMongoClient.getDB("twitter_mini");
} catch (UnknownHostException ex) {
System.err
.println("The database could not be initialized because of an UnknownHostException.");
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null,
ex);
}
}
public long[] fetchChosenUsers(String col) {
long[] user_ids = new long[(int) db.getCollection(col).count()];
Cursor cursor = db.getCollection(col).find();
int i = 0;
while (cursor.hasNext()) {
DBObject e = cursor.next();
if (e.get("_id") instanceof Long)
user_ids[i++] = (Long) e.get("_id");
else if (e.get("_id") instanceof Integer)
user_ids[i++] = ((Integer) e.get("_id")).longValue();
}
return user_ids;
}
//public DBCollection getTweets() {
// return db.getCollection("tweets");
//}
public void insertDoc(String col, String json) {
DBObject ob = (DBObject) JSON.parse(json);
db.getCollection(col).insert(ob);
}
public long tweetCount() {
return db.getCollection("chosen_user_tweets").getCount();
}
@SuppressWarnings("deprecation")
public void initUserCollection(String usr_col) {
if (db.collectionExists(usr_col))
//throw new RuntimeException(
System.out.println("Mongo: Users collection already exists.");
db.getCollection(usr_col).drop();
db.getCollection(usr_col).ensureIndex(
new BasicDBObject("tweets", "text"));
}
public DBCollection getCollection(String collection) {
return db.getCollection(collection);
}
public boolean exists(String collection) {
return db.collectionExists(collection);
}
}
| gpl-2.0 |
CvO-Theory/apt | src/test/uniol/apt/util/equations/InequalitySystemSolverTest.java | 13433 | /*-
* APT - Analysis of Petri Nets and labeled Transition systems
* Copyright (C) 2014-2015 Uli Schlachter
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package uniol.apt.util.equations;
import java.math.BigInteger;
import java.util.List;
import uniol.apt.util.interrupt.Interrupter;
import uniol.apt.util.interrupt.InterrupterRegistry;
import uniol.apt.util.interrupt.UncheckedInterruptedException;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/** @author Uli Schlachter */
public class InequalitySystemSolverTest {
static private BigInteger bi(long num) {
return BigInteger.valueOf(num);
}
@Test
public void testSimpleSystem0() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 1, 0, 1);
system.addInequality(0, ">=", -1, 0, -1);
system.addInequality(0, ">=", 0, 1, 1);
system.addInequality(0, ">=", 0, -1, -1);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(x.add(z), is(bi(0)));
assertThat(y.add(z), is(bi(0)));
}
@Test
public void testSimpleSystem1() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 2, 1, 3);
system.addInequality(0, ">=", 1, 1, 2);
system.addInequality(0, ">=", 1, 2, 3);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(bi(2).multiply(x).add(bi(1).multiply(y)).add(bi(3).multiply(z)), lessThanOrEqualTo(bi(0)));
assertThat(bi(1).multiply(x).add(bi(1).multiply(y)).add(bi(2).multiply(z)), lessThanOrEqualTo(bi(0)));
assertThat(bi(1).multiply(x).add(bi(2).multiply(y)).add(bi(3).multiply(z)), lessThanOrEqualTo(bi(0)));
}
@Test
public void testSimpleSystem2() {
InequalitySystem system = new InequalitySystem();
system.addInequality(1, ">=", 2, 1, 3);
system.addInequality(2, ">=", 1, 1, 2);
system.addInequality(3, ">=", 1, 2, 3);
system.addInequality(4, ">=", 3, 3, 6);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(bi(2).multiply(x).add(bi(1).multiply(y)).add(bi(3).multiply(z)), lessThanOrEqualTo(bi(1)));
assertThat(bi(1).multiply(x).add(bi(1).multiply(y)).add(bi(2).multiply(z)), lessThanOrEqualTo(bi(2)));
assertThat(bi(1).multiply(x).add(bi(2).multiply(y)).add(bi(3).multiply(z)), lessThanOrEqualTo(bi(3)));
assertThat(bi(3).multiply(x).add(bi(3).multiply(y)).add(bi(6).multiply(z)), lessThanOrEqualTo(bi(4)));
}
@Test
public void testSimpleSystem3() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 1, 2);
system.addInequality(0, ">=", 0, 1, 1);
system.addInequality(0, ">=", 1, 0, 1);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(bi(1).multiply(x).add(bi(2).multiply(y)).add(bi(0).multiply(z)), lessThanOrEqualTo(bi(0)));
assertThat(bi(0).multiply(x).add(bi(1).multiply(y)).add(bi(1).multiply(z)), lessThanOrEqualTo(bi(0)));
assertThat(bi(1).multiply(x).add(bi(0).multiply(y)).add(bi(1).multiply(z)), lessThanOrEqualTo(bi(0)));
}
@Test
public void testSimpleSystem4() {
InequalitySystem system = new InequalitySystem();
system.addInequality(10, ">=", 4, 2, 6);
system.addInequality(10, ">=", 2, 2, 4);
system.addInequality(10, ">=", 2, 4, 6);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(bi(4).multiply(x).add(bi(2).multiply(y)).add(bi(6).multiply(z)), lessThanOrEqualTo(bi(10)));
assertThat(bi(2).multiply(x).add(bi(2).multiply(y)).add(bi(4).multiply(z)), lessThanOrEqualTo(bi(10)));
assertThat(bi(2).multiply(x).add(bi(4).multiply(y)).add(bi(6).multiply(z)), lessThanOrEqualTo(bi(10)));
}
@Test
public void testSimpleSystem5() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 4, 2, 5);
system.addInequality(0, ">=", 2, 2, 4);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(bi(4).multiply(x).add(bi(2).multiply(y)).add(bi(5).multiply(z)), lessThanOrEqualTo(bi(0)));
assertThat(bi(2).multiply(x).add(bi(2).multiply(y)).add(bi(4).multiply(z)), lessThanOrEqualTo(bi(0)));
}
@Test
public void testSimpleSystem6() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 0, 0);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(2));
}
@Test
public void testSimpleSystem7() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 0, 42);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(2));
BigInteger y = solution.get(1);
assertThat(y, lessThanOrEqualTo(bi(0)));
}
@Test
public void testSimpleSystem8() {
InequalitySystem system = new InequalitySystem();
system.addInequality(2, ">", 1, 1);
system.addInequality(1, "<=", 1, 1);
system.addInequality(1, "<", 1, 0, 1);
system.addInequality(1, "=", 0, 0, 1);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(3));
BigInteger x = solution.get(0), y = solution.get(1), z = solution.get(2);
assertThat(x.add(y), is(bi(1)));
assertThat(x.add(z), greaterThan(bi(1)));
assertThat(z, is(bi(1)));
}
@Test
public void testSimpleSystemWithInequality0() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, "!=", 1);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(1));
BigInteger x = solution.get(0);
assertThat(x, is(not(bi(0))));
}
@Test
public void testSimpleSystemWithInequality1() {
InequalitySystem system = new InequalitySystem();
system.addInequality(41, "<", 1);
system.addInequality(43, ">", 1);
system.addInequality(42, "!=", 1);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, empty());
}
@Test
public void testEmptySystem1() {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=");
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, empty());
}
@Test
public void testEmptySystem2() {
InequalitySystem system = new InequalitySystem();
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, empty());
}
@Test
public void testLotsOfTrivialInequalities() {
InequalitySystem system = new InequalitySystem();
for (int i = 1; i <= 300; i++)
system.addInequality(-1, ">=", i);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(1));
BigInteger x = solution.get(0);
assertThat(x, lessThanOrEqualTo(bi(-1)));
}
@Test
public void testSystemWithIncorrectSolution() {
// The following system was created while synthesizing the word b(ab^20)^10b. The solution found
// was x = (20, 0) which violates the first inequality: 0 > 1*x[1]. A correct solution is, for
// example, (201, -10) or (21, -1)
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">", 0, 1);
for (int i = 0; i < 200; i++)
system.addInequality(0, ">", -1 - (i / 20), -i);
system.addInequality(0, ">", -10, -200);
List<BigInteger> solution = new InequalitySystemSolver().assertDisjunction(system).findSolution();
assertThat(solution, hasSize(2));
BigInteger x = solution.get(0), y = solution.get(1);
assertThat(x, greaterThan(bi(-20).multiply(y)));
assertThat(y, lessThan(bi(0)));
assertThat(system.fulfilledBy(solution), is(true));
}
@Test
public void testAnyOf() {
InequalitySystem[] required = new InequalitySystem[] { new InequalitySystem() };
required[0].addInequality(42, "=", 1);
InequalitySystem[] anyOf = new InequalitySystem[] {
new InequalitySystem(), new InequalitySystem()
};
anyOf[0].addInequality(21, "=", 1);
anyOf[1].addInequality(21, "=", 1, -1);
List<BigInteger> solution = new InequalitySystemSolver()
.assertDisjunction(required)
.assertDisjunction(anyOf)
.findSolution();
assertThat(solution, hasSize(2));
BigInteger x = solution.get(0), y = solution.get(1);
assertThat(x, equalTo(bi(42)));
assertThat(y, equalTo(bi(21)));
assertThat(required[0].fulfilledBy(solution), is(true));
assertThat(anyOf[0].fulfilledBy(solution), is(false));
assertThat(anyOf[1].fulfilledBy(solution), is(true));
}
@Test
public void testAnyOfUnsat() {
// x[0] is either 10 or 20
InequalitySystem[] first = new InequalitySystem[] {
new InequalitySystem(), new InequalitySystem()
};
first[0].addInequality(10, "=", 1);
first[1].addInequality(20, "=", 1);
// 0 = x[0] + x[1] or 0 = x[0] - x[1]
InequalitySystem[] second = new InequalitySystem[] {
new InequalitySystem(), new InequalitySystem()
};
second[0].addInequality(0, "=", 1, 1);
second[1].addInequality(0, "=", 1, -1);
// x[1] is either 1 or 2
InequalitySystem[] third = new InequalitySystem[] {
new InequalitySystem(), new InequalitySystem()
};
third[0].addInequality(1, "=", 0, 1);
third[1].addInequality(2, "=", 0, 1);
List<BigInteger> solution = new InequalitySystemSolver()
.assertDisjunction(first)
.assertDisjunction(second)
.assertDisjunction(third)
.findSolution();
assertThat(solution, empty());
}
@Test
public void testAnyOfEmpty() {
InequalitySystem[] required = new InequalitySystem[] { new InequalitySystem() };
required[0].addInequality(42, "=", 1);
InequalitySystem[] empty = new InequalitySystem[0];
List<BigInteger> solution = new InequalitySystemSolver()
.assertDisjunction(empty)
.assertDisjunction(required)
.assertDisjunction(empty)
.findSolution();
assertThat(solution, hasSize(1));
BigInteger x = solution.get(0);
assertThat(x, equalTo(bi(42)));
}
@Test
public void testAnyOfEmpty2() {
InequalitySystem[] required = new InequalitySystem[] { new InequalitySystem(), new InequalitySystem() };
required[0].addInequality(42, "=", 1);
InequalitySystem[] empty = new InequalitySystem[0];
List<BigInteger> solution = new InequalitySystemSolver()
.assertDisjunction(empty)
.assertDisjunction(required)
.assertDisjunction(empty)
.findSolution();
assertThat(solution, hasSize(1));
BigInteger x = solution.get(0);
assertThat(x, equalTo(bi(42)));
}
@Test
public void testPushPop() {
InequalitySystemSolver solver = new InequalitySystemSolver();
// x[0] is 42
InequalitySystem system = new InequalitySystem();
system.addInequality(42, "=", 1);
solver.assertDisjunction(system);
assertThat(solver.findSolution(), contains(bi(42)));
solver.push();
// x[0] == -x[1]
system = new InequalitySystem();
system.addInequality(0, "=", 1, 1);
solver.assertDisjunction(system);
assertThat(solver.findSolution(), contains(bi(42), bi(-42)));
solver.pop();
// x[0] == 2*x[1]
system = new InequalitySystem();
system.addInequality(0, "=", 2, -1);
solver.assertDisjunction(system);
assertThat(solver.findSolution(), contains(bi(42), bi(84)));
}
@Test(expectedExceptions = UncheckedInterruptedException.class)
public void testInterruption() {
InterrupterRegistry.setCurrentThreadInterrupter(new Interrupter() {
@Override
public boolean isInterruptRequested() {
return true;
}
});
try {
InequalitySystem system = new InequalitySystem();
system.addInequality(0, ">=", 0, 0);
new InequalitySystemSolver().assertDisjunction(system).findSolution();
throw new AssertionError("This line should be unreachable");
} finally {
InterrupterRegistry.clearCurrentThreadInterrupter();
}
}
}
// vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
| gpl-2.0 |
BianBianKing/XidianLife | src/main/java/com/xidian/weichat/MyX509TrustManager.java | 540 | package com.xidian.weichat;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} | gpl-2.0 |
ReagentX/heidnerComputerScienceProjects | lab09_while_doWhile/Divisors.java | 1072 | //© A+ Computer Science - www.apluscompsci.com
//Name - Chris Sardegna
//Date - 3/27/2014
//Class - Period 5
//Lab -
import static java.lang.System.*;
public class Divisors
{
public static String getDivisors( int number )
{
//String divisors=number + " has divisors ";
int count = 0;
String divisors=number + " has divisors: ";
double num = number;
double divisor=1;
while(divisor <= num ){
//System.out.println((num/divisor)%2);
//double q = num/divisor;
String s="";
//System.out.println(q);
if ((num/divisor)%1 == 0){
s = (int)divisor + " ";
count++;
}
//System.out.println( number % 10 );
//String divisors=number + " has " + count + " divisors: ";
divisors += s;
divisor++;
}
//System.out.println( total );
System.out.println(divisors + " (" + count + ") ");
return divisors;
}
} | gpl-2.0 |
sloscal1/PFS-NEAT | src/mil/af/rl/anji/learner/package-info.java | 756 | /**
* This package contains the primary algorithmic changes to the ANJI code base to
* get the predictive feature selection framework implemented. The standard ANJI
* Evolver class has been replaced by this version of Evolver which supports the
* collection of sample observations during learning, as well as changing the
* feature subset of the current genotype. ConcurrentFitnessFunction enables the
* genotype to be evaluated in parallel, and the NEAT_Learner classes are the
* other halves of the evaluation process. NEAT_LearnerPFS allows for sample
* collection during the evaluation process (which can save time when compared with
* going back to re-evaluate chromosomes at the end of a NEAT generation).
*/
package mil.af.rl.anji.learner; | gpl-2.0 |
Lmctruck30/RiotScape-Client | src/Class3_Sub13_Sub14.java | 5592 |
final class Class3_Sub13_Sub14 extends Class3_Sub13 {
static int anInt3158 = -8 + (int)(17.0D * Math.random());
static Class73 aClass73_3159;
private int anInt3160 = 0;
static Class94 aClass94_3161 = Class3_Sub4.buildString("_");
private int anInt3163 = 20;
private int anInt3164 = 1365;
private int anInt3165 = 0;
static boolean aBoolean3166 = false;
static Class94 aClass94_3168 = Class3_Sub4.buildString("cross");
static Class94 aClass94_3169 = Class3_Sub4.buildString("Lade Sprites )2 ");
private static Class94 aClass94_3170 = Class3_Sub4.buildString("Loaded textures");
static int[] anIntArray3171 = new int[]{0, 4, 4, 8, 0, 0, 8, 0, 0};
static Class94 aClass94_3172 = Class3_Sub4.buildString("Regarder dans cette direction");
static Class153 aClass153_3173;
static Class94 aClass94_3167 = aClass94_3170;
final void method157(int var1, Class3_Sub30 var2, boolean var3) {
try {
if(!var3) {
aClass94_3168 = (Class94)null;
}
if(-1 != ~var1) {
if(-2 != ~var1) {
if(~var1 != -3) {
if(var1 == 3) {
this.anInt3165 = var2.method737(1);
}
} else {
this.anInt3160 = var2.method737(1);
}
} else {
this.anInt3163 = var2.method737(1);
}
} else {
this.anInt3164 = var2.method737(1);
}
} catch (RuntimeException var5) {
throw Class44.method1067(var5, "gm.A(" + var1 + ',' + (var2 != null?"{...}":"null") + ',' + var3 + ')');
}
}
static final void method236(byte var0) {
try {
if(var0 == 64) {
Class3_Sub13_Sub32.aBoolean3387 = true;
}
} catch (RuntimeException var2) {
throw Class44.method1067(var2, "gm.C(" + var0 + ')');
}
}
static final void method237(int var0) {
try {
Class66.anInt997 = 0;
Class139.anInt1829 = 0;
Class24.method945((byte)-11);
Class167.method2261(113);
Class75_Sub4.method1349(var0 ^ 8106);
int var1;
for(var1 = 0; ~var1 > ~Class139.anInt1829; ++var1) {
int var2 = Class3_Sub7.anIntArray2292[var1];
if(~Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[var2].anInt2838 != ~Class44.anInt719) {
if(Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[var2].aClass90_3976.method1474(-1)) {
Class3_Sub28_Sub8.method574(Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[var2], false);
}
Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[var2].method1987(-1, (Class90)null);
Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[var2] = null;
}
}
if(var0 != 8169) {
method237(96);
}
if(Class130.anInt1704 == Class28.aClass3_Sub30_Sub1_532.anInt2595) {
for(var1 = 0; var1 < Class163.anInt2046; ++var1) {
if(null == Class3_Sub13_Sub24.aClass140_Sub4_Sub2Array3292[Class15.anIntArray347[var1]]) {
throw new RuntimeException("gnp2 pos:" + var1 + " size:" + Class163.anInt2046);
}
}
} else {
throw new RuntimeException("gnp1 pos:" + Class28.aClass3_Sub30_Sub1_532.anInt2595 + " psize:" + Class130.anInt1704);
}
} catch (RuntimeException var3) {
throw Class44.method1067(var3, "gm.B(" + var0 + ')');
}
}
final int[] method154(int var1, byte var2) {
try {
int var4 = -72 % ((30 - var2) / 36);
int[] var3 = this.aClass114_2382.method1709(-16409, var1);
if(this.aClass114_2382.aBoolean1580) {
for(int var5 = 0; ~Class113.anInt1559 < ~var5; ++var5) {
int var7 = this.anInt3165 + (Class163_Sub3.anIntArray2999[var1] << 12) / this.anInt3164;
int var6 = this.anInt3160 + (Class102.anIntArray2125[var5] << 12) / this.anInt3164;
int var8 = var6;
int var10 = var6;
int var9 = var7;
int var11 = var7;
int var14 = 0;
int var12 = var6 * var6 >> 12;
for(int var13 = var7 * var7 >> 12; ~(var12 - -var13) > -16385 && ~this.anInt3163 < ~var14; var12 = var10 * var10 >> 12) {
var11 = (var10 * var11 >> 12) * 2 + var9;
++var14;
var10 = var12 + -var13 + var8;
var13 = var11 * var11 >> 12;
}
var3[var5] = ~var14 <= ~(this.anInt3163 + -1)?0:(var14 << 12) / this.anInt3163;
}
}
return var3;
} catch (RuntimeException var15) {
throw Class44.method1067(var15, "gm.D(" + var1 + ',' + var2 + ')');
}
}
public static void method238(int var0) {
try {
if(var0 == 9423) {
aClass94_3169 = null;
anIntArray3171 = null;
aClass73_3159 = null;
aClass153_3173 = null;
aClass94_3168 = null;
aClass94_3167 = null;
aClass94_3161 = null;
aClass94_3170 = null;
aClass94_3172 = null;
}
} catch (RuntimeException var2) {
throw Class44.method1067(var2, "gm.E(" + var0 + ')');
}
}
public Class3_Sub13_Sub14() {
super(0, true);
}
}
| gpl-2.0 |
piaolinzhi/fight | dubbo/pay/pay-common/src/main/java/wusc/edu/pay/common/enums/BankCertificateSwitchEnum.java | 1459 | package wusc.edu.pay.common.enums;
import java.util.HashMap;
import java.util.Map;
public enum BankCertificateSwitchEnum {
OPEN("开启",1),CLOSE("关闭",2);
private BankCertificateSwitchEnum(String desc , int value){
this.desc = desc;
this.value = value;
}
private String desc;
private int value;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static BankCertificateSwitchEnum getEnum(int value) {
BankCertificateSwitchEnum resultEnum = null;
BankCertificateSwitchEnum[] enumAry = BankCertificateSwitchEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].getValue() == value) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() {
BankCertificateSwitchEnum[] ary = BankCertificateSwitchEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = String.valueOf(getEnum(ary[num].getValue()));
map.put("value", String.valueOf(ary[num].getValue()));
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
}
| gpl-2.0 |
sworisbreathing/jpathwatch | jpathwatch-java/src/main/java/name/pachler/nio/file/impl/PathWatchEventModifier.java | 1336 | /*
* Copyright 2008-2011 Uwe Pachler
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. This particular file is
* subject to the "Classpath" exception as provided in the LICENSE file
* that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package name.pachler.nio.file.impl;
import name.pachler.nio.file.Path;
import name.pachler.nio.file.WatchEvent.Modifier;
/**
*
* @author count
*/
public class PathWatchEventModifier implements Modifier<Path> {
private final String name;
public PathWatchEventModifier(String name){
this.name = name;
}
public String name() {
return name;
}
}
| gpl-2.0 |
AcademicTorrents/AcademicTorrents-Downloader | frostwire-merge/org/minicastle/x509/X509Attribute.java | 2097 | package org.minicastle.x509;
import org.minicastle.asn1.ASN1Encodable;
import org.minicastle.asn1.ASN1EncodableVector;
import org.minicastle.asn1.ASN1Set;
import org.minicastle.asn1.DERObject;
import org.minicastle.asn1.DERObjectIdentifier;
import org.minicastle.asn1.DERSet;
import org.minicastle.asn1.x509.Attribute;
/**
* Class for carrying the values in an X.509 Attribute.
*/
public class X509Attribute
extends ASN1Encodable
{
Attribute attr;
/**
* @param at an object representing an attribute.
*/
X509Attribute(
ASN1Encodable at)
{
this.attr = Attribute.getInstance(at);
}
/**
* Create an X.509 Attribute with the type given by the passed in oid and
* the value represented by an ASN.1 Set containing value.
*
* @param oid type of the attribute
* @param value value object to go into the atribute's value set.
*/
public X509Attribute(
String oid,
ASN1Encodable value)
{
this.attr = new Attribute(new DERObjectIdentifier(oid), new DERSet(value));
}
/**
* Create an X.59 Attribute with the type given by the passed in oid and the
* value represented by an ASN.1 Set containing the objects in value.
*
* @param oid type of the attribute
* @param value vector of values to go in the attribute's value set.
*/
public X509Attribute(
String oid,
ASN1EncodableVector value)
{
this.attr = new Attribute(new DERObjectIdentifier(oid), new DERSet(value));
}
public String getOID()
{
return attr.getAttrType().getId();
}
public ASN1Encodable[] getValues()
{
ASN1Set s = attr.getAttrValues();
ASN1Encodable[] values = new ASN1Encodable[s.size()];
for (int i = 0; i != s.size(); i++)
{
values[i] = (ASN1Encodable)s.getObjectAt(i);
}
return values;
}
public DERObject toASN1Object()
{
return attr.toASN1Object();
}
}
| gpl-2.0 |
cerisara/jsafran | src/jsafran/parsing/Malt4Jsafran.java | 4315 | package jsafran.parsing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.maltparser.MaltConsoleEngine;
import org.maltparser.MaltParserService;
import org.maltparser.core.exception.MaltChainedException;
import org.maltparser.core.options.OptionManager;
import org.maltparser.ml.lib.MaltLiblinearModel;
import jsafran.DetGraph;
import jsafran.GraphIO;
import jsafran.JSafran;
/**
* Attention: il y a des bugs dans MaltParser.
*
* Notamment lorsqu'on utiliser plusieurs containers (?), il semble que le CombinedTableContainer se retrouve avec des cachedSymbol qui contiennent
* des chars nulls, et ca fait planter KBestList.add(ActionCode)
*
*
* .... ==> version plus simple avec experiments
*
* @author xtof
*
*/
public class Malt4Jsafran {
public Malt4Jsafran() {
}
public void train(String modelName, List<DetGraph> gs) {
// try {
GraphIO.saveConLL06(gs, "tmpmalt.conll");
File f = new File(modelName+".mco");
if (f.exists()) f.delete();
try {
String cmd = "java -jar ../maltparser/dist/maltparser-1.7.2/maltparser-1.7.2.jar -c "+modelName+" -i tmpmalt.conll -m learn -ne true -nr false";
String[] cmds = cmd.split(" ");
ProcessBuilder pb = new ProcessBuilder(cmds);
// not 1.6 compatible
// pb.redirectOutput(new File("tmpmaltstdout.log"));
Process p = pb.start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
// new MaltParserService(0).runExperiment("-c "+modelName+" -i tmpmalt.conll -m learn -ne true -nr false");
// } catch (MaltChainedException e) {
// System.err.println("MaltParser exception : " + e.getMessage());
// }
}
public void parse(String modelName, List<DetGraph> gs) {
// try {
GraphIO.saveConLL06(gs, "tmpmalt.conll");
try {
String cmd = "java -jar ../maltparser/dist/maltparser-1.7.2/maltparser-1.7.2.jar -c "+modelName+" -i tmpmalt.conll -o tmpmaltout.conll -m parse";
String[] cmds = cmd.split(" ");
ProcessBuilder pb = new ProcessBuilder(cmds);
// not 1.6 compatible
// pb.redirectOutput(new File("tmpmaltstdout.log"));
Process p = pb.start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
// MaltLiblinearModel.saveAndResetScores();
// new MaltParserService(0).runExperiment("-c "+modelName+" -i tmpmalt.conll -o tmpmaltout.conll -m parse");
// System.out.println("after XP "+MaltLiblinearModel.scores.size()+" "+MaltLiblinearModel.uttStartIdx.size()+" "+gs.size());
List<DetGraph> gg = GraphIO.loadConll06("tmpmaltout.conll", false);
for (int i=0;i<gg.size();i++) {
JSafran.projectOnto(gg.get(i), gs.get(i), true, false, false);
// gs.get(i).conf=(float)MaltLiblinearModel.getScoreUtt(i);
}
try {
BufferedReader f = new BufferedReader(new FileReader("tmpmaltstdout.log"));
for (int i=0;i<gs.size();i++) {
float sc=0;
int j=0;
for (;;) {
String s=f.readLine();
if (s.startsWith("DETMALTNEWUTT")) break;
int k=s.indexOf(' ');
sc+=Float.parseFloat(s.substring(k+1));
++j;
}
if (j==0) sc=0;
else sc/=(float)j;
gs.get(i).conf=sc;
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
// MaltLiblinearModel.scores.clear();
// } catch (MaltChainedException e) {
// System.err.println("MaltParser exception : " + e.getMessage());
// }
}
public void parse(String modelName, DetGraph g) {
ArrayList<DetGraph> gs = new ArrayList<DetGraph>();
gs.add(g);
parse(modelName,gs);
}
static void test2() {
GraphIO gio = new GraphIO(null);
Malt4Jsafran parser = new Malt4Jsafran();
if (true) {
List<DetGraph> gs = gio.loadAllGraphs("../jsafran/tmp.xml");
parser.train("tmpmod", gs);
}
if (true) {
List<DetGraph> gs = gio.loadAllGraphs("../jsafran/test2009.xml");
parser.parse("tmpmod", gs);
gio.save(gs, "res1.xml");
}
if (true) {
List<DetGraph> gs = gio.loadAllGraphs("../jsafran/test2009.xml");
parser.train("tmpmod", gs);
}
{
List<DetGraph> gs = gio.loadAllGraphs("../jsafran/test2009.xml");
parser.parse("tmpmod", gs);
gio.save(gs, "res2.xml");
}
}
public static void main(String args[]) {
test2();
}
}
| gpl-2.0 |
Team-OfferManager/ebay-jaxb-bindings | src/main/java/de/idealo/offers/imports/offermanager/ebay/api/binding/jaxb/trading/GetPromotionalSaleDetailsRequestType.java | 3608 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.11.06 um 02:47:13 AM CET
//
package de.idealo.offers.imports.offermanager.ebay.api.binding.jaxb.trading;
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.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Retrieves information about promotional sales set up by an eBay store owner
* (the authenticated caller).
*
*
* <p>Java-Klasse für GetPromotionalSaleDetailsRequestType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="GetPromotionalSaleDetailsRequestType">
* <complexContent>
* <extension base="{urn:ebay:apis:eBLBaseComponents}AbstractRequestType">
* <sequence>
* <element name="PromotionalSaleID" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="PromotionalSaleStatus" type="{urn:ebay:apis:eBLBaseComponents}PromotionalSaleStatusCodeType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetPromotionalSaleDetailsRequestType", propOrder = {
"promotionalSaleID",
"promotionalSaleStatus"
})
public class GetPromotionalSaleDetailsRequestType
extends AbstractRequestType
{
@XmlElement(name = "PromotionalSaleID")
protected Long promotionalSaleID;
@XmlElement(name = "PromotionalSaleStatus")
@XmlSchemaType(name = "token")
protected List<PromotionalSaleStatusCodeType> promotionalSaleStatus;
/**
* Ruft den Wert der promotionalSaleID-Eigenschaft ab.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getPromotionalSaleID() {
return promotionalSaleID;
}
/**
* Legt den Wert der promotionalSaleID-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setPromotionalSaleID(Long value) {
this.promotionalSaleID = value;
}
/**
* Gets the value of the promotionalSaleStatus 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 promotionalSaleStatus property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPromotionalSaleStatus().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PromotionalSaleStatusCodeType }
*
*
*/
public List<PromotionalSaleStatusCodeType> getPromotionalSaleStatus() {
if (promotionalSaleStatus == null) {
promotionalSaleStatus = new ArrayList<PromotionalSaleStatusCodeType>();
}
return this.promotionalSaleStatus;
}
}
| gpl-2.0 |
dfreiretioc/IOC1 | JavaApplication3/src/javaapplication3/IOC.java | 430 | /*
* 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 ioc;
/**
*
* @author Dan
*/
public class IOC {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| gpl-2.0 |
Mjolinir/CSC275 | Final/Plant.java | 924 | package Final;
public class Plant {
//Instance variables
private String name;
private String id;
//Constructor Methods
public Plant()
{
name = " ";
id = " ";
}
public Plant(String nm, String uid)
{
name = nm;
id = uid;
}
//Mutator methods
public void setname (String fn)
{
name = fn;
}
public void setid (String uid)
{
id = uid;
}
//Accessor methods
public String getname()
{
return name;
}
public String getid()
{
return id;
}
//Other methods
public String toString()
{
String str;
str = "Name .....: " + name + "\n" +
"ID .......: " + id + "\n";
return str;
}
}
| gpl-2.0 |
enjoy0924/plum-distribute | src/main/java/com/plum/jpush/JPushMessageQueueImpl.java | 783 | package com.plum.jpush;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by G_dragon on 2015/8/27.
*/
public class JPushMessageQueueImpl {
private static final Logger logger = LoggerFactory.getLogger(JPushMessageQueueImpl.class);
private JPushClient jPushClient;
public JPushClient getjPushClient() {
return jPushClient;
}
public void setjPushClient(JPushClient jPushClient) {
this.jPushClient = jPushClient;
}
//@Override
public boolean notifyMessage(String message, String... topic) {
if(null == jPushClient)
return false;
String result = jPushClient.notifyMessage(message, topic);
logger.debug(result);
return true;
}
}
| gpl-2.0 |
tmmachado/uk.aber.spam | app/controllers/Application.java | 8110 | package controllers;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.typesafe.plugin.MailerAPI;
import com.typesafe.plugin.MailerPlugin;
import play.data.DynamicForm;
import play.data.Form;
import play.db.DB;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render(""));
}
public static Result summary() {
return ok(summary.render(""));
}
public static Result studentReport(){
String feedback = "";
if (session("feedback") != null){
feedback = session("feedback");
session().remove("feedback");
}
return ok(student_report.render(feedback));
}
public static Result ytList(){
String feedback = "";
if (session("feedback") != null){
feedback = session("feedback");
session().remove("feedback");
}
return ok(yt_list.render(feedback));
}
public static Result dotList(){
String feedback = "";
if (session("feedback") != null){
feedback = session("feedback");
session().remove("feedback");
}
return ok(dot_list.render(feedback));
}
@SuppressWarnings("unchecked")
public static Result jsonSummary(String stud_uid, String academic_year) throws SQLException {
// DynamicForm formArray = Form.form().bindFromRequest();
Connection conn = DB.getConnection();
Statement stmt = null;
JSONArray jArray = new JSONArray();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select \n" +
" stp.EMAIL as stud_uid, \n" +
" CONCAT(CONCAT(stp.SURNAME, ', '), stp.FORENAMES) as stud_name, \n" +
" stp.ACADEMIC_YEAR, \n" +
" stp.SS_YEAR as year_of_study, \n" +
" decode(stp.status, 'R', 'Y', 'N') as repeating, \n" +
" sus.STAGE_OF_PROCESS, \n" +
" sm.DATETIME as datetime_meeting, \n" +
" CONCAT(CONCAT(st.SURNAME, ', '), st.FORENAMES) as responsible_name, \n" +
" sm.OUTCOME \n" +
"from stp_live_view stp \n" +
" inner join SPAM_MEETING sm on (stp.STUD_REF = sm.stud_ref) \n" +
" inner join st_staff st on (st.USER_ID = sm.RESPONSIBLE_ID) \n" +
" inner join spam_unsatisfactory_student sus on (sus.STUD_REF = stp.STUD_REF) \n" +
"where \n" +
" stp.EMAIL = '" + stud_uid + "' \n" +
" and stp.ACADEMIC_YEAR = '" + academic_year + "' "
);
while (rs.next()) {
JSONObject studJSON = new JSONObject();
studJSON.put("stud_uid", rs.getString("stud_uid"));
studJSON.put("stud_name", rs.getString("stud_name"));
studJSON.put("academic_year", rs.getString("academic_year"));
studJSON.put("year_of_study", rs.getString("year_of_study"));
studJSON.put("repeating", rs.getString("repeating"));
studJSON.put("datetime_meeting", rs.getString("datetime_meeting"));
studJSON.put("responsible_name", rs.getString("responsible_name"));
studJSON.put("outcome", rs.getString("outcome"));
studJSON.put("stage_of_process", rs.getString("stage_of_process"));
jArray.add(studJSON);
}
conn.close();
} catch (Exception e) {
conn.close();
System.out.println("sql error");
}
return ok(jArray.toJSONString());
}
/**
* Send an email to responsible and student with the details of the meeting
* @param formArray
* @param responsible
* @param email_std
* @return true or false
* @throws SQLException
*/
public static boolean sendEmail(DynamicForm formArray, String responsible, boolean email_std) throws SQLException{
Parameters.getParameters();
try {
String stud_name = formArray.get("stud_name").split(", ")[1] + " " + formArray.get("stud_name").split(", ")[0];
String date = "";
String time = "";
String location = "";
String responsible_uid = "";
String stud_uid = "";
String email_body = "";
String email_subject = "";
String dot_name = "";
if(email_std){
date = formArray.get("date");
time = formArray.get("hours") + ":" + formArray.get("minutes");
location = formArray.get("location");
}
MailerAPI mail = play.Play.application().plugin(MailerPlugin.class).email();
stud_uid = formArray.get("stud_uid");
String responsible_name = "";
if (!responsible.toUpperCase().equals("ADMIN")){
int year_of_study = Integer.parseInt(formArray.get("year_of_study"));
responsible_uid = Parameters.getResponsibleUid(year_of_study, formArray.get("stage_of_process"));
responsible_name = Parameters.getResponsibleName(year_of_study, formArray.get("stage_of_process"));
}
if(responsible.toUpperCase().equals("YEAR_TUTOR") && email_std){
mail.setRecipient(responsible_uid + Parameters.EMAIL_DOMAIN, stud_uid + Parameters.EMAIL_DOMAIN);
mail.setBcc(Parameters.ADMIN_UID + Parameters.EMAIL_DOMAIN);
email_subject = Parameters.EMAIL_SUBJECT_YT_STD;
email_body = Parameters.EMAIL_BODY_YT_STD;
email_body = email_body.replace("{date}", date);
email_body = email_body.replace("{time}", time);
email_body = email_body.replace("{location}", location);
email_body = email_body.replace("{stud_name}", stud_name);
email_body = email_body.replace("{year_tutor_name}", responsible_name);
email_body += Parameters.EMAIL_GREETING;
}else if(responsible.toUpperCase().equals("YEAR_TUTOR") && !email_std){
mail.setRecipient(responsible_uid + Parameters.EMAIL_DOMAIN);
email_subject = Parameters.EMAIL_SUBJECT_YT;
email_subject = email_subject.replace("{stud_name}", stud_name);
email_body = Parameters.EMAIL_BODY_YT;
email_body = email_body.replace("{stud_name}", stud_name);
email_body = email_body.replace("{year_tutor_uid}", responsible_uid);
email_body = email_body.replace("{stud_uid}", stud_uid);
email_body += Parameters.EMAIL_GREETING;
}else if(responsible.toUpperCase().equals("DOT") && email_std){
mail.setRecipient(responsible_uid + Parameters.EMAIL_DOMAIN, stud_uid + Parameters.EMAIL_DOMAIN);
email_subject = Parameters.EMAIL_SUBJECT_DOT_STD;
mail.setBcc(Parameters.ADMIN_UID + Parameters.EMAIL_DOMAIN);
email_body = Parameters.EMAIL_BODY_DOT_STD;
email_body = email_body.replace("{date}", date);
email_body = email_body.replace("{time}", time);
email_body = email_body.replace("{location}", location);
email_body = email_body.replace("{stud_name}", stud_name);
email_body = email_body.replace("{dot_name}", responsible_name);
}else if(responsible.toUpperCase().equals("DOT") && !email_std){
mail.setRecipient(responsible_uid + Parameters.EMAIL_DOMAIN);
email_subject = Parameters.EMAIL_SUBJECT_DOT;
email_subject = email_subject.replace("{stud_name}", stud_name);
email_body = Parameters.EMAIL_BODY_DOT;
email_body = email_body.replace("{stud_name}", stud_name);
email_body = email_body.replace("{dot_uid}", responsible_uid);
email_body = email_body.replace("{stud_uid}", stud_uid);
email_body += Parameters.EMAIL_GREETING;
} else {
email_subject = Parameters.EMAIL_SUBJECT_ADMIN;
email_subject = email_subject.replace("{stud_name}", stud_name);
mail.setRecipient(Parameters.ADMIN_UID + Parameters.EMAIL_DOMAIN);
mail.setSubject(email_subject);
email_body = Parameters.EMAIL_BODY_ADMIN;
email_body = email_body.replace("{stud_uid}", stud_uid);
email_body = email_body.replace("{stud_name}", stud_name);
email_body += Parameters.EMAIL_GREETING;
}
mail.setFrom(Parameters.ADMIN_UID + Parameters.EMAIL_DOMAIN);
mail.setSubject(email_subject);
mail.send("", email_body);
System.out.println(responsible_uid+"\n\n"+email_body);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| gpl-2.0 |
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/subversion/bindings/javahl/src/org/tigris/subversion/javahl/MergeinfoLogKind.java | 1028 | /**
* @copyright
* ====================================================================
* Copyright (c) 2008 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*/
package org.tigris.subversion.javahl;
/**
* class for kind of mergeinfo logs
*/
public interface MergeinfoLogKind
{
/** does not exist */
public static final int eligible = 0;
/** exists, but uninteresting */
public static final int merged = 1;
}
| gpl-2.0 |
orph/jujitsu | src/e/edit/CompareSelectionAndClipboardAction.java | 2059 | package e.edit;
import e.util.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
/**
* Shows a patch to turn the clipboard into the selection. Useful for confirming
* that you're looking at copy & paste code before you remove it.
*
* Obvious extensions:
*
* 1. We don't know much about the data on the clipboard, but we know a lot
* about the selection; we could use that to allow double-clicking to take
* you to the line in question.
*
* 2. Suppose you're comparing code where someone's changed an identifier or
* a magic number, and there are bogus differences where all you need is a
* parameter. Would something like replaceAll("\\b(\\d+|0x[0-9a-fA-F]+)\\b",
* "123") to replace numeric literals with one constant -- and similar for
* string literals and identifiers -- be helpful?
*/
public class CompareSelectionAndClipboardAction extends ETextAction {
public CompareSelectionAndClipboardAction() {
super("Compare Selection and Clipboard...");
}
public void actionPerformed(ActionEvent e) {
ETextWindow window = getFocusedTextWindow();
if (window == null) {
return;
}
String selection = window.getTextArea().getSelectedText();
String clipboard = getClipboardText();
// Avoid diff(1) warnings about "No newline at end of file".
selection += "\n";
clipboard += "\n";
SimplePatchDialog.showPatchBetween("Selection/Clipboard Comparison", "selection", selection, "clipboard", clipboard);
}
private String getClipboardText() {
String result = "";
try {
Clipboard selection = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = selection.getContents(null);
result = (String) transferable.getTransferData(DataFlavor.stringFlavor);
} catch (Exception ex) {
Log.warn("Couldn't get clipboard contents.", ex);
}
return result;
}
}
| gpl-2.0 |
shenzeyu/3dweb | src/main/java/com/kuquo/app/order/buy/rebate/action/RebateItemAction.java | 4725 | package com.kuquo.app.order.buy.rebate.action;
import com.kuquo.app.baseInfo.supplier.model.Supplier;
import com.kuquo.app.order.buy.rebate.model.Rebate;
import com.kuquo.app.order.buy.rebate.model.RebateItem;
import com.kuquo.app.order.buy.rebate.service.RebateItemService;
import com.kuquo.app.system.user.model.SysUser;
import com.kuquo.code.struct.BaseAction;
import com.kuquo.code.util.PageInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class RebateItemAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(RebateItemAction.class);
private Rebate rebate;
private RebateItem rebateItem;
private RebateItemService rebateItemService;
private Supplier supplier;
public String list() {
return "list_rebateItem";
}
public String listJosn() {
logger.info("start list rebateItem");
List<RebateItem> resultList = null;
int totalRows = 0;
try {
PageInfo pageInfo = createPageInfo();
if (this.rebateItem == null) {
this.rebateItem = new RebateItem();
}
resultList = this.rebateItemService.pageList(pageInfo, this.rebateItem, true);
totalRows = pageInfo.getCount();
} catch (Exception e) {
logger.error("erro occur when list rebateItem", e);
}
if (resultList == null) {
resultList = new ArrayList();
}
this.jsonMap = new HashMap();
this.jsonMap.put("total", Integer.valueOf(totalRows));
this.jsonMap.put("rows", resultList);
logger.info("finish list all supplier");
return "success";
}
public String edit() {
SysUser loginMan = getSessionUserInfo();
if (this.rebateItem == null) {
this.rebateItem = new RebateItem();
}
try {
Date startTime = this.rebate.getStartTime();
Date endTime = this.rebate.getEndTime();
if ((startTime != null) && (endTime != null)) {
getRequest().setAttribute("startTime", startTime);
getRequest().setAttribute("endTime", endTime);
}
if (StringUtils.isBlank(this.rebateItem.getId())) {
String rebateId = this.rebateItem.getRebateId();
this.rebateItem.setState("c");
this.rebateItem.setRebateId(rebateId);
initModel(true, this.rebateItem, loginMan);
} else {
this.rebateItem = ((RebateItem) this.rebateItemService.getModel(this.rebateItem.getId()));
initModel(false, this.rebateItem, loginMan);
}
} catch (Exception e) {
logger.error("error occur when list rebateItem", e);
}
return "edit_rebateItem";
}
public String show() {
SysUser loginMan = getSessionUserInfo();
if (this.rebateItem == null) {
this.rebateItem = new RebateItem();
}
try {
this.rebateItem = ((RebateItem) this.rebateItemService.getModel(this.rebateItem.getId()));
initModel(false, this.rebateItem, loginMan);
} catch (Exception e) {
logger.error("error occur when list rebateItem", e);
}
return "show_rebateItem";
}
public void save() {
logger.info("start to update rebateItem information");
try {
if (this.rebateItem == null) {
this.rebateItem = new RebateItem();
}
if (StringUtils.isBlank(this.rebateItem.getId())) {
String id = this.rebateItemService.makeId();
this.rebateItem.setId(id);
this.rebateItemService.insert(this.rebateItem);
} else {
this.rebateItemService.update(this.rebateItem);
}
responseFlag(true);
} catch (Exception e) {
logger.info("error occur when save rebateItem information", e);
e.printStackTrace();
responseFlag(false);
}
}
public void delete() {
SysUser loginMan = getSessionUserInfo();
try {
if (this.rebateItem == null) {
this.rebateItem = new RebateItem();
}
this.rebateItemService.delete(this.rebateItem.getId());
logger.info(loginMan.getCode() + "delete rebateItem,id:" + this.rebateItem.getId());
responseFlag(true);
} catch (Exception e) {
responseFlag(false);
logger.info("error occur when delete a supplier", e);
}
}
public Rebate getRebate() {
return this.rebate;
}
public void setRebate(Rebate rebate) {
this.rebate = rebate;
}
public Supplier getSupplier() {
return this.supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
public RebateItem getRebateItem() {
return this.rebateItem;
}
public void setRebateItem(RebateItem rebateItem) {
this.rebateItem = rebateItem;
}
public RebateItemService getRebateItemService() {
return this.rebateItemService;
}
public void setRebateItemService(RebateItemService rebateItemService) {
this.rebateItemService = rebateItemService;
}
}
| gpl-2.0 |
thalespf/demos-alura | demo-designpatterns/src/com/thalespf/demos/dp/examples/state/orcamento/EstadoAprovado.java | 859 | /**
*
*/
package com.thalespf.demos.dp.examples.state.orcamento;
import com.thalespf.demos.dp.domain.Orcamento;
/**
* @author Thales Ferreira / l.thales.x@gmail.com
*
*/
public class EstadoAprovado implements EstadoDoOrcamento {
private boolean aplicado;
@Override
public boolean foiAplicado() {
return aplicado;
}
@Override
public void aplicaDescontoExtra(Orcamento orcamento) {
orcamento.setValor(orcamento.getValor() - (orcamento.getValor() * 0.02));
aplicado = true;
}
@Override
public void aprova(Orcamento orcamento) {
throw new RuntimeException("Orcamento ja esta aprovado");
}
@Override
public void reprovado(Orcamento orcamento) {
throw new RuntimeException("Orcamento nao pode ser reprovado.");
}
@Override
public void finaliza(Orcamento orcamento) {
orcamento.setEstadoAtual(new EstadoFinalizado());
}
}
| gpl-2.0 |
specify/specify6 | src/edu/ku/brc/specify/tests/PreferenceTest.java | 12764 | /* Copyright (C) 2022, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.specify.tests;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import junit.framework.TestCase;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.log4j.Logger;
import edu.ku.brc.af.auth.UserAndMasterPasswordMgr;
import edu.ku.brc.af.prefs.AppPreferences;
import edu.ku.brc.af.prefs.AppPrefsCache;
import edu.ku.brc.dbsupport.DBConnection;
import edu.ku.brc.dbsupport.HibernateUtil;
import edu.ku.brc.ui.ColorWrapper;
import edu.ku.brc.ui.UIHelper;
import edu.ku.brc.ui.UIRegistry;
import edu.ku.brc.util.Pair;
/**
* Tests the AppPreferences and AppPreferences cache
*
* @code_status Unknown (auto-generated)
*
* @author rods
*
*/
public class PreferenceTest extends TestCase
{
private static final Logger log = Logger.getLogger(PreferenceTest.class);
private static final String databaseName = "fish";
protected AppPreferences appPrefs = null;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp()
{
//-----------------------------------------------------
// This is needed for loading views
//-----------------------------------------------------
UIRegistry.getInstance(); // initializes it first thing
if (UIRegistry.getAppName() == null) // this is needed because the setUp gets run separately for each test
{
System.setProperty("edu.ku.brc.af.core.AppContextMgrFactory", "edu.ku.brc.specify.config.SpecifyAppContextMgr");
System.setProperty("AppPrefsIOClassName", "edu.ku.brc.specify.config.AppPrefsDBIOIImpl");
UIRegistry.getInstance(); // initializes it first thing
UIRegistry.setAppName("Specify");
// Load Local Prefs
AppPreferences localPrefs = AppPreferences.getLocalPrefs();
localPrefs.setDirPath(UIRegistry.getAppDataDir());
localPrefs.load();
Pair<String, String> usernamePassword = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
String hostName = "localhost";
// This will log us in and return true/false
if (!UIHelper.tryLogin("com.mysql.jdbc.Driver",
"org.hibernate.dialect.MySQLDialect",
databaseName,
"jdbc:mysql://"+hostName+"/"+databaseName,
usernamePassword.first,
usernamePassword.second))
{
throw new RuntimeException("Couldn't login into ["+databaseName+"] "+DBConnection.getInstance().getErrorMsg());
}
HibernateUtil.getCurrentSession();
AppPreferences.getRemote().load(); // Loads prefs from the database
}
}
public void testLocalPrefs()
{
AppPreferences localPrefs = AppPreferences.getLocalPrefs();
localPrefs.put("test", "test");
try
{
localPrefs.flush();
} catch (Exception ex)
{
assertTrue(false);
}
String test = localPrefs.get("test", null);
assertNotNull(test);
assertTrue(test.equals("test"));
}
/**
* Upadtes a preference value and calls flush to make sure the listeners get notified
* @param section the section
* @param pref the preference node name
* @param attr the actual preference attribute name
* @param value the new value
*/
protected void updatePref(final String section, final String pref, final String attr, final String value)
{
AppPreferences.getRemote().put(section+"."+pref+"."+attr, value);
//try {
// AppPreferences.getInstance().flush();
//} catch (BackingStoreException ex) {}
}
/**
* Tests the Date formating
*/
public void testStrings()
{
AppPreferences appPrefsMgr = AppPreferences.getRemote();
appPrefsMgr.put("text.ui.str", "string value");
appPrefsMgr.put("text.ui.formatting.str", "string value");
appPrefsMgr.put("text.ui.formatting.xxx.str", "string value");
String[] keys = appPrefsMgr.keys("text.ui");
log.info("Keys:");
for (String s : keys)
{
log.info(s);
}
assert(keys.length != 1);
String[] names = appPrefsMgr.childrenNames("text.ui");
log.info("Child Names:");
for (String s : names)
{
log.info(s);
}
assert(names.length != 1);
try
{
appPrefsMgr.flush();
} catch (Exception ex)
{
assert(false);
}
}
/**
* Tests the Date formating
*/
public void testSimpleDateFormat()
{
FastDateFormat fastDateFormat = FastDateFormat.getDateInstance(FastDateFormat.SHORT);
SimpleDateFormat df = new SimpleDateFormat(fastDateFormat.getPattern());
log.info(df.toPattern());
log.info(df.format(new Date()));
fastDateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM);
df = new SimpleDateFormat(fastDateFormat.getPattern());
log.info(df.toPattern());
log.info(df.format(new Date()));
fastDateFormat = FastDateFormat.getDateInstance(FastDateFormat.LONG);
df = new SimpleDateFormat(fastDateFormat.getPattern());
log.info(df.toPattern());
log.info(df.format(new Date()));
}
/**
* Tests the Date formating
*/
@SuppressWarnings("unused")
public void testColorWrapper()
{
try
{
ColorWrapper cw = new ColorWrapper("xx, 1, 1");
assertFalse(false);
} catch (RuntimeException re)
{
assertTrue(true);
}
try
{
ColorWrapper cw = new ColorWrapper("1, 1");
assertFalse(false);
} catch (RuntimeException re)
{
assertTrue(true);
}
try
{
ColorWrapper cw = new ColorWrapper("");
assertFalse(false);
} catch (RuntimeException re)
{
assertTrue(true);
}
try
{
ColorWrapper cw = new ColorWrapper((String)null);
assertFalse(false);
} catch (RuntimeException re)
{
assertTrue(true);
}
try
{
ColorWrapper cw = new ColorWrapper((Color)null);
assertFalse(false);
} catch (RuntimeException re)
{
assertTrue(true);
}
ColorWrapper cw = new ColorWrapper("128, 255, 32");
log.info(cw+" "+cw.getColor().toString());
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper(128, 255, 32);
log.info(cw+" "+cw.getColor().toString());
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper(128, 999, 32);
log.info(cw+" "+cw.getColor().toString());
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper("128,255,32");
log.info(cw+" "+cw.getColor().toString());
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper("0,0,0");
log.info(cw+" "+cw.getColor().toString());
cw.setRGB(128, 999, 32);
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper("0,0,0");
log.info(cw+" "+cw.getColor().toString());
cw.setRGB("128,255,32");
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper(new Color(128, 255, 32));
log.info(cw+" "+cw.getColor().toString());
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
cw = new ColorWrapper(new Color(0, 0, 0));
log.info(cw+" "+cw.getColor().toString());
cw.setColor(new Color(128, 255, 32));
assertTrue(cw.getColor().getRed() == 128 && cw.getColor().getGreen() == 255 && cw.getColor().getBlue() == 32);
}
/**
* Tests the Date formating
*/
public void testDateFormatCache()
{
SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy");
Date date = Calendar.getInstance().getTime();
AppPrefsCache.register(format, "ui", "formatting", "dateTest");
String newFormat = "yyyy/MM/DD";
AppPreferences.getRemote().put("ui.formatting.dateTest", newFormat);
//try {
// AppPreferences.getInstance().flush();
//} catch (BackingStoreException ex) {}
log.info("New Date Format: "+format.toPattern());
log.info(format.format(date));
log.info("Actual pref value["+AppPrefsCache.getValue("ui", "formatting", "dateTest")+"]");
log.info("newFormat["+newFormat+"]");
assertTrue(AppPrefsCache.getValue("ui", "formatting", "dateTest").equals(newFormat));
assertTrue(format.toPattern().equals(newFormat));
}
/**
* Tests the Color
*/
public void testColorWrapperCache()
{
String attrName = "valErrColorTest";
ColorWrapper colorWrapper = new ColorWrapper("255, 128, 64");
Color oldColor = new Color(255, 128, 64);
assertTrue(oldColor.toString().equals(colorWrapper.getColor().toString()));
AppPrefsCache.register(colorWrapper, "ui", "formatting", attrName);
String newColorStr = "64, 255, 128";
//Color newColor = new Color(64, 255, 128);
AppPreferences.getRemote().put("ui.formatting."+attrName, newColorStr);
//try {
// AppPreferences.getInstance().flush();
//} catch (BackingStoreException ex) {}
log.info("New Color: "+ colorWrapper.toString()+" ["+newColorStr+"]");
assertTrue(AppPrefsCache.getValue("ui", "formatting", attrName).equals(newColorStr));
assertTrue(colorWrapper.toString().equals(newColorStr));
}
/**
* Tests a simple set (register) and then gets the value
*/
public void testPrefSetGet()
{
String rgb = "255, 0, 0";
AppPrefsCache.register("ui", "formatting", "testColor", rgb);
assertTrue(AppPrefsCache.getValue("ui", "formatting", "testColor").equals(rgb));
}
/**
* Tests registering a value, then updates it external, then gets it
*/
public void testPrefSetUpdateGet()
{
String rgb = "255, 0, 0";
String newRGB = "255, 255, 255";
AppPrefsCache.register("ui", "formatting", "testColor", rgb);
updatePref("ui", "formatting", "testColor", newRGB);
log.info("New RGB: "+AppPrefsCache.getValue("ui", "formatting", "testColor"));
log.info("newRGB: "+newRGB);
assertTrue(AppPrefsCache.getValue("ui", "formatting", "testColor").equals(newRGB));
}
/**
* The best verification is to go check the actual prefs file
*/
public void testRemovePrefs()
{
assertTrue(AppPrefsCache.remove("ui", "formatting", "testColor"));
assertTrue(AppPrefsCache.remove("ui", "formatting", "dateTest"));
assertTrue(AppPrefsCache.remove("ui", "formatting", "valErrColorTest"));
}
}
| gpl-2.0 |
vinhqdang/COMP107x-Introduction-to-Mobile-Application-Development-using-Android | ChatClientColors/app/src/main/java/hk/ust/cse/comp107x/chatclientcolors/Contacts.java | 2483 | package hk.ust.cse.comp107x.chatclientcolors;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Contacts extends AppCompatActivity implements AdapterView.OnItemClickListener {
Toolbar toolbar;
String[] names;
ListView friendView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
names = getResources().getStringArray(R.array.friends);
// If you are using a ListView widget, then your activity should implement
// the onItemClickListener. Then you should set the OnItemClickListener for
// teh ListView.
friendView = (ListView) findViewById(R.id.friendListView);
friendView.setAdapter(new ArrayAdapter<String>(this, R.layout.friend_item, names));
friendView.setOnItemClickListener(this);
toolbar = (Toolbar) findViewById(R.id.tool_bar_contacts); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar); // Setting toolbar as the ActionBar with setSupportActionBar() call
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent mIntent = new Intent(this,ChatClient.class);
mIntent.putExtra(getString(R.string.friend), names[position]);
startActivity(mIntent);
}
@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_contacts, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| gpl-2.0 |
saasrobotics/5619 | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/teleop/MecanumDrivingTest.java | 1357 | package org.firstinspires.ftc.teamcode.teleop;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.teamcode.utilities.Chassis;
import java.text.DecimalFormat;
/**
* Created by Eric Golde on 9/26/2017.
*/
@TeleOp(name = "Mecanum Driving Test", group = "testing")
public class MecanumDrivingTest extends OpMode {
private Chassis chassis = new Chassis(this);
private DecimalFormat df = new DecimalFormat("#.##");
@Override
public void init(){
chassis.init();
}
@Override
public void loop(){
double rotation = Math.hypot(gamepad1.left_stick_x, gamepad1.left_stick_y);
double robotAngle = Math.atan2(gamepad1.left_stick_x, gamepad1.left_stick_y);
double rightX = gamepad1.right_stick_x;
double fl = rotation * Math.cos(robotAngle) + rightX;
double fr = rotation * Math.sin(robotAngle) - rightX;
double bl = rotation * Math.sin(robotAngle) + rightX;
double br = rotation * Math.cos(robotAngle) - rightX;
chassis.frontLeft.setPower(fl);
chassis.frontRight.setPower(fr);
chassis.backLeft.setPower(bl);
chassis.backRight.setPower(br);
telemetry.addData("FL: ", df.format(fl));
telemetry.addData("FR: ", df.format(fr));
telemetry.addData("BL: ", df.format(bl));
telemetry.addData("BR: ", df.format(br));
chassis.loop();
}
}
| gpl-2.0 |
BuddhaLabs/DeD-OSX | soot/soot-2.3.0/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/attributes/VisManLauncher.java | 6246 | /* Soot - a J*va Optimization Framework
* Copyright (C) 2004 Jennifer Lhotak
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package ca.mcgill.sable.soot.attributes;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.*;
import org.eclipse.ui.*;
import ca.mcgill.sable.soot.*;
import ca.mcgill.sable.soot.ui.*;
import java.util.*;
import org.eclipse.core.resources.*;
import org.eclipse.jdt.core.*;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.dialogs.*;
public class VisManLauncher implements IWorkbenchWindowActionDelegate {
private IProject proj;
private IResource rec;
public VisManLauncher() {
super();
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
*/
public void dispose() {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
*/
public void init(IWorkbenchWindow window) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
IWorkbenchWindow window = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
AnalysisVisManipDialog dialog = new AnalysisVisManipDialog(window.getShell());
dialog.setFileList(getFilesFromCon(getProj()));
dialog.setProj(getProj());
dialog.open();
if (dialog.getReturnCode() == Dialog.OK){
if (dialog.getAllSelected() != null){
Iterator selIt = dialog.getAllSelected().iterator();
while (selIt.hasNext()){
Object next = selIt.next();
SootAttributesHandler handler = SootPlugin.getDefault().getManager().getAttributesHandlerForFile((IFile)next);
Object [] elems;
if ((dialog.getCurrentSettingsMap() != null) && (dialog.getCurrentSettingsMap().containsKey(next))){
elems = (Object [])dialog.getCurrentSettingsMap().get(next);
}
else {
elems = dialog.getCheckTypes().getCheckedElements();
}
ArrayList toShow = new ArrayList();
for (int i = 0; i < elems.length; i++){
toShow.add(elems[i]);
}
handler.setTypesToShow(toShow);
handler.setShowAllTypes(false);
// also update currently shown editor and legend
handler.setUpdate(true);
final IEditorPart activeEdPart = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
SootPlugin.getDefault().getPartManager().updatePart(activeEdPart);
}
}
}
}
public HashMap configureDataMap(){
HashMap map = new HashMap();
// get all .java and .jimple files in the project
// for each determine if attr xml exist and if yes which
// kinds of attrs there are
ArrayList files = getFilesFromCon(getProj());
Iterator it = files.iterator();
while (it.hasNext()){
IFile next = (IFile)it.next();
SootAttributesHandler handler;
if (next.getFileExtension().equals("java")){
JavaAttributesComputer jac = new JavaAttributesComputer();
jac.setProj(getProj());
jac.setRec(getRec());
handler = jac.getAttributesHandler(next);
}
else {
JimpleAttributesComputer jac = new JimpleAttributesComputer();
jac.setProj(getProj());
jac.setRec(getRec());
handler = jac.getAttributesHandler(next);
}
if ((handler != null) && (handler.getAttrList() != null)){
Iterator attrsIt = handler.getAttrList().iterator();
ArrayList types = new ArrayList();
while (attrsIt.hasNext()){
SootAttribute sa = (SootAttribute)attrsIt.next();
Iterator typesIt = sa.getAnalysisTypes().iterator();
while (typesIt.hasNext()){
String val = (String)typesIt.next();
if (!types.contains(val)){
types.add(val);
}
}
}
map.put(next, types);
}
else {
map.put(next, null);
}
}
return map;
}
public ArrayList getFilesFromCon(IContainer con){
ArrayList files = new ArrayList();
try {
IResource [] recs = con.members();
for (int i = 0; i < recs.length; i++){
if (recs[i] instanceof IFile){
IFile file = (IFile)recs[i];
if (file.getFileExtension() == null) continue;
if (file.getFileExtension().equals("jimple") || file.getFileExtension().equals("java")){
files.add(recs[i]);
}
}
else if (recs[i] instanceof IContainer){
files.addAll(getFilesFromCon((IContainer)recs[i]));
}
else {
throw new RuntimeException("unknown member type");
}
}
}
catch(CoreException e){
}
return files;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
if (selection instanceof IStructuredSelection){
IStructuredSelection struct = (IStructuredSelection)selection;
Iterator it = struct.iterator();
while (it.hasNext()){
Object next = it.next();
if (next instanceof IResource) {
setProj(((IResource)next).getProject());
setRec((IResource)next);
}
else if (next instanceof IJavaElement) {
IJavaElement jElem = (IJavaElement)next;
setProj(jElem.getJavaProject().getProject());
setRec(jElem.getResource());
}
}
}
}
/**
* @return
*/
public IProject getProj() {
return proj;
}
/**
* @param project
*/
public void setProj(IProject project) {
proj = project;
}
/**
* @return
*/
public IResource getRec() {
return rec;
}
/**
* @param resource
*/
public void setRec(IResource resource) {
rec = resource;
}
}
| gpl-2.0 |
jianghouwei/SunnyDay | common/common-memcached/src/main/java/com/sun/memcached/service/impl/SpyTwoUserServiceImpl.java | 892 | package com.sun.memcached.service.impl;
import net.spy.memcached.MemcachedClient;
import org.springframework.stereotype.Service;
import com.sun.memcached.model.User;
import com.sun.memcached.service.SpyTwoUserService;
@Service
public class SpyTwoUserServiceImpl implements SpyTwoUserService {
private MemcachedClient twomcacheClient;
public void saveUser(User user) {
twomcacheClient.add(user.getUserId(), 3600, user);
}
public User getById(String userId) {
return (User) twomcacheClient.get(userId);
}
public void updateUser(User user) {
twomcacheClient.replace(user.getUserId(), 3600, user);
}
public void deleteUser(String userId) {
twomcacheClient.delete(userId);
}
public MemcachedClient getTwomcacheClient() {
return twomcacheClient;
}
public void setTwomcacheClient(MemcachedClient twomcacheClient) {
this.twomcacheClient = twomcacheClient;
}
}
| gpl-2.0 |
carvalhomb/tsmells | sample/argouml/argouml/org/argouml/uml/ui/behavior/collaborations/UMLMessageInteractionListModel.java | 2660 | // $Id: UMLMessageInteractionListModel.java 7646 2005-01-30 20:48:48Z linus $
// Copyright (c) 1996-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.behavior.collaborations;
import org.argouml.model.Model;
import org.argouml.uml.ui.UMLModelElementListModel2;
/**
*
* @author jaap.branderhorst@xs4all.nl
* @since Jan 25, 2003
*/
public class UMLMessageInteractionListModel extends UMLModelElementListModel2 {
/**
* Constructor for UMLMessageInteractionListModel.
*/
public UMLMessageInteractionListModel() {
super("interaction");
}
/**
* @see org.argouml.uml.ui.UMLModelElementListModel2#buildModelList()
*/
protected void buildModelList() {
if (Model.getFacade().isAMessage(getTarget())) {
removeAllElements();
addElement(Model.getFacade().getInteraction(getTarget()));
}
}
/**
* @see org.argouml.uml.ui.UMLModelElementListModel2#isValidElement(Object)
*/
protected boolean isValidElement(Object/*MBase*/ element) {
return Model.getFacade().isAInteraction(element)
&& Model.getFacade().getInteraction(getTarget()) == element;
}
}
| gpl-2.0 |
BlackKitten/MineSweeperBot | Brain/src/controller/NNHandler_MineSolverV3.java | 501 | package controller;
import org.neuroph.nnet.MultiLayerPerceptron;
import org.neuroph.nnet.learning.DynamicBackPropagation;
public class NNHandler_MineSolverV3 extends NNHandler_MineSolverV2 {
@Override
protected MultiLayerPerceptron createNN() {
MultiLayerPerceptron nn= new MultiLayerPerceptron(25,100,100,1);
DynamicBackPropagation rule=new DynamicBackPropagation();
rule.setMaxIterations(10000);
rule.setMaxError(0.01);
nn.setLearningRule(rule);
return nn;
}
}
| gpl-2.0 |
otmarjr/jtreg-fork | src/share/test/javatest/regtest/data/javac/JavacTest.java | 1454 | /*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*/
import java.io.*;
import com.sun.source.tree.*;
public class JavacTest {
public static void main(String... args) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
int rc = com.sun.tools.javac.Main.compile(args, pw);
pw.close();
System.err.println("rc: " + rc);
System.err.println(sw.toString());
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04281.java | 2523 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest04281")
public class BenchmarkTest04281 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> names = request.getParameterNames();
if (names.hasMoreElements()) {
param = names.nextElement(); // just grab first element
}
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(2);
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bobs_your_uncle";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bobs_your_uncle";
break;
}
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing hash - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
}
}
| gpl-2.0 |
christianfriedl/Vality | src/vality/type/BooleanType.java | 65 | package vality.type;
public class BooleanType extends Type {
}
| gpl-2.0 |
zxbin2000/zhoubangbang | zhoubian_android/src/com/zhixinzhoubian/net/UrlResources.java | 709 | package com.zhixinzhoubian.net;
public final class UrlResources{
//public static final String BASE_URL = "http://zhoubangbang.duapp.com/";
public static final String BASE_URL = "http://172.21.210.18:8090/";
//public static final String ACTION_POI_QUERY = "poiQuery";
public static final String ACTION_SAVE_USER = "submit";
public static final String ACTION_PUB_POI = "postMessage";
public static final String ACTION_SUB_INTST = "subscibe";
public static final String ACTION_SEARCH_POI = "poiSearch";
public static final String ACTION_SEND_FEEDBACK = "reply/reply";
public static final String ACTION_GET_FEEDBACKS = "reply/getList";
public static final String ACTION_GET_POI_MSG = "msgQuery";
} | gpl-2.0 |
bdaum/zoraPD | com.bdaum.zoom.css/src/org/akrogen/tkui/css/core/dom/properties/converters/ICSSValueConverterColorConfig.java | 1359 | /*******************************************************************************
* Copyright (c) 2008, Original authors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo ZERR <angelo.zerr@gmail.com>
*******************************************************************************/
package org.akrogen.tkui.css.core.dom.properties.converters;
import org.w3c.dom.css.RGBColor;
/**
* {@link ICSSValueConverterConfig} to manage format String of the
* {@link RGBColor}.
*
* @version 1.0.0
* @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
*
*/
public interface ICSSValueConverterColorConfig extends ICSSValueConverterConfig {
/*
* Format CSSValue string color into Hexadecimal.
*/
public static final int COLOR_HEXA_FORMAT = 0;
/*
* Format CSSValue string color into Color Name.
*/
public static final int COLOR_NAME_FORMAT = 1;
/*
* Format CSSValue string color into RGB.
*/
public static final int COLOR_RGB_FORMAT = 2;
/**
* Return format (Hexadecimal color, Color name, RGB color).
*
* @return
*/
public int getFormat();
}
| gpl-2.0 |
aktion-hip/vif | org.hip.vif.core.test/src/org/hip/vif/core/bom/impl/JoinParticipantToMemberHomeTest.java | 13432 | package org.hip.vif.core.bom.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import org.hip.kernel.bom.KeyObject;
import org.hip.kernel.bom.KeyObject.BinaryBooleanOperator;
import org.hip.kernel.bom.impl.KeyObjectImpl;
import org.hip.kernel.exc.VException;
import org.hip.vif.core.DataHouseKeeper;
import org.hip.vif.core.IndexHouseKeeper;
import org.hip.vif.core.bom.BOMHelper;
import org.hip.vif.core.bom.JoinParticipantToMemberHome;
import org.hip.vif.core.bom.MemberHome;
import org.hip.vif.core.bom.Participant;
import org.hip.vif.core.bom.ParticipantHome;
import org.hip.vif.core.bom.QuestionAuthorReviewerHome;
import org.hip.vif.core.bom.VIFMember;
import org.hip.vif.core.exc.NoReviewerException;
import org.hip.vif.core.interfaces.IReviewable;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/** Created on 14.08.2003
*
* @author Luthiger */
public class JoinParticipantToMemberHomeTest {
private static DataHouseKeeper data;
@SuppressWarnings("serial")
private class JoinParticipantToMemberHomeSub extends JoinParticipantToMemberHome {
@Override
public Vector<Object> createTestObjects() {
final Vector<Object> outTest = new Vector<Object>();
try {
final KeyObject lKey = new KeyObjectImpl();
lKey.setValue(ParticipantHome.KEY_GROUP_ID, new Integer(32));
outTest.add(createSelectString(lKey));
} catch (final VException exc) {
fail(exc.getMessage());
}
return outTest;
}
@Override
public VIFMember randomIteration(final KeyObject inKey, final int inNumberOfParticipants,
final Long inAuthorID, final Collection<IReviewable> inContributions, final Long inGroupID)
throws VException, SQLException, NoReviewerException {
return super.randomIteration(inKey, inNumberOfParticipants, inAuthorID, inContributions, inGroupID);
}
}
@BeforeClass
public static void init() {
data = DataHouseKeeper.getInstance();
}
@Before
public void setUp() throws Exception {
IndexHouseKeeper.redirectDocRoot(true);
}
@After
public void tearDown() throws Exception {
data.deleteAllInAll();
IndexHouseKeeper.deleteTestIndexDir();
}
@Test
public void testObjects() {
String lExpected = "";
if (data.isDBMySQL()) {
lExpected = "SELECT tblParticipant.GROUPID, tblParticipant.DTSUSPENDFROM, tblParticipant.DTSUSPENDTO, tblMember.MEMBERID, tblMember.SUSERID, tblMember.SNAME, tblMember.SFIRSTNAME, tblMember.SMAIL, tblMember.BSEX FROM tblParticipant INNER JOIN tblMember ON tblParticipant.MEMBERID = tblMember.MEMBERID WHERE tblParticipant.GROUPID = 32";
}
else if (data.isDBOracle()) {
lExpected = "";
}
final JoinParticipantToMemberHome lSubHome = new JoinParticipantToMemberHomeSub();
final Iterator<Object> lTest = lSubHome.getTestObjects();
assertEquals("test object", lExpected, lTest.next());
}
@Test
public void testSelectActive() throws Exception {
int lCount = data.getGroupHome().getCount();
final Long[] lGroupIDs = data.create2Groups();
assertEquals("count 1", lCount + 2, data.getGroupHome().getCount());
lCount = data.getMemberHome().getCount();
final String lMemberID1 = data.createMember("1");
final String lMemberID2 = data.createMember("2");
final String lMemberID3 = data.createMember("3");
final String lMemberID4 = data.createMember("4");
final String lMemberID5 = data.createMember("5");
assertEquals("count 2", lCount + 5, data.getMemberHome().getCount());
final ParticipantHome lHome = data.getParticipantHome();
lCount = lHome.getCount();
lHome.create(lMemberID1, lGroupIDs[0].toString());
lHome.create(lMemberID2, lGroupIDs[0].toString());
lHome.create(lMemberID3, lGroupIDs[0].toString());
lHome.create(lMemberID4, lGroupIDs[0].toString());
lHome.create(lMemberID3, lGroupIDs[1].toString());
lHome.create(lMemberID4, lGroupIDs[1].toString());
lHome.create(lMemberID5, lGroupIDs[1].toString());
assertEquals("count 3", lCount + 7, data.getParticipantHome().getCount());
String[] lExpected = new String[] { lMemberID1, lMemberID2, lMemberID3, lMemberID4 };
data.checkQueryResult(lExpected, data.getJoinParticipantToMemberHome().selectActive(new Long(lGroupIDs[0])),
MemberHome.KEY_ID, "group 1");
lExpected = new String[] { lMemberID3, lMemberID4, lMemberID5 };
data.checkQueryResult(lExpected, data.getJoinParticipantToMemberHome().selectActive(new Long(lGroupIDs[1])),
MemberHome.KEY_ID, "group 2");
final Timestamp lFrom = new Timestamp(System.currentTimeMillis() - 100000000);
final Timestamp lTo = new Timestamp(System.currentTimeMillis() + 100000000);
final KeyObject lKey = new KeyObjectImpl();
lKey.setValue(ParticipantHome.KEY_MEMBER_ID, new Integer(lMemberID5));
lKey.setValue(ParticipantHome.KEY_GROUP_ID, lGroupIDs[1]);
((Participant) data.getParticipantHome().findByKey(lKey)).suspend(lFrom, lTo);
lExpected = new String[] { lMemberID3, lMemberID4 };
data.checkQueryResult(lExpected, data.getJoinParticipantToMemberHome().selectActive(new Long(lGroupIDs[1])),
MemberHome.KEY_ID, "suspended in group 2");
}
@Test
public void testGetParticipantsMail() throws Exception {
final String[] lExpected = new String[] { "mail1@test", "mail2@test", "mail3@test", "mail4@test" };
final Long lGroupID = data.createGroup();
final String lMemberID1 = data.createMember("1", lExpected[0]);
final String lMemberID2 = data.createMember("2", lExpected[1]);
final String lMemberID3 = data.createMember("3", lExpected[2]);
final String lMemberID4 = data.createMember("4", lExpected[3]);
final ParticipantHome lHome = data.getParticipantHome();
lHome.create(lMemberID1, lGroupID.toString());
lHome.create(lMemberID2, lGroupID.toString());
lHome.create(lMemberID3, lGroupID.toString());
lHome.create(lMemberID4, lGroupID.toString());
final Collection<String> lMails = data.getJoinParticipantToMemberHome().getParticipantsMail(new Long(lGroupID));
assertEquals("number of mails", 4, lMails.size());
for (int i = 0; i < lExpected.length; i++) {
assertTrue("contains " + String.valueOf(i), lMails.contains(lExpected[i]));
}
}
// number of participants < THRESHOLD
@Test
public void testGetRandomParticipant() throws Exception {
final Long lGroupID = data.createGroup();
final String[] lMemberIDs = data.create3Members();
final Long lAuthorID = new Long(lMemberIDs[0]);
final Collection<String> lPotential = new Vector<String>();
lPotential.add(lMemberIDs[1]);
lPotential.add(lMemberIDs[2]);
data.getParticipantHome().create(lMemberIDs[0], lGroupID.toString());
data.getParticipantHome().create(lMemberIDs[1], lGroupID.toString());
data.getParticipantHome().create(lMemberIDs[2], lGroupID.toString());
final JoinParticipantToMemberHome lHome = data.getJoinParticipantToMemberHome();
VIFMember lReviewer;
// note: JoinParticipantToMemberHome.getRandomParticipant() may occasionally throw a false NoReviewerException
// in case of very few participants.
try {
lReviewer = lHome.getRandomParticipant(new Long(lGroupID), lAuthorID, new Vector<IReviewable>());
final String lReviewerID = lReviewer.getMemberID().toString();
assertTrue(lPotential.contains(lReviewerID));
assertFalse(lReviewerID.equals(lMemberIDs[0]));
} catch (final NoReviewerException exc) {
// intentionally left empty
}
// now we set the participants suspend date to provoke a NoReviewerException
final Timestamp lFrom = new Timestamp(System.currentTimeMillis() - 3600000);
final Timestamp lTo = new Timestamp(System.currentTimeMillis() + 3600000);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[1]), lFrom, lTo);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[2]), lFrom, lTo);
try {
lHome.getRandomParticipant(new Long(lGroupID), lAuthorID, new Vector<IReviewable>());
fail("shouldn't get here");
} catch (final NoReviewerException exc) {
// intentionally left empty
}
// test with reviewers that refused
final Timestamp lZero = new Timestamp(1000);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[1]), lZero, lZero);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[2]), lZero, lZero);
// contribution a member refused to review
final Collection<IReviewable> lContributions = new Vector<IReviewable>();
lContributions.add(createContribution(new Long(lMemberIDs[2])));
try {
lReviewer = lHome.getRandomParticipant(new Long(lGroupID), lAuthorID, lContributions);
assertEquals(lMemberIDs[1], lReviewer.getMemberID().toString());
} catch (final NoReviewerException exc) {
// intentionally left empty
}
}
// number of participants > THRESHOLD
@Test
public void testGetRandomParticipant2() throws Exception {
final Long lGroupID = data.createGroup();
final String[] lMemberIDs = data.create3Members();
final Long lAuthorID = new Long(lMemberIDs[0]);
final Collection<String> lPotential = new Vector<String>();
lPotential.add(lMemberIDs[1]);
lPotential.add(lMemberIDs[2]);
data.getParticipantHome().create(lMemberIDs[0], lGroupID.toString());
data.getParticipantHome().create(lMemberIDs[1], lGroupID.toString());
data.getParticipantHome().create(lMemberIDs[2], lGroupID.toString());
final KeyObject lKey = new KeyObjectImpl();
lKey.setValue(ParticipantHome.KEY_GROUP_ID, lGroupID);
lKey.setValue(getKeyActive());
final JoinParticipantToMemberHomeSub lHome = new JoinParticipantToMemberHomeSub();
VIFMember lReviewer = lHome.randomIteration(lKey, lHome.getCount(lKey), lAuthorID, new Vector<IReviewable>(),
new Long(lGroupID));
final String lReviewerID = lReviewer.getMemberID().toString();
assertTrue(lPotential.contains(lReviewerID));
assertFalse(lReviewerID.equals(lMemberIDs[0]));
// now we set the participants suspend date to provoke a NoReviewerException
final Timestamp lFrom = new Timestamp(System.currentTimeMillis() - 3600000);
final Timestamp lTo = new Timestamp(System.currentTimeMillis() + 3600000);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[1]), lFrom, lTo);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[2]), lFrom, lTo);
try {
lHome.randomIteration(lKey, lHome.getCount(lKey), lAuthorID, new Vector<IReviewable>(), new Long(lGroupID));
fail("shouldn't get here");
} catch (final NoReviewerException exc) {
// intentionally left empty
}
// test with reviewers that refused
final Timestamp lZero = new Timestamp(1000);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[1]), lZero, lZero);
data.getParticipantHome().suspendParticipation(new Long(lMemberIDs[2]), lZero, lZero);
// contribution a member refused to review
final Collection<IReviewable> lContributions = new Vector<IReviewable>();
lContributions.add(createContribution(new Long(lMemberIDs[2])));
lReviewer = lHome.randomIteration(lKey, lHome.getCount(lKey), lAuthorID, lContributions, new Long(lGroupID));
assertEquals(lMemberIDs[1], lReviewer.getMemberID().toString());
}
private IReviewable createContribution(final Long inReviewerID) throws VException, SQLException {
final Long lContributionID = new Long(data.createQuestion("Test contribution", "1:1"));
final QuestionAuthorReviewerHome lHome = BOMHelper.getQuestionAuthorReviewerHome();
lHome.setReviewer(inReviewerID, lContributionID);
lHome.removeReviewer(inReviewerID, lContributionID);
return (IReviewable) data.getQuestionHome().getQuestion(lContributionID.toString());
}
private KeyObject getKeyActive() throws VException {
final Timestamp lNow = new Timestamp(System.currentTimeMillis());
final KeyObject outKey = new KeyObjectImpl();
outKey.setValue(ParticipantHome.KEY_SUSPEND_FROM, lNow, ">", BinaryBooleanOperator.OR);
outKey.setValue(ParticipantHome.KEY_SUSPEND_TO, lNow, "<", BinaryBooleanOperator.OR);
return outKey;
}
}
| gpl-2.0 |
gspd/iSPD | src/main/java/gspd/ispd/fxgui/workload/dag/editor/TaskEditor.java | 2337 | package gspd.ispd.fxgui.workload.dag.editor;
import gspd.ispd.commons.StringConstants;
import gspd.ispd.fxgui.commons.Icon;
import gspd.ispd.fxgui.commons.IconEditor;
import gspd.ispd.fxgui.workload.dag.icons.TaskIcon;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class TaskEditor extends NodeEditor {
private TextField labelInput;
private TextField mflopInput;
private ComboBox<String> lockInput;
public TaskEditor() {
setTitle(StringConstants.TASK_TITLE);
// LABEL
Label labelLabel = new Label("Label");
labelInput = new TextField("");
labelInput.setPrefWidth(INPUT_WIDTH);
labelInput.textProperty().addListener((obs, n, v) -> {
((TaskIcon)getIcon()).setLabel(labelInput.getText());
});
add(labelLabel, 0, 1);
add(labelInput, 1, 1);
// MFLOP
Label mflopLabel = new Label("MFLOP");
mflopInput = new TextField();
mflopInput.setPrefWidth(INPUT_WIDTH);
mflopInput.textProperty().addListener((obs, o, n) -> {
if (!n.matches("\\d*(\\.\\d*)?")) {
mflopInput.setText(n.replaceAll("[^.\\d]", ""));
}
});
mflopInput.textProperty().addListener((obs, o, n) -> {
((TaskIcon)getIcon()).setComputingSize(Double.parseDouble(mflopInput.getText()));
});
add(mflopLabel, 0, 2);
add(mflopInput, 1, 2);
// LOCK
Label lockLabel = new Label("Lock");
lockInput = new ComboBox<>();
lockInput.setPrefWidth(INPUT_WIDTH);
lockInput.setEditable(true);
lockInput.valueProperty().addListener((obs, o, n) -> {
if (n == null || n.equals("")) {
((TaskIcon)getIcon()).setLock(null);
} else {
((TaskIcon)getIcon()).setLock(n);
}
});
add(lockLabel, 0, 3);
add(lockInput, 1, 3);
}
@Override
protected void setup(Icon icon) {
super.setup(icon);
TaskIcon taskIcon = (TaskIcon) icon;
labelInput.setText(taskIcon.getLabel());
mflopInput.setText(String.valueOf(taskIcon.getComputingSize()));
lockInput.setValue(taskIcon.getLock() == null ? "" : taskIcon.getLock());
}
}
| gpl-2.0 |
m-31/qedeq | QedeqKernelSe/src/org/qedeq/kernel/se/visitor/QedeqVisitor.java | 31685 | /* This file is part of the project "Hilbert II" - http://www.qedeq.org
*
* Copyright 2000-2014, Michael Meyling <mime@qedeq.org>.
*
* "Hilbert II" 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.
*/
package org.qedeq.kernel.se.visitor;
import org.qedeq.kernel.se.base.module.Add;
import org.qedeq.kernel.se.base.module.Author;
import org.qedeq.kernel.se.base.module.AuthorList;
import org.qedeq.kernel.se.base.module.Axiom;
import org.qedeq.kernel.se.base.module.ChangedRule;
import org.qedeq.kernel.se.base.module.ChangedRuleList;
import org.qedeq.kernel.se.base.module.Chapter;
import org.qedeq.kernel.se.base.module.ChapterList;
import org.qedeq.kernel.se.base.module.Conclusion;
import org.qedeq.kernel.se.base.module.ConditionalProof;
import org.qedeq.kernel.se.base.module.Existential;
import org.qedeq.kernel.se.base.module.FormalProof;
import org.qedeq.kernel.se.base.module.FormalProofLine;
import org.qedeq.kernel.se.base.module.FormalProofLineList;
import org.qedeq.kernel.se.base.module.FormalProofList;
import org.qedeq.kernel.se.base.module.Formula;
import org.qedeq.kernel.se.base.module.FunctionDefinition;
import org.qedeq.kernel.se.base.module.Header;
import org.qedeq.kernel.se.base.module.Hypothesis;
import org.qedeq.kernel.se.base.module.Import;
import org.qedeq.kernel.se.base.module.ImportList;
import org.qedeq.kernel.se.base.module.InitialFunctionDefinition;
import org.qedeq.kernel.se.base.module.InitialPredicateDefinition;
import org.qedeq.kernel.se.base.module.Latex;
import org.qedeq.kernel.se.base.module.LatexList;
import org.qedeq.kernel.se.base.module.LinkList;
import org.qedeq.kernel.se.base.module.LiteratureItem;
import org.qedeq.kernel.se.base.module.LiteratureItemList;
import org.qedeq.kernel.se.base.module.Location;
import org.qedeq.kernel.se.base.module.LocationList;
import org.qedeq.kernel.se.base.module.ModusPonens;
import org.qedeq.kernel.se.base.module.Node;
import org.qedeq.kernel.se.base.module.PredicateDefinition;
import org.qedeq.kernel.se.base.module.Proof;
import org.qedeq.kernel.se.base.module.ProofList;
import org.qedeq.kernel.se.base.module.Proposition;
import org.qedeq.kernel.se.base.module.Qedeq;
import org.qedeq.kernel.se.base.module.Reason;
import org.qedeq.kernel.se.base.module.Rename;
import org.qedeq.kernel.se.base.module.Rule;
import org.qedeq.kernel.se.base.module.Section;
import org.qedeq.kernel.se.base.module.SectionList;
import org.qedeq.kernel.se.base.module.Specification;
import org.qedeq.kernel.se.base.module.Subsection;
import org.qedeq.kernel.se.base.module.SubsectionList;
import org.qedeq.kernel.se.base.module.SubsectionType;
import org.qedeq.kernel.se.base.module.SubstFree;
import org.qedeq.kernel.se.base.module.SubstFunc;
import org.qedeq.kernel.se.base.module.SubstPred;
import org.qedeq.kernel.se.base.module.Term;
import org.qedeq.kernel.se.base.module.Universal;
import org.qedeq.kernel.se.base.module.UsedByList;
import org.qedeq.kernel.se.common.ModuleDataException;
/**
* Here are all elements to visit assembled that can be visited within a QEDEQ module.
*
* @author Michael Meyling
*/
public interface QedeqVisitor extends ListVisitor {
/**
* Visit certain element. Begin of visit.
*
* @param author Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Author author) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param authorList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(AuthorList authorList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param axiom Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Axiom axiom) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param chapter Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Chapter chapter) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param chapterList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ChapterList chapterList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param formula Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Formula formula) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param functionDefinition Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(InitialFunctionDefinition functionDefinition) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param functionDefinition Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(FunctionDefinition functionDefinition) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param header Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Header header) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param imp Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Import imp) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param importList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ImportList importList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param latex Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Latex latex) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param latexList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(LatexList latexList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param linkList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(LinkList linkList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param literatureItem Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(LiteratureItem literatureItem) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param literatureItemList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(LiteratureItemList literatureItemList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param location Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Location location) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param locationList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(LocationList locationList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param node Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Node node) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param predicateDefinition Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(InitialPredicateDefinition predicateDefinition) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param predicateDefinition Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(PredicateDefinition predicateDefinition) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proof Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(FormalProof proof) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proofList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(FormalProofList proofList) throws ModuleDataException;
/**
* Visit formal proof line (but not an conditional proof line).
*
* @param proofLine Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(FormalProofLine proofLine) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Reason reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ModusPonens reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Add reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Rename reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SubstFree reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SubstFunc reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SubstPred reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Existential reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Universal reason) throws ModuleDataException;
/**
* Visit conditional proof line.
*
* @param reason Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ConditionalProof reason) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param hypothesis Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Hypothesis hypothesis) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param conclusion Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Conclusion conclusion) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proofLineList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(FormalProofLineList proofLineList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proof Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Proof proof) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proofList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ProofList proofList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param proposition Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Proposition proposition) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param qedeq Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Qedeq qedeq) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param rule Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Rule rule) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param list Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ChangedRuleList list) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param rule Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(ChangedRule rule) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param section Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Section section) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param sectionList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SectionList sectionList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param specification Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Specification specification) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param subsection Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Subsection subsection) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param subsectionList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SubsectionList subsectionList) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param subsectionType Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(SubsectionType subsectionType) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param term Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(Term term) throws ModuleDataException;
/**
* Visit certain element. Begin of visit.
*
* @param usedByList Begin visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitEnter(UsedByList usedByList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param author End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Author author) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param authorList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(AuthorList authorList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param axiom End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Axiom axiom) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param chapter End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Chapter chapter) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param chapterList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ChapterList chapterList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param formula End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Formula formula) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param functionDefinition End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(InitialFunctionDefinition functionDefinition) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param functionDefinition End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(FunctionDefinition functionDefinition) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param header End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Header header) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param imp End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Import imp) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param importList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ImportList importList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param latex End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Latex latex) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param latexList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(LatexList latexList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param linkList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(LinkList linkList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param literatureItem End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(LiteratureItem literatureItem) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param literatureItemList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(LiteratureItemList literatureItemList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param location End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Location location) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param locationList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(LocationList locationList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param node End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Node node) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param predicateDefinition End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(InitialPredicateDefinition predicateDefinition) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param predicateDefinition End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(PredicateDefinition predicateDefinition) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proofList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(FormalProofList proofList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proof End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(FormalProof proof) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proofLine End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(FormalProofLine proofLine) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Reason reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proofLineList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(FormalProofLineList proofLineList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ModusPonens reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Add reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Rename reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SubstFree reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SubstFunc reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SubstPred reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Existential reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Universal reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param reason End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ConditionalProof reason) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param hypothesis End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Hypothesis hypothesis) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param conclusion End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Conclusion conclusion) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proof End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Proof proof) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proofList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ProofList proofList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param proposition End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Proposition proposition) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param qedeq End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Qedeq qedeq) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param rule End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Rule rule) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param list End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ChangedRuleList list) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param rule End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(ChangedRule rule) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param section End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Section section) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param sectionList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SectionList sectionList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param specification End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Specification specification) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param subsection End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Subsection subsection) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param subsectionList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SubsectionList subsectionList) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param subsectionType End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(SubsectionType subsectionType) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param term End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(Term term) throws ModuleDataException;
/**
* Visit certain element. End of visit.
*
* @param usedByList End visit of this element.
* @throws ModuleDataException Major problem occurred.
*/
public void visitLeave(UsedByList usedByList) throws ModuleDataException;
}
| gpl-2.0 |
mikegr/snipsnap | src/org/snipsnap/serialization/rdf/RDFSerializerBase.java | 5465 | package org.snipsnap.serialization.rdf;
import java.util.Properties;
import java.util.Iterator;
import java.util.List;
import com.hp.hpl.mesa.rdf.jena.model.Resource;
import com.hp.hpl.mesa.rdf.jena.model.Model;
import org.snipsnap.snip.Snip;
import org.snipsnap.snip.Links;
import org.snipsnap.snip.SnipLink;
import org.snipsnap.snip.label.Label;
import org.snipsnap.snip.attachment.*;
import org.snipsnap.serialization.Serializer;
import org.snipsnap.serialization.LabelContext;
import java.io.Writer;
import com.hp.hpl.mesa.rdf.jena.model.RDFException;
public abstract class RDFSerializerBase extends Serializer {
RDFSerializerBase(int outputFormat) {
super(outputFormat);
}
// properties for Namespace and RDF output format:
protected String _uriPrefix;
protected String _rdfFormat;
/**
* set the namespace for the generated RDF. If not set, a default URI is used (http://snipsnap.org/rdf/default)
* @param uri the namespace URI to use (must not end with '#' or '/')
*/
public void setURIPrefix(String uri) {
// TODO: use URI checker to test if given URI is valid ...
if (uri.length() > 0 && (uri.endsWith("#") || uri.endsWith("/"))) {
_uriPrefix = uri.substring(0, uri.length() - 1);
}
else
_uriPrefix = uri;
}
/**
* get the associated namespace URI
* @return the URI used in generated RDF
*/
public String getURIPrefix() {
return _uriPrefix;
}
/**
* set the RDF output format for the generated RDF ("RDF/XML", "RDF/XML-ABBREV", "N-TRIPLE", "N3").
* If not set, the default "RDF/XML-ABBREV" is used
* @param format the RDF output format to use
*/
public void setRDFFormat(String format) {
// TODO: use of constant values (?) ...
_rdfFormat = format;
}
/** Hook for subclasses to use a custom LabelContext */
protected LabelContext getLabelContext(Label label, Snip snip, Model model) {
m_labelContext.snip = snip;
m_labelContext.snipResource = getSnipResource(model, snip);
m_labelContext.uriPrefix = _uriPrefix;
m_labelContext.model = model;
m_labelContext.label = label;
return m_labelContext;
}
public void configure(Properties props) {
super.configure(props);
_uriPrefix = m_props.getProperty("uri.prefix", "http://snipsnap.org/rdf/default");
_rdfFormat = m_props.getProperty("rdf.format", "RDF/XML-ABBREV");
}
/**
* serialize the single given Snip to the given Writer
* @param snip the Snip to serialize (perhaps only the "entry point" or "root snip")
* @param writer a Writer to write generated RDF to
*/
public final void serialize(Snip snip, Writer writer) {
serialize(snip, writer, 0); // just one level
}
/**
* recursively serialize the given Snip to the given Writer
* @param snip the Snip to serialize (perhaps only the "entry point" or "root snip")
* @param writer a Writer to write generated RDF to
* @param depth How many levels of snips shall be serialized. Set to -1 if you want to serialize ALL of them.
*/
public final void serialize(Snip startSnip, Writer writer, int depth) {
if (startSnip == null || writer == null) {
throw new RuntimeException("snip and writer must not be null!");
}
try {
Model model = createModel();
recursiveFillModel(startSnip, model, depth);
writeModel(model, writer); // flush the model down the drain
}
catch (RDFException e) {
e.printStackTrace();
}
}
protected abstract Model createModel();
protected abstract void recursiveFillModel(Snip snip, Model model, int depth) throws RDFException;
protected abstract void writeModel(Model model, Writer writer) throws RDFException;
protected final static Iterator getCommentsIterator(Snip snip) {
List comments = snip.getComments().getComments();
if (comments == null) {
return null;
} else {
return comments.iterator();
}
}
protected final static Iterator getLinksIterator(Snip snip) {
Links snipLinks = snip.getSnipLinks();
if (snipLinks == null) {
return null;
} else {
return snipLinks.iterator();
}
}
protected final static Iterator getAttachmentsIterator(Snip snip) {
Attachments attachments = snip.getAttachments();
if (attachments == null) {
return null;
} else {
return attachments.iterator();
}
}
protected Resource getSnipResource(Model model, Snip snip) {
Resource snipResource = null;
try {
snipResource = model.getResource(getSnipResURI(snip));
} catch (Exception e) {
e.printStackTrace();
}
return snipResource;
}
protected String getSnipResURI(Snip snip) {
return _uriPrefix + '#' + snip.getNameEncoded();
}
protected String getAttachmentURL(Attachment att, Snip snip) {
String url = _uriPrefix.substring(0, _uriPrefix.lastIndexOf("/rdf"));
url = url.concat("/space/" + SnipLink.encode(snip.getName()) + "/" + SnipLink.encode(att.getName()));
return url;
}
protected RDFLabelContext m_labelContext = new RDFLabelContext();
}
| gpl-2.0 |
aosm/gcc_40 | libjava/javax/swing/plaf/basic/BasicSplitPaneDivider.java | 24364 | /* BasicSplitPaneDivider.java
Copyright (C) 2003, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.plaf.basic;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JSplitPane;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
/**
* The divider that separates the two parts of a JSplitPane in the Basic look
* and feel.
*
* <p>
* Implementation status: We do not have a real implementation yet. Currently,
* it is mostly a stub to allow compiling other parts of the
* javax.swing.plaf.basic package, although some parts are already
* functional.
* </p>
*
* @author Sascha Brawer (brawer_AT_dandelis.ch)
*/
public class BasicSplitPaneDivider extends Container
implements PropertyChangeListener
{
/**
* Determined using the <code>serialver</code> tool of Apple/Sun JDK 1.3.1
* on MacOS X 10.1.5.
*/
static final long serialVersionUID = 1463404307042803342L;
/**
* The width and height of the little buttons for showing and hiding parts
* of a JSplitPane in a single mouse click.
*/
protected static final int ONE_TOUCH_SIZE = 6;
/** The distance the one touch buttons will sit from the divider's edges. */
protected static final int ONE_TOUCH_OFFSET = 2;
/**
* An object that performs the tasks associated with an ongoing drag
* operation, or <code>null</code> if the user is currently not dragging
* the divider.
*/
protected DragController dragger;
/**
* The delegate object that is responsible for the UI of the
* <code>JSplitPane</code> that contains this divider.
*/
protected BasicSplitPaneUI splitPaneUI;
/** The thickness of the divider in pixels. */
protected int dividerSize;
/** A divider that is used for layout purposes. */
protected Component hiddenDivider;
/** The JSplitPane containing this divider. */
protected JSplitPane splitPane;
/**
* The listener for handling mouse events from both the divider and the
* containing <code>JSplitPane</code>.
*
* <p>
* The reason for also handling MouseEvents from the containing
* <code>JSplitPane</code> is that users should be able to start a drag
* gesture from inside the JSplitPane, but slightly outisde the divider.
* </p>
*/
protected MouseHandler mouseHandler = new MouseHandler();
/**
* The current orientation of the containing <code>JSplitPane</code>, which
* is either {@link javax.swing.JSplitPane#HORIZONTAL_SPLIT} or {@link
* javax.swing.JSplitPane#VERTICAL_SPLIT}.
*/
protected int orientation;
/**
* The button for showing and hiding the left (or top) component of the
* <code>JSplitPane</code>.
*/
protected JButton leftButton;
/**
* The button for showing and hiding the right (or bottom) component of the
* <code>JSplitPane</code>.
*/
protected JButton rightButton;
/**
* The border of this divider. Typically, this will be an instance of {@link
* javax.swing.plaf.basic.BasicBorders.SplitPaneDividerBorder}.
*
* @see #getBorder()
* @see #setBorder(javax.swing.border.Border)
*/
private Border border;
// This is not a pixel count.
// This int should be able to take 3 values.
// left (top), middle, right(bottom)
// 0 1 2
/** Keeps track of where the divider should be placed when using one touch expand
* buttons. */
private transient int currentDividerLocation = 1;
private transient Border tmpBorder = new Border()
{
public Insets getBorderInsets(Component c)
{
return new Insets(2, 2, 2, 2);
}
public boolean isBorderOpaque()
{
return false;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
{
Color saved = g.getColor();
g.setColor(Color.BLACK);
g.drawRect(x + 2, y + 2, width - 4, height - 4);
g.setColor(saved);
}
};
/**
* Constructs a new divider.
*
* @param ui the UI delegate of the enclosing <code>JSplitPane</code>.
*/
public BasicSplitPaneDivider(BasicSplitPaneUI ui)
{
setLayout(new DividerLayout());
setBasicSplitPaneUI(ui);
setDividerSize(splitPane.getDividerSize());
setBorder(tmpBorder);
}
/**
* Sets the delegate object that is responsible for the UI of the {@link
* javax.swing.JSplitPane} containing this divider.
*
* @param newUI the UI delegate, or <code>null</code> to release the
* connection to the current delegate.
*/
public void setBasicSplitPaneUI(BasicSplitPaneUI newUI)
{
/* Remove the connection to the existing JSplitPane. */
if (splitPane != null)
{
splitPane.removePropertyChangeListener(this);
splitPane.removeMouseListener(mouseHandler);
splitPane.removeMouseMotionListener(mouseHandler);
removeMouseListener(mouseHandler);
removeMouseMotionListener(mouseHandler);
splitPane = null;
hiddenDivider = null;
}
/* Establish the connection to the new JSplitPane. */
splitPaneUI = newUI;
if (splitPaneUI != null)
splitPane = newUI.getSplitPane();
if (splitPane != null)
{
splitPane.addPropertyChangeListener(this);
splitPane.addMouseListener(mouseHandler);
splitPane.addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
hiddenDivider = splitPaneUI.getNonContinuousLayoutDivider();
orientation = splitPane.getOrientation();
oneTouchExpandableChanged();
}
}
/**
* Returns the delegate object that is responsible for the UI of the {@link
* javax.swing.JSplitPane} containing this divider.
*
* @return The UI for the JSplitPane.
*/
public BasicSplitPaneUI getBasicSplitPaneUI()
{
return splitPaneUI;
}
/**
* Sets the thickness of the divider.
*
* @param newSize the new width or height in pixels.
*/
public void setDividerSize(int newSize)
{
this.dividerSize = newSize;
}
/**
* Retrieves the thickness of the divider.
*
* @return The thickness of the divider.
*/
public int getDividerSize()
{
return dividerSize;
}
/**
* Sets the border of this divider.
*
* @param border the new border. Typically, this will be an instance of
* {@link
* javax.swing.plaf.basic.BasicBorders.SplitPaneDividerBorder}.
*
* @since 1.3
*/
public void setBorder(Border border)
{
if (border != this.border)
{
Border oldValue = this.border;
this.border = border;
firePropertyChange("border", oldValue, border);
}
}
/**
* Retrieves the border of this divider.
*
* @return the current border, or <code>null</code> if no border has been
* set.
*
* @since 1.3
*/
public Border getBorder()
{
return border;
}
/**
* Retrieves the insets of the divider. If a border has been installed on
* the divider, the result of calling its <code>getBorderInsets</code>
* method is returned. Otherwise, the inherited implementation will be
* invoked.
*
* @see javax.swing.border.Border#getBorderInsets(java.awt.Component)
*/
public Insets getInsets()
{
if (border != null)
return border.getBorderInsets(this);
else
return super.getInsets();
}
/**
* Returns the preferred size of this divider, which is
* <code>dividerSize</code> by <code>dividerSize</code> pixels.
*
* @return The preferred size of the divider.
*/
public Dimension getPreferredSize()
{
return getLayout().preferredLayoutSize(this);
}
/**
* Returns the minimal size of this divider, which is
* <code>dividerSize</code> by <code>dividerSize</code> pixels.
*
* @return The minimal size of the divider.
*/
public Dimension getMinimumSize()
{
return getPreferredSize();
}
/**
* Processes events from the <code>JSplitPane</code> that contains this
* divider.
*
* @param e The PropertyChangeEvent.
*/
public void propertyChange(PropertyChangeEvent e)
{
if (e.getPropertyName().equals(JSplitPane.ONE_TOUCH_EXPANDABLE_PROPERTY))
oneTouchExpandableChanged();
else if (e.getPropertyName().equals(JSplitPane.ORIENTATION_PROPERTY))
{
orientation = splitPane.getOrientation();
if (splitPane.isOneTouchExpandable())
{
layout();
repaint();
}
}
else if (e.getPropertyName().equals(JSplitPane.DIVIDER_SIZE_PROPERTY))
dividerSize = splitPane.getDividerSize();
}
/**
* Paints the divider by painting its border.
*
* @param g The Graphics Object to paint with.
*/
public void paint(Graphics g)
{
Dimension dividerSize;
super.paint(g);
if (border != null)
{
dividerSize = getSize();
border.paintBorder(this, g, 0, 0, dividerSize.width, dividerSize.height);
}
}
/**
* Reacts to changes of the <code>oneToughExpandable</code> property of the
* containing <code>JSplitPane</code>.
*/
protected void oneTouchExpandableChanged()
{
if (splitPane.isOneTouchExpandable())
{
leftButton = createLeftOneTouchButton();
rightButton = createRightOneTouchButton();
add(leftButton);
add(rightButton);
leftButton.addMouseListener(mouseHandler);
rightButton.addMouseListener(mouseHandler);
// Set it to 1.
currentDividerLocation = 1;
}
else
{
if (leftButton != null && rightButton != null)
{
leftButton.removeMouseListener(mouseHandler);
rightButton.removeMouseListener(mouseHandler);
remove(leftButton);
remove(rightButton);
leftButton = null;
rightButton = null;
}
}
layout();
repaint();
}
/**
* Creates a button for showing and hiding the left (or top) part of a
* <code>JSplitPane</code>.
*
* @return The left one touch button.
*/
protected JButton createLeftOneTouchButton()
{
int dir = SwingConstants.WEST;
if (orientation == JSplitPane.VERTICAL_SPLIT)
dir = SwingConstants.NORTH;
JButton button = new BasicArrowButton(dir);
button.setBorderPainted(false);
return button;
}
/**
* Creates a button for showing and hiding the right (or bottom) part of a
* <code>JSplitPane</code>.
*
* @return The right one touch button.
*/
protected JButton createRightOneTouchButton()
{
int dir = SwingConstants.EAST;
if (orientation == JSplitPane.VERTICAL_SPLIT)
dir = SwingConstants.SOUTH;
JButton button = new BasicArrowButton(dir);
button.setBorderPainted(false);
return button;
}
/**
* Prepares the divider for dragging by calling the
* <code>startDragging</code> method of the UI delegate of the enclosing
* <code>JSplitPane</code>.
*
* @see BasicSplitPaneUI#startDragging()
*/
protected void prepareForDragging()
{
if (splitPaneUI != null)
splitPaneUI.startDragging();
}
/**
* Drags the divider to a given location by calling the
* <code>dragDividerTo</code> method of the UI delegate of the enclosing
* <code>JSplitPane</code>.
*
* @param location the new location of the divider.
*
* @see BasicSplitPaneUI#dragDividerTo(int location)
*/
protected void dragDividerTo(int location)
{
if (splitPaneUI != null)
splitPaneUI.dragDividerTo(location);
}
/**
* Finishes a dragging gesture by calling the <code>finishDraggingTo</code>
* method of the UI delegate of the enclosing <code>JSplitPane</code>.
*
* @param location the new, final location of the divider.
*
* @see BasicSplitPaneUI#finishDraggingTo(int location)
*/
protected void finishDraggingTo(int location)
{
if (splitPaneUI != null)
splitPaneUI.finishDraggingTo(location);
}
/**
* This helper method moves the divider to one of the
* three locations when using one touch expand buttons.
* Location 0 is the left (or top) most location.
* Location 1 is the middle.
* Location 2 is the right (or bottom) most location.
*
* @param locationIndex The location to move to.
*/
private void moveDividerTo(int locationIndex)
{
Insets insets = splitPane.getInsets();
switch (locationIndex)
{
case 1:
splitPane.setDividerLocation(splitPane.getLastDividerLocation());
break;
case 0:
int top = (orientation == JSplitPane.HORIZONTAL_SPLIT) ? insets.left
: insets.top;
splitPane.setDividerLocation(top);
break;
case 2:
int bottom;
if (orientation == JSplitPane.HORIZONTAL_SPLIT)
bottom = splitPane.getBounds().width - insets.right - dividerSize;
else
bottom = splitPane.getBounds().height - insets.bottom - dividerSize;
splitPane.setDividerLocation(bottom);
break;
}
}
/**
* The listener for handling mouse events from both the divider and the
* containing <code>JSplitPane</code>.
*
* <p>
* The reason for also handling MouseEvents from the containing
* <code>JSplitPane</code> is that users should be able to start a drag
* gesture from inside the JSplitPane, but slightly outisde the divider.
* </p>
*
* @author Sascha Brawer (brawer_AT_dandelis.ch)
*/
protected class MouseHandler extends MouseAdapter
implements MouseMotionListener
{
/** Keeps track of whether a drag is occurring. */
private transient boolean isDragging;
/**
* This method is called when the mouse is pressed.
*
* @param e The MouseEvent.
*/
public void mousePressed(MouseEvent e)
{
if (splitPane.isOneTouchExpandable())
{
if (e.getSource() == leftButton)
{
currentDividerLocation--;
if (currentDividerLocation < 0)
currentDividerLocation = 0;
moveDividerTo(currentDividerLocation);
return;
}
else if (e.getSource() == rightButton)
{
currentDividerLocation++;
if (currentDividerLocation > 2)
currentDividerLocation = 2;
moveDividerTo(currentDividerLocation);
return;
}
}
isDragging = true;
currentDividerLocation = 1;
if (orientation == JSplitPane.HORIZONTAL_SPLIT)
dragger = new DragController(e);
else
dragger = new VerticalDragController(e);
prepareForDragging();
}
/**
* This method is called when the mouse is released.
*
* @param e The MouseEvent.
*/
public void mouseReleased(MouseEvent e)
{
if (isDragging)
dragger.completeDrag(e);
isDragging = false;
}
/**
* Repeatedly invoked when the user is dragging the mouse cursor while
* having pressed a mouse button.
*
* @param e The MouseEvent.
*/
public void mouseDragged(MouseEvent e)
{
if (dragger != null)
dragger.continueDrag(e);
}
/**
* Repeatedly invoked when the user is dragging the mouse cursor without
* having pressed a mouse button.
*
* @param e The MouseEvent.
*/
public void mouseMoved(MouseEvent e)
{
// Do nothing.
}
}
/**
* Performs the tasks associated with an ongoing drag operation.
*
* @author Sascha Brawer (brawer_AT_dandelis.ch)
*/
protected class DragController
{
/** The difference between where the mouse is clicked and the
* initial divider location. */
transient int offset;
/**
* Creates a new DragController object.
*
* @param e The MouseEvent to initialize with.
*/
protected DragController(MouseEvent e)
{
offset = e.getX();
}
/**
* This method returns true if the divider can move.
*
* @return True if dragging is allowed.
*/
protected boolean isValid()
{
// Views can always be resized?
return true;
}
/**
* Returns a position for the divider given the MouseEvent.
*
* @param e MouseEvent.
*
* @return The position for the divider to move to.
*/
protected int positionForMouseEvent(MouseEvent e)
{
return e.getX() + getX() - offset;
}
/**
* This method returns one of the two paramters
* for the orientation. In this case, it returns x.
*
* @param x The x coordinate.
* @param y The y coordinate.
*
* @return The x coordinate.
*/
protected int getNeededLocation(int x, int y)
{
return x;
}
/**
* This method is called to pass on the drag information
* to the UI through dragDividerTo.
*
* @param newX The x coordinate of the MouseEvent.
* @param newY The y coordinate of the MouseEvent.
*/
protected void continueDrag(int newX, int newY)
{
if (isValid())
dragDividerTo(adjust(newX, newY));
}
/**
* This method is called to pass on the drag information
* to the UI through dragDividerTo.
*
* @param e The MouseEvent.
*/
protected void continueDrag(MouseEvent e)
{
if (isValid())
dragDividerTo(positionForMouseEvent(e));
}
/**
* This method is called to finish the drag session
* by calling finishDraggingTo.
*
* @param x The x coordinate of the MouseEvent.
* @param y The y coordinate of the MouseEvent.
*/
protected void completeDrag(int x, int y)
{
finishDraggingTo(adjust(x, y));
}
/**
* This method is called to finish the drag session
* by calling finishDraggingTo.
*
* @param e The MouseEvent.
*/
protected void completeDrag(MouseEvent e)
{
finishDraggingTo(positionForMouseEvent(e));
}
/**
* This is a helper method that includes the offset
* in the needed location.
*
* @param x The x coordinate of the MouseEvent.
* @param y The y coordinate of the MouseEvent.
*
* @return The needed location adjusted by the offsets.
*/
int adjust(int x, int y)
{
return getNeededLocation(x, y) + getX() - offset;
}
}
/**
* This is a helper class that controls dragging when
* the orientation is VERTICAL_SPLIT.
*/
protected class VerticalDragController extends DragController
{
/**
* Creates a new VerticalDragController object.
*
* @param e The MouseEvent to initialize with.
*/
protected VerticalDragController(MouseEvent e)
{
super(e);
offset = e.getY();
}
/**
* This method returns one of the two parameters given
* the orientation. In this case, it returns y.
*
* @param x The x coordinate of the MouseEvent.
* @param y The y coordinate of the MouseEvent.
*
* @return The y coordinate.
*/
protected int getNeededLocation(int x, int y)
{
return y;
}
/**
* This method returns the new location of the divider
* given a MouseEvent.
*
* @param e The MouseEvent.
*
* @return The new location of the divider.
*/
protected int positionForMouseEvent(MouseEvent e)
{
return e.getY() + getY() - offset;
}
/**
* This is a helper method that includes the offset
* in the needed location.
*
* @param x The x coordinate of the MouseEvent.
* @param y The y coordinate of the MouseEvent.
*
* @return The needed location adjusted by the offsets.
*/
int adjust(int x, int y)
{
return getNeededLocation(x, y) + getY() - offset;
}
}
/**
* This helper class acts as the Layout Manager for
* the divider.
*/
protected class DividerLayout implements LayoutManager
{
/**
* Creates a new DividerLayout object.
*/
protected DividerLayout()
{
}
/**
* This method is called when a Component is added.
*
* @param string The constraints string.
* @param c The Component to add.
*/
public void addLayoutComponent(String string, Component c)
{
// Do nothing.
}
/**
* This method is called to lay out the container.
*
* @param c The container to lay out.
*/
public void layoutContainer(Container c)
{
if (splitPane.isOneTouchExpandable())
{
changeButtonOrientation();
positionButtons();
}
}
/**
* This method returns the minimum layout size.
*
* @param c The container to calculate for.
*
* @return The minimum layout size.
*/
public Dimension minimumLayoutSize(Container c)
{
return preferredLayoutSize(c);
}
/**
* This method returns the preferred layout size.
*
* @param c The container to calculate for.
*
* @return The preferred layout size.
*/
public Dimension preferredLayoutSize(Container c)
{
return new Dimension(dividerSize, dividerSize);
}
/**
* This method is called when a component is removed.
*
* @param c The component to remove.
*/
public void removeLayoutComponent(Component c)
{
// Do nothing.
}
/**
* This method changes the button orientation when
* the orientation of the SplitPane changes.
*/
private void changeButtonOrientation()
{
if (orientation == JSplitPane.HORIZONTAL_SPLIT)
{
((BasicArrowButton) rightButton).setDirection(SwingConstants.EAST);
((BasicArrowButton) leftButton).setDirection(SwingConstants.WEST);
}
else
{
((BasicArrowButton) rightButton).setDirection(SwingConstants.SOUTH);
((BasicArrowButton) leftButton).setDirection(SwingConstants.NORTH);
}
}
/**
* This method sizes and positions the buttons.
*/
private void positionButtons()
{
int w = 0;
int h = 0;
if (orientation == JSplitPane.HORIZONTAL_SPLIT)
{
rightButton.setLocation(ONE_TOUCH_OFFSET, ONE_TOUCH_OFFSET);
leftButton.setLocation(ONE_TOUCH_OFFSET,
ONE_TOUCH_OFFSET + 2 * ONE_TOUCH_SIZE);
w = dividerSize - 2 * ONE_TOUCH_OFFSET;
h = 2 * ONE_TOUCH_SIZE;
}
else
{
leftButton.setLocation(ONE_TOUCH_OFFSET, ONE_TOUCH_OFFSET);
rightButton.setLocation(ONE_TOUCH_OFFSET + 2 * ONE_TOUCH_SIZE,
ONE_TOUCH_OFFSET);
h = dividerSize - 2 * ONE_TOUCH_OFFSET;
w = 2 * ONE_TOUCH_SIZE;
}
Dimension dims = new Dimension(w, h);
leftButton.setSize(dims);
rightButton.setSize(dims);
}
}
}
| gpl-2.0 |
Hatzen/EasyPeasyVPN | src/main/java/de/hartz/vpn/helper/Logger.java | 123 | package de.hartz.vpn.helper;
/**
* Interface to log.
*/
public interface Logger {
void addLogLine(String line);
}
| gpl-2.0 |
SigmaOne/TaskManager-Portlet | src/main/java/elcom/entities/converters/GroupEntityConverter.java | 974 | package elcom.entities.converters;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.bean.RequestScoped;
import javax.faces.convert.Converter;
import javax.faces.bean.ManagedBean;
import elcom.ejbs.DataProvider;
import javax.ejb.EJB;
@ManagedBean
@RequestScoped
public class GroupEntityConverter implements Converter, defaultFilterable {
private String noFilterOption = "-- Все --";
@EJB
DataProvider dp;
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
return (s != null && !isNoFilterOption(s))? dp.getGroupEntityByName(s) : null;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
return (o != null)? o.toString() : null;
}
@Override
public boolean isNoFilterOption(String stringFilter) {
return noFilterOption.equals(stringFilter);
}
}
| gpl-2.0 |
ricardobaumann/android | libs/android_application_2d_adventure_game-master/AndEngineScriptingExtension-GLES2/src/org/andengine/extension/scripting/opengl/texture/TextureProxy.java | 909 | package org.andengine.extension.scripting.opengl.texture;
import org.andengine.opengl.texture.ITextureStateListener;
import org.andengine.opengl.texture.PixelFormat;
import org.andengine.opengl.texture.Texture;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import java.lang.IllegalArgumentException;
public abstract class TextureProxy extends Texture {
private final long mAddress;
public TextureProxy(final long pAddress,
final TextureManager pTextureManager, final PixelFormat pPixelFormat,
final TextureOptions pTextureOptions,
final ITextureStateListener pTextureStateListener)
throws IllegalArgumentException {
super(pTextureManager, pPixelFormat, pTextureOptions,
pTextureStateListener);
this.mAddress = pAddress;
}
public static native void nativeInitClass();
}
| gpl-2.0 |
openjdk/jdk8u | jdk/src/share/classes/javax/crypto/spec/RC5ParameterSpec.java | 7263 | /*
* Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.crypto.spec;
import java.security.spec.AlgorithmParameterSpec;
/**
* This class specifies the parameters used with the
* <a href="http://www.ietf.org/rfc/rfc2040.txt"><i>RC5</i></a>
* algorithm.
*
* <p> The parameters consist of a version number, a rounds count, a word
* size, and optionally an initialization vector (IV) (only in feedback mode).
*
* <p> This class can be used to initialize a {@code Cipher} object that
* implements the <i>RC5</i> algorithm as supplied by
* <a href="http://www.rsasecurity.com">RSA Security Inc.</a>,
* or any parties authorized by RSA Security.
*
* @author Jan Luehe
*
* @since 1.4
*/
public class RC5ParameterSpec implements AlgorithmParameterSpec {
private byte[] iv = null;
private int version;
private int rounds;
private int wordSize; // the word size in bits
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds and word size (in bits).
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
*/
public RC5ParameterSpec(int version, int rounds, int wordSize) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
}
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> Note that the size of the IV (block size) must be twice the word
* size. The bytes that constitute the IV are those between
* {@code iv[0]} and {@code iv[2*(wordSize/8)-1]} inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first {@code 2*(wordSize/8)
* } bytes of the buffer are copied to protect against subsequent
* modification.
* @exception IllegalArgumentException if {@code iv} is
* {@code null} or {@code (iv.length < 2 * (wordSize / 8))}
*/
public RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv) {
this(version, rounds, wordSize, iv, 0);
}
/**
* Constructs a parameter set for RC5 from the given version, number of
* rounds, word size (in bits), and IV.
*
* <p> The IV is taken from {@code iv}, starting at
* {@code offset} inclusive.
* Note that the size of the IV (block size), starting at
* {@code offset} inclusive, must be twice the word size.
* The bytes that constitute the IV are those between
* {@code iv[offset]} and {@code iv[offset+2*(wordSize/8)-1]}
* inclusive.
*
* @param version the version.
* @param rounds the number of rounds.
* @param wordSize the word size in bits.
* @param iv the buffer with the IV. The first {@code 2*(wordSize/8)
* } bytes of the buffer beginning at {@code offset}
* inclusive are copied to protect against subsequent modification.
* @param offset the offset in {@code iv} where the IV starts.
* @exception IllegalArgumentException if {@code iv} is
* {@code null} or
* {@code (iv.length - offset < 2 * (wordSize / 8))}
*/
public RC5ParameterSpec(int version, int rounds, int wordSize,
byte[] iv, int offset) {
this.version = version;
this.rounds = rounds;
this.wordSize = wordSize;
if (iv == null) {
throw new IllegalArgumentException("IV missing");
}
if (offset < 0) {
throw new ArrayIndexOutOfBoundsException("offset is negative");
}
int blockSize = (wordSize / 8) * 2;
if (iv.length - offset < blockSize) {
throw new IllegalArgumentException("IV too short");
}
this.iv = new byte[blockSize];
System.arraycopy(iv, offset, this.iv, 0, blockSize);
}
/**
* Returns the version.
*
* @return the version.
*/
public int getVersion() {
return this.version;
}
/**
* Returns the number of rounds.
*
* @return the number of rounds.
*/
public int getRounds() {
return this.rounds;
}
/**
* Returns the word size in bits.
*
* @return the word size in bits.
*/
public int getWordSize() {
return this.wordSize;
}
/**
* Returns the IV or null if this parameter set does not contain an IV.
*
* @return the IV or null if this parameter set does not contain an IV.
* Returns a new array each time this method is called.
*/
public byte[] getIV() {
return (iv == null? null:iv.clone());
}
/**
* Tests for equality between the specified object and this
* object. Two RC5ParameterSpec objects are considered equal if their
* version numbers, number of rounds, word sizes, and IVs are equal.
* (Two IV references are considered equal if both are {@code null}.)
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false if
* {@code obj} is null or otherwise.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RC5ParameterSpec)) {
return false;
}
RC5ParameterSpec other = (RC5ParameterSpec) obj;
return ((version == other.version) &&
(rounds == other.rounds) &&
(wordSize == other.wordSize) &&
java.util.Arrays.equals(iv, other.iv));
}
/**
* Calculates a hash code value for the object.
* Objects that are equal will also have the same hashcode.
*/
public int hashCode() {
int retval = 0;
if (iv != null) {
for (int i = 1; i < iv.length; i++) {
retval += iv[i] * i;
}
}
retval += (version + rounds + wordSize);
return retval;
}
}
| gpl-2.0 |
indiyskiy/WorldOnline | src/model/phone/requesthandler/CardsForUpdateHandler.java | 1443 | package model.phone.requesthandler;
import controller.phone.entity.CardsForUpdateRequest;
import controller.phone.entity.MobileRequest;
import model.additionalentity.phone.CardUpdateAggregator;
import model.database.requests.UserDataRequest;
import model.exception.IllegalTypeException;
import model.phone.responseentity.CardsForUpdateResponse;
import model.phone.responseentity.MobileResponseEntity;
import javax.servlet.ServletException;
import java.sql.SQLException;
public class CardsForUpdateHandler implements MobileHandler {
public CardsForUpdateResponse handleRequest(CardsForUpdateRequest cardsForUpdateRequest) {
CardUpdateAggregator cardUpdateAggregator = UserDataRequest.getCardUpdateInfo(cardsForUpdateRequest.getUserID());
CardsForUpdateResponse cardsForUpdateResponse = new CardsForUpdateResponse();
cardsForUpdateResponse.setCardUpdateAggregator(cardUpdateAggregator);
return cardsForUpdateResponse;
}
@Override
public MobileResponseEntity handleRequest(MobileRequest mobileRequest) throws IllegalTypeException, ServletException, SQLException {
if (mobileRequest.getClass() != CardsForUpdateRequest.class) {
throw new IllegalTypeException(MobileRequest.class, CardsForUpdateRequest.class);
}
CardsForUpdateRequest cardsForUpdateRequest = (CardsForUpdateRequest) mobileRequest;
return handleRequest(cardsForUpdateRequest);
}
}
| gpl-2.0 |
leocockroach/JasperServer5.6 | jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/common/service/impl/SwapFileVirtualizerFactory.java | 3383 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is 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.jaspersoft.jasperserver.api.engine.common.service.impl;
import net.sf.jasperreports.engine.JRVirtualizer;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRSwapFile;
import net.sf.jasperreports.engine.util.StreamCompression;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: SwapFileVirtualizerFactory.java 47331 2014-07-18 09:13:06Z kklein $
*/
public class SwapFileVirtualizerFactory extends AbstractIndividualVirtualizerFactory {
private static final Log log = LogFactory.getLog(SwapFileVirtualizerFactory.class);
public static final int DEFAULT_MAX_SIZE = 200;
public static final int DEFAULT_BLOCK_SIZE = 4096;
public static final int DEFAULT_MIN_BLOCK_GROW_COUNT = 100;
private int maxSize;
private String tempDirectory;
private int blockSize;
private int minBlockGrowCount;
private StreamCompression compression;
public SwapFileVirtualizerFactory() {
// default values
maxSize = DEFAULT_MAX_SIZE;
tempDirectory = System.getProperty("java.io.tmpdir");
blockSize = DEFAULT_MIN_BLOCK_GROW_COUNT;
minBlockGrowCount = DEFAULT_MIN_BLOCK_GROW_COUNT;
}
public JRVirtualizer getVirtualizer() {
JRSwapFile swapFile = getSwapFile();
JRSwapFileVirtualizer virtualizer = new JRSwapFileVirtualizer(maxSize, swapFile, true, compression);
if (log.isDebugEnabled()) {
log.debug("Created swap file virtualizer " + virtualizer);
}
return virtualizer;
}
protected JRSwapFile getSwapFile() {
JRSwapFile swapFile = new JRSwapFile(tempDirectory, blockSize, minBlockGrowCount);
return swapFile;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public String getTempDirectory() {
return tempDirectory;
}
public void setTempDirectory(String tempDirectory) {
this.tempDirectory = tempDirectory;
}
public int getBlockSize() {
return blockSize;
}
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
public int getMinBlockGrowCount() {
return minBlockGrowCount;
}
public void setMinBlockGrowCount(int minBlockGrowCount) {
this.minBlockGrowCount = minBlockGrowCount;
}
public StreamCompression getCompression() {
return compression;
}
public void setCompression(StreamCompression compression) {
this.compression = compression;
}
}
| gpl-2.0 |
RobertoRiera/KataBD2 | KataBD2/src/kataoracle/KataBD2.java | 1216 |
package kataoracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.OracleDriver;
public class KataBD2 {
private static final String URL = "jdbc:oracle:thin:@";
private static final String USERNAME = "system";
private static final String PASSWORD = "orcl";
private static final String SERVER = "localhost:1521:orcl";
public static void main(String[] args) throws SQLException {
DriverManager.registerDriver(new OracleDriver());
//jdbc:oracle:thin:@server,username,password
Connection connection = DriverManager.getConnection(URL+SERVER,USERNAME,PASSWORD);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("Select * from CAMBIO_EUR_A");
while(resultSet.next()){
printRegister(resultSet);
}
connection.close();
}
private static void printRegister(ResultSet set) throws SQLException {
System.out.print(set.getString("DIVISA")+" ");
System.out.println(set.getBigDecimal("CAMBIO"));
}
} | gpl-2.0 |
wangtaoenter/Books | Main/src/org/geometerplus/android/fbreader/network/NetworkLibrarySecondaryActivity.java | 932 | /*
* Copyright (C) 2010-2014 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.network;
public class NetworkLibrarySecondaryActivity extends NetworkLibraryActivity {
}
| gpl-2.0 |
Romenig/iVProg_2 | tests/interpreter/code/RecursiveCallWithUserInputTest.java | 4290 | /**
* Instituto de Matemática e Estatística da Universidade de São Paulo (IME-USP)
* iVProg is a open source and free software of Laboratório de Informática na
* Educação (LInE) licensed under GNU GPL2.0 license.
* Prof. Dr. Leônidas de Oliveira Brandão - leo@ime.usp.br
* Romenig da Silva Ribeiro - romenig@ime.usp.br | romenig@gmail.com
* @author Romenig
*/
package interpreter.code;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.HashMap;
import org.junit.Test;
import usp.ime.line.ivprog.interpreter.DataFactory;
import usp.ime.line.ivprog.interpreter.DataObject;
import usp.ime.line.ivprog.interpreter.execution.Context;
import usp.ime.line.ivprog.interpreter.execution.code.Function;
import usp.ime.line.ivprog.interpreter.execution.code.IfElse;
import usp.ime.line.ivprog.interpreter.execution.code.RecursiveCall;
import usp.ime.line.ivprog.interpreter.execution.code.Return;
import usp.ime.line.ivprog.interpreter.execution.code.UserInput;
import usp.ime.line.ivprog.interpreter.execution.expressions.arithmetic.Multiplication;
import usp.ime.line.ivprog.interpreter.execution.expressions.arithmetic.Subtraction;
import usp.ime.line.ivprog.interpreter.execution.expressions.booleans.comparisons.EqualTo;
import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPBoolean;
import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPNumber;
import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPValue;
public class RecursiveCallWithUserInputTest {
@Test
public void recursiveCall() {
DataFactory factory = new DataFactory();
Context context = new Context();
HashMap map = new HashMap();
Function fatorial = factory.createFunction();
context.setFunctionID(fatorial.getUniqueID());
fatorial.setFunctionName("fatorial");
fatorial.setFunctionReturnType(IVPValue.INTEGER_TYPE);
fatorial.addArgument(IVPValue.INTEGER_TYPE, context, map, factory);
IVPNumber argu = (IVPNumber) map.get(fatorial.getArgument(0));
map.put(fatorial.getUniqueID(), fatorial);
UserInput input = factory.createUserInput();
input.setType(IVPValue.INTEGER_TYPE);
input.setValueID(argu.getUniqueID());
map.put(input.getUniqueID(), input);
Return r1 = factory.createReturn();
IVPNumber one = factory.createIVPNumber();
one.setValueType(IVPValue.INTEGER_TYPE);
fatorial.addConstant(one, "1", context, map);
r1.setReturnable(one.getUniqueID());
map.put(r1.getUniqueID(), r1);
Return r2 = factory.createReturn();
RecursiveCall recursion = factory.createRecursiveCall();
map.put(recursion.getUniqueID(), recursion);
recursion.setFunctionID(fatorial.getUniqueID());
map.put(r2.getUniqueID(), r2);
IfElse ifElse = factory.createIfElse();
ifElse.addChild(r1.getUniqueID());
ifElse.addElseChild(r2.getUniqueID());
map.put(ifElse.getUniqueID(), ifElse);
EqualTo eq = factory.createEqualTo();
eq.setExpressionA(fatorial.getArgument(0));
eq.setExpressionB(one.getUniqueID());
ifElse.setFlowCondition(eq.getUniqueID());
map.put(eq.getUniqueID(), eq);
fatorial.addChild(ifElse.getUniqueID());
IVPBoolean resultEq = factory.createIVPBoolean();
eq.setOperationResultID(resultEq.getUniqueID());
map.put(resultEq.getUniqueID(), resultEq);
Multiplication m = factory.createMultiplication();
m.setExpressionA(fatorial.getArgument(0));
m.setExpressionB(recursion.getUniqueID());
r2.setReturnable(m.getUniqueID());
map.put(m.getUniqueID(), m);
IVPNumber resultM = factory.createIVPNumber();
m.setOperationResultID(resultM.getUniqueID());
map.put(resultM.getUniqueID(), resultM);
Subtraction sub = factory.createSubtraction();
sub.setExpressionA(fatorial.getArgument(0));
sub.setExpressionB(one.getUniqueID());
map.put(sub.getUniqueID(), sub);
recursion.addParameter(0, sub.getUniqueID());
IVPNumber resultS = factory.createIVPNumber();
sub.setOperationResultID(resultS.getUniqueID());
map.put(resultS.getUniqueID(), resultS);
input.evaluate(context, map, factory);
IVPNumber result = (IVPNumber) fatorial.evaluate(context, map, factory);
assertTrue(context.getInt(result.getUniqueID()) == 120);
}
}
| gpl-2.0 |
SunLabsAST/AURA | MainSite/src/java/com/sun/labs/aura/website/StatBean.java | 2536 | /*
* Copyright 2007-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* only, as published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo
* Park, CA 94025 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.labs.aura.website;
import com.sun.labs.aura.datastore.DataStore;
import com.sun.labs.aura.datastore.Item.ItemType;
import com.sun.labs.aura.util.AuraException;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
/**
* A JavaBean that holds some stats about the data store
*/
public class StatBean {
public static DecimalFormat longForm = new DecimalFormat("###,###,###,###");
public static DecimalFormat doubForm = new DecimalFormat("###,###,###,###.#");
protected long numUsers = 0;
protected long numItems = 0;
protected long numAttn = 0;
public StatBean() {
}
public StatBean(DataStore dataStore) {
try {
numUsers = dataStore.getItemCount(ItemType.USER);
numItems = dataStore.getItemCount(null);
numAttn = dataStore.getAttentionCount(null);
} catch (AuraException e) {
} catch (RemoteException e) {
}
}
public String getNumUsers() {
return longForm.format(numUsers);
}
public void setNumUsers(long numUsers) {
this.numUsers = numUsers;
}
public String getNumItems() {
return longForm.format(numItems);
}
public void setNumItems(long numItems) {
this.numItems = numItems;
}
public String getNumAttn() {
return longForm.format(numAttn);
}
public void setNumAttn(long numAttn) {
this.numAttn = numAttn;
}
}
| gpl-2.0 |
ogz00/SpringHibernateJPA | src/main/java/com/crossover/trialtest/app/rest/rest/representation/OptionRep.java | 339 | package com.crossover.trialtest.app.rest.rest.representation;
import com.crossover.trialtest.domain.question.QuestionOption;
public class OptionRep {
public String description;
public boolean isChecked;
public OptionRep(QuestionOption qo) {
this.description = qo.getDescription();
}
public OptionRep() {}
}
| gpl-2.0 |
snkchrist/fundamentus | Fundamentus/src/com/snk/fundamentus/utils/DemonstrativoComparator.java | 416 | package com.snk.fundamentus.utils;
import java.util.Comparator;
import com.snk.fundamentus.models.DemonstrativoResultado;
public class DemonstrativoComparator implements Comparator<DemonstrativoResultado> {
@Override
public int compare(final DemonstrativoResultado o1, final DemonstrativoResultado o2) {
return o1.getDataDemonstrativo().compareTo(o2.getDataDemonstrativo());
}
}
| gpl-2.0 |
GenomicParisCentre/doelan | src/main/java/fr/ens/transcriptome/doelan/algorithms/DoelanConfigure.java | 6767 | /*
* Doelan development code
*
* This code may be freely distributed and modified under the
* terms of the GNU General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/gpl.txt
*
* Copyright (c) 2004-2005 ENS Microarray Platform
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the Doelan project and its aims,
* or to join the Doelan mailing list, visit the home page
* at:
*
* http://www.transcriptome.ens.fr/doelan
*/
package fr.ens.transcriptome.doelan.algorithms;
import fr.ens.transcriptome.doelan.Defaults;
import fr.ens.transcriptome.doelan.DoelanRegistery;
import fr.ens.transcriptome.doelan.data.DoelanDataUtils;
import fr.ens.transcriptome.doelan.data.TestSuiteResult;
import fr.ens.transcriptome.nividic.om.BioAssay;
import fr.ens.transcriptome.nividic.om.DefaultSpotEmptyTester;
import fr.ens.transcriptome.nividic.om.SpotEmptyTester;
import fr.ens.transcriptome.nividic.platform.PlatformException;
import fr.ens.transcriptome.nividic.platform.module.AboutModule;
import fr.ens.transcriptome.nividic.platform.module.Module;
import fr.ens.transcriptome.nividic.platform.module.ModuleDescription;
import fr.ens.transcriptome.nividic.platform.workflow.Container;
import fr.ens.transcriptome.nividic.platform.workflow.SimpleAlgorithmEvent;
import fr.ens.transcriptome.nividic.util.SystemUtils;
import fr.ens.transcriptome.nividic.util.parameter.FixedParameters;
import fr.ens.transcriptome.nividic.util.parameter.Parameter;
import fr.ens.transcriptome.nividic.util.parameter.ParameterBuilder;
import fr.ens.transcriptome.nividic.util.parameter.ParameterException;
import fr.ens.transcriptome.nividic.util.parameter.Parameters;
/**
* Configure Defaults for the test suite.
* @author Laurent Jourdren
*/
public class DoelanConfigure extends QualityTest implements Module {
private static final String IDENTIFIER_COLUMN = "Identifier";
private static final String DESCRIPTION_COLUMN = "Description";
/**
* Get the description of the module.
* @return The description of the module
*/
public AboutModule aboutModule() {
ModuleDescription md = null;
try {
md = new ModuleDescription("DoelanConfigure",
"Configure global parameters for the test suite");
md.setStability(AboutModule.STATE_STABLE);
md.setWebsite(DoelanRegistery.getAppURL());
md.setHTMLDocumentation(SystemUtils.readTextRessource("/files/test-"
+ SystemUtils.getClassShortName(this.getClass()) + ".html"));
md.setVersion(Defaults.DEFAULT_TEST_VERSION);
} catch (PlatformException e) {
getLogger().error("Unable to create the module description");
}
return md;
}
/**
* Set the parameters of the element.
* @return The defaults parameters to set.
*/
protected Parameters defineParameters() {
try {
final Parameter emptyIds = new ParameterBuilder().withName("emptyIds")
.withLongName("Empty identifiers").withType(
Parameter.DATATYPE_ARRAY_STRING).withDescription(
"Identifiers for empty spots").withDefaultValue("\"empty\"")
.getParameter();
final Parameter emptyIdColumn = new ParameterBuilder().withName(
"emptyIdColumn").withLongName("Empty identifiers column").withType(
Parameter.DATATYPE_STRING).withDescription(
"Column for empty identifiers").withChoices(
new String[] {IDENTIFIER_COLUMN, DESCRIPTION_COLUMN})
.withDefaultValue(IDENTIFIER_COLUMN).getParameter();
final Parameter rejectedlId = new ParameterBuilder().withName(
"rejectedlId").withLongName("New identifier for rejected spots")
.withType(Parameter.DATATYPE_STRING).withDescription(
"New identifier for rejected spots").withDefaultValue(
Defaults.REJECTED_SPOT_IDENTIFIER).getParameter();
final FixedParameters params = new FixedParameters();
params.addParameter(emptyIds);
params.addParameter(emptyIdColumn);
params.addParameter(rejectedlId);
return params;
} catch (ParameterException e) {
getLogger().error("Error while creating parameters: " + e);
}
return null;
}
/**
* Test if the test is deletable().
* @return true if the test is deletable
*/
public boolean isDeletable() {
return false;
}
/**
* Test if only one instance of the test could be created.
* @return true if only one instance of the test could be created
*/
public boolean isUniqueInstance() {
return true;
}
/**
* Test if the test is modifiable.
* @return true if the test is modifiable
*/
public boolean isModifiable() {
return true;
}
/**
* Test if the test could be showed.
* @return true if the test could be showed
*/
public boolean isShowable() {
return true;
}
/**
* Test if the test could be diplayed in the list of tests to add.
* @return true if the test could be showed
*/
public boolean isAddable() {
return false;
}
protected void doIt(final Container c, final Parameters parameters)
throws PlatformException {
// Get test suite result
BioAssay bioAssay = DoelanDataUtils.getBioAssay(c);
BioAssay gal = DoelanDataUtils.getArrayList(c);
TestSuiteResult tsr = DoelanDataUtils.getTestSuiteResult(c);
String[] emptyIds;
try {
emptyIds = parameters.getParameter("emptyIds").getArrayStringValues();
final String rejectedlId = parameters.getParameter("rejectedlId")
.getStringValue();
final String emptyIdColumn = parameters.getParameter("emptyIdColumn")
.getStringValue();
tsr.setSpotRejectedId(rejectedlId);
tsr.setEmptySpotIds(emptyIds);
if (emptyIds != null) {
SpotEmptyTester set = new DefaultSpotEmptyTester(emptyIds,
DESCRIPTION_COLUMN.equals(emptyIdColumn));
bioAssay.setSpotEmptyTester(set);
if (gal != null)
gal.setSpotEmptyTester(bioAssay.getSpotEmptyTester());
}
} catch (ParameterException e) {
getLogger().error(
"Error while creating parameters (" + this.getClass().getName()
+ "): " + e.getMessage());
}
sendEvent(new SimpleAlgorithmEvent(this, CONFIGURE_TEST_EVENT,
this.getId(), "set configure global parameters"));
} //
// Constructor
//
/**
* Public constructor.
* @throws PlatformException If the name or the version of the element is
* <b>null </b>.
*/
public DoelanConfigure() throws PlatformException {
// MUST BE EMPTY
}
}
| gpl-2.0 |
andi-git/boatpos | boatpos-common/boatpos-common-service/boatpos-common-service-api/src/main/java/org/boatpos/common/service/api/bean/AbstractBean.java | 455 | package org.boatpos.common.service.api.bean;
import com.google.gson.GsonBuilder;
/**
* Basic class for DTOs to have the method {@link #toString()}.
*/
@SuppressWarnings("unused")
public abstract class AbstractBean {
public AbstractBean() {
}
@Override
public String toString() {
return new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create()
.toJson(this);
}
}
| gpl-2.0 |
Piski/VariousSmallProjects | Exercises/Exercises/src/com/exams/frontend/exam2009/question2/Values.java | 379 | package com.exams.frontend.exam2009.question2;
public class Values<T extends Number> {
private T the_value;
public Values(T the_value) {
setThe_value(the_value);
}
public T getThe_value() {
return the_value;
}
public void setThe_value(T the_value) {
this.the_value = the_value;
}
@Override
public String toString() {
return String.valueOf(the_value);
}
}
| gpl-2.0 |
SunLabsAST/AURA | aura/src/com/sun/labs/aura/datastore/impl/MultiNoDupDBIterator.java | 3179 | /*
* Copyright 2007-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* only, as published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo
* Park, CA 94025 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.labs.aura.datastore.impl;
import com.sun.labs.aura.datastore.DBIterator;
import com.sun.labs.aura.datastore.Item;
import com.sun.labs.aura.datastore.impl.store.persist.PersistentAttention;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Set;
/**
* An iterator that
*/
public class MultiNoDupDBIterator<E> extends MultiDBIterator<E> {
/**
* The current element to be returned
*/
protected E currElem = null;
/**
* The set of keys or IDs of seel elements. This will only work for
* known types: ItemImpl and PersistentAttention
*/
protected Set seenElems = null;
/**
* Constructs a one-iterator-at-a-time MultiDBNoDupIterator.
*
* @param iterators a set of iterators over values to return values from
*/
public MultiNoDupDBIterator(Collection<DBIterator<E>> iterators) {
super(iterators);
}
@SuppressWarnings(value="DMI_CALLING_NEXT_FROM_HASNEXT",
justification="hasNext calls next and caches the result")
public boolean hasNext() throws RemoteException {
if (currElem != null) {
return true;
}
Object id = null;
do {
if (super.hasNext()) {
currElem = next();
if (currElem instanceof Item) {
id = ((Item)currElem).getKey();
} else if (currElem instanceof PersistentAttention) {
id = ((PersistentAttention)currElem).getID();
}
} else {
currElem = null;
}
} while (currElem != null && seenElems.contains(id));
if (currElem != null) {
return true;
}
return false;
}
public E next() throws RemoteException {
//
// cue up the next one if need be
hasNext();
//
// Now null out the curr and return it
E next = currElem;
currElem = null;
return next;
}
}
| gpl-2.0 |
hanz0r/server289 | hanonator/src/main/java/org/hanonator/net/grizzly/TempFilter.java | 3968 | package org.hanonator.net.grizzly;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.memory.HeapBuffer;
import org.hanonator.net.Session;
import org.hanonator.net.Session.State;
import org.hanonator.net.event.ConnectEvent;
import org.hanonator.net.event.DisconnectEvent;
import org.hanonator.net.event.ReadEvent;
import org.hanonator.net.io.Header;
public class TempFilter extends BaseFilter {
/**
* The grizzly server this filter is filtering
*/
private final GrizzlyServer server;
public TempFilter(GrizzlyServer server) {
this.server = server;
}
@Override
public NextAction handleRead(FilterChainContext ctx) throws IOException {
Session<?> session = (Session<?>) ctx.getConnection().getAttributes().getAttribute("session");
/*
* The session cannot be null
*/
if (session == null || session.getState() == State.DISCONNECTED) {
ctx.getConnection().closeSilently();
return ctx.getStopAction();
}
/*
* Get the client's data
*/
final HeapBuffer heap_buffer = (HeapBuffer) ctx.getMessage();
/*
* Convert to a ByteBuffer
*/
final ByteBuffer buffer = ByteBuffer.allocate(heap_buffer.capacity());
/*
* Fill the buffer
*/
heap_buffer.get(buffer);
/*
* Flip the buffer
*/
buffer.flip();
/*
* Read the message's header
*/
Header header = session.getState() == State.CONNECTED ? Header.wrap(buffer) : Header.estimate(buffer);
/*
* Send the message to the channel for distribution
*/
server.getListener().fire(new ReadEvent(header.resolve(buffer), session));
/*
* If there is still data remaining in the buffer, rerun this filter to get the leftover data
*/
if (buffer.remaining() - header.size() > 0) {
Buffer out = ctx.getMemoryManager().allocate(buffer.remaining());
out.put((ByteBuffer) buffer.flip());
return ctx.getRerunFilterAction();
}
/*
* Invoke next filter
*/
return ctx.getInvokeAction();
}
@Override
public NextAction handleWrite(FilterChainContext ctx) throws IOException {
Session<?> session = (Session<?>) ctx.getAttributes().getAttribute("session");
/*
* The session cannot be null
*/
if (session == null || session.getState() == State.DISCONNECTED) {
ctx.getConnection().closeSilently();
return ctx.getStopAction();
}
// TODO
/*
* Let superclass handle the next action
*/
return super.handleWrite(ctx);
}
@Override
public NextAction handleAccept(FilterChainContext ctx) throws IOException {
/*
* Create session
*/
Session<Connection<?>> session = new Session<Connection<?>>();
/*
* Register the grizzly channel and bind it to the connection
*/
session.register(new GrizzlyChannel()).bind(ctx.getConnection());
/*
* Add the session to the attributes
*/
ctx.getConnection().getAttributes().setAttribute("session", session);
/*
* Fire event
*/
server.getListener().fire(new ConnectEvent(session, (SocketAddress) ctx.getConnection().getPeerAddress()));
/*
* Let superclass handle the next action
*/
return ctx.getInvokeAction();
}
@Override
public NextAction handleClose(FilterChainContext ctx) throws IOException {
Session<?> session = (Session<?>) ctx.getAttributes().getAttribute("session");
/*
* Fire event
*/
server.getListener().fire(new DisconnectEvent(session, (SocketAddress) ctx.getConnection().getPeerAddress()));
/*
* Let superclass handle the next action
*/
return super.handleClose(ctx);
}
} | gpl-2.0 |
philipwhiuk/j3d-core | src/classes/share/javax/media/j3d/InputDeviceScheduler.java | 6558 | /*
* $RCSfile$
*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* $Revision: 892 $
* $Date: 2008-02-28 20:18:01 +0000 (Thu, 28 Feb 2008) $
* $State$
*/
package javax.media.j3d;
import java.util.*;
/**
* This thread manages all input device scheduling. It monitors and caches
* all device additions and removals. It spawns new threads for blocking
* devices, manages all non-blocking drivers itself, and tags the sensors
* of demand_driven devices. This implementation assume that
* processMode of InputDevice will not change after addInputDevice().
*
*/
class InputDeviceScheduler extends J3dThread {
// list of devices that have been added with the phys env interface
ArrayList nonBlockingDevices = new ArrayList(1);
// This condition holds blockingDevices.size() == threads.size()
ArrayList blockingDevices = new ArrayList(1);
ArrayList threads = new ArrayList(1);
// This is used by MasterControl to keep track activeViewRef
PhysicalEnvironment physicalEnv;
// store all inputDevices
Vector devices = new Vector(1);
J3dThreadData threadData = new J3dThreadData();
boolean active = false;
// The time to sleep before next processAndProcess() is invoked
// for non-blocking input device
static int samplingTime = 5;
// Some variables used to name threads correctly
private static int numInstances = 0;
private int instanceNum = -1;
private synchronized int newInstanceNum() {
return (++numInstances);
}
int getInstanceNum() {
if (instanceNum == -1)
instanceNum = newInstanceNum();
return instanceNum;
}
InputDeviceScheduler(ThreadGroup threadGroup,
PhysicalEnvironment physicalEnv) {
super(threadGroup);
setName("J3D-InputDeviceScheduler-" + getInstanceNum());
threadData.threadType = J3dThread.INPUT_DEVICE_SCHEDULER;
threadData.thread = this;
this.physicalEnv = physicalEnv;
synchronized (physicalEnv.devices) {
Enumeration elm = physicalEnv.devices.elements();
while (elm.hasMoreElements()) {
addInputDevice((InputDevice) elm.nextElement());
}
physicalEnv.inputsched = this;
}
}
void addInputDevice(InputDevice device) {
switch(device.getProcessingMode()) {
case InputDevice.BLOCKING:
InputDeviceBlockingThread thread =
VirtualUniverse.mc.getInputDeviceBlockingThread(device);
thread.start();
synchronized (blockingDevices) {
threads.add(thread);
blockingDevices.add(device);
}
break;
case InputDevice.NON_BLOCKING:
synchronized (nonBlockingDevices) {
nonBlockingDevices.add(device);
if (active && (nonBlockingDevices.size() == 1)) {
VirtualUniverse.mc.addInputDeviceScheduler(this);
}
}
break;
default: // InputDevice.DEMAND_DRIVEN:
// tag the sensors
for (int i=device.getSensorCount()-1; i>=0; i--) {
device.getSensor(i).demand_driven = true;
}
break;
}
}
void removeInputDevice(InputDevice device) {
switch(device.getProcessingMode()) {
case InputDevice.BLOCKING:
// tell the thread to clean up and permanently block
synchronized (blockingDevices) {
int idx = blockingDevices.indexOf(device);
InputDeviceBlockingThread thread =
(InputDeviceBlockingThread) threads.remove(idx);
thread.finish();
blockingDevices.remove(idx);
}
break;
case InputDevice.NON_BLOCKING:
// remove references that are in this thread
synchronized (nonBlockingDevices) {
nonBlockingDevices.remove(nonBlockingDevices.indexOf(device));
if (active && (nonBlockingDevices.size() == 0)) {
VirtualUniverse.mc.removeInputDeviceScheduler(this);
}
}
break;
default: // InputDevice.DEMAND_DRIVEN:
// untag the sensors
for (int i=device.getSensorCount()-1; i>=0; i--) {
device.getSensor(i).demand_driven = false;
}
}
}
// Add this thread to MC (Callback from MC thread)
void activate() {
if (!active) {
active = true;
synchronized (nonBlockingDevices) {
if (nonBlockingDevices.size() > 0) {
VirtualUniverse.mc.addInputDeviceScheduler(this);
}
}
// run all spawn threads
synchronized (blockingDevices) {
for (int i=threads.size()-1; i >=0; i--) {
((InputDeviceBlockingThread)threads.get(i)).restart();
}
}
}
}
// Remove this thread from MC (Callback from MC thread)
void deactivate() {
if (active) {
synchronized (nonBlockingDevices) {
if (nonBlockingDevices.size() > 0) {
VirtualUniverse.mc.removeInputDeviceScheduler(this);
}
}
// stop all spawn threads
synchronized (blockingDevices) {
for (int i=threads.size()-1; i >=0; i--) {
((InputDeviceBlockingThread)threads.get(i)).sleep();
}
}
active = false;
}
}
J3dThreadData getThreadData() {
return threadData;
}
void doWork(long referenceTime) {
synchronized (nonBlockingDevices) {
for (int i = nonBlockingDevices.size()-1; i >=0; i--) {
((InputDevice)nonBlockingDevices.get(i)).pollAndProcessInput();
}
}
}
void shutdown() {
// stop all spawn threads
for (int i=threads.size()-1; i >=0; i--) {
((InputDeviceBlockingThread)threads.get(i)).finish();
}
// for gc
threads.clear();
blockingDevices.clear();
nonBlockingDevices.clear();
devices.clear();
}
}
| gpl-2.0 |
lorenzocorneo/JAM | src/comunication/IPushNotification.java | 568 | package comunication;
/**
* This interface defines all methods for a device that manages PUSH notification.
*
* @author Lorenzo Corneo
*
*/
public interface IPushNotification {
/**
* Enables push notifications for a sensor.
*/
public void enablePushNotification();
/**
* Disables push notifications for a sensor.
*/
public void disablePushNotification();
/**
* Says if push notifications are enabled for current sensor.
* @return True if push notifications are enabled, false otherwise.
*/
public boolean isPushNotificatoinEnabled();
}
| gpl-2.0 |
NxS-BloodNote/MinExtension | src/main/java/mcmod/nxs/minextension/core/TabHandler.java | 296 | package mcmod.nxs.minextension.core;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class TabHandler {
public static CreativeTabs nxsTab = new CreativeTabs("MinExtension") {
public Item getTabIconItem() {
return ItemHandler.copper_ingot;
}
};
}
| gpl-2.0 |
tobiasKaminsky/android | src/main/java/com/owncloud/android/ui/fragment/FileDetailActivitiesFragment.java | 19255 | /*
* Nextcloud Android client application
*
* @author Andy Scherzinger
* Copyright (C) 2018 Andy Scherzinger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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.owncloud.android.ui.fragment;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Context;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.GetActivitiesRemoteOperation;
import com.owncloud.android.lib.resources.activities.model.RichObject;
import com.owncloud.android.lib.resources.comments.MarkCommentsAsReadRemoteOperation;
import com.owncloud.android.lib.resources.files.ReadFileVersionsRemoteOperation;
import com.owncloud.android.lib.resources.files.model.FileVersion;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.operations.CommentFileOperation;
import com.owncloud.android.ui.activity.ComponentsGetter;
import com.owncloud.android.ui.activity.FileActivity;
import com.owncloud.android.ui.adapter.ActivityAndVersionListAdapter;
import com.owncloud.android.ui.events.CommentsEvent;
import com.owncloud.android.ui.helpers.FileOperationsHelper;
import com.owncloud.android.ui.interfaces.ActivityListInterface;
import com.owncloud.android.ui.interfaces.VersionListInterface;
import com.owncloud.android.utils.ThemeUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class FileDetailActivitiesFragment extends Fragment implements ActivityListInterface, VersionListInterface.View {
private static final String TAG = FileDetailActivitiesFragment.class.getSimpleName();
private static final String ARG_FILE = "FILE";
private static final String ARG_ACCOUNT = "ACCOUNT";
private ActivityAndVersionListAdapter adapter;
private Unbinder unbinder;
private OwnCloudClient ownCloudClient;
private OCFile file;
private Account account;
private String nextPageUrl;
private boolean isLoadingActivities;
@BindView(R.id.empty_list_view)
public LinearLayout emptyContentContainer;
@BindView(R.id.swipe_containing_list)
public SwipeRefreshLayout swipeListRefreshLayout;
@BindView(R.id.swipe_containing_empty)
public SwipeRefreshLayout swipeEmptyListRefreshLayout;
@BindView(R.id.empty_list_view_text)
public TextView emptyContentMessage;
@BindView(R.id.empty_list_view_headline)
public TextView emptyContentHeadline;
@BindView(R.id.empty_list_icon)
public ImageView emptyContentIcon;
@BindView(R.id.empty_list_progress)
public ProgressBar emptyContentProgressBar;
@BindView(android.R.id.list)
public RecyclerView recyclerView;
@BindView(R.id.commentInputField)
public TextInputEditText commentInput;
@BindString(R.string.activities_no_results_headline)
public String noResultsHeadline;
@BindString(R.string.activities_no_results_message)
public String noResultsMessage;
private boolean restoreFileVersionSupported;
private String userId;
private FileOperationsHelper operationsHelper;
private VersionListInterface.CommentCallback callback;
public static FileDetailActivitiesFragment newInstance(OCFile file, Account account) {
FileDetailActivitiesFragment fragment = new FileDetailActivitiesFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_FILE, file);
args.putParcelable(ARG_ACCOUNT, account);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
file = getArguments().getParcelable(ARG_FILE);
account = getArguments().getParcelable(ARG_ACCOUNT);
if (savedInstanceState != null) {
file = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
account = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
}
View view = inflater.inflate(R.layout.file_details_activities_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
setupView();
onCreateSwipeToRefresh(swipeEmptyListRefreshLayout);
onCreateSwipeToRefresh(swipeListRefreshLayout);
fetchAndSetData(null);
swipeListRefreshLayout.setOnRefreshListener(() -> onRefreshListLayout(swipeListRefreshLayout));
swipeEmptyListRefreshLayout.setOnRefreshListener(() -> onRefreshListLayout(swipeEmptyListRefreshLayout));
AccountManager accountManager = AccountManager.get(getContext());
userId = accountManager.getUserData(account,
com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
callback = new VersionListInterface.CommentCallback() {
@Override
public void onSuccess() {
commentInput.getText().clear();
fetchAndSetData(null);
}
@Override
public void onError(int error) {
Snackbar.make(recyclerView, error, Snackbar.LENGTH_LONG).show();
}
};
commentInput.getBackground().setColorFilter(
ThemeUtils.primaryAccentColor(getContext()),
PorterDuff.Mode.SRC_ATOP
);
return view;
}
@OnClick(R.id.submitComment)
public void submitComment() {
Editable commentField = commentInput.getText();
if (commentField == null) {
return;
}
String trimmedComment = commentField.toString().trim();
if (trimmedComment.length() > 0) {
new SubmitCommentTask(trimmedComment, userId, file.getLocalId(), callback, ownCloudClient).execute();
}
}
private void onRefreshListLayout(SwipeRefreshLayout refreshLayout) {
setLoadingMessage();
if (refreshLayout != null && refreshLayout.isRefreshing()) {
refreshLayout.setRefreshing(false);
}
fetchAndSetData(null);
}
private void setLoadingMessage() {
emptyContentHeadline.setText(R.string.file_list_loading);
emptyContentMessage.setText("");
emptyContentIcon.setVisibility(View.GONE);
emptyContentProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
private void setupView() {
FileDataStorageManager storageManager = new FileDataStorageManager(account, requireActivity().getContentResolver());
operationsHelper = ((ComponentsGetter) requireActivity()).getFileOperationsHelper();
OCCapability capability = storageManager.getCapability(account.name);
OwnCloudVersion serverVersion = AccountUtils.getServerVersion(account);
restoreFileVersionSupported = capability.getFilesVersioning().isTrue() &&
serverVersion.compareTo(OwnCloudVersion.nextcloud_14) >= 0;
emptyContentProgressBar.getIndeterminateDrawable().setColorFilter(ThemeUtils.primaryAccentColor(getContext()),
PorterDuff.Mode.SRC_IN);
emptyContentIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_activity_light_grey));
adapter = new ActivityAndVersionListAdapter(getContext(), this, this, storageManager, capability);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemIndex = layoutManager.findFirstVisibleItemPosition();
// synchronize loading state when item count changes
if (!isLoadingActivities && (totalItemCount - visibleItemCount) <= (firstVisibleItemIndex + 5)
&& nextPageUrl != null && !nextPageUrl.isEmpty()) {
// Almost reached the end, continue to load new activities
fetchAndSetData(nextPageUrl);
}
}
});
}
public void reload() {
fetchAndSetData(null);
}
/**
* @param pageUrl String
*/
private void fetchAndSetData(String pageUrl) {
final Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
final Context context = MainApp.getAppContext();
final FragmentActivity activity = getActivity();
final SwipeRefreshLayout empty = swipeEmptyListRefreshLayout;
final SwipeRefreshLayout list = swipeListRefreshLayout;
Thread t = new Thread(() -> {
OwnCloudAccount ocAccount;
try {
ocAccount = new OwnCloudAccount(currentAccount, context);
ownCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, MainApp.getAppContext());
ownCloudClient.setOwnCloudVersion(AccountUtils.getServerVersion(currentAccount));
isLoadingActivities = true;
GetActivitiesRemoteOperation getRemoteNotificationOperation = new GetActivitiesRemoteOperation(
file.getLocalId());
if (pageUrl != null) {
getRemoteNotificationOperation.setNextUrl(pageUrl);
}
Log_OC.d(TAG, "BEFORE getRemoteActivitiesOperation.execute");
final RemoteOperationResult result = getRemoteNotificationOperation.execute(ownCloudClient);
ArrayList<Object> versions = null;
if (restoreFileVersionSupported) {
ReadFileVersionsRemoteOperation readFileVersionsOperation = new ReadFileVersionsRemoteOperation(
file.getLocalId(), userId);
RemoteOperationResult result1 = readFileVersionsOperation.execute(ownCloudClient);
versions = result1.getData();
}
if (result.isSuccess() && result.getData() != null) {
final List<Object> data = result.getData();
final List<Object> activitiesAndVersions = (ArrayList) data.get(0);
if (restoreFileVersionSupported && versions != null) {
activitiesAndVersions.addAll(versions);
}
nextPageUrl = (String) data.get(1);
activity.runOnUiThread(() -> {
populateList(activitiesAndVersions, pageUrl == null);
if (activitiesAndVersions.isEmpty()) {
setEmptyContent(noResultsHeadline, noResultsMessage);
list.setVisibility(View.GONE);
empty.setVisibility(View.VISIBLE);
} else {
empty.setVisibility(View.GONE);
list.setVisibility(View.VISIBLE);
}
isLoadingActivities = false;
});
} else {
Log_OC.d(TAG, result.getLogMessage());
// show error
String logMessage = result.getLogMessage();
if (result.getHttpCode() == HttpStatus.SC_NOT_MODIFIED) {
logMessage = noResultsMessage;
}
final String finalLogMessage = logMessage;
activity.runOnUiThread(() -> {
setErrorContent(finalLogMessage);
isLoadingActivities = false;
});
}
hideRefreshLayoutLoader(activity);
} catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException | IOException |
OperationCanceledException | AuthenticatorException e) {
Log_OC.e(TAG, "Error fetching file details activities", e);
}
});
t.start();
}
public void markCommentsAsRead() {
new Thread(() -> {
if (file.getUnreadCommentsCount() > 0) {
MarkCommentsAsReadRemoteOperation unreadOperation = new MarkCommentsAsReadRemoteOperation(
file.getLocalId());
RemoteOperationResult remoteOperationResult = unreadOperation.execute(ownCloudClient);
if (remoteOperationResult.isSuccess()) {
EventBus.getDefault().post(new CommentsEvent(file.getRemoteId()));
}
}
}).start();
}
private void populateList(List<Object> activities, boolean clear) {
adapter.setActivityAndVersionItems(activities, ownCloudClient, clear);
}
private void setEmptyContent(String headline, String message) {
if (emptyContentContainer != null && emptyContentMessage != null) {
emptyContentIcon.setImageDrawable(requireContext().getResources().getDrawable(R.drawable.ic_activity_light_grey));
emptyContentHeadline.setText(headline);
emptyContentMessage.setText(message);
emptyContentMessage.setVisibility(View.VISIBLE);
emptyContentProgressBar.setVisibility(View.GONE);
emptyContentIcon.setVisibility(View.VISIBLE);
}
}
private void setErrorContent(String message) {
if (emptyContentContainer != null && emptyContentMessage != null) {
emptyContentHeadline.setText(R.string.common_error);
emptyContentIcon.setImageDrawable(requireContext().getResources().getDrawable(R.drawable.ic_alert_octagon));
emptyContentMessage.setText(message);
emptyContentMessage.setVisibility(View.VISIBLE);
emptyContentProgressBar.setVisibility(View.GONE);
emptyContentIcon.setVisibility(View.VISIBLE);
}
}
private void hideRefreshLayoutLoader(FragmentActivity activity) {
activity.runOnUiThread(() -> {
if (swipeListRefreshLayout != null) {
swipeListRefreshLayout.setRefreshing(false);
}
if (swipeEmptyListRefreshLayout != null) {
swipeEmptyListRefreshLayout.setRefreshing(false);
}
isLoadingActivities = false;
});
}
protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) {
int primaryColor = ThemeUtils.primaryColor(getContext());
int darkColor = ThemeUtils.primaryDarkColor(getContext());
int accentColor = ThemeUtils.primaryAccentColor(getContext());
// Colors in animations
refreshLayout.setColorSchemeColors(accentColor, primaryColor, darkColor);
}
@Override
public void onActivityClicked(RichObject richObject) {
// TODO implement activity click
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(FileActivity.EXTRA_FILE, file);
outState.putParcelable(FileActivity.EXTRA_ACCOUNT, account);
}
@Override
public void onRestoreClicked(FileVersion fileVersion) {
operationsHelper.restoreFileVersion(fileVersion, userId);
}
private static class SubmitCommentTask extends AsyncTask<Void, Void, Boolean> {
private String message;
private String userId;
private String fileId;
private VersionListInterface.CommentCallback callback;
private OwnCloudClient client;
private SubmitCommentTask(String message, String userId, String fileId,
VersionListInterface.CommentCallback callback, OwnCloudClient client) {
this.message = message;
this.userId = userId;
this.fileId = fileId;
this.callback = callback;
this.client = client;
}
@Override
protected Boolean doInBackground(Void... voids) {
CommentFileOperation commentFileOperation = new CommentFileOperation(message, fileId, userId);
RemoteOperationResult result = commentFileOperation.execute(client);
return result.isSuccess();
}
@Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (success) {
callback.onSuccess();
} else {
callback.onError(R.string.error_comment_file);
}
}
}
}
| gpl-2.0 |
SixByNine/pulsarhunter | src/pulsarhunter/datatypes/EpnFileFactory.java | 1272 | /*
* EpnFileFactory.java
*
* Created on July 22, 2007, 7:51 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package pulsarhunter.datatypes;
import java.io.File;
import java.io.IOException;
import pulsarhunter.Data;
import pulsarhunter.DataFactory;
import pulsarhunter.IncorrectDataTypeException;
/**
*
* @author mkeith
*/
public class EpnFileFactory implements DataFactory{
/** Creates a new instance of EpnFileFactory */
public EpnFileFactory() {
}
public Data createData(String filename) throws IncorrectDataTypeException {
return new EpnFile(new File(filename));
}
public Data loadData(String filename, int buffersize) throws IncorrectDataTypeException {
if(!filename.endsWith(".epn")) throw new IncorrectDataTypeException("EPN data file names must end with .epn");
try {
EpnFile epn = new EpnFile(new File(filename));
epn.read();
return epn;
} catch (IOException ex) {
throw new IncorrectDataTypeException("IOException trying to load file "+filename+" of type "+this.getName(),ex);
}
}
public String getName() {
return "EPN";
}
}
| gpl-2.0 |
kompics/kompics-scala | docs/src/main/java/jexamples/networking/pingpong/Pinger.java | 1951 | package jexamples.networking.pingpong;
import se.sics.kompics.Kompics;
import se.sics.kompics.ComponentDefinition;
import se.sics.kompics.Positive;
import se.sics.kompics.Handler;
import se.sics.kompics.Start;
import se.sics.kompics.timer.*;
import se.sics.kompics.network.Network;
import java.util.UUID;
public class Pinger extends ComponentDefinition {
Positive<Network> net = requires(Network.class);
Positive<Timer> timer = requires(Timer.class);
private long counter = 0;
private UUID timerId;
private final TAddress self;
public Pinger(Init init) {
this.self = init.self;
}
Handler<Start> startHandler =
new Handler<Start>() {
public void handle(Start event) {
SchedulePeriodicTimeout spt = new SchedulePeriodicTimeout(0, 1000);
PingTimeout timeout = new PingTimeout(spt);
spt.setTimeoutEvent(timeout);
trigger(spt, timer);
timerId = timeout.getTimeoutId();
}
};
Handler<Pong> pongHandler =
new Handler<Pong>() {
public void handle(Pong event) {
counter++;
logger.info("Got Pong #{}!", counter);
if (counter > 10) {
Kompics.asyncShutdown();
}
}
};
Handler<PingTimeout> timeoutHandler =
new Handler<PingTimeout>() {
public void handle(PingTimeout event) {
trigger(new Ping(self, self), net);
}
};
{
subscribe(startHandler, control);
subscribe(pongHandler, net);
subscribe(timeoutHandler, timer);
}
@Override
public void tearDown() {
trigger(new CancelPeriodicTimeout(timerId), timer);
}
public static class PingTimeout extends Timeout {
public PingTimeout(SchedulePeriodicTimeout spt) {
super(spt);
}
}
public static class Init extends se.sics.kompics.Init<Pinger> {
public final TAddress self;
public Init(TAddress self) {
this.self = self;
}
}
}
| gpl-2.0 |
codlab/flappi_kachu | flappi/src/main/java/eu/codlab/flappi/games/instance/objects/player/Player.java | 2695 | package eu.codlab.flappi.games.instance.objects.player;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import eu.codlab.flappi.games.instance.objects.descriptor.GameObjectAnimatedSprite;
/**
* Created by kevin on 18/02/14.
*/
public class Player extends GameObjectAnimatedSprite {
int _time_counter = 0;
boolean play = false;
float bottom;
private final static int NORMAL = 0;
private final static int MONTEE = 1;
private final static int DESCENTE = 2;
int _type = NORMAL;
public Player(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTiledTextureRegion, pVertexBufferObjectManager);
}
private float montee(int tmp) {
return 2 * tmp - 800;
}
private float descente(int tmp) {
return 550 * tmp / 400;
}
@Override
public void move(float pSecondsElapsed) {
if (play) {
if (_time_counter <= 0) {
_time_counter = 0;
if (_type == MONTEE) {
_type = DESCENTE;
_time_counter = 400;
} else if (_type == DESCENTE) {
_type = NORMAL;
}
} else {
_time_counter -= pSecondsElapsed * 1000;
}
if (_type == MONTEE) {
this.mPhysicsHandler.setVelocityY(montee(400 - _time_counter));
} else if (_type == DESCENTE) {
this.mPhysicsHandler.setVelocityY(descente(400 - _time_counter));
} else {
this.mPhysicsHandler.setVelocityY(1000);
}
}
}
public void setBottom(float bottom) {
this.bottom = bottom;
}
public void start() {
this.mPhysicsHandler.setVelocityX(0);
_time_counter = 0;
play = true;
}
public void stop() {
play = false;
this.mPhysicsHandler.setVelocityY(0);
this.mPhysicsHandler.setVelocityX(0);
_time_counter = 0;
}
public void failed() {
if (play == true) {
play = false;
this.mPhysicsHandler.setVelocityY(1200);
this.mPhysicsHandler.setVelocityX(-400);
}
}
public void stopFall() {
play = false;
this.mPhysicsHandler.setVelocityY(0);
this.mPhysicsHandler.setVelocityX(-400);
}
public boolean isPlaying() {
return play;
}
public void onTouch() {
_type = MONTEE;
_time_counter = 400;
play = true;
}
}
| gpl-2.0 |
ruslanrf/wpps | wpps_plugins/tuwien.dbai.wpps.core/src/tuwien/dbai/wpps/core/config/WPPSConfigProvider.java | 20459 | /**
*
*/
package tuwien.dbai.wpps.core.config;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.commons.configuration.tree.ExpressionEngine;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.apache.log4j.Logger;
import tuwien.dbai.wpps.common.TSForLog;
import tuwien.dbai.wpps.common.callback.IProcedure;
import tuwien.dbai.wpps.common.exceptions.UnknownType;
import tuwien.dbai.wpps.common.exceptions.UnknownValueFromPredefinedList;
import tuwien.dbai.wpps.core.WPPSCoreActivator;
import tuwien.dbai.wpps.core.annotation.AnnotWPPSConfig;
import tuwien.dbai.wpps.core.config.WPPSConfig.EClientRectangleCreation;
import tuwien.dbai.wpps.core.config.WPPSConfig.ELocation;
import tuwien.dbai.wpps.core.config.WPPSConfig.EOneToManyRelation;
import tuwien.dbai.wpps.core.config.WPPSConfig.EOntologyFormalism;
import tuwien.dbai.wpps.core.config.WPPSConfig.EQltBMBorderMuType;
import tuwien.dbai.wpps.core.config.WPPSConfig.EReasonerType;
import tuwien.dbai.wpps.core.wpmodel.logmodel.instadp.ELMInstType;
import tuwien.dbai.wpps.core.wpmodel.ontology.EWPOntSubModel;
import tuwien.dbai.wpps.core.wpmodel.ontology.EWPSchemaOntology;
import tuwien.dbai.wpps.core.wpmodel.ontology.impllib.JenaModelsUtilLib;
import tuwien.dbai.wpps.core.wpmodel.physmodel.bgm.instadp.EBGMInstType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.bgm.instadp.EBlockQltRelationType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.bgm.instadp.EBlockQntAttrType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.bgm.instadp.EBlockQntRelationType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.bgm.instadp.EBlockStructRelation;
import tuwien.dbai.wpps.core.wpmodel.physmodel.dom.instadp.EDOMAttrType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.dom.instadp.EDOMInstType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.dom.instadp.EDOMRelation;
import tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp.EIMAttrType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp.EIMInstType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.im.instadp.EIMRelation;
import tuwien.dbai.wpps.core.wpmodel.physmodel.vm.instadp.EVMInstType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.vm.instadp.EVOQntAttrType;
import tuwien.dbai.wpps.core.wpmodel.physmodel.vm.instadp.EVOQntRelationType;
import com.google.common.base.Enums;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner.RuleMode;
import com.hp.hpl.jena.vocabulary.ReasonerVocabulary;
/**
* Guice Provider.
* Simple configurator which create an instance of {@link WPPSConfig}.
*
* @author Ruslan (ruslanrf@gmail.com)
* @created Nov 22, 2011 8:19:56 PM
*/
@Singleton // binding must be in a module + Singletone
public final class WPPSConfigProvider implements Provider<WPPSConfig> {
private static final Logger log = Logger.getLogger(WPPSConfigProvider.class);
private final XPathExpressionEngine xPathExpressionEngine = new XPathExpressionEngine();
private File wppsConfigFile;
@Inject
public WPPSConfigProvider(@AnnotWPPSConfig File wppsConfogFile) {
this.wppsConfigFile = wppsConfogFile;
}
@Override
public WPPSConfig get() {
if (log.isTraceEnabled()) log.trace(TSForLog.getTS(log)+"Providing instance.");
if (log.isTraceEnabled()) log.trace(TSForLog.getTS(log)+"START. Read configuration");
final WPPSConfig config = new WPPSConfig();
try
{
final XMLConfiguration configFile = new XMLConfiguration(wppsConfigFile);
// final XMLConfiguration configFile = new XMLConfiguration(new File(WPPSCoreActivator.getPluginFolder()
// , "config/wpps-config.xml"));
// configFile.setExpressionEngine(new XPathExpressionEngine());
// --- Ontology configuration
configureOntology(configFile, config);
// --- Configuration parameters ---
createInOntology(configFile, config);
computeByRequestBasedOnQntFeatures(configFile, config);
computeByRequestBasedOnFundFeatures(configFile, config);
compositeBasicDependence(configFile, config);
supportInOntology(configFile, config);
structOneToManyRelationMap(configFile, config);
locationAndArea(configFile, config);
clientRectangleCreation(configFile, config);
qltBGMFuzzyness(configFile, config);
}
catch(ConfigurationException cex)
{
log.fatal("Cannot initialize wpps configuration. Reason: "+cex.getMessage());
cex.printStackTrace();
return null;
}
if (log.isTraceEnabled()) log.trace(TSForLog.getTS(log)+"FINISH. Read configuration");
return config;
}
private final boolean isNullEmptyOrBlank(final String str) {
return str == null || str.trim().length() == 0;
}
private final <T extends Enum<T>> T opt1(final AbstractConfiguration configFile, String xmlPath, Class<T> e) {
final String str = configFile.getString(xmlPath);
Preconditions.checkArgument(!isNullEmptyOrBlank(str));
T ontType = (T)Enums.valueOfFunction(e).apply(str);
Preconditions.checkNotNull(ontType);
return ontType;
}
/**
* Read a configuration of ontology into memory.
* Configured: {@linkplain WPPSConfig#setOntologyInstanceNSGenBase(String)}, {@linkplain WPPSConfig#getCreateOntology()},
* {@linkplain WPPSConfig#getOntologyType()}, {@linkplain WPPSConfig#getOntologyReasonerType()},
* {@linkplain WPPSConfig#getJenaRDFSReasoner()}, {@linkplain WPPSConfig#getJenaOWLReasoner()},
* {@linkplain WPPSConfig#getLoadSchema()}, {@linkplain WPPSConfig#getOntologyModels()},
* {@linkplain WPPSConfig#getAltSchemaUri()}, {@linkplain WPPSConfig#setSimplification(boolean)}.
* @param configFile
* @param config
*/
@SuppressWarnings("rawtypes")
private final void configureOntology(final XMLConfiguration configFile, final WPPSConfig config) {
// ---
String str = configFile.getString("ontology-instance-ns-gen-base");
if (!isNullEmptyOrBlank(str))
config.setOntologyInstanceNSGenBase(str);
// ---
List list = configFile.configurationsAt("ontology");
Preconditions.checkArgument(list.size()>0, "Non of the ontologies are configured to be created.");
for (Iterator it = list.iterator(); it.hasNext();) {
HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
// ---
str = sub.getString("uri");
String str2 = null;
if (isNullEmptyOrBlank(str)) {
Preconditions.checkNotNull(config.getOntologyInstanceNSGenBase()
, "Ontology must have property ontology-instance-ns-gen-base or uri defined.");
str2 = JenaModelsUtilLib.genOntologyNS(config.getOntologyInstanceNSGenBase());
}
else { str2 = str; }
config.getCreateOntology().add(str2);
// ---
config.getOntologyType().put(str2, opt1(sub, "type", EOntologyFormalism.class));
// ---
config.getOntologyReasonerType().put(str2, opt1(sub, "reasoner-type", EReasonerType.class));
// ---
str = sub.getString("jena-reasoner");
if (str != null && str.trim().length() != 0) {
String rdfsR = returnRDFSReasonerSpec(str);
OntModelSpec owlR = null;
if (rdfsR == null) {
owlR = returnOWLReasonerSpec(str);
if (owlR == null)
throw new UnknownType(log, str);
else {
config.getJenaOWLReasoner().put(str2, owlR);
config.getJenaOWLReasonerName().put(str2, str);
}
}
else
config.getJenaRDFSReasoner().put(str2, rdfsR);
}
// ---
boolean bool = sub.getBoolean("load-schemata"); // NoSuchElementException
config.getLoadSchema().put(str2, bool);
// ---
List subModels = sub.getList("sub-model");
Preconditions.checkArgument(subModels.size() > 0, "Ontology "+str2+" does not contain any models.");
EWPOntSubModel[] ontModelArr = new EWPOntSubModel[subModels.size()];
int it3 = 0;
for (Iterator it2 = subModels.iterator(); it2.hasNext();) {
String subModel = (String) it2.next();
EWPOntSubModel ontModel = Enums.valueOfFunction(EWPOntSubModel.class).apply(subModel);
Preconditions.checkNotNull(ontModel);
ontModelArr[it3] = ontModel;
it3++;
}
config.getOntologyModels().put(str2, ontModelArr);
// --- RULES ---
// --- rules.uri
str = sub.getString("rules.uri");
if (str != null && str.trim().length() != 0) {
config.getJenaModelRulesUri().put(str2, str);
} else {
str = sub.getString("rules.relative-uri");
if (str != null && str.trim().length() != 0) {
str = "file://"+WPPSCoreActivator.getFile(str).getAbsolutePath();
config.getJenaModelRulesUri().put(str2, str);
}
}
// --- rules.mode
str = sub.getString("rules.ruleMode");
if (str != null && str.trim().length() != 0) {
RuleMode ruleMode = returnRuleModel(str);
if (ruleMode == null)
throw new UnknownType(log, str);
config.getJenaModelRules().put(str2, ruleMode);
}
}
// ---
list = configFile.configurationsAt("schemata.alt-load"); // It can be of size 0.
for (Iterator it = list.iterator(); it.hasNext();) {
HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
// ---
EWPSchemaOntology schName = opt1(sub, "schemata-name", EWPSchemaOntology.class);
// ---
str = sub.getString("alt-uri");
if (isNullEmptyOrBlank(str)) {
// ---
str = sub.getString("alt-relative-uri");
Preconditions.checkArgument(!isNullEmptyOrBlank(str), "Either alt-relative-uri or alt-uri should be defined.");
str = "file://"+WPPSCoreActivator.getFile(str).getAbsolutePath();
// str = "file://"+(new File(WPPSCoreActivator.getPluginFolder(), str)).getAbsolutePath();
}
config.getAltSchemaUri().put(schName, str);
}
// ---
boolean bol = configFile.getBoolean("simplification");
config.setSimplification(bol);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private final void listProcedure(final AbstractConfiguration configFile, final String xmlPath, final IProcedure<Object> proc
, final Class<? extends Enum>[] e ) {
List list = configFile.getList(xmlPath);
for (Iterator it = list.iterator(); it.hasNext();) {
String item = (String) it.next();
for (int i=0; i<e.length; i++) {
Enum instType = (Enum)Enums.valueOfFunction(e[i]).apply(item);
if (instType != null) {
proc.apply(instType);
break;
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static final Class<? extends Enum>[] arrayOfEnums = (Class<? extends Enum>[]) new Class[] {
// --- BGM Instances ---
EBGMInstType.class,
// --- SBGM relations types ---
EBlockStructRelation.class,
// --- QntBGM attributes ---
EBlockQntAttrType.class
// --- QntBGM relations types ---
, EBlockQntRelationType.class,
// --- QltBGM attributes ---
// --- QltBGM relations types ---
EBlockQltRelationType.class,
// --- IM Instances, attributes and relations ---
EIMInstType.class,
EIMAttrType.class,
EIMRelation.class,
// --- VM Instances ---
EVMInstType.class,
// --- QntVM attributes ---
EVOQntAttrType.class,
// --- QntVM relations types ---
EVOQntRelationType.class,
// --- LM Instances ---
ELMInstType.class,
// --- DOM Instances ---
EDOMInstType.class,
// --- DOM attributes ---
EDOMAttrType.class,
// --- DOM relations ---
EDOMRelation.class
};
@SuppressWarnings("rawtypes")
private final <T extends Enum<T>> Class<? extends Enum>[] getArrayOfEnums() {
return arrayOfEnums;
}
/**
* Configured: {@linkplain WPPSConfig#getCreateInOntology()}.
* @param configFile
* @param config
*/
private final void createInOntology(final XMLConfiguration configFile, final WPPSConfig config) {
listProcedure(configFile, "create-in-ontology.item"
, new IProcedure<Object>() {
@Override public void apply(Object avar) {
config.getCreateInOntology().add(avar);
} }, getArrayOfEnums() );
}
/**
* Configured: {@linkplain WPPSConfig#getComputeByRequestBasedOnQntFeatures()}
* @param configFile
* @param config
*/
private final void computeByRequestBasedOnQntFeatures(final XMLConfiguration configFile, final WPPSConfig config) {
final ExpressionEngine ee = configFile.getExpressionEngine();
configFile.setExpressionEngine(xPathExpressionEngine);
listProcedure(configFile, "compute-by-request[@basis='quantitative']/item"
, new IProcedure<Object>() {
@Override public void apply(Object avar) {
config.getComputeByRequestBasedOnQntFeatures().add(avar);
} }, getArrayOfEnums() );
configFile.setExpressionEngine(ee);
}
/**
* Configured: {@linkplain WPPSConfig#getComputeByRequestBasedOnFundFeatures()}
* @param configFile
* @param config
*/
private final void computeByRequestBasedOnFundFeatures(final XMLConfiguration configFile, final WPPSConfig config) {
final ExpressionEngine ee = configFile.getExpressionEngine();
listProcedure(configFile, "compute-by-request[@bases='fundamental']/item"
, new IProcedure<Object>() {
@Override public void apply(Object avar) {
config.getComputeByRequestBasedOnFundFeatures().add(avar);
} }, getArrayOfEnums() );
configFile.setExpressionEngine(ee);
}
/**
* Configured: {@linkplain WPPSConfig#getCompositeBasicDependence()}.
* @param configFile
* @param config
*/
private final void compositeBasicDependence(final XMLConfiguration configFile, final WPPSConfig config) {
listProcedure(configFile, "composite-basic-dependence.item"
, new IProcedure<Object>() {
@Override public void apply(Object avar) {
config.getCompositeBasicDependence().add(avar);
} }, getArrayOfEnums() );
}
/**
* Configured: {@linkplain WPPSConfig#getSupportInOntology()}.
* @param configFile
* @param config
*/
private final void supportInOntology(final XMLConfiguration configFile, final WPPSConfig config) {
listProcedure(configFile, "support-in-ontology.item"
, new IProcedure<Object>() {
@Override public void apply(Object avar) {
config.getSupportInOntology().add(avar);
} }, getArrayOfEnums() );
}
/**
* Configured: {@linkplain WPPSConfig#getStructOneToManyRelationMap()}.
* @param configFile
* @param config
*/
private final void structOneToManyRelationMap(final XMLConfiguration configFile, final WPPSConfig config) {
List<HierarchicalConfiguration> nodes = configFile.configurationsAt("struct-one-to-many-relation");
for (HierarchicalConfiguration c : nodes) {
ConfigurationNode node = c.getRootNode();
EOneToManyRelation oneToMany = Enums.valueOfFunction(EOneToManyRelation.class)
.apply(node.getValue().toString());
Preconditions.checkNotNull(oneToMany);
EWPOntSubModel subModel = Enums.valueOfFunction(EWPOntSubModel.class)
.apply(((ConfigurationNode)node.getAttributes("sub-model").get(0)).getValue().toString());
Preconditions.checkNotNull(subModel);
config.getStructOneToManyRelationMap().put(subModel, oneToMany);
}
}
/**
* Configured: {@linkplain WPPSConfig#getLocation()}, {@linkplain WPPSConfig#getArea()}
* @param configFile
* @param config
*/
@SuppressWarnings("rawtypes")
private final void locationAndArea(final XMLConfiguration configFile, final WPPSConfig config) {
// ---
ELocation loc = opt1(configFile, "location", ELocation.class);
config.setLocation(loc);
// ---
List list = configFile.configurationsAt("area");
Preconditions.checkArgument(loc != ELocation.OVERLAPS_AREA && loc != ELocation.INSIDE_AREA || list.size() > 0
, "Location is not correctly specified.");
for (Iterator it = list.iterator(); it.hasNext();) {
HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
config.getArea().xMin = sub.getDouble("top-left-x");
config.getArea().yMin = sub.getDouble("top-left-y");
config.getArea().xMax = sub.getDouble("bottom-right-x");
config.getArea().yMax = sub.getDouble("bottom-right-y");
}
}
/**
* Configured: {@linkplain WPPSConfig#getClientRectangleCreation()}.
* @param configFile
* @param config
*/
private final void clientRectangleCreation(final XMLConfiguration configFile, final WPPSConfig config) {
// ---
EClientRectangleCreation crc = opt1(configFile, "client-rectangle-creation", EClientRectangleCreation.class);
config.setClientRectangleCreation(crc);
}
/**
* Configured: {@linkplain WPPSConfig#getQltBMBorderMuType()}, {@linkplain WPPSConfig#getQltBMLeftBorderInterval()},
* {@linkplain WPPSConfig#getQltBMRightBorderInterval()}, {@linkplain WPPSConfig#getQltBMCenterInterval()},
* {@linkplain WPPSConfig#getQltBMBorderNu()}.
* @param configFile
* @param config
*/
@SuppressWarnings("rawtypes")
private final void qltBGMFuzzyness(final XMLConfiguration configFile, final WPPSConfig config) {
// ---
EQltBMBorderMuType muType = opt1(configFile, "qltbm-border-mu-type", EQltBMBorderMuType.class);
config.setQltBMBorderMuType(muType);
switch (muType) {
case INTERVAL:
{
// ---
List list = configFile.configurationsAt("qltbm-left-border-mu");
Preconditions.checkArgument(list.size() > 0, "Mu for the left border is not defined.");
HierarchicalConfiguration sub = (HierarchicalConfiguration) list.iterator().next();
config.getQltBMLeftBorderInterval()[0] = sub.getDouble("left-point");
config.getQltBMLeftBorderInterval()[1] = sub.getDouble("right-point");
// ---
list = configFile.configurationsAt("qltbm-right-border-mu");
Preconditions.checkArgument(list.size() > 0, "Mu for the right border is not defined.");
sub = (HierarchicalConfiguration) list.iterator().next();
config.getQltBMRightBorderInterval()[0] = sub.getDouble("left-point");
config.getQltBMRightBorderInterval()[1] = sub.getDouble("right-point");
// ---
list = configFile.configurationsAt("qltbm-center-mu");
Preconditions.checkArgument(list.size() > 0, "Mu for the center is not defined.");
sub = (HierarchicalConfiguration) list.iterator().next();
config.getQltBMCenterInterval()[0] = sub.getDouble("left-point");
config.getQltBMCenterInterval()[1] = sub.getDouble("right-point");
}
break;
default:
throw new UnknownValueFromPredefinedList(log, muType);
}
// ---
List list = configFile.configurationsAt("qltbm-border-nu");
Preconditions.checkArgument(list.size() > 0, "Nu for the borders is not defined.");
// TODO: add possibility to omit this value
HierarchicalConfiguration sub = (HierarchicalConfiguration) list.iterator().next();
config.getQltBMBorderNu()[0] = sub.getDouble("center");
config.getQltBMBorderNu()[1] = sub.getDouble("delta");
}
// =====================
// Supporting functions
// =====================
/**
* <a href="http://www.openjena.org/javadoc/com/hp/hpl/jena/ontology/OntModelSpec.html">For OWL model</a>.
* @param input
* @return
*/
private static OntModelSpec returnOWLReasonerSpec(String input) {
if ("OWL_MEM".equals(input))
return OntModelSpec.OWL_MEM;
if ("OWL_MEM_TRANS_INF".equals(input))
return OntModelSpec.OWL_MEM_TRANS_INF;
if ("OWL_DL_MEM_RDFS_INF".equals(input))
return OntModelSpec.OWL_DL_MEM_RDFS_INF;
if ("OWL_DL_MEM_RULE_INF".equals(input))
return OntModelSpec.OWL_DL_MEM_RULE_INF;
// ...
return null;
}
/**
* <a href="http://jena.sourceforge.net/javadoc/com/hp/hpl/jena/vocabulary/ReasonerVocabulary.html">For RDF model</a>.
* @param input
* @return
*/
private static String returnRDFSReasonerSpec(String input) {
if ("RDFS_SIMPLE".equals(input))
return ReasonerVocabulary.RDFS_SIMPLE;
if ("RDFS_DEFAULT".equals(input))
return ReasonerVocabulary.RDFS_DEFAULT;
if ("RDFS_FULL".equals(input))
return ReasonerVocabulary.RDFS_FULL;
return null;
}
private static RuleMode returnRuleModel(String input) {
if ("FORWARD".equals(input))
return GenericRuleReasoner.FORWARD;
if ("FORWARD_RETE".equals(input))
return GenericRuleReasoner.FORWARD_RETE;
if ("BACKWARD".equals(input))
return GenericRuleReasoner.BACKWARD;
if ("HYBRID".equals(input))
return GenericRuleReasoner.HYBRID;
// ...
return null;
}
}
| gpl-2.0 |
sjhalaz/hypertable | src/java/Core/org/hypertable/AsyncComm/IOHandlerData.java | 9968 | /**
* Copyright (C) 2008 Doug Judd (Zvents, Inc.)
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.hypertable.AsyncComm;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
import org.hypertable.Common.Error;
import org.hypertable.Common.HypertableException;
class IOHandlerData extends IOHandler {
private static AtomicInteger msNextId = new AtomicInteger(1);
public IOHandlerData(SocketChannel chan, DispatchHandler dh,
ConnectionMap cm) {
super(chan, dh, cm);
mSocketChannel = chan;
mHeaderBuffer = ByteBuffer.allocate(64);
mHeaderBuffer.order(ByteOrder.LITTLE_ENDIAN);
mSendQueue = new LinkedList<CommBuf>();
mShutdown = false;
reset_incoming_message_state();
}
public void SetRemoteAddress(InetSocketAddress addr) {
mAddr = addr;
mEvent.addr = addr;
}
public void SetTimeout(long timeout) {
mTimeout = timeout;
}
InetSocketAddress GetAddress() { return mAddr; }
private void reset_incoming_message_state() {
mGotHeader = false;
mEvent = new Event(Event.Type.MESSAGE, mAddr);
mHeaderBuffer.clear();
mHeaderBuffer.limit( mEvent.header.fixed_length() );
mPayloadBuffer = null;
}
private void handle_disconnect(int error) {
if (mAddr != null)
mConnMap.Remove(mAddr);
DeliverEvent(new Event(Event.Type.DISCONNECT, mAddr, error) );
mReactor.CancelRequests(this);
try {
mSocketChannel.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void run(SelectionKey selkey) {
try {
Socket socket = mSocketChannel.socket();
if (!selkey.isValid()) {
selkey.cancel();
handle_disconnect(Error.COMM_BROKEN_CONNECTION);
}
if (selkey.isConnectable()) {
try {
if (mSocketChannel.finishConnect() == false) {
mSocketChannel.close();
System.err.println("Connection error");
return;
}
mAddr = new InetSocketAddress(socket.getInetAddress(),
socket.getPort());
DeliverEvent(new Event(Event.Type.CONNECTION_ESTABLISHED,
mAddr, Error.OK));
SetInterest(SelectionKey.OP_READ);
mConnMap.Put(mAddr, this);
}
catch (ConnectException e) {
selkey.cancel();
handle_disconnect(Error.COMM_CONNECT_ERROR);
}
return;
}
if (selkey.isReadable()) {
int nread;
while (true) {
if (!mGotHeader) {
nread = mSocketChannel.read(mHeaderBuffer);
if (nread == -1) {
selkey.cancel();
handle_disconnect(Error.COMM_BROKEN_CONNECTION);
return;
}
if (mHeaderBuffer.hasRemaining())
return;
handle_message_header();
}
if (mGotHeader) {
nread = mSocketChannel.read(mPayloadBuffer);
if (nread == -1) {
selkey.cancel();
handle_disconnect(Error.COMM_BROKEN_CONNECTION);
return;
}
if (mPayloadBuffer.hasRemaining())
return;
handle_message_body();
}
}
}
if (selkey.isWritable()) {
synchronized (this) {
if (!mSendQueue.isEmpty()) {
CommBuf cbuf;
int nwritten;
// try to drain the output queue
while (!mSendQueue.isEmpty()) {
cbuf = mSendQueue.peek();
if (!SendBuf(cbuf))
break;
mSendQueue.remove();
}
if (mSendQueue.isEmpty())
RemoveInterest(SelectionKey.OP_WRITE);
}
}
}
}
catch (Exception e) {
try {
selkey.cancel();
handle_disconnect(Error.COMM_BROKEN_CONNECTION);
}
catch(Exception e2) {
e2.printStackTrace();
}
DeliverEvent(new Event(Event.Type.DISCONNECT, mAddr,
Error.COMM_BROKEN_CONNECTION));
e.printStackTrace();
}
}
private void handle_message_header() throws HypertableException {
mHeaderBuffer.position(1);
int header_len = mHeaderBuffer.get();
mHeaderBuffer.position( mHeaderBuffer.limit() );
// check to see if there is any variable length header
// after the fixed length portion that needs to be read
if (header_len > mHeaderBuffer.limit()) {
mHeaderBuffer.limit( header_len );
return;
}
mHeaderBuffer.flip();
mEvent.load_header(mSocketChannel.socket().getInetAddress().hashCode(),
mHeaderBuffer);
mPayloadBuffer = ByteBuffer.allocate(mEvent.header.total_len
- header_len);
mPayloadBuffer.order(ByteOrder.LITTLE_ENDIAN);
mHeaderBuffer.clear();
mGotHeader = true;
}
private void handle_message_body() {
DispatchHandler dh = mReactor.RemoveRequest(mEvent.header.id);
if ((mEvent.header.flags & CommHeader.FLAGS_BIT_REQUEST) == 0 &&
(mEvent.header.id == 0 || dh == null)) {
if ((mEvent.header.flags & CommHeader.FLAGS_BIT_IGNORE_RESPONSE)
== 0) {
log.warning("Received response for non-pending event (id=" +
mEvent.header.id + ",version="
+ mEvent.header.version + ",total_len="
+ mEvent.header.total_len + ")");
}
else {
java.lang.System.out.println("nope id=" + mEvent.header.id);
}
mPayloadBuffer = null;
mEvent = null;
}
else {
mPayloadBuffer.flip();
mEvent.payload = mPayloadBuffer;
DeliverEvent( mEvent, dh );
}
reset_incoming_message_state();
}
synchronized void RegisterRequest(int id, DispatchHandler responseHandler) {
long now = System.currentTimeMillis();
mReactor.AddRequest(id, this, responseHandler, now + mTimeout);
}
boolean SendBuf(CommBuf cbuf) throws IOException {
int nwritten;
if (cbuf.data != null && cbuf.data.remaining() > 0) {
nwritten = mSocketChannel.write(cbuf.data);
if (cbuf.data.remaining() > 0)
return false;
}
if (cbuf.ext != null && cbuf.ext.remaining() > 0) {
nwritten = mSocketChannel.write(cbuf.ext);
if (cbuf.ext.remaining() > 0)
return false;
}
return true;
}
synchronized int SendMessage(CommBuf cbuf) {
CommBuf tbuf;
boolean initiallyEmpty = mSendQueue.isEmpty();
try {
// try to drain the send queue
while (!mSendQueue.isEmpty()) {
tbuf = mSendQueue.peek();
if (!SendBuf(tbuf))
break;
mSendQueue.remove();
}
// try to send the message directly
if (mSendQueue.isEmpty()) {
if (SendBuf(cbuf)) {
if (!initiallyEmpty)
RemoveInterest(SelectionKey.OP_WRITE);
return Error.OK;
}
}
mSendQueue.add(cbuf);
if (initiallyEmpty)
AddInterest(SelectionKey.OP_WRITE);
}
catch (Exception e) {
e.printStackTrace();
Shutdown();
return Error.COMM_BROKEN_CONNECTION;
}
return Error.OK;
}
private SocketChannel mSocketChannel;
private ByteBuffer mHeaderBuffer;
private ByteBuffer mPayloadBuffer;
private boolean mGotHeader;
private LinkedList<CommBuf> mSendQueue;
private long mTimeout;
private boolean mShutdown;
private Event mEvent;
}
| gpl-2.0 |
itplanter/itpManager2 | src/Control.java | 1683 | import java.sql.Time;
import java.util.ArrayList;
public class Control {
private Time[] lampTime=null;
private ArrayList<Time[]> lampSchedule;
private ArrayList<Time> pumpSchedule;
private ArrayList<Duty> dutySchedule;
private ArrayList<Time> cameraSchedule;
private PlanterClass currentPlanter=null;
public Control(PlanterClass planterClass) {
this.currentPlanter = planterClass;// eNXðÛ·é@@eNXÍqNX©ç©¦éÌ©H
}
//
public void setLamp(boolean b)
{
// Lamp status b false:OFF true:ON
}
public void setPump(boolean b)
{
// Pump status b false:OFF, true:ON
}
public void setMode(int i)
{
// set mode 0:AUTO, 1:PC, 2:Manual
}
public void setPrgMode(int n)
{
// 0: Daily mode, 1:Night mode
}
//
// addLampTime( Lamp ON Time, Lamp OFF Time)
//
public void addLampTime(Time tON, Time tOFF)
{
lampTime=new Time[2];
lampTime[0]=tON;
lampTime[1]=tOFF;
lampSchedule.add(lampTime);
}
//
// addPumpTIme(Pump ON Time)
//
public void addPumpTime(Time t)
{
pumpSchedule.add(t);
}
//
// addDutyTime((duty.setDuty(duty), duty.setTime(time)))
//
public void addDutyTime(Duty d)
{
dutySchedule.add(d);
}
public int getLampScheduleSize()
{
return lampSchedule.size();
}
public int getPumpScheduleSize()
{
return pumpSchedule.size();
}
public ArrayList<Time> getCameraSchedule() {
return cameraSchedule;
}
public void setCameraSchedule(ArrayList<Time> cameraSchedule) {
this.cameraSchedule = cameraSchedule;
}
public int getCurrentPlanterNo() {
return this.currentPlanter.getPlanterNo();
}
public PlanterClass getCurrentPlanter() {
return currentPlanter;
}
}
| gpl-2.0 |
ParallelAndReconfigurableComputing/Pyjama | src/pj/parser/ast/type/ClassOrInterfaceType.java | 3573 | /*
* Copyright (C) 2013-2016 Parallel and Reconfigurable Computing Group, University of Auckland.
*
* Authors: <http://homepages.engineering.auckland.ac.nz/~parallel/ParallelIT/People.html>
*
* This file is part of Pyjama, a Java implementation of OpenMP-like directive-based
* parallelisation compiler and its runtime routines.
*
* Pyjama is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pyjama 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 Pyjama. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2007 Julio Vilmar Gesser.
*
* This file is part of Java 1.5 parser and Abstract Syntax Tree.
*
* Java 1.5 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java 1.5 parser and Abstract Syntax Tree 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 Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Created on 05/10/2006
*/
package pj.parser.ast.type;
import pj.parser.ast.visitor.GenericVisitor;
import pj.parser.ast.visitor.VoidVisitor;
import java.util.List;
/**
* @author Julio Vilmar Gesser
*/
public final class ClassOrInterfaceType extends Type {
private ClassOrInterfaceType scope;
private String name;
private List<Type> typeArgs;
public ClassOrInterfaceType() {
}
public ClassOrInterfaceType(String name) {
this.name = name;
}
public ClassOrInterfaceType(ClassOrInterfaceType scope, String name) {
this.scope = scope;
this.name = name;
}
public ClassOrInterfaceType(int beginLine, int beginColumn, int endLine, int endColumn, ClassOrInterfaceType scope, String name, List<Type> typeArgs) {
super(beginLine, beginColumn, endLine, endColumn);
this.scope = scope;
this.name = name;
this.typeArgs = typeArgs;
}
@Override
public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
return v.visit(this, arg);
}
@Override
public <A> void accept(VoidVisitor<A> v, A arg) {
v.visit(this, arg);
}
public String getName() {
return name;
}
public ClassOrInterfaceType getScope() {
return scope;
}
public List<Type> getTypeArgs() {
return typeArgs;
}
public void setName(String name) {
this.name = name;
}
public void setScope(ClassOrInterfaceType scope) {
this.scope = scope;
}
public void setTypeArgs(List<Type> typeArgs) {
this.typeArgs = typeArgs;
}
}
| gpl-2.0 |
ctalau/javainthebrowser | src/javac/com/sun/tools/javac/file/RelativePath.java | 6572 | /**
* This file was changed in order to make it compilable
* with GWT and to integrate it in the JavaInTheBrowser
* project (http://javainthebrowser.appspot.com).
*
* Date: 2013-05-14
*/
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javac.com.sun.tools.javac.file;
import gwtjava.io.File;
import gwtjava.util.zip.ZipEntry;
import gwtjava.util.zip.ZipFile;
import javac.javax.tools.JavaFileObject;
/**
* Used to represent a platform-neutral path within a platform-specific
* container, such as a directory or zip file.
* Internally, the file separator is always '/'.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public abstract class RelativePath implements Comparable<RelativePath> {
/**
* @param p must use '/' as an internal separator
*/
protected RelativePath(String p) {
path = p;
}
public abstract RelativeDirectory dirname();
public abstract String basename();
public File getFile(File directory) {
if (path.length() == 0)
return directory;
return new File(directory, path.replace('/', File.separatorChar));
}
public int compareTo(RelativePath other) {
return path.compareTo(other.path);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof RelativePath))
return false;
return path.equals(((RelativePath) other).path);
}
@Override
public int hashCode() {
return path.hashCode();
}
@Override
public String toString() {
return "RelPath[" + path + "]";
}
public String getPath() {
return path;
}
protected final String path;
/**
* Used to represent a platform-neutral subdirectory within a platform-specific
* container, such as a directory or zip file.
* Internally, the file separator is always '/', and if the path is not empty,
* it always ends in a '/' as well.
*/
public static class RelativeDirectory extends RelativePath {
static RelativeDirectory forPackage(CharSequence packageName) {
return new RelativeDirectory(packageName.toString().replace('.', '/'));
}
/**
* @param p must use '/' as an internal separator
*/
public RelativeDirectory(String p) {
super(p.length() == 0 || p.endsWith("/") ? p : p + "/");
}
/**
* @param p must use '/' as an internal separator
*/
public RelativeDirectory(RelativeDirectory d, String p) {
this(d.path + p);
}
@Override
public RelativeDirectory dirname() {
int l = path.length();
if (l == 0)
return this;
int sep = path.lastIndexOf('/', l - 2);
return new RelativeDirectory(path.substring(0, sep + 1));
}
@Override
public String basename() {
int l = path.length();
if (l == 0)
return path;
int sep = path.lastIndexOf('/', l - 2);
return path.substring(sep + 1, l - 1);
}
/**
* Return true if this subdirectory "contains" the other path.
* A subdirectory path does not contain itself.
**/
boolean contains(RelativePath other) {
return other.path.length() > path.length() && other.path.startsWith(path);
}
@Override
public String toString() {
return "RelativeDirectory[" + path + "]";
}
}
/**
* Used to represent a platform-neutral file within a platform-specific
* container, such as a directory or zip file.
* Internally, the file separator is always '/'. It never ends in '/'.
*/
public static class RelativeFile extends RelativePath {
static RelativeFile forClass(CharSequence className, JavaFileObject.Kind kind) {
return new RelativeFile(className.toString().replace('.', '/') + kind.extension);
}
public RelativeFile(String p) {
super(p);
if (p.endsWith("/"))
throw new IllegalArgumentException(p);
}
/**
* @param p must use '/' as an internal separator
*/
public RelativeFile(RelativeDirectory d, String p) {
this(d.path + p);
}
RelativeFile(RelativeDirectory d, RelativePath p) {
this(d, p.path);
}
@Override
public RelativeDirectory dirname() {
int sep = path.lastIndexOf('/');
return new RelativeDirectory(path.substring(0, sep + 1));
}
@Override
public String basename() {
int sep = path.lastIndexOf('/');
return path.substring(sep + 1);
}
ZipEntry getZipEntry(ZipFile zip) {
return zip.getEntry(path);
}
@Override
public String toString() {
return "RelativeFile[" + path + "]";
}
}
}
| gpl-2.0 |
knard/autoSwing | src/main/java/org/knard/tools/autoSwing/parser/PropertyBasedSelector.java | 2663 | package org.knard.tools.autoSwing.parser;
import java.util.regex.Pattern;
import org.knard.tools.autoSwing.core.conversion.ConvertorHelper;
import org.knard.tools.autoSwing.model.GuiElement;
import org.knard.tools.autoSwing.model.GuiElementList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyBasedSelector implements TreeSelector {
private final static Logger log = LoggerFactory
.getLogger(PropertyBasedSelector.class);
private Pattern attributeNamePattern;
private Pattern attributeValuePattern;
public PropertyBasedSelector(String attributeNameRegEx,
String attributeValue) {
if (log.isDebugEnabled()) {
log.debug("PropertyBasedSelector (" + attributeNameRegEx + ", "
+ attributeValue + ")");
}
attributeNamePattern = Pattern.compile(attributeNameRegEx);
attributeValuePattern = Pattern.compile(attributeValue);
}
@Override
public GuiElementList select(GuiElementList elements) {
if (log.isTraceEnabled()) {
log.trace("apply " + this.getClass().getName() + " to " + elements);
}
GuiElementList selectedComponent = new GuiElementList();
for (GuiElement element : elements) {
for (String propertyName : element.getPropertyNames()) {
if (log.isTraceEnabled()) {
log.trace("try to match property " + propertyName
+ " with pattern " + attributeNamePattern.pattern());
}
if (attributeNamePattern.matcher(propertyName).matches()) {
Class<?> valueType = element.getPropertyType(propertyName);
Object value = element.getProperty(propertyName);
if (log.isTraceEnabled()) {
log.trace("try to match value " + value + " of type "
+ valueType.getName() + " with pattern "
+ attributeValuePattern.pattern());
}
if (value != null) {
if (CharSequence.class.isAssignableFrom(valueType)) {
if (attributeValuePattern.matcher(
(CharSequence) value).matches()) {
if (log.isTraceEnabled()) {
log.trace("matched");
}
selectedComponent.add(element);
}
} else {
Object expectedValue = ConvertorHelper.fromString(
attributeValuePattern.pattern(), valueType);
if (expectedValue.equals(value)) {
if (log.isTraceEnabled()) {
log.trace("matched");
}
selectedComponent.add(element);
}
}
}
}
}
}
return selectedComponent;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PropertyBasedSelector [attributeNamePattern="
+ attributeNamePattern + ", attributeValuePattern="
+ attributeValuePattern + "]";
}
}
| gpl-2.0 |
skymania/Cirrus | src/com/synox/android/ui/dialog/parcel/MenuItemParcelable.java | 1495 | package com.synox.android.ui.dialog.parcel;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.MenuItem;
public class MenuItemParcelable implements Parcelable {
int mMenuItemId;
String mMenuText;
public MenuItemParcelable() {}
public MenuItemParcelable(MenuItem menuItem) {
mMenuItemId = menuItem.getItemId();
mMenuText = menuItem.getTitle().toString();
}
public MenuItemParcelable(Parcel read) {
mMenuItemId = read.readInt();
}
public void setMenuItemId(int id) {
mMenuItemId = id;
}
public int getMenuItemId() {
return mMenuItemId;
}
public String getMenuText() {
return mMenuText;
}
public void setMenuText(String mMenuText) {
this.mMenuText = mMenuText;
}
public static final Parcelable.Creator<MenuItemParcelable> CREATOR =
new Parcelable.Creator<MenuItemParcelable>() {
@Override
public MenuItemParcelable createFromParcel(Parcel source) {
return new MenuItemParcelable(source);
}
@Override
public MenuItemParcelable[] newArray(int size) {
return new MenuItemParcelable[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mMenuItemId);
}
}
| gpl-2.0 |
Aptoide/aptoide-client | amethystengine/src/main/java/com/aptoide/amethyst/openiab/webservices/json/IabPurchasesJson.java | 2941 | package com.aptoide.amethyst.openiab.webservices.json;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by j-pac on 19-02-2014.
*/
public class IabPurchasesJson {
public String status;
public PublisherResponse publisher_response;
public String getStatus() { return status; }
public PublisherResponse getPublisher_response() {
return publisher_response;
}
public static class PublisherResponse {
@JsonProperty("INAPP_PURCHASE_ITEM_LIST") public List<String> itemList;
@JsonProperty("INAPP_PURCHASE_DATA_LIST") public List<PurchaseDataObject> purchaseDataList;
@JsonProperty("INAAP_DATA_SIGNATURE_LIST") public List<String> signatureList;
@JsonProperty("INAPP_CONTINUATION_TOKEN") public String inapp_continuation_token;
public List<String> getItemList() {
return itemList;
}
public List<PurchaseDataObject> getPurchaseDataList() { return purchaseDataList; }
public List<String> getSignatureList() {
return signatureList;
}
public String getInapp_continuation_token() {
return inapp_continuation_token;
}
public static class PurchaseDataObject {
public int orderId;
public String packageName;
public String productId;
public long purchaseTime;
public String purchaseState;
public String developerPayload;
public String token;
public String purchaseToken;
public int getOrderId() { return orderId; }
public String getPackageName() {
return packageName;
}
public String getToken() {
return token;
}
public String getJson() {
Map<String, Object> myJson = new LinkedHashMap<String, Object>();
myJson.put("orderId", orderId);
myJson.put("packageName", packageName);
myJson.put("productId", productId);
myJson.put("purchaseTime", purchaseTime);
myJson.put("purchaseToken", purchaseToken);
if(developerPayload != null) myJson.put("developerPayload", developerPayload);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
return mapper.writeValueAsString(myJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
}
}
| gpl-2.0 |
peterbartha/j2eecm | edu.bme.vik.iit.j2eecm.diagram/src/components/diagram/part/ModelDiagramUpdater.java | 30981 | package components.diagram.part;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.update.DiagramUpdater;
import components.AppReleationship;
import components.ApplicationClient;
import components.Browser;
import components.Client;
import components.ComponentsPackage;
import components.ContainerReleationship;
import components.DataReleationship;
import components.Database;
import components.EJBContainer;
import components.J2EEServer;
import components.Model;
import components.WebContainer;
import components.WebReleationship;
import components.diagram.edit.parts.AppReleationshipEditPart;
import components.diagram.edit.parts.ApplicationClientEditPart;
import components.diagram.edit.parts.BrowserEditPart;
import components.diagram.edit.parts.ClientApplicationCompartmentEditPart;
import components.diagram.edit.parts.ClientBrowserCompartmentEditPart;
import components.diagram.edit.parts.ClientEditPart;
import components.diagram.edit.parts.ContainerReleationshipEditPart;
import components.diagram.edit.parts.DataReleationshipEditPart;
import components.diagram.edit.parts.DatabaseEditPart;
import components.diagram.edit.parts.EJBContainerEditPart;
import components.diagram.edit.parts.J2EEServerEJBContainerCompartmentEditPart;
import components.diagram.edit.parts.J2EEServerEditPart;
import components.diagram.edit.parts.J2EEServerWebContainerCompartmentEditPart;
import components.diagram.edit.parts.ModelEditPart;
import components.diagram.edit.parts.WebContainerEditPart;
import components.diagram.edit.parts.WebReleationshipEditPart;
import components.diagram.providers.ModelElementTypes;
/**
* @generated
*/
public class ModelDiagramUpdater {
/**
* @generated
*/
public static List<ModelNodeDescriptor> getSemanticChildren(View view) {
switch (ModelVisualIDRegistry.getVisualID(view)) {
case ModelEditPart.VISUAL_ID:
return getModel_1000SemanticChildren(view);
case ClientBrowserCompartmentEditPart.VISUAL_ID:
return getClientBrowserCompartment_7001SemanticChildren(view);
case ClientApplicationCompartmentEditPart.VISUAL_ID:
return getClientApplicationCompartment_7002SemanticChildren(view);
case J2EEServerWebContainerCompartmentEditPart.VISUAL_ID:
return getJ2EEServerWebContainerCompartment_7003SemanticChildren(view);
case J2EEServerEJBContainerCompartmentEditPart.VISUAL_ID:
return getJ2EEServerEJBContainerCompartment_7004SemanticChildren(view);
}
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelNodeDescriptor> getModel_1000SemanticChildren(
View view) {
if (!view.isSetElement()) {
return Collections.emptyList();
}
Model modelElement = (Model) view.getElement();
LinkedList<ModelNodeDescriptor> result = new LinkedList<ModelNodeDescriptor>();
{
Client childElement = modelElement.getClient();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == ClientEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
{
Database childElement = modelElement.getDatabase();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == DatabaseEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
{
J2EEServer childElement = modelElement.getServer();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == J2EEServerEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
return result;
}
/**
* @generated
*/
public static List<ModelNodeDescriptor> getClientBrowserCompartment_7001SemanticChildren(
View view) {
if (false == view.eContainer() instanceof View) {
return Collections.emptyList();
}
View containerView = (View) view.eContainer();
if (!containerView.isSetElement()) {
return Collections.emptyList();
}
Client modelElement = (Client) containerView.getElement();
LinkedList<ModelNodeDescriptor> result = new LinkedList<ModelNodeDescriptor>();
{
Browser childElement = modelElement.getBrowser();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == BrowserEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
return result;
}
/**
* @generated
*/
public static List<ModelNodeDescriptor> getClientApplicationCompartment_7002SemanticChildren(
View view) {
if (false == view.eContainer() instanceof View) {
return Collections.emptyList();
}
View containerView = (View) view.eContainer();
if (!containerView.isSetElement()) {
return Collections.emptyList();
}
Client modelElement = (Client) containerView.getElement();
LinkedList<ModelNodeDescriptor> result = new LinkedList<ModelNodeDescriptor>();
{
ApplicationClient childElement = modelElement.getApplication();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == ApplicationClientEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
return result;
}
/**
* @generated
*/
public static List<ModelNodeDescriptor> getJ2EEServerWebContainerCompartment_7003SemanticChildren(
View view) {
if (false == view.eContainer() instanceof View) {
return Collections.emptyList();
}
View containerView = (View) view.eContainer();
if (!containerView.isSetElement()) {
return Collections.emptyList();
}
J2EEServer modelElement = (J2EEServer) containerView.getElement();
LinkedList<ModelNodeDescriptor> result = new LinkedList<ModelNodeDescriptor>();
{
WebContainer childElement = modelElement.getWebContainer();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == WebContainerEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
return result;
}
/**
* @generated
*/
public static List<ModelNodeDescriptor> getJ2EEServerEJBContainerCompartment_7004SemanticChildren(
View view) {
if (false == view.eContainer() instanceof View) {
return Collections.emptyList();
}
View containerView = (View) view.eContainer();
if (!containerView.isSetElement()) {
return Collections.emptyList();
}
J2EEServer modelElement = (J2EEServer) containerView.getElement();
LinkedList<ModelNodeDescriptor> result = new LinkedList<ModelNodeDescriptor>();
{
EJBContainer childElement = modelElement.getEjbContainer();
int visualID = ModelVisualIDRegistry.getNodeVisualID(view,
childElement);
if (visualID == EJBContainerEditPart.VISUAL_ID) {
result.add(new ModelNodeDescriptor(childElement, visualID));
}
}
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getContainedLinks(View view) {
switch (ModelVisualIDRegistry.getVisualID(view)) {
case ModelEditPart.VISUAL_ID:
return getModel_1000ContainedLinks(view);
case ClientEditPart.VISUAL_ID:
return getClient_2001ContainedLinks(view);
case DatabaseEditPart.VISUAL_ID:
return getDatabase_2002ContainedLinks(view);
case J2EEServerEditPart.VISUAL_ID:
return getJ2EEServer_2003ContainedLinks(view);
case BrowserEditPart.VISUAL_ID:
return getBrowser_3001ContainedLinks(view);
case ApplicationClientEditPart.VISUAL_ID:
return getApplicationClient_3002ContainedLinks(view);
case WebContainerEditPart.VISUAL_ID:
return getWebContainer_3003ContainedLinks(view);
case EJBContainerEditPart.VISUAL_ID:
return getEJBContainer_3004ContainedLinks(view);
case WebReleationshipEditPart.VISUAL_ID:
return getWebReleationship_4001ContainedLinks(view);
case DataReleationshipEditPart.VISUAL_ID:
return getDataReleationship_4002ContainedLinks(view);
case AppReleationshipEditPart.VISUAL_ID:
return getAppReleationship_4003ContainedLinks(view);
case ContainerReleationshipEditPart.VISUAL_ID:
return getContainerReleationship_4004ContainedLinks(view);
}
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getIncomingLinks(View view) {
switch (ModelVisualIDRegistry.getVisualID(view)) {
case ClientEditPart.VISUAL_ID:
return getClient_2001IncomingLinks(view);
case DatabaseEditPart.VISUAL_ID:
return getDatabase_2002IncomingLinks(view);
case J2EEServerEditPart.VISUAL_ID:
return getJ2EEServer_2003IncomingLinks(view);
case BrowserEditPart.VISUAL_ID:
return getBrowser_3001IncomingLinks(view);
case ApplicationClientEditPart.VISUAL_ID:
return getApplicationClient_3002IncomingLinks(view);
case WebContainerEditPart.VISUAL_ID:
return getWebContainer_3003IncomingLinks(view);
case EJBContainerEditPart.VISUAL_ID:
return getEJBContainer_3004IncomingLinks(view);
case WebReleationshipEditPart.VISUAL_ID:
return getWebReleationship_4001IncomingLinks(view);
case DataReleationshipEditPart.VISUAL_ID:
return getDataReleationship_4002IncomingLinks(view);
case AppReleationshipEditPart.VISUAL_ID:
return getAppReleationship_4003IncomingLinks(view);
case ContainerReleationshipEditPart.VISUAL_ID:
return getContainerReleationship_4004IncomingLinks(view);
}
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getOutgoingLinks(View view) {
switch (ModelVisualIDRegistry.getVisualID(view)) {
case ClientEditPart.VISUAL_ID:
return getClient_2001OutgoingLinks(view);
case DatabaseEditPart.VISUAL_ID:
return getDatabase_2002OutgoingLinks(view);
case J2EEServerEditPart.VISUAL_ID:
return getJ2EEServer_2003OutgoingLinks(view);
case BrowserEditPart.VISUAL_ID:
return getBrowser_3001OutgoingLinks(view);
case ApplicationClientEditPart.VISUAL_ID:
return getApplicationClient_3002OutgoingLinks(view);
case WebContainerEditPart.VISUAL_ID:
return getWebContainer_3003OutgoingLinks(view);
case EJBContainerEditPart.VISUAL_ID:
return getEJBContainer_3004OutgoingLinks(view);
case WebReleationshipEditPart.VISUAL_ID:
return getWebReleationship_4001OutgoingLinks(view);
case DataReleationshipEditPart.VISUAL_ID:
return getDataReleationship_4002OutgoingLinks(view);
case AppReleationshipEditPart.VISUAL_ID:
return getAppReleationship_4003OutgoingLinks(view);
case ContainerReleationshipEditPart.VISUAL_ID:
return getContainerReleationship_4004OutgoingLinks(view);
}
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getModel_1000ContainedLinks(
View view) {
Model modelElement = (Model) view.getElement();
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getContainedTypeModelFacetLinks_WebReleationship_4001(modelElement));
result.addAll(getContainedTypeModelFacetLinks_DataReleationship_4002(modelElement));
result.addAll(getContainedTypeModelFacetLinks_AppReleationship_4003(modelElement));
result.addAll(getContainedTypeModelFacetLinks_ContainerReleationship_4004(modelElement));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getClient_2001ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDatabase_2002ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getJ2EEServer_2003ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getBrowser_3001ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getApplicationClient_3002ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebContainer_3003ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getEJBContainer_3004ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebReleationship_4001ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDataReleationship_4002ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getAppReleationship_4003ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getContainerReleationship_4004ContainedLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getClient_2001IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDatabase_2002IncomingLinks(
View view) {
Database modelElement = (Database) view.getElement();
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences = EcoreUtil.CrossReferencer
.find(view.eResource().getResourceSet().getResources());
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getIncomingTypeModelFacetLinks_DataReleationship_4002(
modelElement, crossReferences));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getJ2EEServer_2003IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getBrowser_3001IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getApplicationClient_3002IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebContainer_3003IncomingLinks(
View view) {
WebContainer modelElement = (WebContainer) view.getElement();
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences = EcoreUtil.CrossReferencer
.find(view.eResource().getResourceSet().getResources());
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getIncomingTypeModelFacetLinks_WebReleationship_4001(
modelElement, crossReferences));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getEJBContainer_3004IncomingLinks(
View view) {
EJBContainer modelElement = (EJBContainer) view.getElement();
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences = EcoreUtil.CrossReferencer
.find(view.eResource().getResourceSet().getResources());
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getIncomingTypeModelFacetLinks_AppReleationship_4003(
modelElement, crossReferences));
result.addAll(getIncomingTypeModelFacetLinks_ContainerReleationship_4004(
modelElement, crossReferences));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebReleationship_4001IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDataReleationship_4002IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getAppReleationship_4003IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getContainerReleationship_4004IncomingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getClient_2001OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDatabase_2002OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getJ2EEServer_2003OutgoingLinks(
View view) {
J2EEServer modelElement = (J2EEServer) view.getElement();
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getOutgoingTypeModelFacetLinks_DataReleationship_4002(modelElement));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getBrowser_3001OutgoingLinks(
View view) {
Browser modelElement = (Browser) view.getElement();
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getOutgoingTypeModelFacetLinks_WebReleationship_4001(modelElement));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getApplicationClient_3002OutgoingLinks(
View view) {
ApplicationClient modelElement = (ApplicationClient) view.getElement();
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getOutgoingTypeModelFacetLinks_AppReleationship_4003(modelElement));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebContainer_3003OutgoingLinks(
View view) {
WebContainer modelElement = (WebContainer) view.getElement();
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
result.addAll(getOutgoingTypeModelFacetLinks_ContainerReleationship_4004(modelElement));
return result;
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getEJBContainer_3004OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getWebReleationship_4001OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getDataReleationship_4002OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getAppReleationship_4003OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
public static List<ModelLinkDescriptor> getContainerReleationship_4004OutgoingLinks(
View view) {
return Collections.emptyList();
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getContainedTypeModelFacetLinks_WebReleationship_4001(
Model container) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
WebReleationship link = container.getWebRealtion();
if (WebReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
WebContainer dst = link.getWebContainer();
Browser src = link.getBrowser();
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.WebReleationship_4001,
WebReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getContainedTypeModelFacetLinks_DataReleationship_4002(
Model container) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
DataReleationship link = container.getDataRelation();
if (DataReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
Database dst = link.getDatabase();
J2EEServer src = link.getServer();
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.DataReleationship_4002,
DataReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getContainedTypeModelFacetLinks_AppReleationship_4003(
Model container) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
AppReleationship link = container.getAppRelation();
if (AppReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
EJBContainer dst = link.getEjbs();
ApplicationClient src = link.getApp();
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.AppReleationship_4003,
AppReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getContainedTypeModelFacetLinks_ContainerReleationship_4004(
Model container) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
ContainerReleationship link = container.getContainerRelation();
if (ContainerReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
EJBContainer dst = link.getEjbs();
WebContainer src = link.getWeb();
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.ContainerReleationship_4004,
ContainerReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getIncomingTypeModelFacetLinks_WebReleationship_4001(
WebContainer target,
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
Collection<EStructuralFeature.Setting> settings = crossReferences
.get(target);
for (EStructuralFeature.Setting setting : settings) {
if (setting.getEStructuralFeature() != ComponentsPackage.eINSTANCE
.getWebReleationship_WebContainer()
|| false == setting.getEObject() instanceof WebReleationship) {
continue;
}
WebReleationship link = (WebReleationship) setting.getEObject();
if (WebReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
continue;
}
Browser src = link.getBrowser();
result.add(new ModelLinkDescriptor(src, target, link,
ModelElementTypes.WebReleationship_4001,
WebReleationshipEditPart.VISUAL_ID));
}
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getIncomingTypeModelFacetLinks_DataReleationship_4002(
Database target,
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
Collection<EStructuralFeature.Setting> settings = crossReferences
.get(target);
for (EStructuralFeature.Setting setting : settings) {
if (setting.getEStructuralFeature() != ComponentsPackage.eINSTANCE
.getDataReleationship_Database()
|| false == setting.getEObject() instanceof DataReleationship) {
continue;
}
DataReleationship link = (DataReleationship) setting.getEObject();
if (DataReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
continue;
}
J2EEServer src = link.getServer();
result.add(new ModelLinkDescriptor(src, target, link,
ModelElementTypes.DataReleationship_4002,
DataReleationshipEditPart.VISUAL_ID));
}
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getIncomingTypeModelFacetLinks_AppReleationship_4003(
EJBContainer target,
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
Collection<EStructuralFeature.Setting> settings = crossReferences
.get(target);
for (EStructuralFeature.Setting setting : settings) {
if (setting.getEStructuralFeature() != ComponentsPackage.eINSTANCE
.getAppReleationship_Ejbs()
|| false == setting.getEObject() instanceof AppReleationship) {
continue;
}
AppReleationship link = (AppReleationship) setting.getEObject();
if (AppReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
continue;
}
ApplicationClient src = link.getApp();
result.add(new ModelLinkDescriptor(src, target, link,
ModelElementTypes.AppReleationship_4003,
AppReleationshipEditPart.VISUAL_ID));
}
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getIncomingTypeModelFacetLinks_ContainerReleationship_4004(
EJBContainer target,
Map<EObject, Collection<EStructuralFeature.Setting>> crossReferences) {
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
Collection<EStructuralFeature.Setting> settings = crossReferences
.get(target);
for (EStructuralFeature.Setting setting : settings) {
if (setting.getEStructuralFeature() != ComponentsPackage.eINSTANCE
.getContainerReleationship_Ejbs()
|| false == setting.getEObject() instanceof ContainerReleationship) {
continue;
}
ContainerReleationship link = (ContainerReleationship) setting
.getEObject();
if (ContainerReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
continue;
}
WebContainer src = link.getWeb();
result.add(new ModelLinkDescriptor(src, target, link,
ModelElementTypes.ContainerReleationship_4004,
ContainerReleationshipEditPart.VISUAL_ID));
}
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getOutgoingTypeModelFacetLinks_WebReleationship_4001(
Browser source) {
Model container = null;
// Find container element for the link.
// Climb up by containment hierarchy starting from the source
// and return the first element that is instance of the container class.
for (EObject element = source; element != null && container == null; element = element
.eContainer()) {
if (element instanceof Model) {
container = (Model) element;
}
}
if (container == null) {
return Collections.emptyList();
}
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
WebReleationship link = container.getWebRealtion();
if (WebReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
WebContainer dst = link.getWebContainer();
Browser src = link.getBrowser();
if (src != source) {
return result;
}
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.WebReleationship_4001,
WebReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getOutgoingTypeModelFacetLinks_DataReleationship_4002(
J2EEServer source) {
Model container = null;
// Find container element for the link.
// Climb up by containment hierarchy starting from the source
// and return the first element that is instance of the container class.
for (EObject element = source; element != null && container == null; element = element
.eContainer()) {
if (element instanceof Model) {
container = (Model) element;
}
}
if (container == null) {
return Collections.emptyList();
}
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
DataReleationship link = container.getDataRelation();
if (DataReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
Database dst = link.getDatabase();
J2EEServer src = link.getServer();
if (src != source) {
return result;
}
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.DataReleationship_4002,
DataReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getOutgoingTypeModelFacetLinks_AppReleationship_4003(
ApplicationClient source) {
Model container = null;
// Find container element for the link.
// Climb up by containment hierarchy starting from the source
// and return the first element that is instance of the container class.
for (EObject element = source; element != null && container == null; element = element
.eContainer()) {
if (element instanceof Model) {
container = (Model) element;
}
}
if (container == null) {
return Collections.emptyList();
}
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
AppReleationship link = container.getAppRelation();
if (AppReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
EJBContainer dst = link.getEjbs();
ApplicationClient src = link.getApp();
if (src != source) {
return result;
}
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.AppReleationship_4003,
AppReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
private static Collection<ModelLinkDescriptor> getOutgoingTypeModelFacetLinks_ContainerReleationship_4004(
WebContainer source) {
Model container = null;
// Find container element for the link.
// Climb up by containment hierarchy starting from the source
// and return the first element that is instance of the container class.
for (EObject element = source; element != null && container == null; element = element
.eContainer()) {
if (element instanceof Model) {
container = (Model) element;
}
}
if (container == null) {
return Collections.emptyList();
}
LinkedList<ModelLinkDescriptor> result = new LinkedList<ModelLinkDescriptor>();
ContainerReleationship link = container.getContainerRelation();
if (ContainerReleationshipEditPart.VISUAL_ID != ModelVisualIDRegistry
.getLinkWithClassVisualID(link)) {
return result;
}
EJBContainer dst = link.getEjbs();
WebContainer src = link.getWeb();
if (src != source) {
return result;
}
result.add(new ModelLinkDescriptor(src, dst, link,
ModelElementTypes.ContainerReleationship_4004,
ContainerReleationshipEditPart.VISUAL_ID));
return result;
}
/**
* @generated
*/
public static final DiagramUpdater TYPED_INSTANCE = new DiagramUpdater() {
/**
* @generated
*/
public List<ModelNodeDescriptor> getSemanticChildren(View view) {
return ModelDiagramUpdater.getSemanticChildren(view);
}
/**
* @generated
*/
public List<ModelLinkDescriptor> getContainedLinks(View view) {
return ModelDiagramUpdater.getContainedLinks(view);
}
/**
* @generated
*/
public List<ModelLinkDescriptor> getIncomingLinks(View view) {
return ModelDiagramUpdater.getIncomingLinks(view);
}
/**
* @generated
*/
public List<ModelLinkDescriptor> getOutgoingLinks(View view) {
return ModelDiagramUpdater.getOutgoingLinks(view);
}
};
}
| gpl-2.0 |
perdisci/fluxbuster | src/edu/uga/cs/fluxbuster/classification/Classifier.java | 8868 | /*
* Copyright (C) 2012 Chris Neasbitt
* Author: Chris Neasbitt
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package edu.uga.cs.fluxbuster.classification;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import edu.uga.cs.fluxbuster.clustering.StoredDomainCluster;
import edu.uga.cs.fluxbuster.db.DBInterface;
import edu.uga.cs.fluxbuster.db.DBInterfaceFactory;
import edu.uga.cs.fluxbuster.utils.PropertiesUtils;
/**
* This class runs the classifier on the clusters and stores
* the derived classes in the database.
*
* @author Chris Neasbitt
*/
public class Classifier {
private static final String featuresHeader = "@RELATION FastFlux\n\n"+
"@ATTRIBUTE Network_Cardinality NUMERIC\n"+
"@ATTRIBUTE Network_Prefixes NUMERIC\n" +
"@ATTRIBUTE Domains_Per_Network NUMERIC\n" +
"@ATTRIBUTE Number_of_Domains NUMERIC\n" +
"@ATTRIBUTE TTL_Per_Domain NUMERIC\n" +
"@ATTRIBUTE IP_Growth_Ratio NUMERIC\n" +
"@ATTRIBUTE class {Flux, NOT_Flux}\n\n" +
"@DATA\n";
private static final String MODEL_PATHKEY = "MODEL_PATH";
private String modelfile;
private DBInterface dbi;
private Properties localprops = null;
private static Log log = LogFactory.getLog(Classifier.class);
/**
* Instantiates a new classifier. The object is configured via
* the properties file.
*
* @throws IOException if there is an error reading the
* Classifer.properties file
*/
public Classifier() throws IOException{
this(DBInterfaceFactory.loadDBInterface());
}
/**
* Instantiates a new feature calculator with a specific database
* interface. The object is configured via the properties file.
*
* @param dbi the database interface
* @throws IOException if there is an error reading the
* Classifer.properties file
*/
public Classifier(DBInterface dbi) throws IOException{
if(localprops == null){
localprops = PropertiesUtils.loadProperties(this.getClass());
}
setModelPath(new File(localprops.getProperty(MODEL_PATHKEY))
.getCanonicalPath());
this.dbi = dbi;
}
/**
* Instantiates a new classifier.
*
* @param modelfile the path to the classification model file
*/
public Classifier(String modelfile){
this(modelfile, DBInterfaceFactory.loadDBInterface());
}
/**
* Instantiates a new feature calculator with a specific database
* interface.
*
* @param modelfile the absolute path to the classification model file
* @param dbi the database interface
*/
public Classifier(String modelfile, DBInterface dbi){
this.modelfile = modelfile;
this.dbi = dbi;
}
/**
* Sets the path to the trained J48 decision tree.
*
* @param modelfile the path to the serialized model
*/
public void setModelPath(String modelfile){
this.modelfile = modelfile;
}
/**
* Gets the path to the trained J48 decision tree.
*/
public String getModelPath(){
return this.modelfile;
}
/**
* Prepares the features from the db, executes the classifier, and
* stores the results in the database.
*
* @param logDate the clustering run date
* @param minCardinality the minimum network cardinality of clusters
* to classify
* @throws IOException if there is an error creating the features file
*/
public void updateClusterClasses(Date logDate, int minCardinality) throws IOException{
String simplename = null;
if(log.isInfoEnabled()){
simplename = this.getClass().getSimpleName();
log.info(simplename + " Started: "
+ Calendar.getInstance().getTime());
}
dbi.initClassificationTables(logDate);
Map<ClusterClass, List<StoredDomainCluster>> clusterClasses =
classifyClusters(logDate, minCardinality);
if(log.isDebugEnabled()){
String retval = "";
for(ClusterClass cls : clusterClasses.keySet()){
retval += "Cluster Class: " + cls + "\n";
for(StoredDomainCluster cluster : clusterClasses.get(cls)){
retval += "\t" + cluster.getClusterId() + "\n";
}
}
log.debug(retval);
}
storeClusterClasses(logDate, clusterClasses);
if(log.isInfoEnabled()){
log.info(simplename + " Finished: "
+ Calendar.getInstance().getTime());
}
}
/**
* Prepares the features from the db and executes the classifier.
*
* @param logDate the run date of the clusters
* @param minCardinality the minimum network cardinality for a cluster
* to be consider for classification
* @return a map of the classified clusters, the keys are the classes
* and the values are lists of cluster id's belonging to those classes
* @throws IOException
*/
public Map<ClusterClass, List<StoredDomainCluster>> classifyClusters(Date logDate,
int minCardinality) throws IOException{
Map<ClusterClass, List<StoredDomainCluster>> retval = null;
if(log.isDebugEnabled()){
log.debug("Retrieving features from db.");
}
List<StoredDomainCluster> clusters = dbi.getClusters(logDate, minCardinality);
if(log.isDebugEnabled()){
log.debug("Features retrieved.");
log.debug("Preparing features file.");
}
String prepfeatures = prepareFeatures(clusters);
if(log.isDebugEnabled()){
log.debug("File prepared.");
log.debug("Executing J48 classifier.");
}
retval = executeClassifier(prepfeatures, modelfile, clusters);
if(log.isDebugEnabled()){
log.debug("J48 execution complete.");
}
return retval;
}
/**
* Generates a String of the features in arff format
*
* @param clusters the list of clusters from which to pull features
* @return the arff format version of the features
*/
private String prepareFeatures(List<StoredDomainCluster> clusters){
StringBuffer buf = new StringBuffer();
buf.append(featuresHeader);
for(StoredDomainCluster cluster : clusters){
buf.append(cluster.getNetworkCardinality() + ", " + cluster.getIpDiversity() +
", " + cluster.getDomainsPerNetwork() + ", " + cluster.getNumberOfDomains() +
", " + cluster.getTtlPerDomain() + ", " + cluster.getIpGrowthRatio() +
", " + ClusterClass.NOT_FLUX + "\n");
}
return buf.toString();
}
/**
* Executes the classifier.
*
* @param prepfeatures the prepared features in arff format
* @param modelfile the path to the serialized model
* @param clusters the clusters to classify
* @return a map of the classified clusters, the keys are the classes
* and the values are lists of cluster id's belonging to those classes
*/
private Map<ClusterClass, List<StoredDomainCluster>> executeClassifier(String prepfeatures, String modelfile,
List<StoredDomainCluster> clusters){
Map<ClusterClass, List<StoredDomainCluster>> retval =
new HashMap<ClusterClass, List<StoredDomainCluster>>();
try{
DataSource source = new DataSource(new ByteArrayInputStream(prepfeatures.getBytes()));
Instances data = source.getDataSet();
if (data.classIndex() == -1){
data.setClassIndex(data.numAttributes() - 1);
}
String[] options = weka.core.Utils.splitOptions("-p 0");
J48 cls = (J48)weka.core.SerializationHelper.read(modelfile);
cls.setOptions(options);
for(int i = 0; i < data.numInstances(); i++){
double pred = cls.classifyInstance(data.instance(i));
ClusterClass clusClass = ClusterClass.valueOf(
data.classAttribute().value((int)pred).toUpperCase());
if(!retval.containsKey(clusClass)){
retval.put(clusClass, new ArrayList<StoredDomainCluster>());
}
retval.get(clusClass).add(clusters.get(i));
}
} catch (Exception e) {
if(log.isErrorEnabled()){
log.error("Error executing classifier.", e);
}
}
return retval;
}
/**
* Store cluster classes in the database.
*
* @param logDate the clustering run date
* @param clusterClasses the map of classified clusters
*/
private void storeClusterClasses(Date logDate, Map<ClusterClass, List<StoredDomainCluster>> clusterClasses){
dbi.storeClusterClasses(logDate, clusterClasses, false);
}
}
| gpl-2.0 |
EliaNekipeloff/Coursera | test/com/elianekipeloff/coursera/algorithms/TwoSumCounterTest.java | 1071 | package com.elianekipeloff.coursera.algorithms;
import org.junit.Test;
import static org.junit.Assert.*;
public class TwoSumCounterTest {
@Test
public void test1() throws Exception {
TwoSumCounter counter = new TwoSumCounter("array1.txt");
assertEquals(17, counter.countAll());
}
@Test
public void test10ElsWithHashSet() throws Exception {
TwoSumCounter counter = new TwoSumCounter("array2.txt");
assertEquals(5, counter.count(10));
}
@Test
public void test10ElsWithSort() throws Exception {
TwoSumCounter counter = new TwoSumCounter("array2.txt");
assertEquals(5, counter.countWithSort(10));
}
@Test
public void testRepeatedElsWithHashSet() throws Exception {
TwoSumCounter counter = new TwoSumCounter("array3.txt");
assertEquals(5, counter.count(10));
}
@Test
public void testRepeatedElsWithSort() throws Exception {
TwoSumCounter counter = new TwoSumCounter("array3.txt");
assertEquals(5, counter.countWithSort(10));
}
} | gpl-2.0 |
ancalotoru/Data-Mining | Práctica 5/Preprocess.java | 1061 | package org.md.practica5_Boosting;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.instance.Normalize;
import weka.filters.unsupervised.instance.Randomize;
import weka.filters.unsupervised.instance.RemoveRange;
public class Preprocess {
private Instances data;
public Preprocess(Instances pData){
data = pData;
}
public Instances filterRemoveRange(Instances data, String range) throws Exception{
RemoveRange remRange = new RemoveRange();
remRange.setInputFormat(data);
remRange.setInstancesIndices(range);
return Filter.useFilter(data, remRange);
}
public Instances filterRandomize(Instances data) throws Exception{
Randomize randomize = new Randomize();
randomize.setRandomSeed(42);
randomize.setInputFormat(data);
data = Filter.useFilter(data, randomize);
return data;
}
public Instances filterNormalize(Instances data) throws Exception{
Normalize normalize = new Normalize();
normalize.setInputFormat(data);
data = Filter.useFilter(data, normalize);
return data;
}
}
| gpl-2.0 |
vishalmanohar/databene-benerator | src/main/java/org/databene/benerator/consumer/FormattingConsumer.java | 3993 | /*
* (c) Copyright 2007-2011 by Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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.databene.benerator.consumer;
import org.databene.commons.Capitalization;
import org.databene.commons.converter.ToStringConverter;
/**
* Provides a datePattern property for child classes.<br/><br/>
* Created at 08.04.2008 07:18:17
* @since 0.5.1
* @author Volker Bergmann
*/
public abstract class FormattingConsumer extends AbstractConsumer {
protected ToStringConverter plainConverter = new ToStringConverter();
public String getNullString() {
return plainConverter.getNullString();
}
public void setNullString(String nullString) {
plainConverter.setNullString(nullString);
}
public String getDatePattern() {
return plainConverter.getDatePattern();
}
public void setDatePattern(String datePattern) {
plainConverter.setDatePattern(datePattern);
}
public Capitalization getDateCapitalization() {
return plainConverter.getDateCapitalization();
}
public void setDateCapitalization(Capitalization dateCapitalization) {
plainConverter.setDateCapitalization(dateCapitalization);
}
public String getDateTimePattern() {
return plainConverter.getDateTimePattern();
}
public void setDateTimePattern(String dateTimePattern) {
plainConverter.setDateTimePattern(dateTimePattern);
}
public String getTimestampPattern() {
return plainConverter.getTimestampPattern();
}
public void setTimestampPattern(String timestampPattern) {
plainConverter.setTimestampPattern(timestampPattern);
}
public Capitalization getTimestampCapitalization() {
return plainConverter.getTimestampCapitalization();
}
public void setTimestampCapitalization(Capitalization timestampCapitalization) {
plainConverter.setTimestampCapitalization(timestampCapitalization);
}
public String getDecimalPattern() {
return plainConverter.getDecimalPattern();
}
public void setDecimalPattern(String decimalPattern) {
plainConverter.setDecimalPattern(decimalPattern);
}
public char getDecimalSeparator() {
return plainConverter.getDecimalSeparator();
}
public void setDecimalSeparator(char decimalSeparator) {
plainConverter.setDecimalSeparator(decimalSeparator);
}
public String getTimePattern() {
return plainConverter.getTimePattern();
}
public void setTimePattern(String timePattern) {
plainConverter.setTimePattern(timePattern);
}
public String getIntegralPattern() {
return plainConverter.getIntegralPattern();
}
public void setIntegralPattern(String integralPattern) {
plainConverter.setIntegralPattern(integralPattern);
}
protected String format(Object o) {
return plainConverter.convert(o);
}
}
| gpl-2.0 |
PhilippPfeiffer/MultimediaTourEditor | src/main/java/pfeiffer/mte/api/FreebaseSearchClient.java | 6306 | /*
* © Copyright 2014, Philipp Pfeiffer
*
* This file is part of MultimediaTourEditor.
MultimediaTourEditor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MultimediaTourEditor 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 MultimediaTourEditor. If not, see <http://www.gnu.org/licenses/>.
*/
package pfeiffer.mte.api;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import pfeiffer.mte.entities.Wiki;
/**
* This class handles all communication with the Freebase web service. It
* sends an HTTP request for information about a city and receives several
* pieces of data in response. All data is encapsulated by a Wiki object.
* @author Philipp Pfeiffer
*/
public class FreebaseSearchClient {
public static String API_KEY = "AIzaSyCT9W_P2am39nyEdnSX13ap4ujJbLtXLU0";
/**
* Sends an HTTP Request to the Freebase web service and extracts the
* information that is received in the response. The data is encapsuled by
* a Wiki object, which is then returned
* @param searchTerm
* @param wiki
* @return Wiki Object with found data
*/
public Wiki search(String searchTerm, Wiki wiki, String locale) {
try {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
url.put("query", URLEncoder.encode(searchTerm, "utf8"));
url.put("type", "City/Town/Village");
url.put("limit", "1");
url.put("indent", "true");
url.put("filter", "(all type:/location/citytown type:/location/location type:/common/topic)");
url.put("output", "(/location/location/area /common/topic/description /location/statistical_region/population /location/location/containedby)");
if(locale.equals("EN")) {
url.put("lang", "d/en");
} else if(locale.equals("DE")) {
url.put("lang", "d/de");
} else {
url.put("lang", "d/en");
}
url.put("key", FreebaseSearchClient.API_KEY);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
JSONArray results = (JSONArray)response.get("result");
org.json.JSONObject result = new org.json.JSONObject(results.get(0).toString());
org.json.JSONObject output = new org.json.JSONObject(result.get("output").toString());
org.json.JSONObject populationObj = new org.json.JSONObject(output.get("/location/statistical_region/population").toString());
org.json.JSONObject areaObj = new org.json.JSONObject(output.get("/location/location/area").toString());
org.json.JSONObject containedByObj = new org.json.JSONObject(output.get("/location/location/containedby").toString());
org.json.JSONObject descriptionObj = new org.json.JSONObject(output.get("/common/topic/description").toString());
try{
org.json.JSONArray populationArray = populationObj.getJSONArray("/location/statistical_region/population");
String population = populationArray.getJSONObject(0).getString("value");
String populationDate = populationArray.getJSONObject(0).getString("date");
wiki.setPopulation(population, locale);
wiki.setPopulationDate(populationDate, locale);
} catch (Exception ex) {
wiki.setPopulation("No data found", locale);
wiki.setPopulationDate("", locale);
Logger.getLogger(GooglePlacesClient.class.getName()).log(Level.INFO, null, ex);
}
try{
org.json.JSONArray areaArray = areaObj.getJSONArray("/location/location/area");
String area = areaArray.getString(0);
wiki.setArea(area, locale);
} catch (Exception ex) {
wiki.setArea("No data found", locale);
Logger.getLogger(GooglePlacesClient.class.getName()).log(Level.INFO, null, ex);
}
try{
org.json.JSONArray containedByArray = containedByObj.getJSONArray("/location/location/containedby");
String containedBy = containedByArray.getJSONObject(0).getString("name");
wiki.setCountry(containedBy, locale);
} catch (Exception ex) {
wiki.setCountry("No data found", locale);
Logger.getLogger(GooglePlacesClient.class.getName()).log(Level.INFO, null, ex);
}
try{
org.json.JSONArray descriptionArray = descriptionObj.getJSONArray("/common/topic/description");
String description = descriptionArray.getString(0);
description = description.replaceAll("\n", "");
description = description.replaceAll("\"", "");
wiki.setDescription(description, true, locale);
} catch (Exception ex) {
wiki.setDescription("No data found", false, locale);
Logger.getLogger(GooglePlacesClient.class.getName()).log(Level.INFO, null, ex);
}
} catch (Exception ex) {
Logger.getLogger(GooglePlacesClient.class.getName()).log(Level.INFO, null, ex);
}
return wiki;
}
}
| gpl-2.0 |
gilmario-kpslow/sis-aluguel | src/main/java/br/com/gilmariosoftware/aluguel/controlealuguel/infra/modelos/Evento.java | 4588 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.gilmariosoftware.aluguel.controlealuguel.infra.modelos;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author gilmario
*/
@Entity
@Table(name = "evento")
public class Evento implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "evento", nullable = false)
private Long id;
@Column(name = "data_emitido", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date dataEmitido;
@Column(name = "data_evento")
@Temporal(TemporalType.TIMESTAMP)
private Date dataEvento;
@JoinColumn(name = "cliente", referencedColumnName = "cliente", nullable = false)
@ManyToOne
private Cliente cliente;
@Column(name = "valor", nullable = false)
private BigDecimal valor;
@Column(length = 1024)
private String observacao;
@Column(length = 150)
private String logradouro;
@Column(length = 20)
private String numero;
@Column(length = 40)
private String bairro;
@Column(length = 11)
private String cep;
@Column
private String complemento;
@JoinColumn(name = "cidade")
@ManyToOne
private Cidade cidade;
@Column(name = "hora_inicio")
@Temporal(TemporalType.TIME)
private Date horaInicio;
@Column(name = "hora_termino")
@Temporal(TemporalType.TIME)
private Date horaTermino;
public Evento() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDataEmitido() {
return dataEmitido;
}
public void setDataEmitido(Date dataEmitido) {
this.dataEmitido = dataEmitido;
}
public Date getDataEvento() {
return dataEvento;
}
public void setDataEvento(Date dataEvento) {
this.dataEvento = dataEvento;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public BigDecimal getValor() {
return valor;
}
public void setValor(BigDecimal valor) {
this.valor = valor;
}
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public Date getHoraInicio() {
return horaInicio;
}
public void setHoraInicio(Date horaInicio) {
this.horaInicio = horaInicio;
}
public Date getHoraTermino() {
return horaTermino;
}
public void setHoraTermino(Date horaTermino) {
this.horaTermino = horaTermino;
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
return Objects.equals(this.id, other.id);
}
@Override
public String toString() {
return "Aluguel{" + "cliente=" + cliente + '}';
}
}
| gpl-2.0 |
thatkide/lydia | Autosense/Autosense/src/main/java/com/autosenseapp/alertDialogs/NewPlaylistAlert.java | 2451 | package com.autosenseapp.alertDialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.autosenseapp.R;
import ca.efriesen.lydia_common.media.Playlist;
/**
* Created by eric on 1/14/2014.
*/
public class NewPlaylistAlert {
private static final String TAG = "lydia newplaylistalert";
private static int playlistId = -1;
public static AlertDialog.Builder build(final Activity activity, int... ids) {
LayoutInflater inflater = LayoutInflater.from(activity);
final View playlistView = inflater.inflate(R.layout.playlist_alert_dialog, null);
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final EditText name = (EditText) playlistView.findViewById(R.id.playlist_name);
final Playlist playlist;
// check if we've been passed a playlist id or not
if (ids.length > 0) {
playlistId = ids[0];
playlist = Playlist.get(activity, playlistId);
// we have an id, populate the edit text with the name
name.setText(playlist.getName());
} else {
playlist = new Playlist(activity);
playlist.setId(playlistId);
}
builder.setTitle(R.string.new_playlist)
.setView(playlistView)
.setCancelable(true)
.setPositiveButton(R.string.save,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
playlist.setName(name.getText().toString());
// hide the keyboard
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(name.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// hide the keyboard
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(name.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// hide the keyboard
dialogInterface.dismiss();
}
});
return builder;
}
}
| gpl-2.0 |
ritchieg9/ProgSys | Practica_4/src/Alojamiento.java | 2394 |
import java.util.StringTokenizer;
public class Alojamiento {
private String Etiqueta;
private String Instruccion;
private String Operando;
private String Dirr;
private String Local;
public Alojamiento (String Etiqueta, String Instruccion,String Operando, String Dirr, String Local){
super();
this.Etiqueta = Etiqueta;
this.Instruccion = Instruccion;
this.Operando = Operando;
this.Dirr = Dirr;
this.Local = Local;
}
public String getEtiqueta() {
return Etiqueta;
}
public void setEtiqueta(String Etiqueta) {
this.Etiqueta = Etiqueta;
}
public String getInstruccion() {
return Instruccion;
}
public void setInstruccion(String Instruccion) {
this.Instruccion = Instruccion;
}
public String getOperando() {
return Operando;
}
public void setOperando(String Operando) {
this.Operando = Operando;
}
public String getDirr() {
return Dirr;
}
public void setDir(String Dirr) {
this.Dirr = Dirr;
}
public String getLocal() {
return Local;
}
public void setLocal(String Local) {
this.Dirr = Local;
}
String imprimirVector (int nlinea) {
String Etiquetav = this.getEtiqueta();
String Instruccionv = this.getInstruccion();
String topoperando= this.getOperando();
String gdirr= this.getDirr();
String gcloca = this.getLocal();
StringTokenizer opersplit = new StringTokenizer(topoperando, ",");
String ardillacu= null;
int countoperando = 0;
System.out.println ("Etiqueta: " + Etiquetav);
System.out.println ("Instruccion: " + Instruccionv);
System.out.println ("Operando(s): " );
while(opersplit.hasMoreTokens()){
System.out.println(opersplit.nextToken());
countoperando++;
}
System.out.println ("Numero de Operandos: " + countoperando);
System.out.println ("Direccionamiento: " + gdirr);
System.out.println ("Contador Localidad : " + gcloca);
ardillacu=gcloca+"\t\t\t"+Etiquetav+"\t\t\t"+Instruccionv+"\t\t\t"+topoperando+"\n";
if(Instruccionv.compareTo("")==0){
return "";
}
else{
return ardillacu;
}
}
String escribir(){
String Etiquetav = this.getEtiqueta();
String gcloca = this.getLocal();
String ardillacu= "";
if(Etiquetav.compareTo("")==0){
}
else{
ardillacu=Etiquetav+"\t\t\t"+gcloca+"\n";
}
return ardillacu;
}
}
| gpl-2.0 |
dstepien/project-euler | src/ProjectEuler_7.java | 1118 | /**
* Project Euler - problem 7
* <p/>
* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
* we can see that the 6th prime is 13.
* <p/>
* What is the 10 001st prime number?
*
* @author Dawid Stępień <https://github.com/dstepien>
*/
import java.util.ArrayList;
import java.util.Iterator;
public class ProjectEuler_7 {
public static void main(String[] args) {
int nPrimeNumber = 10001;
int i = 2;
boolean noPrimeNumber;
ArrayList<Integer> primeNumbers = new ArrayList<Integer>(nPrimeNumber);
primeNumbers.add(i);
while (primeNumbers.size() < nPrimeNumber) {
i++;
noPrimeNumber = false;
Iterator iterator = primeNumbers.iterator();
while (!noPrimeNumber && iterator.hasNext()) {
if (i % (Integer) iterator.next() == 0)
noPrimeNumber = true;
}
if (!noPrimeNumber)
primeNumbers.add(i);
}
System.out.println("The 10 001st prime number is: " + (primeNumbers.get(primeNumbers.size() - 1)));
}
}
| gpl-2.0 |
dpisarenko/pcc-logic | src/main/java/at/silverstrike/pcc/api/xmlserialization/XmlSerializerFactory.java | 432 | /**
* This file is part of Project Control Center (PCC).
*
* PCC (Project Control Center) project is intellectual property of
* Dmitri Anatol'evich Pisarenko.
*
* Copyright 2010, 2011 Dmitri Anatol'evich Pisarenko
* All rights reserved
*
**/
package at.silverstrike.pcc.api.xmlserialization;
import ru.altruix.commons.api.conventions.Factory;
public interface XmlSerializerFactory extends Factory<XmlSerializer> {
}
| gpl-2.0 |
skyczhao/Tmail | src/com/tmail/client/LoginPanel.java | 5779 | package com.tmail.client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by tobin on 12/24/14.
*/
public class LoginPanel extends JPanel {
// outer container
ClientFrame frame;
// login information
JTextField username = new JTextField();
JPasswordField password = new JPasswordField();
JButton loginBut = new JButton();
JButton registBut = new JButton();
JLabel message = new JLabel();
/**
* login system
*
*/
private void login() {
String user = username.getText();
String pass = new String(password.getPassword());
// check authentication
boolean flag = frame.loginTMail(user, pass);
if (flag) {
frame.switchToMain();
}
else {
message.setText("Password error!");
}
}
/**
* set the button listener and keyboard listener
*
*/
private void setListener() {
// login click
this.loginBut.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
login();
}
});
// regist click
this.registBut.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
frame.switchToRegist();
}
});
// username enter to input password
this.username.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
password.requestFocus();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
// password enter to login
this.password.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// loginBut.doClick();
login();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
}
/**
* init the login window
*
*/
private void init() {
// init position
int begin = 10;
int height = 20;
int margin = 10;
int next = height + margin;
// set title
JPanel titPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel("Login into TMail");
// title.setHorizontalAlignment(SwingConstants.CENTER);
// title.setVerticalAlignment(SwingConstants.TOP);
titPane.add(title);
this.add(titPane, BorderLayout.NORTH);
// main
JPanel mainPane = new JPanel();
mainPane.setLayout(null);
// set username label
JLabel userLabel = new JLabel("Username:");
userLabel.setLabelFor(this.username);
userLabel.setBounds(30, begin, 90, height);
// set username input
this.username.setBounds(120, begin, 150, height);
mainPane.add(userLabel);
mainPane.add(this.username);
// set password label
JLabel passLabel = new JLabel("Password:");
passLabel.setLabelFor(this.password);
passLabel.setBounds(30, begin + next, 90, height);
// set password input
this.password.setBounds(120, begin + next, 150, height);
mainPane.add(passLabel);
mainPane.add(this.password);
// control panel
JPanel ctlPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
// login & register button
this.loginBut.setText("Log In");
this.registBut.setText("Sign Up");
ctlPane.add(this.loginBut);
ctlPane.add(this.registBut);
ctlPane.setBounds(30, begin + 2 * next, 240, 2 * height);
mainPane.add(ctlPane);
this.add(mainPane, BorderLayout.CENTER);
// message
JPanel msgPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
this.message.setText("Please input username & password");
this.message.setForeground(Color.RED);
msgPane.add(this.message);
this.add(msgPane, BorderLayout.SOUTH);
// set listener
this.setListener();
}
/**
* init login panel by outer frame
*
* @param frame
*/
public LoginPanel(ClientFrame frame) {
super(new BorderLayout());
// init outer container
this.frame = frame;
// init window
this.init();
}
/**
* reset current panel and reset outer frame
*
*/
public void clear() {
// width: 300 & height: 190
Toolkit toolkit = Toolkit.getDefaultToolkit();
int screenWidth = (int)toolkit.getScreenSize().getWidth();
int screenHeight = (int)toolkit.getScreenSize().getHeight();
int frameWidth = 300;
int frameHeight = 190;
this.frame.setSize(frameWidth, frameHeight);
// this.frame.setResizable(false);
this.frame.setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);
this.frame.validate();
// clear pane
this.username.setText("");
this.password.setText("");
this.message.setText("Please input username & password");
}
}
| gpl-2.0 |
ezScrum/ezScrum_1.7.2_export | test/ntut/csie/ezScrum/web/action/backlog/sprint/ShowAddExistedTask2Test.java | 5734 | package ntut.csie.ezScrum.web.action.backlog.sprint;
import java.io.File;
import java.io.IOException;
import ntut.csie.ezScrum.refactoring.manager.ProjectManager;
import ntut.csie.ezScrum.test.CreateData.AddStoryToSprint;
import ntut.csie.ezScrum.test.CreateData.AddTaskToStory;
import ntut.csie.ezScrum.test.CreateData.CreateProductBacklog;
import ntut.csie.ezScrum.test.CreateData.CreateProject;
import ntut.csie.ezScrum.test.CreateData.CreateSprint;
import ntut.csie.ezScrum.test.CreateData.DropTask;
import ntut.csie.ezScrum.test.CreateData.InitialSQL;
import ntut.csie.ezScrum.test.CreateData.ezScrumInfoConfig;
import ntut.csie.jcis.resource.core.IProject;
import servletunit.struts.MockStrutsTestCase;
public class ShowAddExistedTask2Test extends MockStrutsTestCase {
private CreateProject CP;
private CreateSprint CS;
private ezScrumInfoConfig config = new ezScrumInfoConfig();
private final String ACTION_PATH = "/showAddExistedTask2";
private IProject project;
public ShowAddExistedTask2Test(String testName) {
super(testName);
}
protected void setUp() throws Exception {
// 刪除資料庫
InitialSQL ini = new InitialSQL(config);
ini.exe();
// 新增一個測試專案
this.CP = new CreateProject(1);
this.CP.exeCreate();
this.project = this.CP.getProjectList().get(0);
// 新增一個Sprint
this.CS = new CreateSprint(1, this.CP);
this.CS.exe();
super.setUp();
// ================ set action info ========================
setContextDirectory( new File(config.getBaseDirPath()+ "/WebContent") );
setServletConfigFile("/WEB-INF/struts-config.xml");
setRequestPathInfo( this.ACTION_PATH );
ini = null;
}
protected void tearDown() throws IOException, Exception {
// 刪除資料庫
InitialSQL ini = new InitialSQL(config);
ini.exe();
// 刪除外部檔案
ProjectManager projectManager = new ProjectManager();
projectManager.deleteAllProject();
projectManager.initialRoleBase(this.config.getTestDataPath());
super.tearDown();
ini = null;
projectManager = null;
this.CP = null;
this.CS = null;
}
/**
* 測試沒有Droped Task的情況
*/
public void testShowAddExistTask_1() throws Exception {
// 加入1個Sprint
int sprintID = Integer.valueOf(this.CS.getSprintIDList().get(0));
// Sprint加入1個Story
AddStoryToSprint addStory_Sprint = new AddStoryToSprint(1, 1, sprintID, CP, CreateProductBacklog.TYPE_ESTIMATION);
addStory_Sprint.exe();
// Story加入1個Task
AddTaskToStory addTask_Story = new AddTaskToStory(1, 1, addStory_Sprint, CP);
addTask_Story.exe();
// ================ set request info ========================
String projectName = this.project.getName();
request.setHeader("Referer", "?PID=" + projectName);
// 設定Session資訊
request.getSession().setAttribute("UserSession", config.getUserSession());
request.getSession().setAttribute("Project", project);
// 設定新增Task所需的資訊
String expectedStoryID = "1";
String expectedSprintID = "1";
addRequestParameter("sprintID", expectedSprintID);
addRequestParameter("issueID", expectedStoryID);
// ================ 執行 action ======================
actionPerform();
// ================ assert ========================
verifyNoActionErrors();
verifyNoActionMessages();
StringBuilder expectedResponseText = new StringBuilder();
expectedResponseText.append("<Tasks></Tasks>");
String actualResponseText = response.getWriterBuffer().toString();
assertEquals(expectedResponseText.toString(), actualResponseText);
}
/**
* 測試有一個Droped Task的情況
*/
public void testShowAddExistTask_2() throws Exception {
// 加入1個Sprint
int sprintID = Integer.valueOf(this.CS.getSprintIDList().get(0));
// Sprint加入1個Story
AddStoryToSprint addStory_Sprint = new AddStoryToSprint(1, 1, sprintID, CP, CreateProductBacklog.TYPE_ESTIMATION);
addStory_Sprint.exe();
// Story加入1個Task
AddTaskToStory addTask_Story = new AddTaskToStory(1, 1, addStory_Sprint, CP);
addTask_Story.exe();
// drop Task from story
DropTask dropTask = new DropTask(CP, 1, 1, 2);
dropTask.exe();
// ================ set request info ========================
String projectName = this.project.getName();
request.setHeader("Referer", "?PID=" + projectName);
// 設定Session資訊
request.getSession().setAttribute("UserSession", config.getUserSession());
request.getSession().setAttribute("Project", project);
// 設定新增Task所需的資訊
String expectedTaskName = "TEST_TASK_1";
String expectedStoryID = "1";
String expectedSprintID = "1";
String expectedTaskEstimation= "1";
String expectedTaskNote = "TEST_TASK_NOTES_1";
addRequestParameter("sprintID", expectedSprintID);
addRequestParameter("issueID", expectedStoryID);
// ================ 執行 action ======================
actionPerform();
// ================ assert ========================
verifyNoActionErrors();
verifyNoActionMessages();
StringBuilder expectedResponseText = new StringBuilder();
expectedResponseText.append("<Tasks><Task><Id>").append(2)
.append("</Id><Link>/ezScrum/showIssueInformation.do?issueID=").append(2)
.append("</Link><Name>").append(expectedTaskName)
.append("</Name><Status>").append("new")
.append("</Status><Estimation>").append(expectedTaskEstimation)
.append("</Estimation><Actual>").append(0)
.append("</Actual><Handler></Handler><Partners></Partners><Notes>").append(expectedTaskNote)
.append("</Notes></Task></Tasks>");
String actualResponseText = response.getWriterBuffer().toString();
assertEquals(expectedResponseText.toString(), actualResponseText);
}
}
| gpl-2.0 |
timomwa/cmp | src/main/java/com/pixelandtag/api/CelcomHTTPAPI.java | 3686 | package com.pixelandtag.api;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.util.Queue;
import com.pixelandtag.cmp.entities.IncomingSMS;
import com.pixelandtag.entities.MTsms;
import com.pixelandtag.entities.Notification;
import com.pixelandtag.serviceprocessors.dto.ServiceProcessorDTO;
/**
*
* @author Timothy Mwangi
* @since 2nd Feb 2012.
*
* This interfaces the CELCOM over HTTP(S) API for sending messages.
* See the document - "CMP30 - HTTP(S) API Specification v2.04.pdf"
*
*/
public interface CelcomHTTPAPI extends Settings {
/**
* Sets the server timezone value
* @param server_timezone. Accepted for mia = -05:00, malaysia = +08:00
* @return
*/
public void setFr_tz(String server_timezone);
/**
* gets you the set Server timezone
* @return
*/
public String getFr_tz();
/**
* the destination timestamp malay = +08:00
* @param to_tz
*/
public void setTo_tz(String to_tz);
public String getTo_tz();
/**
* Logs an MT to the database
* @param mt - com.inmobia.celcom.MTsms
*/
public void logMT(MTsms mt);
/**
* When we receive a message, we should acknowledge it's receipt.
* We should send to the operator
* @param mo - com.inmobia.celcom.MO
*/
public void acknowledgeReceipt(IncomingSMS mo);
/**
* Update SMSStatLog.
*
* @param notif
*/
public void updateSMSStatLog(Notification notif);
/**
* Retrieves an MT
* @param cpm_txId - java.lang.String
* @return - com.inmobia.celcom.MTsms
*/
public MTsms findMT(String cpm_txId);
/**
* Deletes an mt from the "to-send" log
* @param id
*/
public boolean deleteMT(long id);
/**
*
* @param http_to_send_id - the Id of the message who'se queue status needs to be modified.
* If a message is in queue,then the boolean inQueue is set to true, else if its out of the queue, its set to false
* @param inQueue - true if the message is now in queue
* @return true if the process was successfull, false if it was not.
*/
public boolean changeQueueStatus(String http_to_send_id,boolean inQueue);
/**
* Marks a message to be in queue
* @param http_to_send_id - Id of the message record who'se queue status needs to be set as inqueue.
* @return true if operation was successfull.
* @throws java.lang.Exception
*/
public boolean markInQueue(long http_to_send_id) throws Exception;
/**
* Marks a message to be sent
* @param http_to_send_id - Id of the message record who'se queue status needs to be set as inqueue.
* @return true if operation was successfull.
*/
public boolean markSent(long http_to_send_id);
public boolean postponeMT(long http_to_send_id);
/**
* Converts String to hex string
* @param input
* @return
*/
//public String toHex(String input) throws UnsupportedEncodingException;
/**
* Checks if an SMS contains one or more unicode characters.
*/
public boolean containsUnicode(String sms);
public Queue<ServiceProcessorDTO> getServiceProcessors();
public void closeConnectionIfNecessary();
public boolean beingProcessedd(long http_to_send_id, boolean inqueue);
public void logResponse(String msisdn, String responseText);
public void myfinalize();
//public long generateNextTxId();
public String toUnicodeString(String sms);
public String toHex(String sms) throws UnsupportedEncodingException;
/**
* If we have MMSs waiting for an SMS to be billed, then we flag it as "paidFor"
* so that it's now sent.
* Sort of a relay mechanism
* @param notification
*/
public void flagMMSIfAny(Notification notification);
public Connection getConnection();
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/android/contacts/preference/DisplayOptionsPreferenceFragment.java | 1158 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.contacts.preference;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import com.android.contacts.R;
/**
* This fragment shows the preferences for the first header.
*/
public class DisplayOptionsPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preference_display_options);
}
}
| gpl-2.0 |
SCADA-LTS/Scada-LTS | src/com/serotonin/mango/rt/dataSource/nmea/NmeaDataSourceRT.java | 6197 | /*
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.serotonin.mango.rt.dataSource.nmea;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.mango.rt.dataImage.DataPointRT;
import com.serotonin.mango.rt.dataImage.PointValueTime;
import com.serotonin.mango.rt.dataImage.types.MangoValue;
import com.serotonin.mango.rt.dataSource.DataSourceUtils;
import com.serotonin.mango.rt.dataSource.EventDataSource;
import com.serotonin.mango.util.timeout.TimeoutClient;
import com.serotonin.mango.util.timeout.TimeoutTask;
import com.serotonin.mango.vo.dataSource.nmea.NmeaDataSourceVO;
import com.serotonin.timer.TimerTask;
import com.serotonin.web.i18n.LocalizableException;
import com.serotonin.web.i18n.LocalizableMessage;
/**
* @author Matthew Lohbihler
*/
public class NmeaDataSourceRT extends EventDataSource implements NmeaMessageListener, TimeoutClient {
public static final int DATA_SOURCE_EXCEPTION_EVENT = 1;
public static final int PARSE_EXCEPTION_EVENT = 2;
private final Log log = LogFactory.getLog(NmeaDataSourceRT.class);
private final NmeaDataSourceVO vo;
private NmeaReceiver nmeaReceiver;
private TimerTask resetTask;
public NmeaDataSourceRT(NmeaDataSourceVO vo) {
super(vo);
this.vo = vo;
}
//
// /
// / Lifecycle
// /
//
@Override
public void initialize() {
SerialParameters params = new SerialParameters();
params.setCommPortId(vo.getCommPortId());
params.setBaudRate(vo.getBaudRate());
params.setPortOwnerName("NMEA Data Source");
nmeaReceiver = new NmeaReceiver(this, params);
if (initNmea()) {
scheduleTimeout();
super.initialize();
}
}
@Override
public void terminate() {
super.terminate();
unscheduleTimeout();
termNmea();
}
synchronized private boolean initNmea() {
try {
nmeaReceiver.initialize();
// Deactivate any existing event.
returnToNormal(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis());
}
catch (Exception e) {
LocalizableMessage message = getSerialExceptionMessage(e, vo.getCommPortId());
raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, message);
log.debug("Error while initializing data source", e);
return false;
}
return true;
}
synchronized private void termNmea() {
nmeaReceiver.terminate();
}
//
// /
// / MessagingConnectionListener
// /
//
public void receivedException(Exception e) {
log.error("Exception from nmea receiver", e);
}
public void receivedMessage(NmeaMessage message) {
long time = System.currentTimeMillis();
unscheduleTimeout();
scheduleTimeout();
LocalizableMessage parseError = null;
synchronized (pointListChangeLock) {
for (DataPointRT dp : dataPoints) {
try {
receivedMessageImpl(dp, message, time);
}
catch (LocalizableException e) {
if (parseError == null)
parseError = e.getLocalizableMessage();
}
catch (Exception e) {
if (parseError == null)
parseError = new LocalizableMessage("event.exception2", dp.getVO().getName(), e.getMessage());
}
}
}
if (parseError != null)
raiseEvent(PARSE_EXCEPTION_EVENT, time, false, parseError);
}
private void receivedMessageImpl(DataPointRT dp, NmeaMessage message, long time) throws Exception {
NmeaPointLocatorRT locator = dp.getPointLocator();
String messageName = message.getName();
if (messageName == null)
return;
if (messageName.equals(locator.getMessageName())) {
// Message name match. Check if the field index is in bounds.
if (locator.getFieldIndex() <= message.getFieldCount()) {
// Get the field by index.
String valueStr = message.getField(locator.getFieldIndex());
// Convert the value
MangoValue value = DataSourceUtils.getValue(valueStr, locator.getDataTypeId(),
locator.getBinary0Value(), dp.getVO().getTextRenderer(), null, dp.getVO().getName());
// Save the new value
dp.updatePointValue(new PointValueTime(value, time));
}
else
throw new Exception("Field index " + locator.getFieldIndex()
+ " is out of bounds. Message field count is " + message.getFieldCount());
}
}
//
// /
// / TimeoutClient
// /
//
public void scheduleTimeout(long fireTime) {
// We haven't heard from the device for too long. Restart the listener.
termNmea();
if (initNmea())
scheduleTimeout();
}
private void scheduleTimeout() {
resetTask = new TimeoutTask(vo.getResetTimeout() * 1000, this);
}
private void unscheduleTimeout() {
TimerTask tt = resetTask;
if (tt != null)
tt.cancel();
}
}
| gpl-2.0 |
sdecri/SetMp3Tags | src/progetto/WindowTypeSetting.java | 3116 | package progetto;
import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class WindowTypeSetting extends JFrame implements ActionListener{
private static String LOOK_AND_FEEL;
//ATTRIBUTI
private JButton button_single;
private JButton button_block;
private JButton button_close;
private JButton button_restore;
//COSTRUTTORI
public WindowTypeSetting() {
super("Converter");
// Set L&F (Loo-n-Feel)
//System look & feel
LOOK_AND_FEEL="javax.swing.plaf.nimbus.NimbusLookAndFeel";
//LOOK_AND_FEEL=UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(LOOK_AND_FEEL);
}
catch (UnsupportedLookAndFeelException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
catch (InstantiationException e) {
// handle exception
}
catch (IllegalAccessException e) {
// handle exception
}
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);// associamo l'evento di chiusura al solito bottone di chiusura
setResizable(false);
setLocation(400, 275);//la finestra è posta al centro delo schermo
setSize(300, 150);//dimensioni della finestra: LARGHEZZA, ALTEZZA in pixel
//istanzio elementi
button_single=new JButton("Single file");
button_block=new JButton("More files");
button_restore=new JButton("Restore");
button_close=new JButton("Close");
//Inserisco gli elementi
add (new Label("Select type setting",Label.CENTER),BorderLayout.NORTH);
JPanel panel1 = new JPanel();
panel1.add(button_single);
panel1.add(button_block);
panel1.add(button_restore);
add(panel1,BorderLayout.CENTER);
JPanel panel2 = new JPanel();
panel2.add(button_close);
add(panel2,BorderLayout.SOUTH);
//associo l'ascoltatore di eventi agli elementi del frame
button_single.addActionListener(this);
button_block.addActionListener(this);
button_close.addActionListener(this);
button_restore.addActionListener(this);
setVisible(true);//rendo non visibile la finestra
}
@Override
public void actionPerformed(ActionEvent e) {
//Handle WavtoMp3 button action
if (e.getSource() == button_single) {
setVisible(false);
new WindowSetTagsMp3("Set tags of single mp3 file", this);
}
//Handle Mp3towav button action
else if (e.getSource() == button_block) {
setVisible(false);
new WindowSetTagsMp3MoreFiles("Set tags of more mp3 files", this);
}
//Handle restore button action
else if (e.getSource() == button_restore) {
setVisible(false);
new WindowRestoreBeckup("Resotre tags from beckup file", this);
}
//Handle Close button action
else if (e.getSource() == button_close) {
System.exit(0);
}
}
}
| gpl-2.0 |
MTrajK/Real-Time-Coin-Detection | Coin Detection/openCVLibrary2411/src/main/java/org/opencv/features2d/DescriptorExtractor.java | 9162 |
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.features2d;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.utils.Converters;
// C++: class javaDescriptorExtractor
/**
* <p>Abstract base class for computing descriptors for image keypoints.</p>
*
* <p>class CV_EXPORTS DescriptorExtractor <code></p>
*
* <p>// C++ code:</p>
*
*
* <p>public:</p>
*
* <p>virtual ~DescriptorExtractor();</p>
*
* <p>void compute(const Mat& image, vector<KeyPoint>& keypoints,</p>
*
* <p>Mat& descriptors) const;</p>
*
* <p>void compute(const vector<Mat>& images, vector<vector<KeyPoint> >& keypoints,</p>
*
* <p>vector<Mat>& descriptors) const;</p>
*
* <p>virtual void read(const FileNode&);</p>
*
* <p>virtual void write(FileStorage&) const;</p>
*
* <p>virtual int descriptorSize() const = 0;</p>
*
* <p>virtual int descriptorType() const = 0;</p>
*
* <p>static Ptr<DescriptorExtractor> create(const string& descriptorExtractorType);</p>
*
* <p>protected:...</p>
*
* <p>};</p>
*
* <p>In this interface, a keypoint descriptor can be represented as a </code></p>
*
* <p>dense, fixed-dimension vector of a basic type. Most descriptors follow this
* pattern as it simplifies computing distances between descriptors. Therefore,
* a collection of descriptors is represented as "Mat", where each row is a
* keypoint descriptor.</p>
*
* @see <a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html#descriptorextractor">DescriptorExtractor : public Algorithm</a>
*/
public class DescriptorExtractor {
protected final long nativeObj;
protected DescriptorExtractor(long addr) { nativeObj = addr; }
private static final int
OPPONENTEXTRACTOR = 1000;
public static final int
SIFT = 1,
SURF = 2,
ORB = 3,
BRIEF = 4,
BRISK = 5,
FREAK = 6,
OPPONENT_SIFT = OPPONENTEXTRACTOR + SIFT,
OPPONENT_SURF = OPPONENTEXTRACTOR + SURF,
OPPONENT_ORB = OPPONENTEXTRACTOR + ORB,
OPPONENT_BRIEF = OPPONENTEXTRACTOR + BRIEF,
OPPONENT_BRISK = OPPONENTEXTRACTOR + BRISK,
OPPONENT_FREAK = OPPONENTEXTRACTOR + FREAK;
//
// C++: void javaDescriptorExtractor::compute(Mat image, vector_KeyPoint& keypoints, Mat descriptors)
//
/**
* <p>Computes the descriptors for a set of keypoints detected in an image (first
* variant) or image set (second variant).</p>
*
* @param image Image.
* @param keypoints Input collection of keypoints. Keypoints for which a
* descriptor cannot be computed are removed and the remaining ones may be
* reordered. Sometimes new keypoints can be added, for example:
* <code>SIFT</code> duplicates a keypoint with several dominant orientations
* (for each orientation).
* @param descriptors Computed descriptors. In the second variant of the method
* <code>descriptors[i]</code> are descriptors computed for a <code>keypoints[i]</code>.
* Row <code>j</code> is the <code>keypoints</code> (or <code>keypoints[i]</code>)
* is the descriptor for keypoint <code>j</code>-th keypoint.
*
* @see <a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html#descriptorextractor-compute">DescriptorExtractor.compute</a>
*/
public void compute(Mat image, MatOfKeyPoint keypoints, Mat descriptors)
{
Mat keypoints_mat = keypoints;
compute_0(nativeObj, image.nativeObj, keypoints_mat.nativeObj, descriptors.nativeObj);
return;
}
//
// C++: void javaDescriptorExtractor::compute(vector_Mat images, vector_vector_KeyPoint& keypoints, vector_Mat& descriptors)
//
/**
* <p>Computes the descriptors for a set of keypoints detected in an image (first
* variant) or image set (second variant).</p>
*
* @param images Image set.
* @param keypoints Input collection of keypoints. Keypoints for which a
* descriptor cannot be computed are removed and the remaining ones may be
* reordered. Sometimes new keypoints can be added, for example:
* <code>SIFT</code> duplicates a keypoint with several dominant orientations
* (for each orientation).
* @param descriptors Computed descriptors. In the second variant of the method
* <code>descriptors[i]</code> are descriptors computed for a <code>keypoints[i]</code>.
* Row <code>j</code> is the <code>keypoints</code> (or <code>keypoints[i]</code>)
* is the descriptor for keypoint <code>j</code>-th keypoint.
*
* @see <a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html#descriptorextractor-compute">DescriptorExtractor.compute</a>
*/
public void compute(List<Mat> images, List<MatOfKeyPoint> keypoints, List<Mat> descriptors)
{
Mat images_mat = Converters.vector_Mat_to_Mat(images);
List<Mat> keypoints_tmplm = new ArrayList<Mat>((keypoints != null) ? keypoints.size() : 0);
Mat keypoints_mat = Converters.vector_vector_KeyPoint_to_Mat(keypoints, keypoints_tmplm);
Mat descriptors_mat = new Mat();
compute_1(nativeObj, images_mat.nativeObj, keypoints_mat.nativeObj, descriptors_mat.nativeObj);
Converters.Mat_to_vector_vector_KeyPoint(keypoints_mat, keypoints);
Converters.Mat_to_vector_Mat(descriptors_mat, descriptors);
return;
}
//
// C++: static javaDescriptorExtractor* javaDescriptorExtractor::create(int extractorType)
//
/**
* <p>Creates a descriptor extractor by name.</p>
*
* <p>The current implementation supports the following types of a descriptor
* extractor:</p>
* <ul>
* <li> <code>"SIFT"</code> -- "SIFT"
* <li> <code>"SURF"</code> -- "SURF"
* <li> <code>"BRIEF"</code> -- "BriefDescriptorExtractor"
* <li> <code>"BRISK"</code> -- "BRISK"
* <li> <code>"ORB"</code> -- "ORB"
* <li> <code>"FREAK"</code> -- "FREAK"
* </ul>
*
* <p>A combined format is also supported: descriptor extractor adapter name
* (<code>"Opponent"</code> -- "OpponentColorDescriptorExtractor") + descriptor
* extractor name (see above), for example: <code>"OpponentSIFT"</code>.</p>
*
* @param extractorType a extractorType
*
* @see <a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html#descriptorextractor-create">DescriptorExtractor.create</a>
*/
public static DescriptorExtractor create(int extractorType)
{
DescriptorExtractor retVal = new DescriptorExtractor(create_0(extractorType));
return retVal;
}
//
// C++: int javaDescriptorExtractor::descriptorSize()
//
public int descriptorSize()
{
int retVal = descriptorSize_0(nativeObj);
return retVal;
}
//
// C++: int javaDescriptorExtractor::descriptorType()
//
public int descriptorType()
{
int retVal = descriptorType_0(nativeObj);
return retVal;
}
//
// C++: bool javaDescriptorExtractor::empty()
//
public boolean empty()
{
boolean retVal = empty_0(nativeObj);
return retVal;
}
//
// C++: void javaDescriptorExtractor::read(string fileName)
//
public void read(String fileName)
{
read_0(nativeObj, fileName);
return;
}
//
// C++: void javaDescriptorExtractor::write(string fileName)
//
public void write(String fileName)
{
write_0(nativeObj, fileName);
return;
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: void javaDescriptorExtractor::compute(Mat image, vector_KeyPoint& keypoints, Mat descriptors)
private static native void compute_0(long nativeObj, long image_nativeObj, long keypoints_mat_nativeObj, long descriptors_nativeObj);
// C++: void javaDescriptorExtractor::compute(vector_Mat images, vector_vector_KeyPoint& keypoints, vector_Mat& descriptors)
private static native void compute_1(long nativeObj, long images_mat_nativeObj, long keypoints_mat_nativeObj, long descriptors_mat_nativeObj);
// C++: static javaDescriptorExtractor* javaDescriptorExtractor::create(int extractorType)
private static native long create_0(int extractorType);
// C++: int javaDescriptorExtractor::descriptorSize()
private static native int descriptorSize_0(long nativeObj);
// C++: int javaDescriptorExtractor::descriptorType()
private static native int descriptorType_0(long nativeObj);
// C++: bool javaDescriptorExtractor::empty()
private static native boolean empty_0(long nativeObj);
// C++: void javaDescriptorExtractor::read(string fileName)
private static native void read_0(long nativeObj, String fileName);
// C++: void javaDescriptorExtractor::write(string fileName)
private static native void write_0(long nativeObj, String fileName);
// native support for java finalize()
private static native void delete(long nativeObj);
}
| gpl-2.0 |
mosscode/appsnap | keeper/src/main/java/com/moss/appsnap/keeper/socketapi/ApiMessageConnection.java | 1986 | /**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of appsnap.
*
* appsnap 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, or (at your option)
* any later version.
*
* appsnap 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 appsnap; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
/**
*
*/
package com.moss.appsnap.keeper.socketapi;
import java.io.InputStream;
import java.io.OutputStream;
public interface ApiMessageConnection {
InputStream in();
OutputStream out();
void close();
} | gpl-2.0 |
zyz963272311/testGitHub | test-spring-boot/xyz.zyzhu.test-spring-boot/src/main/java/xyz/zyzhu/spring/boot/controller/DataExportController.java | 3195 | package xyz.zyzhu.spring.boot.controller;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.liiwin.utils.StrUtil;
import xyz.zyzhu.spring.boot.datafile.export.DataExport;
import xyz.zyzhu.spring.boot.datafile.export.ZipDataExport;
/**
* <p>标题: 数据导入导出定义与实现controller</p>
* <p>功能: </p>
* <p>所属模块: boot</p>
* <p>版权: Copyright © 2018 SNSOFT</p>
* <p>公司: 赵玉柱练习</p>
* <p>创建日期:2018年9月28日 下午1:45:56</p>
* <p>类全名:xyz.zyzhu.spring.boot.controller.DataExportAndImportController</p>
* 作者:赵玉柱
* 初审:
* 复审:
* 监听使用界面:
* @version 8.0
*/
@EnableAutoConfiguration
@RestController
@RequestMapping("/exp")
public class DataExportController
{
@RequestMapping(path = "/get")
public ModelAndView get()
{
ModelAndView view = new ModelAndView("exp");
return view;
}
/**
* 测试数据导出
* @param expcode
* @param type
* @return
* 赵玉柱
*/
@RequestMapping(path = "/dataExp", method = { RequestMethod.GET, RequestMethod.POST })
public void dataExp(@RequestParam(name = "expcode") String expcode, @RequestParam(name = "type", defaultValue = "1") int type, HttpServletResponse response)
{
DataExport ecport = null;
switch (type)
{
case 1:
ecport = new ZipDataExport();
break;
default:
throw new RuntimeException("不存在对应的类型");
}
String export = ecport.export(expcode);
if (!StrUtil.isStrTrimNull(export))
{
int p = export.lastIndexOf(File.separator);
String filename = null;
if (p > 0)
{
filename = export.substring(p + 1);
}
File file = new File(export);
if (file.exists() && file.isFile() && StrUtil.isNoStrTrimNull(filename))
{
response.setContentType("application/force-download");//设置文件为下载
response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try
{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1)
{
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e)
{
} finally
{
if (fis != null)
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
if (bis != null)
{
try
{
bis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
}
}
| gpl-2.0 |
digama0/mmj2 | src/mmj/transforms/EquivalenceInfo.java | 18638 | //*****************************************************************************/
//* Copyright (C) 2014 */
//* ALEXEY MERKULOV steelart (dot) alex (at) gmail (dot) com */
//* License terms: GNU General Public License Version 2 */
//* or any later version */
//*****************************************************************************/
package mmj.transforms;
import java.util.*;
import mmj.lang.*;
import mmj.pa.ProofStepStmt;
/**
* This class is used for equivalence transformations.
* <p>
* Note: Now there is a restriction: the library has to define only one
* equivalence operator for every type. In set.mm we have 2 types: wff, class.
*/
public class EquivalenceInfo extends DBInfo {
/** The map from type to corresponding equivalence operators */
private final Map<Cnst, Stmt> eqMap = new HashMap<>();
/**
* The list of commutative rules for equivalence operators: A = B => B = A
*/
private final Map<Stmt, Assrt> eqCommutatives = new HashMap<>();
/**
* The list of transitive rules for equivalence operators:
* <p>
* A = B & B = C => A = C
*/
private final Map<Stmt, Assrt> eqTransitivies = new HashMap<>();
/** The indicator that we collected rules in deduction form */
private boolean fillDeductRules = false;
/**
* The map from implication operator to the list of commutative deduction
* rules for equivalence operators:
* <p>
* p -> A = B => p -> B = A
*/
private final Map<Stmt, Map<Stmt, Assrt>> eqDeductCom = new HashMap<>();
/**
* The map from implication operator to the list of transitive deduction
* rules for equivalence operators:
* <p>
* p -> A = B & p -> B = C => p -> A = C
*/
private final Map<Stmt, Map<Stmt, Assrt>> eqDeductTrans = new HashMap<>();
// ------------------------------------------------------------------------
// ------------------------Initialization----------------------------------
// ------------------------------------------------------------------------
public EquivalenceInfo(final List<Assrt> assrtList, final TrOutput output,
final boolean dbg)
{
super(output, dbg);
for (final Assrt assrt : assrtList)
findEquivalenceCommutativeRules(assrt);
for (final Assrt assrt : assrtList)
findEquivalenceTransitiveRules(assrt);
filterOnlyEqRules();
}
public void fillDeductRules(final List<Assrt> assrtList,
final ImplicationInfo implInfo)
{
assert !fillDeductRules;
fillDeductRules = true;
final Collection<Stmt> implOps = implInfo.getImplForPrefixOperators();
for (final Stmt op : implOps) {
eqDeductCom.put(op, new HashMap<>());
eqDeductTrans.put(op, new HashMap<>());
}
for (final Assrt assrt : assrtList)
findEquivalenceCommutativeDeductionRules(assrt, implInfo);
for (final Assrt assrt : assrtList)
findEquivalenceTransitiveDeductionRules(assrt, implInfo);
for (final Stmt op : implOps) {
final Map<Stmt, Assrt> dedCom = eqDeductCom.get(op);
final Map<Stmt, Assrt> dedTrans = eqDeductTrans.get(op);
for (final Stmt eqOp : eqCommutatives.keySet()) {
if (!dedCom.containsKey(eqOp))
output.errorMessage(
TrConstants.ERRMSG_MISSING_EQUAL_COMMUT_DEDUCT_RULE, op,
eqOp);
if (!dedTrans.containsKey(eqOp))
output.errorMessage(
TrConstants.ERRMSG_MISSING_EQUAL_TRANSIT_DEDUCT_RULE,
op, eqOp);
}
}
}
/**
* Find commutative equivalence rules, like A = B => B = A
* <p>
*
* @param assrt the candidate
*/
private void findEquivalenceCommutativeRules(final Assrt assrt) {
final VarHyp[] varHypArray = assrt.getMandVarHypArray();
final LogHyp[] logHyps = assrt.getLogHypArray();
final ParseTree assrtTree = assrt.getExprParseTree();
if (logHyps.length != 1)
return;
final ParseTree hypTree = logHyps[0].getExprParseTree();
if (varHypArray.length != 2)
return;
if (hypTree.getMaxDepth() != 2)
return;
if (assrtTree.getMaxDepth() != 2)
return;
final ParseNode root = assrtTree.getRoot();
if (root.child.length != 2)
return;
final Stmt stmt = root.stmt;
final ParseNode hypRoot = hypTree.getRoot();
if (hypRoot.stmt != stmt)
return;
if (hypRoot.child[0].stmt != root.child[1].stmt)
return;
if (hypRoot.child[1].stmt != root.child[0].stmt)
return;
if (eqCommutatives.containsKey(stmt))
return;
output.dbgMessage(dbg, TrConstants.ERRMSG_EQUIV_COMM_ASSRTS, assrt,
assrt.getFormula());
eqCommutatives.put(stmt, assrt);
}
private void findEquivalenceTransitiveDeductionRules(final Assrt assrt,
final ImplicationInfo implInfo)
{
final VarHyp[] mandVarHypArray = assrt.getMandVarHypArray();
final LogHyp[] logHyps = assrt.getLogHypArray();
final ParseTree assrtTree = assrt.getExprParseTree();
if (logHyps.length != 2)
return;
final ParseTree hyp1Tree = logHyps[0].getExprParseTree();
final ParseTree hyp2Tree = logHyps[1].getExprParseTree();
if (mandVarHypArray.length != 3)
return;
if (hyp1Tree.getMaxDepth() != 3 || hyp2Tree.getMaxDepth() != 3)
return;
if (assrtTree.getMaxDepth() != 3)
return;
final ParseNode root = assrtTree.getRoot();
if (root.child.length != 2)
return;
final Stmt implOp = root.stmt;
if (!implInfo.isImplForPrefixOperator(implOp))
return;
final ParseNode hyp1Root = hyp1Tree.getRoot();
final ParseNode hyp2Root = hyp2Tree.getRoot();
if (hyp1Root.stmt != implOp)
return;
if (hyp2Root.stmt != implOp)
return;
final ParseNode prefix = root.child[0];
if (prefix.stmt != mandVarHypArray[0])
return;
final ParseNode hyp1Prefix = hyp1Root.child[0];
if (hyp1Prefix.stmt != mandVarHypArray[0])
return;
final ParseNode hyp2Prefix = hyp2Root.child[0];
if (hyp2Prefix.stmt != mandVarHypArray[0])
return;
final ParseNode core = root.child[1];
final ParseNode hyp1Core = hyp1Root.child[1];
final ParseNode hyp2Core = hyp2Root.child[1];
final Stmt stmt = core.stmt;
if (!isEquivalence(stmt))
return;
if (hyp1Core.stmt != stmt)
return;
if (hyp2Core.stmt != stmt)
return;
// check for 'A' in 'A = B & B = C => A = C'
if (hyp1Core.child[0].stmt != core.child[0].stmt)
return;
// check for 'B' in 'A = B & B = C'
if (hyp1Core.child[1].stmt != hyp2Core.child[0].stmt)
return;
// check for 'C' in 'A = B & B = C => A = C'
if (hyp2Core.child[1].stmt != core.child[1].stmt)
return;
Map<Stmt, Assrt> eqTransMap = eqDeductTrans.get(implOp);
if (eqTransMap == null) {
eqTransMap = new HashMap<>();
eqDeductTrans.put(implOp, eqTransMap);
}
if (eqTransMap.containsKey(stmt))
return;
output.dbgMessage(dbg, TrConstants.ERRMSG_EQUIV_TRANS_DED_ASSRTS, assrt,
assrt.getFormula());
eqTransMap.put(stmt, assrt);
}
/**
* Find transitive equivalence rules, like A = B & B = C => A = C
* <p>
*
* @param assrt the candidate
*/
private void findEquivalenceTransitiveRules(final Assrt assrt) {
final VarHyp[] mandVarHypArray = assrt.getMandVarHypArray();
final LogHyp[] logHyps = assrt.getLogHypArray();
final ParseTree assrtTree = assrt.getExprParseTree();
if (logHyps.length != 2)
return;
final ParseTree hyp1Tree = logHyps[0].getExprParseTree();
final ParseTree hyp2Tree = logHyps[1].getExprParseTree();
if (mandVarHypArray.length != 2)
return;
if (hyp1Tree.getMaxDepth() != 2 || hyp2Tree.getMaxDepth() != 2)
return;
if (assrtTree.getMaxDepth() != 2)
return;
final ParseNode root = assrtTree.getRoot();
if (root.child.length != 2)
return;
final Stmt stmt = root.stmt;
final ParseNode hyp1Root = hyp1Tree.getRoot();
final ParseNode hyp2Root = hyp2Tree.getRoot();
if (hyp1Root.stmt != stmt)
return;
if (hyp2Root.stmt != stmt)
return;
// check for 'A' in 'A = B & B = C => A = C'
if (hyp1Root.child[0].stmt != root.child[0].stmt)
return;
// check for 'B' in 'A = B & B = C'
if (hyp1Root.child[1].stmt != hyp2Root.child[0].stmt)
return;
// check for 'C' in 'A = B & B = C => A = C'
if (hyp2Root.child[1].stmt != root.child[1].stmt)
return;
if (eqTransitivies.containsKey(stmt))
return;
output.dbgMessage(dbg, TrConstants.ERRMSG_EQUIV_TRANS_ASSRTS, assrt,
assrt.getFormula());
eqTransitivies.put(stmt, assrt);
}
/**
* We found candidates for equivalence from commutative and transitive
* sides. Now compare results and remove unsuitable!
*/
private void filterOnlyEqRules() {
while (true) {
boolean changed = false;
for (final Stmt eq : eqTransitivies.keySet())
if (!eqCommutatives.containsKey(eq)) {
eqTransitivies.remove(eq);
changed = true;
break;
}
for (final Stmt eq : eqCommutatives.keySet())
if (!eqTransitivies.containsKey(eq)) {
eqCommutatives.remove(eq);
changed = true;
break;
}
if (!changed)
break;
}
// Debug output:
for (final Stmt eq : eqTransitivies.keySet())
output.dbgMessage(dbg, TrConstants.ERRMSG_EQUIV_RULES, eq,
eqCommutatives.get(eq).getFormula(),
eqTransitivies.get(eq).getFormula());
for (final Stmt eq : eqCommutatives.keySet()) {
final Assrt assrt = eqCommutatives.get(eq);
final ParseTree assrtTree = assrt.getExprParseTree();
final Cnst type = assrtTree.getRoot().child[0].stmt.getTyp();
if (eqMap.containsKey(type)) {
output.errorMessage(
TrConstants.ERRMSG_MORE_THEN_ONE_EQUALITY_OPERATOR, eq,
eqMap.get(type), type);
continue;
}
eqMap.put(type, eq);
output.dbgMessage(dbg, TrConstants.ERRMSG_TYPE_EQUIV, type, eq);
}
}
// can be tested on eqcomd
private void findEquivalenceCommutativeDeductionRules(final Assrt assrt,
final ImplicationInfo implInfo)
{
final VarHyp[] varHypArray = assrt.getMandVarHypArray();
final LogHyp[] logHyps = assrt.getLogHypArray();
final ParseTree assrtTree = assrt.getExprParseTree();
if (logHyps.length != 1)
return;
final ParseTree hypTree = logHyps[0].getExprParseTree();
if (varHypArray.length != 3)
return;
if (hypTree.getMaxDepth() != 3)
return;
if (assrtTree.getMaxDepth() != 3)
return;
final ParseNode root = assrtTree.getRoot();
if (root.child.length != 2)
return;
final Stmt implOp = root.stmt;
if (!implInfo.isImplForPrefixOperator(implOp))
return;
final ParseNode hypRoot = hypTree.getRoot();
if (hypRoot.stmt != implOp)
return;
final ParseNode prefix = root.child[0];
if (prefix.stmt != varHypArray[0])
return;
final ParseNode hypPrefix = hypRoot.child[0];
if (hypPrefix.stmt != varHypArray[0])
return;
final ParseNode core = root.child[1];
final ParseNode hypCore = hypRoot.child[1];
final Stmt stmt = core.stmt;
if (!isEquivalence(stmt))
return;
if (hypCore.stmt != stmt)
return;
assert core.child.length == 2;
if (hypCore.child[0].stmt != core.child[1].stmt)
return;
if (hypCore.child[1].stmt != core.child[0].stmt)
return;
Map<Stmt, Assrt> eqComMap = eqDeductCom.get(implOp);
if (eqComMap == null) {
eqComMap = new HashMap<>();
eqDeductCom.put(implOp, eqComMap);
}
if (eqComMap.containsKey(stmt))
return;
output.dbgMessage(dbg, TrConstants.ERRMSG_EQUIV_COMM_DED_ASSRTS, assrt,
assrt.getFormula());
eqComMap.put(stmt, assrt);
}
// ------------------------------------------------------------------------
// ------------------------Transformations---------------------------------
// ------------------------------------------------------------------------
/**
* Creates equivalence node (e.g. a = b )
*
* @param left the left node
* @param right the right node
* @return the equivalence node
*/
public ParseNode createEqNode(final ParseNode left, final ParseNode right) {
final Cnst type = left.stmt.getTyp();
assert type == right.stmt.getTyp();
final Stmt equalStmt = getEqStmt(type);
assert equalStmt != null;
final ParseNode res = TrUtil.createBinaryNode(equalStmt, left, right);
return res;
}
/**
* Creates reverse step for another equivalence step (e.g. b = a for a = b)
*
* @param info the work sheet info
* @param source the source (e.g. a = b)
* @return the reverse step
*/
public GenProofStepStmt createReverseStep(final WorksheetInfo info,
final GenProofStepStmt source)
{
/*
if (!source.hasPrefix())
return new GenProofStepStmt(createSimpleReverseStep(info,
source.getSimpleStep()), null);
*/
final ParseNode core = source.getCore();
final Stmt equalStmt = core.stmt;
final ParseNode left = core.child[0];
final ParseNode right = core.child[1];
ParseNode revNode = TrUtil.createBinaryNode(equalStmt, right, left);
final Assrt eqComm;
if (!source.hasPrefix())
eqComm = getEqCommutative(equalStmt);
else {
revNode = TrUtil.createBinaryNode(info.implStatement,
info.implPrefix, revNode);
eqComm = getEqDeductCommutative(info.implStatement, equalStmt);
}
assert eqComm != null;
final ProofStepStmt res = info.getOrCreateProofStepStmt(revNode,
new ProofStepStmt[]{source.getAnyStep()}, eqComm);
return new GenProofStepStmt(res, source.getPrefixOrNull());
}
/**
* This function creates transitive inference for two steps (= is the
* example of equivalence operator).
*
* @param info the work sheet info
* @param first the first statement (e.g. a = b )
* @param second the second statement (e.g. b = c )
* @return the result statement (e.g. a = c )
*/
public GenProofStepStmt getTransitiveStep(final WorksheetInfo info,
final GenProofStepStmt first, final GenProofStepStmt second)
{
if (first == null)
return second;
final ParseNode firstCore = first.getCore();
final ParseNode secondCore = second.getCore();
final Stmt equalStmt = firstCore.stmt;
assert equalStmt == secondCore.stmt;
assert firstCore.child[1].isDeepDup(secondCore.child[0]);
ParseNode resNode = TrUtil.createBinaryNode(equalStmt,
firstCore.child[0], secondCore.child[1]);
ParseNode prefix = null;
ProofStepStmt firstStep = first.getAnyStep();
ProofStepStmt secondStep = second.getAnyStep();
final Assrt transitive;
if (first.hasPrefix() || second.hasPrefix()) {
prefix = info.implPrefix;
if (!first.hasPrefix())
firstStep = info.trManager.implInfo.applyStubRule(info,
firstStep);
if (!second.hasPrefix())
secondStep = info.trManager.implInfo.applyStubRule(info,
secondStep);
transitive = getEqDeductTransitive(info.implStatement, equalStmt);
resNode = TrUtil.createBinaryNode(info.implStatement,
info.implPrefix, resNode);
}
else
transitive = getEqTransitive(equalStmt);
final ProofStepStmt resStmt = info.getOrCreateProofStepStmt(resNode,
new ProofStepStmt[]{firstStep, secondStep}, transitive);
return new GenProofStepStmt(resStmt, prefix);
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public boolean isEquivalence(final Stmt stmt) {
return eqMap.containsValue(stmt);
}
public Stmt getEqStmt(final Cnst type) {
return eqMap.get(type);
}
private Assrt getEqCommutative(final Stmt stmt) {
return eqCommutatives.get(stmt);
}
private Assrt getEqTransitive(final Stmt stmt) {
return eqTransitivies.get(stmt);
}
private Assrt getEqDeductCommutative(final Stmt implOp, final Stmt eqOp) {
final Map<Stmt, Assrt> dedCom = eqDeductCom.get(implOp);
if (dedCom == null)
return null;
return dedCom.get(eqOp);
}
private Assrt getEqDeductTransitive(final Stmt implOp, final Stmt eqOp) {
final Map<Stmt, Assrt> dedTrans = eqDeductTrans.get(implOp);
if (dedTrans == null)
return null;
return dedTrans.get(eqOp);
}
}
| gpl-2.0 |
166MMX/openjdk.java.net-openjfx-8u40-rt | modules/graphics/src/main/java/com/sun/prism/PresentableState.java | 8327 | /*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.prism;
import com.sun.glass.ui.Application;
import com.sun.glass.ui.Pixels;
import com.sun.glass.ui.Screen;
import com.sun.glass.ui.View;
import com.sun.glass.ui.Window;
/**
* PresentableState is intended to provide for a shadow copy of View/Window
* state for use off the event thread. It is the task of the invoker of
* Prism to make sure that the state is consistent for a rendering probably
* by use of the AbstractPainter.renderLock to ensure consistent state.
*/
public class PresentableState {
/** The underlying Window and View */
protected Window window;
protected View view;
// Captured state
protected int windowX, windowY;
protected float windowAlpha;
protected long nativeWindowHandle;
protected long nativeView;
protected int viewWidth, viewHeight;
protected int screenHeight;
protected int screenWidth;
protected boolean isWindowVisible;
protected boolean isWindowMinimized;
protected float screenScale;
protected static boolean hasWindowManager =
Application.GetApplication().hasWindowManager();
// Between PaintCollector and *Painter, there is a window where
// the associated View can be closed. This variable allows us
// to shortcut the queued *Painter task.
protected boolean isClosed;
protected final int pixelFormat = Pixels.getNativeFormat();
/** Create a PresentableState based on a View.
*
* Must be called on the event thread.
*/
public PresentableState() {
}
/**
* The screen relative window X
* @return The screen relative window X
*
* May be called on any thread.
*/
public int getWindowX() {
return windowX;
}
/**
* The screen relative window Y
* @return The screen relative window Y
*
* May be called on any thread.
*/
public int getWindowY() {
return windowY;
}
/**
* @return the width of the View
*
* May be called on any thread.
*/
public int getWidth() {
return viewWidth;
}
/**
* @return the height of the View
*
* May be called on any thread.
*/
public int getHeight() {
return viewHeight;
}
/**
* @return Screen.getScale
*
* May be called on any thread
*/
public float getScale() {
return screenScale;
}
/**
* @return the window's alpha level
*
* May be called on any thread.
*/
public float getAlpha() {
return windowAlpha;
}
/**
* @return the native handle of the window represented by this
* PresentableState
*
* May be called on any thread.
*/
public long getNativeWindow() {
return nativeWindowHandle;
}
/**
* @return the native handle of the View represented by this
* PresentableState
*
* May be called on any thread.
*/
public long getNativeView() {
return nativeView;
}
/**
* @return the current height of the screen
*
* May be called on any thread.
*/
public int getScreenHeight() {
return screenHeight;
}
/**
* @return the current width of the screen
*
* May be called on any thread.
*/
public int getScreenWidth() {
return screenWidth;
}
/**
* @return true if the underlying View is closed, false otherwise
*
* May be called on any thread.
*/
public boolean isViewClosed() {
return isClosed;
}
/**
* @return true if the underlying Window is minimized, false otherwise
*
* May be called on any thread.
*/
public boolean isWindowMinimized() {
return isWindowMinimized;
}
/**
* @return true if the underlying Window is Visible, false otherwise
*
* May be called on any thread.
*/
public boolean isWindowVisible() {
return isWindowVisible;
}
/**
* @return true if the underlying window is managed by a window manager
* external to JavaFX
*
* May be called on any thread.
*/
public boolean hasWindowManager() {
return hasWindowManager;
}
/**
* @return the underlying Window
*
* May be called on any thread.
*/
public Window getWindow() {
return window;
}
public boolean isMSAA() { return false; }
/**
* @return the underlying View
*
* May be called on any thread.
*/
public View getView() {
return view;
}
/**
* @return native pixel format
*
* May be called on any thread.
*/
public int getPixelFormat() {
return pixelFormat;
}
/**
* Locks the underlying view for rendering
*
* May be called on any thread.
*/
public void lock() {
if (view != null) view.lock();
}
/**
* Unlocks the underlying view after rendering
*
* May be called on any thread.
*/
public void unlock() {
if (view != null) view.unlock();
}
/**
* Put the pixels on the screen.
*
* @param source - the source for the Pixels object to be uploaded
*/
public void uploadPixels(PixelSource source) {
Pixels pixels = source.getLatestPixels();
if (pixels != null) {
try {
view.uploadPixels(pixels);
} finally {
source.doneWithPixels(pixels);
}
}
}
/** Updates the state of this object based on the current state of its
* nativeWindow.
*
* May only be called from the event thread.
*/
public void update() {
// should only be called on the event thread
if (view != null) {
viewWidth = view.getWidth();
viewHeight = view.getHeight();
window = view.getWindow();
} else {
viewWidth = viewHeight = -1;
window = null;
}
if (window != null) {
windowX = window.getX();
windowY = window.getY();
windowAlpha = window.getAlpha();
nativeView = view.getNativeView();
nativeWindowHandle = window.getNativeWindow();
isClosed = view.isClosed();
isWindowVisible = window.isVisible();
isWindowMinimized = window.isMinimized();
Screen screen = window.getScreen();
if (screen != null) {
// note only used by Embedded Z order painting
// !hasWindowManager so should be safe to ignore
// when null, most likely because of "In Browswer"
screenHeight = screen.getHeight();
screenWidth = screen.getWidth();
screenScale = screen.getScale();
} else {
screenScale = 1.f;
}
} else {
//TODO - should other variables be cleared?
nativeView = -1;
nativeWindowHandle = -1;
isClosed = true;
}
}
}
| gpl-2.0 |
chaosfoal/Coref | src/lv/pipe/MorphoTagger.java | 9251 | /*******************************************************************************
* Copyright 2014,2015 Institute of Mathematics and Computer Science, University of Latvia
* Author: Artūrs Znotiņš
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package lv.pipe;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import lv.label.Annotation;
import lv.label.Labels.LabelIndex;
import lv.label.Labels.LabelMorphoFeatures;
import lv.label.Labels.LabelParagraphs;
import lv.label.Labels.LabelPosTag;
import lv.label.Labels.LabelSentences;
import lv.label.Labels.LabelPosTagSimple;
import lv.label.Labels.LabelText;
import lv.label.Labels.LabelTokens;
import lv.lumii.morphotagger.Dictionary;
import lv.semti.morphology.analyzer.Word;
import lv.semti.morphology.analyzer.Wordform;
import lv.semti.morphology.attributes.AttributeNames;
import edu.stanford.nlp.ie.ner.CMMClassifier;
import edu.stanford.nlp.ling.CoreAnnotations.AnswerAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.LVMorphologyAnalysis;
import edu.stanford.nlp.ling.CoreAnnotations.TextAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.Datum;
import edu.stanford.nlp.sequences.LVMorphologyReaderAndWriter;
@SuppressWarnings("unchecked")
public class MorphoTagger implements PipeTool {
private final static Logger log = Logger.getLogger(MorphoTagger.class.getName());
private static boolean MINI_TAG = false;
private static boolean FEATURES = false;
private static boolean LETA_FEATURES = true;
private static CMMClassifier<CoreLabel> morphoClassifier;
private static MorphoTagger instance;
public static MorphoTagger getInstance() {
if (instance == null)
instance = new MorphoTagger();
return instance;
}
public void init(Properties prop) {
try {
morphoClassifier = CMMClassifier.getClassifier(prop.getProperty("morpho.classifierPath", ""));
} catch (ClassCastException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Annotation process(Annotation doc) {
if (doc.has(LabelParagraphs.class)) {
List<Annotation> pLabels = doc.get(LabelParagraphs.class);
for (Annotation pLabel : pLabels) {
processParagraph(pLabel);
}
}
return doc;
}
public Annotation processParagraph(Annotation paragraph) {
if (paragraph.has(LabelSentences.class)) {
List<Annotation> sLabels = paragraph.get(LabelSentences.class);
for (Annotation sLabel : sLabels) {
processSentence(sLabel);
}
}
return paragraph;
}
public Annotation processSentence(Annotation sentence) {
if (sentence.has(LabelTokens.class)) {
List<Annotation> tokens = sentence.get(LabelTokens.class);
// This is not working returns all "xf":
// List<Word> sent = new ArrayList<Word>(tokens.size());
// for (Annotation token : tokens) {
// String word = token.get(TextLabel.class);
// sent.add(new Word(word));
// }
// List<CoreLabel> coreLabels =
// LVMorphologyReaderAndWriter.analyzeSentence2(sent);
List<CoreLabel> sent = new ArrayList<CoreLabel>(tokens.size());
for (Annotation token : tokens) {
String word = token.get(LabelText.class);
CoreLabel wi = new CoreLabel();
wi.setWord(word);
sent.add(wi);
}
CoreLabel sEnd = new CoreLabel();
sEnd.setWord("<s>");
sent.add(sEnd);
List<CoreLabel> coreLabels = LVMorphologyReaderAndWriter.analyzeLabels(sent);
morphoClassifier.classify(coreLabels);
sentence.remove(LabelTokens.class);
List<Annotation> tLabels = new ArrayList<Annotation>(coreLabels.size());
int counter = 1;
for (CoreLabel w : coreLabels) {
Annotation tLabel = new Annotation();
String token = w.getString(TextAnnotation.class);
// token = token.replace(' ', '_');
if (token.contains("<s>"))
continue;
tLabel.setText(token);
tLabel.set(LabelIndex.class, counter++);
Word analysis = w.get(LVMorphologyAnalysis.class);
Wordform mainwf = analysis.getMatchingWordform(w.getString(AnswerAnnotation.class), false);
if (mainwf != null) {
String lemma = mainwf.getValue(AttributeNames.i_Lemma);
// lemma = lemma.replace(' ', '_');
if (lemma == null || lemma.trim().isEmpty()) {
lemma = "_";
log.log(Level.SEVERE, "Empty lemma for {0}", token);
}
tLabel.setLemma(lemma);
String answer = w.getString(AnswerAnnotation.class);
if (answer == null || answer.trim().isEmpty()) {
answer = "_"; // no empty tag
log.log(Level.SEVERE, "Empty simple pos tag for {0}", token);
}
tLabel.set(LabelPosTagSimple.class, answer);
String posTag = mainwf.getTag();
if (posTag == null || posTag.trim().isEmpty()) {
posTag = "_";
log.log(Level.SEVERE, "Empty pos tag for {0}", token);
}
tLabel.set(LabelPosTag.class, posTag);
// Feature atribūtu filtri
if (MINI_TAG)
mainwf.removeNonlexicalAttributes();
if (LETA_FEATURES) {
addLETAfeatures(mainwf);
// mainwf.removeAttribute(AttributeNames.i_SourceLemma);
// FIXME - atvasinātiem vārdiem šis var būt svarīgs,
// atpriedekļotas lemmas..
mainwf.removeTechnicalAttributes();
}
// vārda fīčas
StringBuilder s = mainwf.pipeDelimitedEntries();
if (FEATURES) {
// visas fīčas, ko lietoja trenējot
Datum<String, String> d = morphoClassifier.makeDatum(coreLabels, counter,
morphoClassifier.featureFactory);
for (String feature : d.asFeatures()) {
// noņemam trailing |C, kas tām fīčām tur ir
s.append(feature.substring(0, feature.length() - 2).replace(' ', '_'));
s.append('|');
}
}
// noņemam peedeejo | separatoru, kas ir lieks
s.deleteCharAt(s.length() - 1);
s.append('\t');
String morphoFeatures = s.toString();
tLabel.set(LabelMorphoFeatures.class, morphoFeatures);
} else {
log.log(Level.SEVERE, "Empty main word form for {0}", token);
}
tLabels.add(tLabel);
}
sentence.set(LabelTokens.class, tLabels);
}
return sentence;
}
private static void addLETAfeatures(Wordform wf) {
String lemma = wf.getValue(AttributeNames.i_Lemma);
if (wf.isMatchingStrong(AttributeNames.i_PartOfSpeech, AttributeNames.i_Number)) {
// uzskatam ka nav atšķirības starp skaitļiem ja ciparu skaits
// vienāds
String numbercode = lemma.replaceAll("\\d", "0");
wf.addAttribute("LETA_lemma", numbercode);
} else if (wf.isMatchingStrong(AttributeNames.i_CapitalLetters, AttributeNames.v_FirstUpper)
&& Dictionary.dict("surnames").contains(lemma))
wf.addAttribute("LETA_lemma", "_surname_");
else if (Dictionary.dict("vocations").contains(lemma))
wf.addAttribute("LETA_lemma", "_vocation_");
else if (Dictionary.dict("relations").contains(lemma))
wf.addAttribute("LETA_lemma", "_relationship_");
else if (Dictionary.dict("partijas").contains(lemma))
wf.addAttribute("LETA_lemma", "_party_");
/*
* TODO - nočekot kā visā procesā sanāk ar case-sensitivity, te tas ir
* svarīgi
*/
else if (Dictionary.dict("months").contains(lemma))
/*
* TODO - te būtu jāčeko, lai personvārdi Marts un Jūlijs te
* neapēdas, ja ir ar lielo burtu ne teikuma sākumā
*/
wf.addAttribute("LETA_lemma", "_month_");
else if (Dictionary.dict("common_lemmas").contains(lemma))
wf.addAttribute("LETA_lemma", lemma);
else
wf.addAttribute("LETA_lemma", "_rare_");
}
public static void main(String[] args) {
Tokenizer tok = Tokenizer.getInstance();
Annotation doc = tok
.process("Uzņēmuma SIA \"Cirvis\" prezidents Jānis Bērziņš. Viņš uzņēmumu vada no 2015. gada.");
MorphoTagger morpho = MorphoTagger.getInstance();
Properties morphoProp = new Properties();
morphoProp.setProperty("morpho.classifierPath", "models/lv-morpho-model.ser.gz");
morphoProp.setProperty("malt.workingDir", "./models");
morphoProp.setProperty("malt.extraParams", "-m parse -lfi parser.log");
morpho.init(morphoProp);
morpho.process(doc);
System.err.println(doc.toStringPretty());
}
}
| gpl-2.0 |
crotwell/fissuresUtil | src/main/java/edu/sc/seis/fissuresUtil/display/ParticleMotionDisplay.java | 11178 | package edu.sc.seis.fissuresUtil.display;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.iris.Fissures.IfEvent.EventAccessOperations;
import edu.iris.Fissures.IfEvent.NoPreferredOrigin;
import edu.iris.Fissures.IfEvent.Origin;
import edu.iris.Fissures.IfNetwork.Channel;
import edu.iris.Fissures.IfNetwork.ChannelId;
import edu.iris.Fissures.IfNetwork.Station;
import edu.sc.seis.TauP.SphericalCoords;
import edu.sc.seis.fissuresUtil.display.registrar.AmpConfig;
import edu.sc.seis.fissuresUtil.display.registrar.AmpEvent;
import edu.sc.seis.fissuresUtil.display.registrar.TimeConfig;
import edu.sc.seis.fissuresUtil.freq.NamedFilter;
import edu.sc.seis.fissuresUtil.xml.DataSet;
import edu.sc.seis.fissuresUtil.xml.DataSetSeismogram;
/**
*
* Created: Tue Jun 11 15:22:30 2002
*
* @author <a href="mailto:">Srinivasa Telukutla</a>
* @version
*/
public class ParticleMotionDisplay extends JPanel{
public ParticleMotionDisplay(DataSetSeismogram datasetSeismogram,
TimeConfig tc, Color color) {
particleDisplayPanel = new JPanel(new BorderLayout());
radioPanel = new JPanel(new GridLayout(1, 0));
setLayout(new BorderLayout());
view = new ParticleMotionView(this);
view.setSize(new Dimension(300, 300));
particleDisplayPanel.add(view);
hAmpScaleMap = new UpdatingAmpScaleMapper(50, 4);
vAmpScaleMap = new UpdatingAmpScaleMapper(50, 4);
ScaleBorder scaleBorder = new ScaleBorder();
scaleBorder.setBottomScaleMapper(hAmpScaleMap);
scaleBorder.setLeftScaleMapper(vAmpScaleMap);
hTitleBorder = new BottomTitleBorder("X - axis Title");
vTitleBorder = new LeftTitleBorder("Y - axis Title");
Border titleBorder = BorderFactory.createCompoundBorder(hTitleBorder,
vTitleBorder);
Border bevelBorder = BorderFactory.createRaisedBevelBorder();
Border bevelTitleBorder = BorderFactory.createCompoundBorder(bevelBorder,
titleBorder);
Border lowBevelBorder = BorderFactory.createLoweredBevelBorder();
Border scaleBevelBorder = BorderFactory.createCompoundBorder(scaleBorder,
lowBevelBorder);
particleDisplayPanel.setBorder(BorderFactory.createCompoundBorder(bevelTitleBorder,
scaleBevelBorder));
add(particleDisplayPanel);
radioPanel.setVisible(false);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
resize();
}
public void componentShown(ComponentEvent e) {
resize();
}
});
ParticleMotionDisplayThread t = new ParticleMotionDisplayThread(datasetSeismogram,
tc,
this, color);
t.execute();
formRadioSetPanel();
initialized = t.getCompletion();
if(initialized){
setInitialButton();
}
add(radioPanel, BorderLayout.SOUTH);
}
private class UpdatingAmpScaleMapper extends AmpScaleMapper{
public UpdatingAmpScaleMapper(int totalPixels, int hintPixels){
super(totalPixels, hintPixels);
}
public void updateAmp(AmpEvent e){
setUnitRange(e.getAmp());
repaint();}
}
public void setActiveAmpConfig(AmpConfig ac) {
hAmpScaleMap.setAmpConfig(ac);
vAmpScaleMap.setAmpConfig(ac);
}
public ParticleMotionView getView(){ return view; }
/**
* the method resize() is overridden so that the view of the
* particleMotionDisplay is always a square.
*/
public synchronized void resize() {
if(getSize().width == 0 || getSize().height == 0) return;
Dimension dim = view.getSize();
Insets insets = view.getInsets();
int width = particleDisplayPanel.getSize().width;
int height = particleDisplayPanel.getSize().height;
width = width - particleDisplayPanel.getInsets().left - particleDisplayPanel.getInsets().right;
height = height - particleDisplayPanel.getInsets().top - particleDisplayPanel.getInsets().bottom;
if(width < height) {
particleDisplayPanel.setSize(new Dimension(particleDisplayPanel.getSize().width,
width + particleDisplayPanel.getInsets().top + particleDisplayPanel.getInsets().bottom));
} else {
particleDisplayPanel.setSize(new Dimension(height + particleDisplayPanel.getInsets().left + particleDisplayPanel.getInsets().right,
particleDisplayPanel.getSize().height));
}
view.resize();
if(hAmpScaleMap != null) {
hAmpScaleMap.setTotalPixels(dim.width - insets.left - insets.right);
vAmpScaleMap.setTotalPixels(dim.height - insets.top - insets.bottom);
}
repaint();
}
public synchronized void addParticleMotionDisplay(DataSetSeismogram datasetSeismogram,
TimeConfig tc, Color color) {
ParticleMotionDisplayThread t = new ParticleMotionDisplayThread(datasetSeismogram,
tc,
this, color);
t.execute();
}
/**
* calculates the backAzimuthAngle and displays the azimuth angle and a sector surrouding
* the azimuth angle.
*
* @param dataset an <code>edu.sc.seis.fissuresUtil.xml.DataSet</code> value
* @param chanId a <code>ChannelId</code> value
*/
public synchronized void displayBackAzimuth(DataSet dataset, ChannelId chanId, Color color) {
EventAccessOperations cacheEvent = dataset.getEvent();
Channel channel = dataset.getChannel(chanId);
if(cacheEvent != null) {
try {
Origin origin = cacheEvent.get_preferred_origin();
Station station = channel.getSite().getStation();
double azimuth = SphericalCoords.azimuth(station.getLocation().latitude,
station.getLocation().longitude,
origin.getLocation().latitude,
origin.getLocation().longitude);
double angle = 90 - azimuth;
view.addAzimuthLine(angle, color);
view.addSector(angle+5, angle-5);
} catch(NoPreferredOrigin npoe) {
logger.debug("no preferred origin");
}
}
}
/**
* builds a radioButtonPanel. using the radioButton Panel only one of the
* particleMotions among all the three planes can be viewed at a time.
* @param channelGroup a <code>ChannelId[]</code> value
*/
private void formRadioSetPanel() {
JRadioButton[] radioButtons = new JRadioButton[3];
for(int i = 0; i < radioButtons.length; i++) {
radioButtons[i] = new JRadioButton(labelStrings[i]);
radioButtons[i].setActionCommand(labelStrings[i]);
radioButtons[i].addItemListener(new RadioButtonListener());
}
initialButton = radioButtons[0];
ButtonGroup buttonGroup = new ButtonGroup();
for(int counter = 0; counter < radioButtons.length; counter++) {
buttonGroup.add(radioButtons[counter]);
radioPanel.add(radioButtons[counter]);
}
radioPanel.setVisible(true);
}
/**
* sets the initialRadioButton or checkBox checked.
*/
private void setInitialButton() {
initialButton.setSelected(true);
}
/**
* sets the title of the Horizontal Border
* @param name a <code>String</code> value
*/
public void setHorizontalTitle(String name) {
hTitleBorder.setTitle(name);
}
/**
* sets the title of the vertical Border
* @param name a <code>String</code> value
*/
public void setVerticalTitle(String name) {
vTitleBorder.setTitle(name);
}
/**
*@returns true if the ParticleMotionThread has correctly initialized the display
*/
public boolean initialized(){ return initialized; }
public void add(NamedFilter filter){
view.add(filter);
}
public void remove(NamedFilter filter){
view.remove(filter);
}
public void setOriginal(boolean visible){
view.setOriginal(visible);
}
private boolean initialized = false;
public static final Integer PARTICLE_MOTION_LAYER = new Integer(2);
protected AmpScaleMapper hAmpScaleMap, vAmpScaleMap;
protected LeftTitleBorder vTitleBorder;
protected BottomTitleBorder hTitleBorder;
protected ParticleMotionView view;
private JPanel particleDisplayPanel;
private JPanel radioPanel;
private AbstractButton initialButton;
static Logger logger = LoggerFactory.getLogger(ParticleMotionDisplay.class);
private static final String[] labelStrings = { DisplayUtils.NORTHEAST,
DisplayUtils.UPNORTH,
DisplayUtils.UPEAST};
private class RadioButtonListener implements ItemListener {
public void itemStateChanged(ItemEvent ae) {
if(ae.getStateChange() == ItemEvent.SELECTED) {
String orientation = ((AbstractButton)ae.getItem()).getText();
view.setDisplayKey(orientation);
if(orientation.equals(labelStrings[0])){
setVerticalTitle("North-South");
setHorizontalTitle("East-West");
}else if(orientation.equals(labelStrings[1])){
setVerticalTitle("Up-Down");
setHorizontalTitle("North-South");
}else{
setVerticalTitle("Up-Down");
setHorizontalTitle("East-West");
}
repaint();
}
repaint();
}
}
}// ParticleMotionDisplay
| gpl-2.0 |