repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Mathieu-S/Pokedeck | src/main/java/com/pokedeck/ui/MainWindow.java | 6878 | package com.pokedeck.ui;
import com.pokedeck.cards.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class MainWindow extends JFrame {
//Attributes window
private JPanel jPanel;
private JButton addCardButton;
private JButton deleteCardButton;
private JList jListCards;
private JTable jTableCardList;
private JButton editCardButton;
//Attributes
private String filename = "cards.ser";
private ArrayList cards = new ArrayList();
private DefaultListModel<String> listCards = new DefaultListModel<String>();
public MainWindow() {
//Initilize basic window informations
this.setContentPane(jPanel);
this.setTitle("PokeDeck");
this.setLocationRelativeTo(null);
//Try to load
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
cards = (ArrayList) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Aucune sauvegarde n'a été trouvée. Une nouvelle sera créer");
}
//Prepare items in JList
for (int i = 0; i < cards.size() ; i++) {
Card tempCard = (Card) cards.get(i);
listCards.add(i, tempCard.getCardName());
}
jListCards.setModel(listCards);
addCardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EditorCardWindow editorCardWindow = new EditorCardWindow(listCards, cards);
editorCardWindow.pack();
editorCardWindow.setSize(260,365);
editorCardWindow.setVisible(true);
}
});
editCardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListCards.getSelectedIndex() >= 0) {
EditorCardWindow editorCardWindow = new EditorCardWindow(listCards, cards, jListCards.getSelectedIndex());
editorCardWindow.pack();
editorCardWindow.setSize(260,365);
editorCardWindow.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Vous n'avez selectionnez aucune carte");
}
}
});
deleteCardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
cards.remove(jListCards.getSelectedIndex());
listCards.remove(jListCards.getSelectedIndex());
jListCards.setModel(listCards);
} catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Vous n'avez selectionnez aucune carte");
}
}
});
jListCards.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
DefaultTableModel defaultTableModel = new DefaultTableModel();
defaultTableModel.addColumn("DataType");
defaultTableModel.addColumn("Value");
Card typeCardSelected = (Card) cards.get(jListCards.getSelectedIndex());
if (typeCardSelected.getType() == CardType.Pokemon) {
PokemonCard cardSelected = (PokemonCard) cards.get(jListCards.getSelectedIndex());
defaultTableModel.addRow(new String[]{"ID", String.valueOf(cardSelected.getCardID())});
defaultTableModel.addRow(new String[]{"Name", cardSelected.getCardName()});
defaultTableModel.addRow(new String[]{"Card Type", String.valueOf(cardSelected.getType())});
defaultTableModel.addRow(new String[]{"Pokemon Type", String.valueOf(cardSelected.getPokemonType())});
defaultTableModel.addRow(new String[]{"Health Points", String.valueOf(cardSelected.getHealthPoint())});
defaultTableModel.addRow(new String[]{"Evolution Stage", String.valueOf(cardSelected.getEvolutionStage())});
defaultTableModel.addRow(new String[]{"Evolve From", String.valueOf(cardSelected.getEvolveFrom().getCardName())});
} else if (typeCardSelected.getType() == CardType.Trainer) {
TrainerCard cardSelected = (TrainerCard) cards.get(jListCards.getSelectedIndex());
defaultTableModel.addRow(new String[]{"ID", String.valueOf(cardSelected.getCardID())});
defaultTableModel.addRow(new String[]{"Name", cardSelected.getCardName()});
defaultTableModel.addRow(new String[]{"Card Type", String.valueOf(cardSelected.getType())});
defaultTableModel.addRow(new String[]{"Trainer Type", String.valueOf(cardSelected.getTrainerType())});
} else if (typeCardSelected.getType() == CardType.Energy) {
EnergyCard cardSelected = (EnergyCard) cards.get(jListCards.getSelectedIndex());
defaultTableModel.addRow(new String[]{"ID", String.valueOf(cardSelected.getCardID())});
defaultTableModel.addRow(new String[]{"Name", cardSelected.getCardName()});
defaultTableModel.addRow(new String[]{"Card Type", String.valueOf(cardSelected.getType())});
defaultTableModel.addRow(new String[]{"Energy Type", String.valueOf(cardSelected.getEnergyType())});
}
jTableCardList.setModel(defaultTableModel);
}
});
// Stop program when close window
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(cards);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null,"Une erreur c'est produite et vos données n'ont pas été sauvegardées");
}
dispose();
}
});
}
}
| gpl-3.0 |
UCSB-CS56-Projects/cs56-android-smoke-signals | app/src/main/java/com/konukoii/smokesignals/storage/PhoneNumberDao.java | 705 | package com.konukoii.smokesignals.storage;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import java.util.List;
/**
* Created by porterhaet on 11/6/17.
*/
@Dao
public interface PhoneNumberDao {
@Query("SELECT * FROM phonenumber where number LIKE :number")
PhoneNumber findByNumber(String number);
@Query("SELECT number FROM phonenumber")
List<PhoneNumber> getAll();
@Query("DELETE FROM phonenumber")
void deleteAll();
@Insert
void addPhoneNumber(PhoneNumber number);
@Delete
void deletePhoneNumber(PhoneNumber number);
}
| gpl-3.0 |
adalee-group/watering-system | server/api-gateway/src/main/java/edu/hucare/ApiGatewayApplication.java | 402 | package edu.hucare;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
| gpl-3.0 |
errebenito/telegrambotapi | src/main/java/io/github/errebenito/telegrambotapi/enums/ChatType.java | 1584 | package io.github.errebenito.telegrambotapi.enums;
/**
* @author Raúl Benito
*
*/
public enum ChatType {
/**
* Chat type: private.
*/
PRIVATE(0, "private"),
/**
* Chat type: group.
*/
GROUP(1, "group"),
/**
* Chat type: supergroup.
*/
SUPERGROUP(2, "supergroup"),
/**
* Chat type: channel.
*/
CHANNEL(3, "channel");
/**
* The ID of the chat type.
*/
private Integer typeId;
/**
* The description of the chat type.
*/
private String description;
/**
*
* Class constructor.
*
* @param ident
* The ID of the chat type
* @param actionDescription
* The description of the chat tpye
*/
private ChatType(final Integer ident, final String actionDescription) {
this.typeId = ident;
this.description = actionDescription;
}
/**
* Accessor for the ID of the chat type.
*
* @return The ID of the chat type
*/
public final Integer getTypeId() {
return this.typeId;
}
/**
* Mutator for the ID of the chat type.
*
* @param ident
* The ID of the chat type
*/
public final void setTypeId(final Integer ident) {
this.typeId = ident;
}
/**
* Accessor for the description of the chat type.
*
* @return The description of the chat type
*/
public final String getDescription() {
return this.description;
}
/**
* Mutator for the description of the chat type.
*
* @param typeDescription
* The description of the chat type
*/
public final void setDescription(final String typeDescription) {
this.description = typeDescription;
}
}
| gpl-3.0 |
SpaceGame-ETSII/spacegame | BaseGameUtils/src/main/gen/com/google/example/games/basegameutils/BuildConfig.java | 280 | /*___Generated_by_IDEA___*/
package com.google.example.games.basegameutils;
/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */
public final class BuildConfig {
public final static boolean DEBUG = Boolean.parseBoolean(null);
} | gpl-3.0 |
pablo-albaladejo/javaee | Modulo7/BookstoreEAR/BookstoreEAR-ejb/src/java/ejb/integration/factory/DAOFactoryImp.java | 739 | package ejb.integration.factory;
import ejb.integration.book.BookDAO;
import ejb.integration.book.IBookDAO;
import ejb.persistence.database.exception.TransactionException;
/**
* This class implements the Data Access Object Factory.
* It is used as Facade for all the DAO objects at the Persistencce Layer
* <p>Pablo Albaladejo Mestre (pablo.albaladejo.mestre@gmail.com)</p>
*/
public class DAOFactoryImp extends DAOFactory{
/**
* Provides a DAO from the Book Entity
* @return A {@link IBookDAO} object
* @throws TransactionException if a DDBB exception occurred
*/
@Override
public IBookDAO getBookDAO() throws TransactionException{
return new BookDAO();
}
}
| gpl-3.0 |
MutinyCraft/AntiBuild | src/com/mutinycraft/jigsaw/AntiBuild/AntiBuild.java | 2995 | package com.mutinycraft.jigsaw.AntiBuild;
import com.mutinycraft.jigsaw.AntiBuild.Listeners.*;
import com.mutinycraft.jigsaw.AntiBuild.Util.ConfigHandler;
import com.mutinycraft.jigsaw.AntiBuild.Util.WorldHandler;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Logger;
/**
* Author: Jigsaw
* *
* Date: 1/1/14
* *
* Copyright 2014 MutinyCraft
* *
* This file is part of AntiBuild.
* *
* AntiBuild 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.
* *
* AntiBuild 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 .AntiBuild. If not, see <http://www.gnu.org/licenses/>.
*/
public class AntiBuild extends JavaPlugin {
private Logger logger;
private ConfigHandler configHandler;
private WorldHandler worldHandler;
@Override
public void onEnable() {
logger = this.getLogger();
/* Load the config.yml from disk */
logger.info("Loading the config.yml from disk...");
configHandler = new ConfigHandler(this);
logger.info("Successfully loaded config.yml");
/* Load the world.yml from disk */
logger.info("Loading the locked world from disk...");
worldHandler = new WorldHandler(this);
logger.info("Successfully loaded locked worlds.");
/* Register commands */
/* Register listeners */
logger.info("Registering listeners...");
getServer().getPluginManager().registerEvents(new BlockBreak(this), this);
getServer().getPluginManager().registerEvents(new BlockPlace(this), this);
getServer().getPluginManager().registerEvents(new BucketEmpty(this), this);
getServer().getPluginManager().registerEvents(new BucketFill(this), this);
getServer().getPluginManager().registerEvents(new ChestAccess(this), this);
getServer().getPluginManager().registerEvents(new EntityInteraction(this), this);
getServer().getPluginManager().registerEvents(new HangingBreak(this), this);
getServer().getPluginManager().registerEvents(new HangingPlace(this), this);
getServer().getPluginManager().registerEvents(new InventoryAccess(this), this);
getServer().getPluginManager().registerEvents(new ItemDrop(this), this);
getServer().getPluginManager().registerEvents(new ItemPickup(this), this);
logger.info("Successfully registered all listeners.");
}
public ConfigHandler getConfigHandler() {
return configHandler;
}
public WorldHandler getWorldHandler() {
return worldHandler;
}
}
| gpl-3.0 |
DSI-Ville-Noumea/pdc | src/main/java/nc/noumea/mairie/pdc/entity/Impact.java | 3650 | package nc.noumea.mairie.pdc.entity;
/*
* #%L
* Logiciel de Gestion des Permis de Construire de la Ville de Nouméa
* %%
* Copyright (C) 2013 - 2016 Mairie de Nouméa, Nouvelle-Calédonie
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import javax.persistence.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nc.noumea.mairie.pdc.core.entity.AbstractEntity;
import nc.noumea.mairie.pdc.enums.StatutImpact;
/**
* Modélise un impact sur un centroïde (voir sous-classes pour des impacts concrets)
*
* @author AgileSoft.NC
*/
@Entity
@DiscriminatorColumn(discriminatorType = DiscriminatorType.INTEGER, name = "dtype_impact_id")
public abstract class Impact extends AbstractEntity {
private static final Logger log = LoggerFactory.getLogger(Impact.class);
private static final long serialVersionUID = 1L;
@Version
private Integer version;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "s_impact")
@SequenceGenerator(name = "s_impact", sequenceName = "s_impact", allocationSize = 1)
Long id;
@Column
private int ordreAffichage = 0;
@Column
private Double pourcentageSig;
@Column(length = 500)
private String complementInfoSig;
@Enumerated(EnumType.ORDINAL)
private StatutImpact statutSig;
@Enumerated(EnumType.ORDINAL)
private StatutImpact statutRetenu;
@Column(length = 500)
private String explication;
public Impact() {
}
@Override
public Long getId() {
return id;
}
@Override
public Integer getVersion() {
return this.version;
}
/**
* @return ordre d'affichage de l'impact (à l'écran et sur l'éditique de renseignement d'urbanisme)
*/
public int getOrdreAffichage() {
return ordreAffichage;
}
public void setOrdreAffichage(int ordreAffichage) {
this.ordreAffichage = ordreAffichage;
}
/**
* @return le pourcentage maximum remonté du SIG
*/
public Double getPourcentageSig() {
return pourcentageSig;
}
public void setPourcentageSig(Double pourcentageSig) {
this.pourcentageSig = pourcentageSig;
}
/**
* @return le complément d'information remonté du SIG
*/
public String getComplementInfoSig() {
return complementInfoSig;
}
public void setComplementInfoSig(String complementInfoSig) {
this.complementInfoSig = complementInfoSig;
}
/**
* @return Le statut de l'impact tel que déterminé "automatiquement" par le SIG
*/
public StatutImpact getStatutSig() {
return statutSig;
}
public void setStatutSig(StatutImpact statutSig) {
this.statutSig = statutSig;
}
/**
* @return Le statut décidé par l'instructeur suite à sa propre analyse
*/
public StatutImpact getStatutRetenu() {
return statutRetenu;
}
public void setStatutRetenu(StatutImpact statutRetenu) {
this.statutRetenu = statutRetenu;
}
/**
* @return l'explication de l'instructeur sur sa décision
*/
public String getExplication() {
return explication;
}
public void setExplication(String explication) {
this.explication = explication;
}
}
| gpl-3.0 |
dksaputra/community | kernel/src/main/java/org/neo4j/kernel/PathDescription.java | 3286 | /**
* Copyright (c) 2002-2012 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel;
import static org.neo4j.kernel.Traversal.expanderForTypes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Expander;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.PathExpander;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.traversal.BranchState;
/**
* Experimental and very crude utility for building a slightly more powerful
* expander to use in a traversal.
*
* @author Mattias Persson
*/
public class PathDescription
{
private final List<Expander> steps;
public PathDescription()
{
this( new ArrayList<Expander>() );
}
private PathDescription( List<Expander> steps )
{
this.steps = steps;
}
public PathDescription step( RelationshipType type )
{
return step( expanderForTypes( type ) );
}
public PathDescription step( RelationshipType type, Direction direction )
{
return step( expanderForTypes( type, direction ) );
}
public PathDescription step( Expander expander )
{
List<Expander> newSteps = new ArrayList<Expander>( steps );
newSteps.add( expander );
return new PathDescription( newSteps );
}
public PathExpander build()
{
return new CrudeAggregatedExpander( steps );
}
private static class CrudeAggregatedExpander implements PathExpander
{
private final List<Expander> steps;
CrudeAggregatedExpander( List<Expander> steps )
{
this.steps = steps;
}
@Override
public Iterable<Relationship> expand( Path path, BranchState state )
{
Expander expansion;
try
{
expansion = steps.get( path.length() );
}
catch ( IndexOutOfBoundsException e )
{
return Collections.emptyList();
}
return expansion.expand( path.endNode() );
}
@Override
public PathExpander reverse()
{
List<Expander> reversedSteps = new ArrayList<Expander>();
for ( Expander step : steps )
reversedSteps.add( step.reversed() );
Collections.reverse( reversedSteps );
return new CrudeAggregatedExpander( reversedSteps );
}
}
}
| gpl-3.0 |
moravianlibrary/kramerius-for-android | app/src/main/java/cz/mzk/kramerius/app/xml/ModsParser.java | 11790 | package cz.mzk.kramerius.app.xml;
import android.util.Log;
import android.util.LruCache;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.Node;
import org.dom4j.QName;
import java.util.List;
import cz.mzk.kramerius.app.metadata.Author;
import cz.mzk.kramerius.app.metadata.Cartographics;
import cz.mzk.kramerius.app.metadata.Location;
import cz.mzk.kramerius.app.metadata.Metadata;
import cz.mzk.kramerius.app.metadata.Part;
import cz.mzk.kramerius.app.metadata.PhysicalDescription;
import cz.mzk.kramerius.app.metadata.Publisher;
import cz.mzk.kramerius.app.metadata.TitleInfo;
public class ModsParser extends XmlParser {
private static final String TAG = ModsParser.class.getName();
private static final boolean CACHING_ENABLED = true;
private static final int CACHE_SIZE = 3;
private static final LruCache<String, ModsParser> INSTANCE_CACHE = CACHING_ENABLED ? new LruCache<String, ModsParser>(CACHE_SIZE) : null;
private final Metadata mMetadata;
public static Metadata getMetadata(String modsUrl) {
if (CACHING_ENABLED) {
ModsParser instance = INSTANCE_CACHE.get(modsUrl);
if (instance == null) {
instance = new ModsParser(modsUrl);
INSTANCE_CACHE.put(modsUrl, instance);
}
return instance.getMetadata();
} else {
return new ModsParser(modsUrl).getMetadata();
}
}
public ModsParser(String modsUrl) {
Log.v(TAG, "initalizing mods parser from: " + modsUrl);
Document document = getDocument(modsUrl);
if (document != null) {
mMetadata = extractMetadata(document);
} else {
mMetadata = null;
}
}
public Metadata getMetadata() {
return mMetadata;
}
private Metadata extractMetadata(Document document) {
Element root = document.getRootElement();
removeNamespaces(root);
Metadata metadata = new Metadata();
Node node = root.selectSingleNode("//identifier[@type='issn']");
if (node != null) {
metadata.setIssn(node.getText());
}
node = root.selectSingleNode("//identifier[@type='isbn']");
if (node != null) {
metadata.setIsbn(node.getText());
}
node = root.selectSingleNode("//identifier[@type='oclc']");
if (node != null) {
metadata.setOclc(node.getText());
}
node = root.selectSingleNode("//identifier[@type='ccnb']");
if (node != null) {
metadata.setCcnb(node.getText());
}
node = root.selectSingleNode("//abstract");
if (node != null) {
String a = node.getText();
if (!a.trim().isEmpty()) {
metadata.setAbstract(a);
}
}
List<Node> nodes = root.selectNodes("//modes/note");
if (nodes != null) {
for (Node n : nodes) {
String note = n.getText();
note = removeSpaces(note);
metadata.addNote(note);
}
}
nodes = root.selectNodes("//subject/topic");
if (nodes != null) {
for (Node n : nodes) {
String keyword = n.getText();
metadata.addKayword(keyword);
}
}
nodes = root.selectNodes("//language/languageTerm[@type='code']");
if (nodes != null) {
for (Node n : nodes) {
String language = n.getText();
metadata.addLanguage(language);
}
}
fillTitleInfo(root, metadata);
fillAuthors(root, metadata);
fillPhysicalDescription(root, metadata);
fillPublishers(root, metadata);
fillPart(root, metadata);
fillCartographics(root, metadata);
fillLocation(root, metadata);
return metadata;
}
private static void fillTitleInfo(Element element, Metadata metadata) {
TitleInfo titleInfo = new TitleInfo();
Node node = null;
node = element.selectSingleNode("//titleInfo/title");
if (node != null) {
titleInfo.setTitle(node.getText());
}
node = element.selectSingleNode("//titleInfo/subTitle");
if (node != null) {
titleInfo.setSubtitle(node.getText());
}
node = element.selectSingleNode("//titleInfo/partName");
if (node != null) {
titleInfo.setPartName(node.getText());
}
node = element.selectSingleNode("//titleInfo/partNumber");
if (node != null) {
titleInfo.setPartNumber(node.getText());
}
metadata.setTitleInfo(titleInfo);
}
private static void fillCartographics(Element element, Metadata metadata) {
Cartographics cartographics = new Cartographics();
Node node = null;
node = element.selectSingleNode("//subject/cartographics/scale");
if (node != null) {
cartographics.setScale(node.getText());
}
node = element.selectSingleNode("//subject/cartographics/coordinates");
if (node != null) {
cartographics.setCoordinates(node.getText());
}
if (!cartographics.isEmpty()) {
metadata.setCartographics(cartographics);
}
}
private static void fillPart(Element element, Metadata metadata) {
Part part = new Part();
Node node = null;
node = element.selectSingleNode("//part/detail[@type='volume']/number");
if (node != null) {
part.setVolumeNumber(node.getText());
}
node = element.selectSingleNode("//part/detail[@type='part']/number");
if (node != null) {
part.setPartNumber(node.getText());
}
node = element.selectSingleNode("//part/detail[@type='issue']/number");
if (node != null) {
part.setIssueNumber(node.getText());
}
node = element.selectSingleNode("//part/detail[@type='pageNumber']/number");
if (node != null) {
part.setPageNumber(node.getText());
}
node = element.selectSingleNode("//part/detail[@type='pageIndex']/number");
if (node != null) {
part.setPageIndex(node.getText());
}
node = element.selectSingleNode("//part/date");
if (node != null) {
part.setDate(node.getText());
}
node = element.selectSingleNode("//part/text");
if (node != null) {
part.setText(node.getText());
}
if (!part.isEmpty()) {
metadata.setPart(part);
}
}
private static void fillAuthors(Element element, Metadata metadata) {
List<Node> nodes = element.selectNodes("//name[@type='personal']");
if (nodes != null) {
for (Node n : nodes) {
Author author = new Author();
Node node = null;
// <namePart type="family">Petrasová</namePart>
// <namePart type="given">Taťána</namePart>
String family = "";
Node familyNode = n.selectSingleNode("namePart[@type='family']");
if (familyNode != null) {
family = familyNode.getText();
}
String given = "";
Node givenNode = n.selectSingleNode("namePart[@type='given']");
if (givenNode != null) {
given = givenNode.getText();
}
if (given.isEmpty() && family.isEmpty()) {
node = n.selectSingleNode("namePart[not(@type)]");
if (node != null) {
author.setName(node.getText());
}
} else {
author.setName(family + ", " + given);
}
node = n.selectSingleNode("namePart[@type='date']");
if (node != null) {
author.setDate(node.getText());
}
List<Node> roleNodes = n.selectNodes("role/roleTerm[@type='code']");
if (roleNodes != null) {
for (Node roleNode : roleNodes) {
String role = roleNode.getText();
if (role != null && !role.isEmpty()) {
author.addRole(role);
}
}
}
if (!author.isEmpty()) {
metadata.addAuthor(author);
}
}
}
}
private static void fillLocation(Element element, Metadata metadata) {
Location location = new Location();
Node node = element.selectSingleNode("//location/physicalLocation");
if (node != null) {
location.setPhysicalLocation(node.getText());
}
List<Node> nodes = element.selectNodes("//location/shelfLocator");
if (nodes != null) {
for (Node n : nodes) {
location.addShelfLocatons(n.getText());
if (!location.isEmpty()) {
metadata.setLocation(location);
}
}
}
}
private static void fillPublishers(Element element, Metadata metadata) {
List<Node> nodes = element.selectNodes("//originInfo");
if (nodes != null) {
for (Node n : nodes) {
Publisher publisher = new Publisher();
Node node = null;
node = n.selectSingleNode("publisher");
if (node != null) {
publisher.setName(node.getText());
}
node = n.selectSingleNode("dateIssued");
if (node != null) {
publisher.setDate(node.getText());
}
node = n.selectSingleNode("place/placeTerm[@type='text']");
if (node != null) {
publisher.setPlace(node.getText());
}
if (!publisher.isEmpty()) {
metadata.addPublisher(publisher);
}
}
}
}
private static void fillPhysicalDescription(Element element, Metadata metadata) {
PhysicalDescription description = new PhysicalDescription();
Node node = element.selectSingleNode("//physicalDescription/extent");
if (node != null) {
description.setExtent(node.getText());
}
List<Node> nodes = element.selectNodes("//physicalDescription/note");
if (nodes != null) {
for (Node n : nodes) {
String note = n.getText();
if (note != null && !note.isEmpty()) {
description.addNote(note);
}
if (!description.isEmpty()) {
metadata.setPhysicalDescription(description);
}
}
}
}
private static String removeSpaces(String s) {
if (s.contains(" ")) {
return removeSpaces(s.replace(" ", " "));
} else {
return s;
}
}
public static void removeNamespaces(Element elem) {
elem.setQName(QName.get(elem.getName(), Namespace.NO_NAMESPACE, elem.getQualifiedName()));
Node n = null;
for (int i = 0; i < elem.content().size(); i++) {
n = (Node) elem.content().get(i);
if (n.getNodeType() == Node.ATTRIBUTE_NODE)
((Attribute) n).setNamespace(Namespace.NO_NAMESPACE);
if (n.getNodeType() == Node.ELEMENT_NODE)
removeNamespaces((Element) n);
}
}
} | gpl-3.0 |
ThEWiZ76/KingdomFactions | src/nl/dusdavidgames/kingdomfactions/modules/kingdom/nexus/CapitalNexus.java | 4086 | package nl.dusdavidgames.kingdomfactions.modules.kingdom.nexus;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.bukkit.Location;
import lombok.Getter;
import lombok.Setter;
import nl.dusdavidgames.kingdomfactions.KingdomFactionsPlugin;
import nl.dusdavidgames.kingdomfactions.modules.database.mysql.databases.KingdomDatabase;
import nl.dusdavidgames.kingdomfactions.modules.exception.DataException;
import nl.dusdavidgames.kingdomfactions.modules.kingdom.KingdomModule;
import nl.dusdavidgames.kingdomfactions.modules.kingdom.kingdom.KingdomType;
import nl.dusdavidgames.kingdomfactions.modules.kingdom.nexus.guardian.CapitalGuard;
import nl.dusdavidgames.kingdomfactions.modules.monster.GuardType;
import nl.dusdavidgames.kingdomfactions.modules.monster.IGuard;
import nl.dusdavidgames.kingdomfactions.modules.nexus.INexus;
import nl.dusdavidgames.kingdomfactions.modules.player.player.online.KingdomFactionsPlayer;
import nl.dusdavidgames.kingdomfactions.modules.utils.IInhabitable;
import nl.dusdavidgames.kingdomfactions.modules.utils.Utils;
import nl.dusdavidgames.kingdomfactions.modules.utils.enums.NexusType;
import nl.dusdavidgames.kingdomfactions.modules.utils.particles.ParticleEffect;
public class CapitalNexus implements INexus {
public CapitalNexus(Location location, KingdomType kingdom) {
this.location = location;
this.health = 800;
this.kingdom = kingdom;
this.nexusId = kingdom.toString();
}
private @Getter Location location;
private @Setter @Getter int health;
private @Setter @Getter KingdomType kingdom;
private @Setter @Getter String nexusId;
private boolean destroy;
private @Getter ArrayList<IGuard> guards = new ArrayList<IGuard>();
@Override
public Location getNexusLocation() {
return location;
}
@Override
public int getProtectedRadius() {
// TODO Auto-generated method stub
try {
return KingdomFactionsPlugin.getInstance().getDataManager().getInteger("kingdom.capital.protected_region");
} catch (DataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 400;
}
public double getDistance(KingdomFactionsPlayer p) {
Location player = Utils.getInstance().getNewLocation(p.getLocation());
Location nexus = Utils.getInstance().getNewLocation(this.getNexusLocation());
player.setY(0);
nexus.setY(0);
return nexus.distance(player);
}
public double getDistance(Location location) {
Location loc = Utils.getInstance().getNewLocation(location);
Location nexus = Utils.getInstance().getNewLocation(this.getNexusLocation());
loc.setY(0);
nexus.setY(0);
return nexus.distance(loc);
}
@Override
public NexusType getType() {
// TODO Auto-generated method stub
return NexusType.CAPITAL;
}
public boolean isDestroyed() {
return destroy;
}
public void setDestroyed(boolean destroy) {
this.destroy = destroy;
}
public ArrayList<CapitalGuard> spawnGuards() {
ArrayList<CapitalGuard> guards = new ArrayList<CapitalGuard>();
for(int i = 0; i <= 4; i++) {
CapitalGuard guard = spawnGuard();
guards.add(guard);
this.guards.add(guard);
}
return guards;
}
private CapitalGuard spawnGuard() {
List<Location> list = Utils.getInstance().drawCircle(this.location, 4, 1, true, false, 0);
Location spawn = list.get(new Random().nextInt(list.size()));
Utils.getInstance().playParticle(spawn, ParticleEffect.WITCH_MAGIC);
CapitalGuard g = new CapitalGuard(this, getRandomType(), spawn);
g.spawn();
return g;
}
private GuardType getRandomType() {
Random r = new Random();
int i = r.nextInt(4);
if(i == 3) {
return GuardType.SKELETON;
}
return GuardType.ZOMBIE;
}
public void save() {
KingdomDatabase.getInstance().saveNexus(this);
}
public void setLocation(Location location) {
this.location = location;
}
@Override
public IInhabitable getOwner() {
return KingdomModule.getInstance().getKingdom(this.getKingdom());
}
@Override
public String toString() {
return Utils.getInstance().getLocationString(this.location) + "/" + this.nexusId;
}
}
| gpl-3.0 |
chenbrjc/wmvc-rtrf | dwmvc-angular-java-sql/src/main/java/wmvc/dwmvc/resources/BlogApp.java | 4616 | package wmvc.dwmvc.resources;
import wmvc.dwmvc.resources.pojo.TopicComments;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.impossibl.postgres.api.jdbc.PGConnection;
import com.impossibl.postgres.api.jdbc.PGNotificationListener;
import java.io.IOException;
import java.sql.Statement;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
import org.json.JSONObject;
@Path("/comments")
public class BlogApp
{
private static final String NO_COMMENTS = "{\"comments\":[]}";
@GET
@Path("/all")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getAllComments() throws Exception
{
final EventOutput eventOutput = new EventOutput();
Statement sqlStatement = null;
try
{
//Query and return current data
String comments = BlogByPostgreSQL.getInstance().findComments(ConfigStringConstants.TOPIC_ID);
this.writeToEventOutput(comments, eventOutput);
//Listen to future change notifications
PGConnection conn = (PGConnection)BlogByPostgreSQL.getInstance().getConnection();
sqlStatement = conn.createStatement();
sqlStatement.execute("LISTEN topics_observer");
conn.addNotificationListener("topics_observer", new PGNotificationListener()
{
@Override
public void notification(int processId, String channelName, String payload)
{
JSONObject plJson = new JSONObject(payload);
String plComments = plJson.getJSONObject("topic_comments").toString();
writeToEventOutput(plComments, eventOutput);
}
});
}
catch (Exception e)
{
throw new RuntimeException(
"Error when writing the event.", e);
}
finally
{
try
{
BlogByPostgreSQL.getInstance().closeSqlStatement(sqlStatement);
}
catch (Exception ioClose)
{
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
return eventOutput;
}
private void writeToEventOutput(String comments, EventOutput eventOutput)
{
OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.mediaType(MediaType.APPLICATION_JSON_TYPE);
if(comments == null || comments.trim().equals(""))
{
comments = NO_COMMENTS;
}
eventBuilder.data(String.class, comments);
OutboundEvent event = eventBuilder.build();
try
{
eventOutput.write(event);
}
catch(IOException e)
{
throw new RuntimeException("Error in writing to event output", e);
}
}
@POST
@Path("/cast")
@Consumes(MediaType.APPLICATION_JSON)
public void addComment(String newComment) throws Exception
{
if(newComment != null && !newComment.trim().equals(""))
{
ObjectMapper mapper = new ObjectMapper();
TopicComments topicComments;
String comments = BlogByPostgreSQL.getInstance().findComments(ConfigStringConstants.TOPIC_ID);
if(comments == null || comments.trim().equals(""))
{
topicComments = new TopicComments();
topicComments.addComment(newComment);
String topicCommentsStr = mapper.writeValueAsString(topicComments);
BlogByPostgreSQL.getInstance().addTopic(topicCommentsStr);
}
else
{
if(!comments.contains(newComment))
{
topicComments = mapper.readValue(comments, TopicComments.class);
topicComments.addComment(newComment);
String topicCommentsStr = mapper.writeValueAsString(topicComments);
BlogByPostgreSQL.getInstance().updateTopic(topicCommentsStr);
}
}
}
}
}
| gpl-3.0 |
ejwa/dinja-engine | engine/src/main/java/com/ejwa/dinja/engine/controller/input/FingerMovementInputController.java | 2395 | /*
* Copyright © 2011-2012 Ejwa Software. All rights reserved.
*
* This file is part of Dinja Engine. Dinja Engine is a OpenGLES2
* 3D engine with physics support developed for the Android platform.
*
* Dinja Engine 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.
*
* Dinja Engine 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 Lesser General
* Public License along with Dinja Engine. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.ejwa.dinja.engine.controller.input;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import org.openmali.FastMath;
import org.openmali.vecmath2.Point2f;
public class FingerMovementInputController {
private final IFingerMovementInputListener fingerMovementInputListener;
private final GLSurfaceView glSurfaceView;
private final Point2f startPosition = new Point2f();
private final Point2f endPosition = new Point2f();
public FingerMovementInputController(IFingerMovementInputListener fingerMovementInputListener, GLSurfaceView glSurfaceView) {
this.fingerMovementInputListener = fingerMovementInputListener;
this.glSurfaceView = glSurfaceView;
}
public void onTouchEvent(MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN || motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
final float x = motionEvent.getX() / glSurfaceView.getWidth();
final float y = motionEvent.getY() / glSurfaceView.getHeight();
float angle;
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startPosition.set(x, y);
endPosition.set(x, y);
angle = 0;
} else {
endPosition.set(x, y);
angle = FastMath.atan2(endPosition.getY() - startPosition.getY(), endPosition.getX() - startPosition.getX());
}
fingerMovementInputListener.onFingerMovementInput(startPosition, endPosition, angle);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
fingerMovementInputListener.onFingerMovementEndInput();
}
}
}
| gpl-3.0 |
truhanen/Weather | Weather/src/fi/tuukka/weather/utils/Rains.java | 9714 | /*******************************************************************************
* Copyright (C) 2015 Tuukka Ruhanen
*
* 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 fi.tuukka.weather.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import fi.tuukka.weather.downloader.Downloader;
import fi.tuukka.weather.downloader.RainDownloader;
import fi.tuukka.weather.downloader.RainDownloader.RainType;
import android.content.Context;
import android.graphics.Bitmap;
public class Rains {
private RainType type;
private long[] rainTimes;
private String[] rainImageUrls;
private Bitmap[] rains;
private boolean[] inUi; // to determine whether images are set to ui
private boolean[] saved; // to determine whether images are saved to file
private long htmlTime = 0l;
public Rains(RainType type2) {
this.type = type2;
this.rains = new Bitmap[type.steps];
this.rainTimes = new long[type.steps];
this.inUi = new boolean[type.steps];
this.saved = new boolean[type.steps];
}
public boolean hasFreshHtml() {
return System.currentTimeMillis() - htmlTime < Downloader.EXPIREDTIME;
}
public long[] rainTimes() {
return rainTimes.clone(); // TODO
}
public Bitmap[] rains() {
return rains.clone(); // TODO
}
public RainType type() {
return type;
}
public boolean hasRain(int i) {
return (Downloader.isRunAlone() && saved[i]) || (!Downloader.isRunAlone() && inUi[i]);
}
public boolean hasRains(int from, int to) {
for (int i = from; i <= to && i < type.steps; i++) {
if (!hasRain(i))
return false;
}
return true;
}
public boolean hasAllRains() {
if (!hasFreshHtml())
return false;
return hasRains(0, type.steps - 1);
}
public List<Integer> rainsDownloaded() {
ArrayList<Integer> downloaded = new ArrayList<Integer>();
for (int i = 0; i < type.steps; i++)
if (hasRain(i))
downloaded.add(i);
return downloaded;
}
/**
* Download the next rain from the given range that has not yet been downloaded.
*/
public void downloadRain(int from, int to, Context context) throws Exception {
int add = 1;
if (from > to)
add = -1;
for (int i = from; (i <= to || (i >= to && from > to)) && i <= type.steps; i += add) {
if (!hasRain(i)) {
downloadRain(i, context);
break;
}
}
}
/**
* Only assign values to inUi[] and saved[] here, do not use them.
*/
public void downloadRain(int i, Context context) throws Exception {
String fileName = getRainFileName(i);
boolean onlyDownload = true; // set this if you do not want to save or load bitmap files
if (!onlyDownload && Downloader.isRunAlone()) {
// save new if we do not have a valid file
if (isObsoleteFile(fileName) || !FileUtils.hasFile(fileName, context)) {
Bitmap bmp;
if (rains[i] != null) {
// System.out.println("rain from ui to file " + type + " " + Integer.toString(i) + " " + fileName);
bmp = rains[i];
} else {
// System.out.println("rain from web to file " + type + " " + Integer.toString(i) + " " + fileName);
bmp = Utils.loadBitmapFromUrl(rainImageUrls[i]);
}
FileUtils.saveBitmap(fileName, bmp, context);
Utils.recycle(rains, i);
}
if (rains[i] != null)
Utils.recycle(rains, i);
inUi[i] = false;
saved[i] = true;
} else {
if (rains[i] == null) {
if (!onlyDownload && !isObsoleteFile(fileName) && FileUtils.hasFile(fileName, context)) {
// System.out.println("rain from file to ui " + type + " " + Integer.toString(i) + " " + fileName);
rains[i] = FileUtils.openBitmap(fileName, context);
}
if (rains[i] == null) { // also in case the opened file was corrupt and returned null
// System.out.println("rain from web to ui " + type + " " + Integer.toString(i));
rains[i] = Utils.loadBitmapFromUrl(rainImageUrls[i]);
}
if (rains[i] == null)
throw new Exception();
}
inUi[i] = true;
}
}
public void downloadHtml(Context context) throws Exception {
String rainHtml = Utils.downloadHtml(type.url);
if (rainHtml == null) {
throw new Exception();
}
long[] oldTimes = rainTimes;
rainTimes = findRainTimeStamps(rainHtml);
rainImageUrls = getRainAddresses(rainHtml);
syncBitmaps(rainTimes, oldTimes);
htmlTime = System.currentTimeMillis();
removeOldFiles(context);
for (int i = 0; i < type.steps; i++) {
inUi[i] = false;
saved[i] = false;
}
}
private void syncBitmaps(long[] newTimes, long[] oldTimes) {
int j = 0;
for (int i = 0; i < type.steps; i++) {
boolean isObservation = type == RainType.MIN15 || i < RainDownloader.FIRSTFORECASTIND;
if (oldTimes[i] == newTimes[j] && isObservation) {
rains[j++] = rains[i];
}
}
for (; j < type.steps; j++)
rains[j] = null;
}
private long[] findRainTimeStamps(String source) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("d.M. HH:mm");
long[] tempTimeStamps = new long[type.steps];
String searchStringLeft = "1)\">";
String searchStringRight = "</b>";
int left = 0;
int right = 0;
for (int i = 0; i < type.steps; i++) {
left = source.indexOf(searchStringLeft,
left + searchStringLeft.length())
+ searchStringLeft.length();
right = source.indexOf(searchStringRight, left);
String timeStampRaw = source.substring(left, right);
timeStampRaw = timeStampRaw.replace(" ", " ");
timeStampRaw = timeStampRaw.replace("<b>", "");
timeStampRaw = timeStampRaw.substring(timeStampRaw.indexOf(' ') + 1);
tempTimeStamps[i] = formatter.parse(timeStampRaw).getTime();
// System.out.println(timeStampRaw);
}
return tempTimeStamps;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private String[] getRainAddresses(String html) {
String[] imageAddresses = new String[type.steps];
String searchStringLeft = "anim_images_anim_anim = new Array(\"";
String searchStringRight = "\");var imagecache = new Array()";
int left = html.indexOf(searchStringLeft, 0)
+ searchStringLeft.length();
int right = html.indexOf(searchStringRight, 0);
String addressArray = html.substring(left, right);
StringTokenizer tokens = new StringTokenizer(addressArray, "\",\"");
for (int i = 0; i < type.steps; ++i) {
imageAddresses[i] = tokens.nextToken();
}
return imageAddresses;
}
public String getRainFileName(int i) {
if (type == RainType.H1 && i >= RainDownloader.FIRSTFORECASTIND) {
return FileUtils.RAINSTART + "_" + type.name() + "_" + rainTimes[i] + "_" + RainDownloader.FORECASTLABEL + "_" + i;
}
return FileUtils.RAINSTART + "_" + type.name() + "_" + rainTimes[i];
}
public static long parseTime(String fileName) {
return Long.parseLong(fileName.split("_")[2]);
}
private void removeOldFiles(Context context) {
for (String fileName : FileUtils.getFileNames(FileUtils.RAINSTART, context)) {
if (isObsoleteFile(fileName)) {
FileUtils.deleteFile(fileName, context);
}
}
}
private boolean isObsoleteFile(String fileName) {
if (!fileName.contains(type.name()))
return false;
if (fileName.contains(RainDownloader.FORECASTLABEL)) {
return !isFreshForecastFile(fileName);
}
else
return parseTime(fileName) < rainTimes[0];
}
public boolean isFreshForecastFile(String fileName) {
if (!fileName.contains(RainDownloader.FORECASTLABEL))
return true;
int i = Integer.parseInt(fileName.substring(fileName.lastIndexOf('_') + 1));
return parseTime(fileName) == rainTimes[i];
}
public void recycle() {
Utils.recycle(rains);
}
}
| gpl-3.0 |
arraydev/snap-desktop | snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/CustomParameterClass.java | 5810 | /*
*
* * Copyright (C) 2015 CS SI
* *
* * This program is free software; you can redistribute it and/or modify it
* * under the terms of the GNU General Public License as published by the Free
* * Software Foundation; either version 3 of the License, or (at your option)
* * any later version.
* * This program is distributed in the hope that it will be useful, but WITHOUT
* * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* * more details.
* *
* * You should have received a copy of the GNU General Public License along
* * with this program; if not, see http://www.gnu.org/licenses/
*
*/
package org.esa.snap.ui.tooladapter.model;
import org.esa.snap.framework.gpf.operators.tooladapter.ToolAdapterConstants;
import java.io.File;
/**
* Enum-like class holding the possible types of operator parameters
*
* @author Ramona Manda
* @author Cosmin Cara
*/
public class CustomParameterClass {
private Class<?> aClass;
private String typeMask;
/**
* Represents a template file that is supposed to be executed before the actual tool execution
*/
public static final CustomParameterClass BeforeTemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_BEFORE_MASK);
/**
* Represents a template file that is supposed to be executed after the actual tool execution
*/
public static final CustomParameterClass AfterTemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_AFTER_MASK);
/**
* Represents a the template file of the actual tool execution
*/
public static final CustomParameterClass TemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_PARAM_MASK);
/**
* Represents a file parameter
*/
public static final CustomParameterClass RegularFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a file list parameter
*/
public static final CustomParameterClass FileListClass = new CustomParameterClass(File[].class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a string/text parameter
*/
public static final CustomParameterClass StringClass = new CustomParameterClass(String.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents an integer parameter
*/
public static final CustomParameterClass IntegerClass = new CustomParameterClass(Integer.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a string list parameter
*/
public static final CustomParameterClass ListClass = new CustomParameterClass(String[].class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a boolean parameter
*/
public static final CustomParameterClass BooleanClass = new CustomParameterClass(Boolean.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a float parameter
*/
public static final CustomParameterClass FloatClass = new CustomParameterClass(Float.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
private CustomParameterClass(Class<?> aClass, String typeMask) {
this.aClass = aClass;
this.typeMask = typeMask;
}
/**
* @return The Java class of the parameter
*/
public Class<?> getParameterClass() {
return aClass;
}
/**
* Checks if the parameter is a template parameter
*/
public boolean isTemplateParameter() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_PARAM_MASK);
}
/**
* Checks if the parameter is a template-before parameter
*/
public boolean isTemplateBefore() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_BEFORE_MASK);
}
/**
* Checks if the parameter is a template-after parameter
*/
public boolean isTemplateAfter() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_AFTER_MASK);
}
/**
* Checks if the parameter is a regular parameter
*/
public boolean isParameter() {
return typeMask.equals(ToolAdapterConstants.REGULAR_PARAM_MASK);
}
/**
* Returns the type mask of the parameter
*/
public String getTypeMask() { return this.typeMask; }
/**
* Returns the CustomParameterClass instance matching the given type mask
*/
public static CustomParameterClass getObject(Class<?> aClass, String typeMask) {
CustomParameterClass result = matchClass(TemplateFileClass, aClass, typeMask);
if (result == null) {
result = matchClass(BeforeTemplateFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(AfterTemplateFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(RegularFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(StringClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(IntegerClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(ListClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(BooleanClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(FloatClass, aClass, typeMask);
}
return result;
}
private static CustomParameterClass matchClass(CustomParameterClass paramClass, Class<?> aClass, String typeMask){
return (paramClass.getParameterClass().equals(aClass) && paramClass.typeMask.equals(typeMask)) ?
paramClass : null;
}
}
| gpl-3.0 |
zncanke/WebIMDemo | src/main/java/com/will/imlearntest/vo/UserStatusVo.java | 1293 | package com.will.imlearntest.vo;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
/**
* Created by willl on 5/18/16.
*/
public class UserStatusVo {
/**
* 用户名
*/
private String username;
/**
* 状态
*/
private int status;
private String email;
private boolean haveUnread;
private String signature;
private String pic;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setHaveUnread(boolean haveUnread) {
this.haveUnread = haveUnread;
}
public boolean getHaveUnread() {
return this.haveUnread;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
| gpl-3.0 |
sarbot/garleon | core/src/de/sarbot/garleon/Objects/CharacterWindow.java | 111 | package de.sarbot.garleon.Objects;
/**
* Created by sarbot on 27.04.17.
*/
public class CharacterWindow {
}
| gpl-3.0 |
fk19841217/Performance-Analysis | src/controller/EdgeController.java | 25576 | package controller;
import controller.dialog.EdgeEditDialogController;
import controller.dialog.MessageEditDialogController;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import model.edges.*;
import util.commands.DirectionChangeEdgeCommand;
import util.commands.MoveMessageCommand;
import util.commands.ReplaceEdgeCommand;
import view.edges.AbstractEdgeView;
import view.edges.MessageEdgeView;
import view.nodes.AbstractNodeView;
import view.nodes.DeploymentNodeView;
import view.nodes.LinkedDeploymentNodeView;
import view.nodes.SequenceActivationBoxView;
import view.nodes.SequenceObjectView;
import view.nodes.UsecaseNodeView;
import java.io.IOException;
/**
*
* Controller class for Edges.
*/
public class EdgeController {
private double dragStartX, dragStartY;
private Line dragLine;
private Pane aDrawPane;
private AbstractDiagramController diagramController;
private AbstractNodeView startNodeView;
private AbstractNodeView endNodeView;
public EdgeController(Pane pDrawPane, AbstractDiagramController diagramController) {
aDrawPane = pDrawPane;
dragLine = new Line();
dragLine.setStroke(Color.DARKGRAY);
dragLine.setStrokeWidth(2);
this.diagramController = diagramController;
}
public void onMousePressedOnNode(MouseEvent event) {
dragStartX = event.getX() + ((AbstractNodeView) event.getSource()).getTranslateX();
dragStartY = event.getY() + ((AbstractNodeView) event.getSource()).getTranslateY();
startNodeView = (AbstractNodeView) event.getSource();
aDrawPane.getChildren().add(dragLine);
}
public void onMousePressedOnCanvas(MouseEvent event){
dragStartX = event.getX();
dragStartY = event.getY();
if(diagramController instanceof SequenceDiagramController){
for(AbstractNodeView node : diagramController.getAllNodeViews()){
double middleOfNode = (node.getX() + (node.getX() + node.getWidth())) /2;
if(event.getX() > middleOfNode - 20 && event.getX() < middleOfNode + 20
&& event.getY() > node.getY()){
startNodeView = node;
}
}
}
/* else if(diagramController instanceof PerformanceController){
for(AbstractNodeView node : diagramController.getAllNodeViews()){
double middleOfNode = (node.getX() + (node.getX() + node.getWidth())) /2;
if(event.getX() > middleOfNode - 20 && event.getX() < middleOfNode + 20
&& event.getY() > node.getY()){
startNodeView = node;
}
}
}*/
aDrawPane.getChildren().add(dragLine);
}
public void onMouseDragged(MouseEvent event){
dragLine.setStartX(dragStartX);
dragLine.setStartY(dragStartY);
if(event.getSource() instanceof AbstractNodeView) {
dragLine.setEndX(event.getX() + ((AbstractNodeView) event.getSource()).getTranslateX());
dragLine.setEndY(event.getY() + ((AbstractNodeView) event.getSource()).getTranslateY());
} else {
dragLine.setEndX(event.getX());
dragLine.setEndY(event.getY());
}
}
/*
* Used for sequence diagrams
*/
public void onMouseReleasedSequence(){
for(AbstractNodeView nodeView : diagramController.getAllNodeViews()){ //TODO implement getAllLifelines
// if(nodeView instanceof SequenceObjectView && ((SequenceObjectView) nodeView).isOnLifeline(getEndPoint())){
// endNodeView = nodeView;
// } else
if(nodeView instanceof SequenceActivationBoxView && ((SequenceActivationBoxView ) nodeView).isOnActivity(getEndPoint())){
endNodeView = nodeView;
}
}
if(endNodeView != null){
if(startNodeView != null){
MessageEdge edge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
((SequenceDiagramController)diagramController).createEdgeView(edge, startNodeView, endNodeView);
} else {
MessageEdge edge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(endNodeView));
((SequenceDiagramController)diagramController).createEdgeView(edge, null, endNodeView);
}
}
finishCreateEdge();
}
/*
* Used for performance
*/
public void onMouseReleasedPerformance(){
for(AbstractNodeView nodeView : diagramController.getAllNodeViews()){ //TODO implement getAllLifelines
if(nodeView instanceof SequenceObjectView && ((SequenceObjectView) nodeView).isOnLifeline(getEndPoint())){
endNodeView = nodeView;
}
else if(nodeView.contains(getEndPoint())){
endNodeView = nodeView;
}
}
if(endNodeView != null){
if(startNodeView != null){
MessageEdge medge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
CompositionEdge aedge = new CompositionEdge(diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
((PerformanceController)diagramController).createEdgeView(aedge, startNodeView, endNodeView);
} /*else {
MessageEdge edge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(endNodeView));
((PerformanceController)diagramController).createEdgeView(edge, null, endNodeView);
}*/
}
finishCreateEdge();
}
public void onMouseReleasedDeployment(){
for(AbstractNodeView nodeView : diagramController.getAllNodeViews()){ //TODO implement getAllLifelines
// if(nodeView instanceof SequenceObjectView && ((SequenceObjectView) nodeView).isOnLifeline(getEndPoint())){
// endNodeView = nodeView;
// } else
if(nodeView instanceof DeploymentNodeView){
endNodeView = nodeView;
}
}
if(endNodeView != null){
if(startNodeView != null){
//MessageEdge medge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
ConnectEdge aedge = new ConnectEdge(diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
// if (diagramController.getNodeMap().get(startNodeView).getType()=="LIFELINE")
//((PerformanceController)diagramController).createEdgeView(medge, startNodeView, endNodeView);
// else
((DeploymentController)diagramController).createEdgeView(aedge, startNodeView, endNodeView);
} /*else {
MessageEdge edge = new MessageEdge(dragStartX, dragStartY, diagramController.getNodeMap().get(endNodeView));
((PerformanceController)diagramController).createEdgeView(edge, null, endNodeView);
}*/
}
finishCreateEdge();
}
/* public void onMouseReleasedPerformance(){
for(AbstractNodeView nodeView : diagramController.getAllNodeViews()){
if(nodeView.contains(getEndPoint())){
endNodeView = nodeView;
}
}
if(endNodeView != null){
AssociationEdge edge = new AssociationEdge(diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
diagramController.createEdgeView(edge, startNodeView, endNodeView);
}
finishCreateEdge();
}*/
/*
* Used for class diagrams
*/
public void onMouseReleasedRelation() {
for(AbstractNodeView nodeView : diagramController.getAllNodeViews()){
if(nodeView.contains(getEndPoint())){
endNodeView = nodeView;
}
}
if(endNodeView != null){
AssociationEdge edge = new AssociationEdge(diagramController.getNodeMap().get(startNodeView), diagramController.getNodeMap().get(endNodeView));
diagramController.createEdgeView(edge, startNodeView, endNodeView);
}
finishCreateEdge();
}
private void finishCreateEdge() {
dragLine.setStartX(0);
dragLine.setStartY(0);
dragLine.setEndX(0);
dragLine.setEndY(0);
aDrawPane.getChildren().remove(dragLine);
startNodeView = null;
endNodeView = null;
}
private double previousEdgeStartY;
private double dragStart;
protected void onMousePressDragEdge(MouseEvent event){
diagramController.mode = AbstractDiagramController.Mode.DRAGGING_EDGE;
previousEdgeStartY = event.getY();
dragStartY = event.getY();
}
protected void onMouseDragEdge(MouseEvent event){
double offsetY = (event.getY() - previousEdgeStartY)*(1/diagramController.drawPane.getScaleY());
previousEdgeStartY = event.getY();
for(AbstractEdgeView edgeView : diagramController.selectedEdges){
if(edgeView instanceof MessageEdgeView){
MessageEdge edge = (MessageEdge)edgeView.getRefEdge();
edge.setStartY(edge.getStartY() + offsetY);
}
}
}
protected void onMouseReleaseDragEdge(MouseEvent event){
diagramController.mode = AbstractDiagramController.Mode.NO_MODE;
for(AbstractEdgeView edgeView : diagramController.selectedEdges) {
diagramController.undoManager.add(new MoveMessageCommand((MessageEdge)edgeView.getRefEdge(), 0, edgeView.getStartY() - dragStartY));
}
previousEdgeStartY = 0;
}
public Point2D getStartPoint() {
return new Point2D(dragStartX, dragStartY);
}
public Point2D getEndPoint() {
return new Point2D(dragLine.getEndX(), dragLine.getEndY());
}
public boolean showEdgeEditDialog(AbstractEdge edge) {
if(!(diagramController instanceof DeploymentController)){
try {
// Load the classDiagramView.fxml file and create a new stage for the popup
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("view/fxml/edgeEditDialog.fxml"));
AnchorPane dialog = loader.load();
dialog.setBackground(new Background(new BackgroundFill(Color.WHITESMOKE, new CornerRadii(1), null)));
dialog.setStyle("-fx-border-color: black");
//Set location for "dialog".
dialog.setLayoutX((edge.getStartNode().getTranslateX() + edge.getEndNode().getTranslateX())/2);
dialog.setLayoutY((edge.getStartNode().getTranslateY() + edge.getEndNode().getTranslateY())/2);
EdgeEditDialogController controller = loader.getController();
controller.setEdge(edge);
ChoiceBox directionBox = controller.getDirectionBox();
ChoiceBox typeBox = controller.getTypeBox();
controller.getOkButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//If no change in type of edge we just change direction of old edge
if(typeBox.getValue().equals(edge.getType()) || typeBox.getValue() == null){
edge.setStartMultiplicity(controller.getStartMultiplicity());
edge.setEndMultiplicity(controller.getEndMultiplicity());
if (directionBox.getValue() != null) {
diagramController.getUndoManager().add(new DirectionChangeEdgeCommand(edge, edge.getDirection(),
AbstractEdge.Direction.valueOf(directionBox.getValue().toString())));
edge.setDirection(AbstractEdge.Direction.valueOf(directionBox.getValue().toString()));
}
} else { //Else we create a new one to replace the old
AbstractEdge newEdge = null;
if (typeBox.getValue().equals("Inheritance")) {
newEdge = new InheritanceEdge(edge.getStartNode(), edge.getEndNode());
} else if (typeBox.getValue().equals("Association") ) {
newEdge = new AssociationEdge(edge.getStartNode(), edge.getEndNode());
} else if (typeBox.getValue().equals("Aggregation")) {
newEdge = new AggregationEdge(edge.getStartNode(), edge.getEndNode());
} else if (typeBox.getValue().equals("Composition")) {
newEdge = new CompositionEdge(edge.getStartNode(), edge.getEndNode());
}
newEdge.setDirection(AbstractEdge.Direction.valueOf(directionBox.getValue().toString()));
newEdge.setStartMultiplicity(controller.getStartMultiplicity());
newEdge.setEndMultiplicity(controller.getEndMultiplicity());
replaceEdge(edge, newEdge);
}
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
}
});
controller.getCancelButton().setOnAction(event -> {
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
});
diagramController.addDialog(dialog);
aDrawPane.getChildren().add(dialog);
return controller.isOkClicked();
} catch (IOException e) {
// Exception gets thrown if the classDiagramView.fxml file could not be loaded
e.printStackTrace();
return false;
}
}
else{
// Load the classDiagramView.fxml file and create a new stage for the popup
VBox group = new VBox();
TextField input = new TextField();
input.setText(edge.getTitle());
TextField bandwidth = new TextField();
if(edge.getBandwidth()>0)
bandwidth.setText(String.valueOf(edge.getBandwidth()));
TextField netdelay = new TextField();
if(edge.getNetdelay()>0)
netdelay.setText(String.valueOf(edge.getNetdelay()));
// TextField cost = new TextField();
// if(edge.getCost()>0)
// cost.setText(String.valueOf(edge.getCost()));
Button okButton = new Button("Ok");
okButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
edge.setTitle(input.getText());
edge.setBandwidth(Integer.valueOf(bandwidth.getText()));
edge.setNetdelay(Double.valueOf(netdelay.getText()));
// edge.setCost(Integer.valueOf(cost.getText()));
aDrawPane.getChildren().remove(group);
}
});
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
aDrawPane.getChildren().remove(group);
}
});
Label label = new Label("Choose title");
group.getChildren().add(label);
group.getChildren().add(input);
Label label1 = new Label("Input Bandwidth ");
group.getChildren().add(label1);
group.getChildren().add(bandwidth);
Label label2 = new Label("Input Network Delay");
group.getChildren().add(label2);
group.getChildren().add(netdelay);
// Label label3 = new Label("Input Cost");
//group.getChildren().add(label3);
//group.getChildren().add(cost);
HBox buttons = new HBox();
buttons.getChildren().add(okButton);
buttons.getChildren().add(cancelButton);
buttons.setPadding(new Insets(15, 0, 0, 0));
group.getChildren().add(buttons);
group.setLayoutX(edge.getStartNode().getX()+edge.getStartNode().getWidth()+5);
group.setLayoutY(edge.getStartNode().getY()+5);
group.setBackground(new Background(new BackgroundFill(Color.WHITESMOKE, new CornerRadii(1), null)));
group.setStyle("-fx-border-color: black");
group.setPadding(new Insets(15, 12, 15, 12));
aDrawPane.getChildren().add(group);
return false;
}
}
public boolean showMessageEditDialog(MessageEdge edge) {
if(!edge.getstartedge()){
//if(diagramController instanceof DeploymentController)
try {
// Load the classDiagramView.fxml file and create a new stage for the popup
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("view/fxml/messageEditDialog.fxml"));
AnchorPane dialog = loader.load();
dialog.setBackground(new Background(new BackgroundFill(Color.WHITESMOKE, new CornerRadii(1), null)));
dialog.setStyle("-fx-border-color: black");
//Set location for "dialog".
if(edge.getStartNode() != null) {
dialog.setLayoutX((edge.getStartNode().getTranslateX() + edge.getEndNode().getTranslateX()) / 2);
dialog.setLayoutY((edge.getStartNode().getTranslateY() + edge.getEndNode().getTranslateY()) / 2);
} else {
dialog.setLayoutX((edge.getStartX() + edge.getEndNode().getTranslateX()) / 2);
dialog.setLayoutY((edge.getStartY() + edge.getEndNode().getTranslateY()) / 2);
}
MessageEditDialogController controller = loader.getController();
controller.setEdge(edge);
ChoiceBox directionBox = controller.getDirectionBox();
ChoiceBox typeBox = controller.getTypeBox();
TextField titleTextField = controller.getTitleTextField();
titleTextField.setText(edge.getTitle());
TextField netTextField = controller.getNetworkTextField();
if(edge.getNetwork()>0)
netTextField.setText(String.valueOf(edge.getNetwork()));
controller.getOkButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
edge.setMessageType((MessageEdge.MessageType)typeBox.getValue());
if (directionBox.getValue() != null) {
diagramController.getUndoManager().add(new DirectionChangeEdgeCommand(edge, edge.getDirection(),
AbstractEdge.Direction.valueOf(directionBox.getValue().toString())));
edge.setDirection(AbstractEdge.Direction.valueOf(directionBox.getValue().toString()));
}
if(titleTextField.getText() != null){
edge.setTitle(titleTextField.getText());
}
if(netTextField.getText() != null){
edge.setNetwork(Integer.valueOf(netTextField.getText()));
}
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
}
});
controller.getCancelButton().setOnAction(event -> {
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
});
diagramController.addDialog(dialog);
aDrawPane.getChildren().add(dialog);
return controller.isOkClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
else{
try {
// Load the classDiagramView.fxml file and create a new stage for the popup
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("view/fxml/startmessageEditDialog.fxml"));
AnchorPane dialog = loader.load();
dialog.setBackground(new Background(new BackgroundFill(Color.WHITESMOKE, new CornerRadii(1), null)));
dialog.setStyle("-fx-border-color: black");
//Set location for "dialog".
if(edge.getStartNode() != null) {
dialog.setLayoutX((edge.getStartNode().getTranslateX() + edge.getEndNode().getTranslateX()) / 2);
dialog.setLayoutY((edge.getStartNode().getTranslateY() + edge.getEndNode().getTranslateY()) / 2);
} else {
dialog.setLayoutX((edge.getStartX() + edge.getEndNode().getTranslateX()) / 2);
dialog.setLayoutY((edge.getStartY() + edge.getEndNode().getTranslateY()) / 2);
}
MessageEditDialogController controller = loader.getController();
controller.setEdge(edge);
ChoiceBox directionBox = controller.getDirectionBox();
ChoiceBox typeBox = controller.getTypeBox();
TextField titleTextField = controller.getTitleTextField();
titleTextField.setText(edge.getTitle());
// ChoiceBox lowfailTextField = controller.getexlowerfailport();
// ChoiceBox upfailTextField = controller.getexuperfailport();
controller.getOkButton().setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
edge.setMessageType((MessageEdge.MessageType)typeBox.getValue());
if (directionBox.getValue() != null) {
diagramController.getUndoManager().add(new DirectionChangeEdgeCommand(edge, edge.getDirection(),
AbstractEdge.Direction.valueOf(directionBox.getValue().toString())));
edge.setDirection(AbstractEdge.Direction.valueOf(directionBox.getValue().toString()));
}
if(titleTextField.getText() != null){
edge.setTitle(titleTextField.getText());
}
// if(lowfailTextField.getValue() != null){
// edge.setLowfail(Double.valueOf(lowfailTextField.getValue().toString()));
// }
// if(upfailTextField.getValue() != null){
// edge.setUpfail(Double.valueOf(upfailTextField.getValue().toString()));
// }
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
}
});
controller.getCancelButton().setOnAction(event -> {
aDrawPane.getChildren().remove(dialog);
diagramController.removeDialog(dialog);
});
diagramController.addDialog(dialog);
aDrawPane.getChildren().add(dialog);
return controller.isOkClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
public boolean replaceEdge(AbstractEdge oldEdge, AbstractEdge newEdge) {
AbstractEdgeView oldEdgeView = null;
for (AbstractEdgeView edgeView : diagramController.getAllEdgeViews()) {
if (edgeView.getRefEdge().equals(oldEdge)) {
oldEdgeView = edgeView;
break;
}
}
if (oldEdgeView == null) {
return false;
}
diagramController.deleteEdgeView(oldEdgeView, null, true, false);
AbstractEdgeView newEdgeView = diagramController.createEdgeView(newEdge, oldEdgeView.getStartNode(), oldEdgeView.getEndNode());
diagramController.getUndoManager().add(
new ReplaceEdgeCommand(oldEdge, newEdge, oldEdgeView, newEdgeView, diagramController, diagramController.getGraphModel())
);
return true;
}
} | gpl-3.0 |
egovernments/egov-playground | eGov/egov/egov-pgrweb/src/main/java/org/egov/pgr/web/controller/masters/escalation/BulkEscalationGenerator.java | 2815 | /*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) <2015> eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org.
*/
package org.egov.pgr.web.controller.masters.escalation;
import java.util.List;
import org.egov.pgr.entity.ComplaintType;
import org.egov.pims.commons.Position;
public class BulkEscalationGenerator {
private List<ComplaintType> complaintTypes;
private Position fromPosition;
private Position toPosition;
public List<ComplaintType> getComplaintTypes() {
return complaintTypes;
}
public void setComplaintTypes(final List<ComplaintType> complaintTypes) {
this.complaintTypes = complaintTypes;
}
public Position getFromPosition() {
return fromPosition;
}
public void setFromPosition(final Position fromPosition) {
this.fromPosition = fromPosition;
}
public Position getToPosition() {
return toPosition;
}
public void setToPosition(final Position toPosition) {
this.toPosition = toPosition;
}
}
| gpl-3.0 |
makercafe/makerbench | src/main/java/be/makercafe/apps/makerbench/editors/utils/VFX3DUtil.java | 4253 | /*
* Copyright (c) 2013, 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 be.makercafe.apps.makerbench.editors.utils;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.shape.MeshView;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.CullFace;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.transform.Rotate;
/**
* Utility class that allows to visualize meshes created with null {@link MathUtil#evaluateFunction(
* eu.mihosoft.vrl.javaone2013.math.Function2D,
* int, int, float, float, float, double, double, double, double)
* }.
*
* @author Michael Hoffer <info@michaelhoffer.de>
*/
public class VFX3DUtil {
private VFX3DUtil() {
throw new AssertionError("don't instanciate me!");
}
/**
* Adds rotation behavior to the specified node.
*
* @param n node
* @param eventReceiver receiver of the event
* @param btn mouse button that shall be used for this behavior
*/
public static void addMouseBehavior(
Node n, Scene eventReceiver, MouseButton btn) {
eventReceiver.addEventHandler(MouseEvent.ANY,
new MouseBehaviorImpl1(n, btn));
}
/**
* Adds rotation behavior to the specified node.
*
* @param n node
* @param eventReceiver receiver of the event
* @param btn mouse button that shall be used for this behavior
*/
public static void addMouseBehavior(
Node n, Node eventReceiver, MouseButton btn) {
eventReceiver.addEventHandler(MouseEvent.ANY,
new MouseBehaviorImpl1(n, btn));
}
}
// rotation behavior implementation
class MouseBehaviorImpl1 implements EventHandler<MouseEvent> {
private double anchorAngleX;
private double anchorAngleY;
private double anchorX;
private double anchorY;
private final Rotate rotateX = new Rotate(0, 0, 0, 0, Rotate.X_AXIS);
private final Rotate rotateZ = new Rotate(0, 0, 0, 0, Rotate.Z_AXIS);
private MouseButton btn;
public MouseBehaviorImpl1(Node n, MouseButton btn) {
n.getTransforms().addAll(rotateX, rotateZ);
this.btn = btn;
if (btn == null) {
this.btn = MouseButton.MIDDLE;
}
}
@Override
public void handle(MouseEvent t) {
if (!btn.equals(t.getButton())) {
return;
}
t.consume();
if (MouseEvent.MOUSE_PRESSED.equals(t.getEventType())) {
anchorX = t.getSceneX();
anchorY = t.getSceneY();
anchorAngleX = rotateX.getAngle();
anchorAngleY = rotateZ.getAngle();
t.consume();
} else if (MouseEvent.MOUSE_DRAGGED.equals(t.getEventType())) {
rotateZ.setAngle(anchorAngleY + (anchorX - t.getSceneX()) * 0.7);
rotateX.setAngle(anchorAngleX - (anchorY - t.getSceneY()) * 0.7);
}
}
}
| gpl-3.0 |
nfloersch/wpgis | jpen/demo/package-info.java | 747 | /* [{
Copyright 2010 Nicolas Carranza <nicarran at gmail.com>
This file is part of jpen.
jpen 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.
jpen 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 jpen. If not, see <http://www.gnu.org/licenses/>.
}] */
/**
Demo utilities.
*/
package jpen.demo; | gpl-3.0 |
Niky4000/UsefulUtils | different/TestProjects/Pump/TestPumpUtils/src/main/java/ru/ibs/testpumputils/IntSmoAktPfFileExporterTest.java | 1990 | ///*
// * 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 ru.ibs.testpumputils;
//
//import java.text.SimpleDateFormat;
//import org.hibernate.SessionFactory;
//import ru.ibs.pmp.api.smo.model.Parcel;
//import ru.ibs.pmp.auth.model.SmoEntity;
//import ru.ibs.pmp.smo.export.mo.ReportExportContext;
//import ru.ibs.testpumputils.utils.FieldUtil;
//
//
///**
// *
// * @author me
// */
//public class IntSmoAktPfFileExporterTest {
// static SessionFactory smoSessionFactory;
//
// public static void test() throws Exception {
// smoSessionFactory = TestPumpUtilsMain.buildSmoSessionFactory();
// try {
// IntSmoAktPfFileExporter intSmoAktPfFileExporter = new IntSmoAktPfFileExporter();
// FieldUtil.setField(intSmoAktPfFileExporter, smoSessionFactory, "sessionFactory");
// FieldUtil.setField(intSmoAktPfFileExporter, "http://test.drzsrv.ru:8082/module-reports-pmp/api/reportsInternal/buildSync", "pmpReportUrl");
// SmoEntity smoEntity = new SmoEntity();
// smoEntity.setCode("SMO");
// ReportExportContext context = new ReportExportContext(null, smoEntity);
// context.setDirectory("/home/me/tmp/reportsPdf");
//// Parcel parcel = (Parcel) Db.select(smoSessionFactory, session -> session.get(Parcel.class, 76645L));
// Parcel parcel = new Parcel();
// parcel.setId(74538L);
// parcel.setMoId(2186L);
// parcel.setPeriod(new SimpleDateFormat("yyyy-MM-dd").parse("2020-11-01"));
// context.setParcel(parcel);
// context.setPeriod(new SimpleDateFormat("yyyy-MM-dd").parse("2020-11-01"));
// context.setMoId(2186L);
// intSmoAktPfFileExporter.exportFile(context);
// } finally {
// smoSessionFactory.close();
// }
// }
//}
| gpl-3.0 |
hantsy/spring-reactive-sample | data-couchbase/src/main/java/com/example/demo/DataInitializer.java | 1329 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
/**
*
* @author hantsy
*/
@Component
@Slf4j
class DataInitializer {
private final PostRepository posts;
public DataInitializer(PostRepository posts) {
this.posts = posts;
}
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization ...");
this.posts
.deleteAll()
.thenMany(
Flux
.just("Post one", "Post two")
.flatMap(
title -> this.posts.save(Post.builder().id(UUID.randomUUID().toString()).title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
}
} | gpl-3.0 |
schwabdidier/GazePlay | gazeplay-games/src/main/java/net/gazeplay/games/magicpotions/Potion.java | 9591 | package net.gazeplay.games.magicpotions;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.gazeplay.IGameContext;
import net.gazeplay.commons.gaze.devicemanager.GazeEvent;
import java.io.IOException;
/**
* @author Johana MARKU
*/
@Slf4j
class Potion extends Parent {
private final double fixationLength;
@Getter
private final Rectangle potion;
@Getter
private final Color potionColor;
@Getter
private final Image image;
/**
* true if the potion has been used/chosen for the mixture
*/
@Setter
@Getter
private boolean chosen;
private final ProgressIndicator progressIndicator;
private Timeline timelineProgressBar; // used to make a selection long = fixation length
private final MagicPotions gameInstance;
private final IGameContext gameContext;
private final MagicPotionsStats stats;
@Getter
final EventHandler<Event> enterEvent;
private Timeline currentTimeline;
Potion(final double positionX, final double positionY, final double width, final double height, final Image image, final Color color,
final IGameContext gameContext, final MagicPotionsStats stats, final MagicPotions gameInstance, final int fixationlength) {
this.potion = new Rectangle((int) positionX, (int) positionY, (int) width, (int) height);
this.potion.setFill(new ImagePattern(image, 0, 0, 1, 1, true));
final DropShadow shadow = new DropShadow();
shadow.setColor(Color.BLACK);
shadow.setWidth(10);
shadow.setHeight(10);
shadow.setOffsetX(5);
shadow.setOffsetY(5);
shadow.setRadius(3);
this.potion.setEffect(shadow);
this.image = image;
this.potionColor = color;
this.chosen = false;
this.gameContext = gameContext;
this.stats = stats;
this.gameInstance = gameInstance;
this.fixationLength = fixationlength;
this.enterEvent = buildEvent();
gameContext.getGazeDeviceManager().addEventFilter(this.potion);
this.addEventFilter(MouseEvent.ANY, enterEvent);
this.addEventFilter(GazeEvent.ANY, enterEvent);
currentTimeline = new Timeline();
this.getChildren().add(this.potion);
this.progressIndicator = createProgressIndicator(width);
this.getChildren().add(this.progressIndicator);
}
private ProgressIndicator createProgressIndicator(final double width) {
final ProgressIndicator indicator = new ProgressIndicator(0);
indicator.setTranslateX(potion.getX());
indicator.setTranslateY(potion.getY() + width * 0.75);
indicator.setMinWidth(width * 0.9);
indicator.setMinHeight(width * 0.9);
indicator.setOpacity(0);
return indicator;
}
private void onMixAchieved() {
gameInstance.currentRoundDetails.getMixPotColor().setFill(gameInstance.currentRoundDetails.getColorRequest());
gameInstance.getPotionBlue().removeEventFilter(MouseEvent.ANY, gameInstance.getPotionBlue().getEnterEvent());
gameInstance.getPotionBlue().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionBlue().getEnterEvent());
gameInstance.getPotionRed().removeEventFilter(MouseEvent.ANY, gameInstance.getPotionRed().getEnterEvent());
gameInstance.getPotionRed().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionRed().getEnterEvent());
gameInstance.getPotionYellow().removeEventFilter(MouseEvent.ANY,
gameInstance.getPotionYellow().getEnterEvent());
gameInstance.getPotionYellow().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionYellow().getEnterEvent());
stats.incrementNumberOfGoalsReached();
currentTimeline.stop();
currentTimeline = new Timeline();
currentTimeline.onFinishedProperty().set(event -> gameContext.playWinTransition(0, event1 -> {
gameInstance.dispose();
gameContext.clear();
gameInstance.launch();
stats.notifyNewRoundReady();
}));
currentTimeline.play();
}
private void onWrongPotionSelected() {
gameInstance.getPotionBlue().removeEventFilter(MouseEvent.ANY, gameInstance.getPotionBlue().getEnterEvent());
gameInstance.getPotionBlue().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionBlue().getEnterEvent());
gameInstance.getPotionRed().removeEventFilter(MouseEvent.ANY, gameInstance.getPotionRed().getEnterEvent());
gameInstance.getPotionRed().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionRed().getEnterEvent());
gameInstance.getPotionYellow().removeEventFilter(MouseEvent.ANY,
gameInstance.getPotionYellow().getEnterEvent());
gameInstance.getPotionYellow().removeEventFilter(GazeEvent.ANY, gameInstance.getPotionYellow().getEnterEvent());
progressIndicator.setStyle(" -fx-progress-color: red;");
progressIndicator.setOpacity(1);
progressIndicator.setAccessibleText("");
currentTimeline.stop();
currentTimeline = new Timeline();
final Explosion exp = new Explosion(gameContext, gameContext.getGamePanelDimensionProvider().getDimension2D());
gameContext.getChildren().add(exp);
gameContext.getChildren().removeAll(gameInstance.currentRoundDetails.getMixPot(), gameInstance.currentRoundDetails.getMixPotColor());
currentTimeline.getKeyFrames().add(new KeyFrame(new Duration(4000), new KeyValue(exp.opacityProperty(), 0)));
currentTimeline.play();
currentTimeline.onFinishedProperty().set(event -> {
gameInstance.dispose();
gameContext.clear();
gameInstance.launch();
try {
stats.saveStats();
} catch (final IOException ex) {
log.info("Io exception");
}
});
}
private EventHandler<Event> buildEvent() {
return event -> {
if (chosen) {
return;
}
if (event.getEventType() == MouseEvent.MOUSE_ENTERED
|| event.getEventType() == GazeEvent.GAZE_ENTERED) {
progressIndicator.setOpacity(1);
progressIndicator.setProgress(0);
timelineProgressBar = new Timeline();
timelineProgressBar.getKeyFrames().add(new KeyFrame(new Duration(fixationLength),
new KeyValue(progressIndicator.progressProperty(), 1)));
timelineProgressBar.setOnFinished(event1 -> {
chosen = true;
gameInstance.currentRoundDetails.getMixture().add(potionColor); // we add the color of the potion to our mixture
// change opacity of potion when it has been selected once
potion.setOpacity(.3);
potion.removeEventFilter(MouseEvent.ANY, enterEvent); // we cannot select anymore this color
potion.removeEventFilter(GazeEvent.ANY, enterEvent);
if (!gameInstance.currentRoundDetails.getPotionsToMix().contains(potionColor)) {
onWrongPotionSelected();
} else if (gameInstance.currentRoundDetails.getMixture().containsAll(gameInstance.currentRoundDetails.getPotionsToMix())) {
onMixAchieved();
} else {
stats.incrementNumberOfGoalsToReach();
}
switch (gameInstance.currentRoundDetails.getMixture().size()) {
case 1:
gameInstance.currentRoundDetails.getMixPotColor().setFill(gameInstance.currentRoundDetails.getMixture().get(0));
break;
case 2:
if (gameInstance.currentRoundDetails.getPotionsToMix().size() == 2) {
gameInstance.currentRoundDetails.getMixPotColor()
.setFill(gameInstance.currentRoundDetails.getRequest().getColor());
} else {
gameInstance.currentRoundDetails.getMixPotColor().setFill(gameInstance.currentRoundDetails.getMixture().get(1));
}
break;
case 3:
gameInstance.currentRoundDetails.getMixPotColor().setFill(Color.BLACK);
break;
default:
throw new IllegalArgumentException("value : " + gameInstance.currentRoundDetails.getMixture().size());
}
});
timelineProgressBar.play();
} else if (event.getEventType() == MouseEvent.MOUSE_EXITED
|| event.getEventType() == GazeEvent.GAZE_EXITED) {
timelineProgressBar.stop();
progressIndicator.setOpacity(0);
progressIndicator.setProgress(0);
}
};
}
}
| gpl-3.0 |
gianitobia/ippocrate-j2ee | Ippocrate-ejb/src/java/Entity/CartellaClinica.java | 2880 | /*
* 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 Entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
/**
*
* @author toby
*/
@Entity
public class CartellaClinica implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(mappedBy = "cartella_clinica")
private Paziente paziente;
private String anamnesi;
@OneToMany
private List<RefertoMedico> lista_referti;
/**
* Get the value of paziente
*
* @return the value of paziente
*/
public Paziente getPaziente() {
return paziente;
}
/**
* Set the value of paziente
*
* @param paziente new value of paziente
*/
public void setPaziente(Paziente paziente) {
this.paziente = paziente;
}
/**
* Get the value of anamnesi
*
* @return the value of anamnesi
*/
public String getAnamnesi() {
return anamnesi;
}
/**
* Set the value of anamnesi
*
* @param anamnesi new value of anamnesi
*/
public void setAnamnesi(String anamnesi) {
this.anamnesi = anamnesi;
}
/**
* Get the value of lista_referti
*
* @return the value of lista_referti
*/
public List<RefertoMedico> getLista_referti() {
return lista_referti;
}
/**
* Set the value of lista_referti
*
* @param lista_referti new value of lista_referti
*/
public void setLista_referti(List<RefertoMedico> lista_referti) {
this.lista_referti = lista_referti;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CartellaClinica)) {
return false;
}
CartellaClinica other = (CartellaClinica) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "CartellaClinica [" + "id " + id + " " + "anamnesi " + anamnesi + " " + "paziente " + paziente + "]";
}
}
| gpl-3.0 |
sjPlot/Zettelkasten | src/main/java/de/danielluedecke/zettelkasten/util/PlatformUtil.java | 6976 | /*
* Zettelkasten - nach Luhmann
* Copyright (C) 2001-2015 by Daniel Lüdecke (http://www.danielluedecke.de)
*
* Homepage: http://zettelkasten.danielluedecke.de
*
*
* 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/>.
*
*
* Dieses Programm ist freie Software. Sie können es unter den Bedingungen der GNU
* General Public License, wie von der Free Software Foundation veröffentlicht, weitergeben
* und/oder modifizieren, entweder gemäß Version 3 der Lizenz oder (wenn Sie möchten)
* jeder späteren Version.
*
* Die Veröffentlichung dieses Programms erfolgt in der Hoffnung, daß es Ihnen von Nutzen sein
* wird, aber OHNE IRGENDEINE GARANTIE, sogar ohne die implizite Garantie der MARKTREIFE oder
* der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Details finden Sie in der
* GNU General Public License.
*
* Sie sollten ein Exemplar der GNU General Public License zusammen mit diesem Programm
* erhalten haben. Falls nicht, siehe <http://www.gnu.org/licenses/>.
*/
package de.danielluedecke.zettelkasten.util;
/**
*
* @author Daniel Luedecke
*/
public class PlatformUtil {
/**
* Indicates whether the programm is running on a mac or not...
* @return {@code true} if current OS is any mac os
*/
public static boolean isMacOS() {
return System.getProperty("os.name").toLowerCase().startsWith("mac os");
}
/**
* Indicates whether the programm is running on a linux or not...
* @return {@code true} if current OS is any linux os
*/
public static boolean isLinux() {
return System.getProperty("os.name").toLowerCase().contains("linux");
}
/**
* Retrieve current Java version.
* @return The current Java version as string.
*/
public static String getJavaVersion() {
return System.getProperty("java.version");
}
/**
* Indicates whether Mac OS X 10.5 (Leopard) is running...
* @return {@code true} if current OS is mac os 10.5 (Leopard)
*/
public static boolean isLeopard() {
return isMacOS() & System.getProperty("os.version").startsWith("10.5");
}
/**
* Indicates whether Mac OS X 10.6 (Snow Leopard) is running...
* @return {@code true} if current OS is mac os 10.6 (snow leopard)
*/
public static boolean isSnowLeopard() {
return isMacOS() & System.getProperty("os.version").startsWith("10.6");
}
/**
* Indicates whether Mac OS X 10.7 (Lion) is running...
* @return {@code true} if current OS is mac os 10.7 (lion)
*/
public static boolean isLion() {
return isMacOS() & System.getProperty("os.version").startsWith("10.7");
}
/**
* Indicates whether Mac OS X 10.8 (Mountain LION) is running...
* @return {@code true} if current OS is mac os 10.8 (mountain lion)
*/
public static boolean isMountainLion() {
return isMacOS() & System.getProperty("os.version").startsWith("10.8");
}
/**
* Indicates whether Mac OS X 10.9 (Mavericks) is running...
* @return {@code true} if current OS is mac os 10.8 (mountain lion)
*/
public static boolean isMavericks() {
return isMacOS() & System.getProperty("os.version").startsWith("10.9");
}
/**
* Indicates whether Mac OS X 10.10 (Yosemite) is running...
* @return {@code true} if current OS is mac os 10.8 (mountain lion)
*/
public static boolean isYosemite() {
return isMacOS() & System.getProperty("os.version").startsWith("10.10");
}
/**
* Indicates whether Mac OS X 10.10 (El Capitan) is running...
* @return {@code true} if current OS is mac os 10.8 (mountain lion)
*/
public static boolean isElCapitan() {
return isMacOS() & System.getProperty("os.version").startsWith("10.11");
}
/**
* Indicates whether the OS is a windows OS
* @return {@code true} if current OS is a windows system
*/
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}
/**
* indicates whether java 7 is running on windows
* @return {@code true} if current OS is a windows system with Java 1.7 installed
*/
public static boolean isJava7OnWindows() {
return isWindows() && getJavaVersion().startsWith("1.7");
}
/**
* indicates whether java 8 is running on windows
* @return {@code true} if current OS is a windows system with Java 1.8 installed
*/
public static boolean isJava8OnWindows() {
return isWindows() && getJavaVersion().startsWith("1.8");
}
/**
* indicates whether java 7 is running on mac
* @return {@code true} if current OS is any mac os with Java 1.7 installed
*/
public static boolean isJava7OnMac() {
return isMacOS() && getJavaVersion().startsWith("1.7");
}
/**
* indicates whether java 8 is running on mac
* @return {@code true} if current OS is any mac os with Java 1.8 installed
*/
public static boolean isJava8OnMac() {
return isMacOS() && getJavaVersion().startsWith("1.8");
}
/**
* indicates whether java 7 is running on current system
* @return {@code true} if Java 1.7 is installed on current system
*/
public static boolean isJava7() {
return getJavaVersion().startsWith("1.7");
}
/**
* indicates whether java 8 is running on current system
* @return {@code true} if Java 1.8 is installed on current system
*/
public static boolean isJava8() {
return getJavaVersion().startsWith("1.8");
}
/**
* indicates whether java 6 is running on mac
* @return {@code true} if current OS is any mac os with Java 1.6 installed
*/
public static boolean isJava6OnMac() {
return isMacOS() && getJavaVersion().startsWith("1.6");
}
/**
* Indicates wether the current OS is Windows 7
* @return {@code true} if current OS is windows 7
*/
public static boolean isWindows7() {
return System.getProperty("os.name").toLowerCase().startsWith("windows 7");
}
/**
* Indicates wether the current OS is Windows 8
* @return {@code true} if current OS is windows 8
*/
public static boolean isWindows8() {
return System.getProperty("os.name").toLowerCase().startsWith("windows 8");
}
}
| gpl-3.0 |
DimsFromDergachy/Mobile-Scanner | app/src/androidTest/java/com/dimsfromdergachy/mobilescanner/ApplicationTest.java | 365 | package com.dimsfromdergachy.mobilescanner;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/tools/grs/src/coop/tecso/grs/page/PageExceptionHelper.java | 601 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package coop.tecso.grs.page;
/**
*
* @author Andrei
*
*/
public class PageExceptionHelper {
private static void checkRequiredField(String type,String field, String value) throws PageException {
if (!"".equals(value) && value!=null){
System.out.println("OK");
}
else
throw new PageException("Error: Required Field");
}
} | gpl-3.0 |
vertigo17/Cerberus | source/src/main/java/org/cerberus/crud/service/ITestCaseStepActionControlExecutionService.java | 3353 | /**
* Cerberus Copyright (C) 2013 - 2017 cerberustesting
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cerberus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.crud.service;
import java.util.List;
import org.cerberus.crud.entity.TestCaseStepActionControlExecution;
import org.cerberus.util.answer.AnswerItem;
import org.cerberus.util.answer.AnswerList;
/**
*
* @author bcivel
*/
public interface ITestCaseStepActionControlExecutionService {
/**
*
* @param testCaseStepActionControlExecution
*/
void insertTestCaseStepActionControlExecution(TestCaseStepActionControlExecution testCaseStepActionControlExecution);
/**
*
* @param testCaseStepActionControlExecution
*/
void updateTestCaseStepActionControlExecution(TestCaseStepActionControlExecution testCaseStepActionControlExecution);
List<TestCaseStepActionControlExecution> findTestCaseStepActionControlExecutionByCriteria(long id, String test, String testCase, int stepId, int index, int sequence);
/**
* Return the testcasestepactioncontrolexecution list of an execution, stepId, action
* @param executionId : ID of the execution
* @param test : test
* @param testcase : testcase
* @param stepId : ID of the stepId
* @param index
* @param sequence : ID of the action
* @return List of testcasestepactioncontrol object
*/
public AnswerList<TestCaseStepActionControlExecution> readByVarious1(long executionId, String test, String testcase, int stepId, int index, int sequence);
/**
* Return the testcasestepactioncontrolexecution list of an execution, stepId, action
* @param executionId : ID of the execution
* @param test : test
* @param testcase : testcase
* @param stepId : ID of the stepId
* @param index
* @param sequence : ID of the action
* @param controlSequence : ID of the control
* @return List of testcasestepactioncontrol object
*/
public AnswerItem<TestCaseStepActionControlExecution> readByKey(long executionId, String test, String testcase, int stepId, int index, int sequence, int controlSequence);
/**
* Return the testcasestepactioncontrolexecution list of an execution, stepId, action
* @param executionId : ID of the execution
* @param test : test
* @param testcase : testcase
* @param stepId : ID of the stepId
* @param index
* @param sequence : ID of the action
* @return List of testcasestepactioncontrol object
*/
public AnswerList<TestCaseStepActionControlExecution> readByVarious1WithDependency(long executionId, String test, String testcase, int stepId, int index, int sequence);
}
| gpl-3.0 |
ashish-gehani/SPADE | src/spade/query/quickgrail/instruction/GetLineage.java | 4202 | /*
--------------------------------------------------------------------------------
SPADE - Support for Provenance Auditing in Distributed Environments.
Copyright (C) 2018 SRI International
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 spade.query.quickgrail.instruction;
import java.util.ArrayList;
import java.util.logging.Logger;
import spade.core.AbstractTransformer;
import spade.query.quickgrail.core.Instruction;
import spade.query.quickgrail.core.QueryInstructionExecutor;
import spade.query.quickgrail.entities.Graph;
import spade.query.quickgrail.utility.TreeStringSerializable;
/**
* Get the lineage of a set of vertices in a graph.
*/
public class GetLineage extends Instruction<String>{
public static final Logger logger = Logger.getLogger(GetLineage.class.getName());
public static enum Direction{
kAncestor, kDescendant, kBoth
}
// Output graph.
public final Graph targetGraph;
// Input graph.
public final Graph subjectGraph;
// Set of starting vertices.
public final Graph startGraph;
// Max depth.
public final int depth;
// Direction (ancestors / descendants, or both).
public final Direction direction;
public GetLineage(Graph targetGraph, Graph subjectGraph, Graph startGraph, int depth, Direction direction){
this.targetGraph = targetGraph;
this.subjectGraph = subjectGraph;
this.startGraph = startGraph;
this.depth = depth;
this.direction = direction;
}
@Override
public String getLabel(){
return "GetLineage";
}
@Override
protected void getFieldStringItems(ArrayList<String> inline_field_names, ArrayList<String> inline_field_values,
ArrayList<String> non_container_child_field_names,
ArrayList<TreeStringSerializable> non_container_child_fields, ArrayList<String> container_child_field_names,
ArrayList<ArrayList<? extends TreeStringSerializable>> container_child_fields){
inline_field_names.add("targetGraph");
inline_field_values.add(targetGraph.name);
inline_field_names.add("subjectGraph");
inline_field_values.add(subjectGraph.name);
inline_field_names.add("startGraph");
inline_field_values.add(startGraph.name);
inline_field_names.add("depth");
inline_field_values.add(String.valueOf(depth));
inline_field_names.add("direction");
inline_field_values.add(direction.name().substring(1));
}
@Override
public void updateTransformerExecutionContext(final QueryInstructionExecutor executor,
final AbstractTransformer.ExecutionContext context){
final spade.core.Graph sourceGraph = executor.exportGraph(startGraph, true);
context.setSourceGraph(sourceGraph);
context.setMaxDepth(depth);
context.setDirection(direction);
}
@Override
public String execute(final QueryInstructionExecutor executor){
if(executor.getGraphCount(startGraph).getVertices() <= 0){
return null;
}
if(executor.getGraphCount(subjectGraph).getEdges() == 0){
// Nothing to start from since no vertices OR no where to go in the subject since no edges
return null;
}
if(Direction.kAncestor.equals(direction) || Direction.kDescendant.equals(direction)){
executor.getLineage(targetGraph, subjectGraph, startGraph, depth, direction);
}else if(Direction.kBoth.equals(direction)){
executor.getLineage(targetGraph, subjectGraph, startGraph, depth, Direction.kAncestor);
executor.getLineage(targetGraph, subjectGraph, startGraph, depth, Direction.kDescendant);
}else{
throw new RuntimeException(
"Unexpected direction: '" + direction + "'. Expected: Ancestor, Descendant or Both");
}
return null;
}
}
| gpl-3.0 |
eztong/xillium | base/src/main/java/org/xillium/base/type/Flags.java | 2302 | package org.xillium.base.type;
import java.util.*;
import org.xillium.base.beans.Strings;
/**
* A String-friendly wrapper of java.util.EnumSet, this bit mask implementation allows its
* value to be represented as a String of concatenated enum names.
* <p/>
* Beans.setValue() recognizes Flags fields and will perform String to Flags assignment.
* However due to type erasure Beans can't resolve the enum type associated with the Flags
* field unless the field is annotated with @typeinfo, as following.
* <xmp>
* @typeinfo(MyEnumType.class) Flags<MyEnumType> flags;
* </xmp>
*/
public class Flags<E extends Enum<E>> {
private final EnumSet<E> _mask;
/**
* Constructs a Flags with all individual flags cleared.
*/
public Flags(Class<E> type) {
_mask = EnumSet.noneOf(type);
}
/**
* Sets a flag corresponding to the given enum value.
*/
public Flags<E> set(E e) {
_mask.add(e);
return this;
}
/**
* Clears all flags.
*/
public Flags<E> clear() {
_mask.clear();
return this;
}
/**
* Tests whether a flag corresponding to the given enum value is set or not.
*/
public boolean isSet(E e) {
return _mask.contains(e);
}
/**
* Tests whether none of the flags is set or not.
*/
public boolean isNone() {
return _mask.size() == 0;
}
/**
* Returns a string representation of this object, in a format compatible with the static valueOf() method.
*/
public String toString() {
return Strings.join(_mask, ':');
}
/**
* Returns a string representation of this object, in a format compatible with the static valueOf() method.
*/
public String getText() {
return Strings.join(_mask, ':');
}
/**
* Returns a Flags with a value represented by a string of concatenated enum literal names
* separated by any combination of a comma, a colon, or a white space.
*/
public static <E extends Enum<E>> Flags<E> valueOf(Class<E> type, String values) {
Flags<E> flags = new Flags<E>(type);
for (String text : values.trim().split("[,:\\s]{1,}")) {
flags.set(Enum.valueOf(type, text));
}
return flags;
}
}
| gpl-3.0 |
TrucklistStudio/truckliststudio | src/com/jhlabs/image/BorderFilter.java | 5178 | /*
Copyright 2006 Jerry Huxtable
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.jhlabs.image;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
/**
* A filter to add a border around an image using the supplied Paint, which may be null for no painting.
*/
public class BorderFilter extends AbstractBufferedImageOp {
private int leftBorder, rightBorder;
private int topBorder, bottomBorder;
private Paint borderPaint;
/**
* Construct a BorderFilter which does nothing.
*/
public BorderFilter() {
}
/**
* Construct a BorderFilter.
* @param leftBorder the left border value
* @param topBorder the top border value
* @param rightBorder the right border value
* @param bottomBorder the bottom border value
* @param borderPaint the paint with which to fill the border
*/
public BorderFilter( int leftBorder, int topBorder, int rightBorder, int bottomBorder, Paint borderPaint ) {
this.leftBorder = leftBorder;
this.topBorder = topBorder;
this.rightBorder = rightBorder;
this.bottomBorder = bottomBorder;
this.borderPaint = borderPaint;
}
/**
* Set the border size on the left edge.
* @param leftBorder the number of pixels of border to add to the edge
* @min-value 0
* @see #getLeftBorder
*/
public void setLeftBorder(int leftBorder) {
this.leftBorder = leftBorder;
}
/**
* Returns the left border value.
* @return the left border value.
* @see #setLeftBorder
*/
public int getLeftBorder() {
return leftBorder;
}
/**
* Set the border size on the right edge.
* @param rightBorder the number of pixels of border to add to the edge
* @min-value 0
* @see #getRightBorder
*/
public void setRightBorder(int rightBorder) {
this.rightBorder = rightBorder;
}
/**
* Returns the right border value.
* @return the right border value.
* @see #setRightBorder
*/
public int getRightBorder() {
return rightBorder;
}
/**
* Set the border size on the top edge.
* @param topBorder the number of pixels of border to add to the edge
* @min-value 0
* @see #getTopBorder
*/
public void setTopBorder(int topBorder) {
this.topBorder = topBorder;
}
/**
* Returns the top border value.
* @return the top border value.
* @see #setTopBorder
*/
public int getTopBorder() {
return topBorder;
}
/**
* Set the border size on the bottom edge.
* @param bottomBorder the number of pixels of border to add to the edge
* @min-value 0
* @see #getBottomBorder
*/
public void setBottomBorder(int bottomBorder) {
this.bottomBorder = bottomBorder;
}
/**
* Returns the border border value.
* @return the border border value.
* @see #setBottomBorder
*/
public int getBottomBorder() {
return bottomBorder;
}
/**
* Set the border paint.
* @param borderPaint the paint with which to fill the border
* @see #getBorderPaint
*/
public void setBorderPaint( Paint borderPaint ) {
this.borderPaint = borderPaint;
}
/**
* Get the border paint.
* @return the paint with which to fill the border
* @see #setBorderPaint
*/
public Paint getBorderPaint() {
return borderPaint;
}
@Override
public BufferedImage filter( BufferedImage src, BufferedImage dst ) {
int width = src.getWidth();
int height = src.getHeight();
if ( dst == null ) {
dst = new BufferedImage( width+leftBorder+rightBorder, height+topBorder+bottomBorder, src.getType() );
}
Graphics2D g = dst.createGraphics();
if ( borderPaint != null ) {
g.setPaint( borderPaint );
if ( leftBorder > 0 ) {
g.fillRect( 0, 0, leftBorder, height );
}
if ( rightBorder > 0 ) {
g.fillRect( width-rightBorder, 0, rightBorder, height );
}
if ( topBorder > 0 ) {
g.fillRect( leftBorder, 0, width-leftBorder-rightBorder, topBorder );
}
if ( bottomBorder > 0 ) {
g.fillRect( leftBorder, height-bottomBorder, width-leftBorder-rightBorder, bottomBorder );
}
}
g.drawRenderedImage( src, AffineTransform.getTranslateInstance( leftBorder, rightBorder ) );
g.dispose();
return dst;
}
@Override
public String toString() {
return "Distort/Border...";
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
| gpl-3.0 |
HannesBuchwald/TimeTracker | app/src/main/java/org/hdm/app/timetracker/datastorage/DataManager.java | 7817 | package org.hdm.app.timetracker.datastorage;
import android.graphics.Bitmap;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeMap;
import static org.hdm.app.timetracker.util.Consts.DEBUGMODE;
/**
* Created by Hannes on 06.05.2016.
*/
public class DataManager {
private final String TAG = "DataManager";
// Instance from DaataManager
private static DataManager instance = null;
public HashMap<String, Bitmap> imageMap = new HashMap<>();
// In this Map are all the Activity Objects stored
// It is used as DataBase from every Screen
public LinkedHashMap<String, ActivityObject> activityMap = new LinkedHashMap<>();
// In this map is stored the activitys for Calender list
public TreeMap<String, ArrayList<String>> calenderMap = new TreeMap<>();
public LinkedHashMap<String, ActivityObject> portionMap = new LinkedHashMap<>();
public LinkedHashMap<String, ActivityObject> foodMap = new LinkedHashMap<>();
public ArrayList<String> activeList = new ArrayList<>();
public List<Stamp> logList = new ArrayList<Stamp>();
public String lastLog = "";
public boolean createActivityObject(String name, ActivityObject activityObject) {
if(name != null) {
if(!activityMap.containsKey(name)) {
if(activityObject != null) {
activityMap.put(name, activityObject);
} else {
activityMap.put(name, new ActivityObject(name));
}
return true;
}
}
return false;
}
public boolean setActivityObject(ActivityObject activityObject) {
String title = activityObject.title;
if (title != null && activityMap != null) {
if(!activityMap.containsKey(title)) {
createActivityObject(title, activityObject);
}
activityMap.put(title, activityObject);
if(DEBUGMODE && activityObject.timeFrameList.size()>1) {
Log.d(TAG, "key:" + activityObject.timeFrameList.get(activityObject.timeFrameList.size()-1).startTime);
}
return true;
}
return false;
}
public ActivityObject getActivityObject(String name) {
if(name != null && activityMap.containsKey(name)) {
return activityMap.get(name);
}
return null;
}
public LinkedHashMap getObjectMap() {
return activityMap;
}
public boolean createPortionObject(String name, ActivityObject activityObject) {
if(name != null) {
if(!portionMap.containsKey(name)) {
if(activityObject != null) {
portionMap.put(name, activityObject);
} else {
portionMap.put(name, new ActivityObject(name));
}
return true;
}
}
return false;
}
public boolean setPortionObject(ActivityObject activityObject) {
String title = activityObject.title;
if (title != null && portionMap != null) {
if(!portionMap.containsKey(title)) {
createPortionObject(title, activityObject);
}
portionMap.put(title, activityObject);
// if(DEBUGMODE && activityObject.timeFrameList.size()>1) {
// Log.d(TAG, "key:" + activityObject.timeFrameList.get(activityObject.timeFrameList.size()-1).startTime);
// }
return true;
}
return false;
}
public ActivityObject getPortionObject(String name) {
if(name != null && portionMap.containsKey(name)) {
return portionMap.get(name);
}
return null;
}
public LinkedHashMap getPortionMap() {
return portionMap;
}
public boolean createFoodObject(String name, ActivityObject activityObject) {
if(name != null) {
if(!foodMap.containsKey(name)) {
if(activityObject != null) {
foodMap.put(name, activityObject);
} else {
foodMap.put(name, new ActivityObject(name));
}
return true;
}
}
return false;
}
public boolean setFoodObject(ActivityObject activityObject) {
String title = activityObject.title;
if (title != null && foodMap != null) {
if(!foodMap.containsKey(title)) {
createFoodObject(title, activityObject);
}
foodMap.put(title, activityObject);
if(DEBUGMODE && activityObject.timeFrameList.size()>1) {
Log.d(TAG, "key:" + activityObject.timeFrameList.get(activityObject.timeFrameList.size()-1).startTime);
}
return true;
}
return false;
}
public ActivityObject getFoodObject(String name) {
if(name != null && foodMap.containsKey(name)) {
return foodMap.get(name);
}
return null;
}
public LinkedHashMap getFoodMap() {
return foodMap;
}
public boolean setCalenderMapEntry(String key, String activity) {
// check if key is not null
if (key != null) {
ArrayList<String> list = null;
if(activity != null && calenderMap.containsKey(key)) {
list = calenderMap.get(key);
// do not add enty if list contains already activitys
if(list.contains(activity)) return true;
list.add(activity);
} else {
list = new ArrayList<String>();
}
calenderMap.put(key, list);
if (DEBUGMODE) {
Log.d(TAG, "key: " + key.toString() + " // value: " + calenderMap.get(key).toString());
}
return true;
} else {
return false;
}
}
public boolean setActivityToCalendarList(String key, String activity) {
// check if key is not null
if (key != null && activity != null) {
if(calenderMap.containsKey(key)) {
ArrayList<String> list = calenderMap.get(key);
// do not add enty if list contains already activitys
if (list.contains(activity)) return false;
list.add(activity);
calenderMap.put(key, list);
if (DEBUGMODE) {
Log.d(TAG, "keyy: " + key.toString() + " // value: " + calenderMap.get(key).toString());
}
return true;
}
}
return false;
}
public boolean deleteCalenderMapEntry(String key, String activity){
if(key != null && activity != null) {
if(calenderMap.containsKey(key)) {
ArrayList<String> list = calenderMap.get(key);
if(DEBUGMODE) Log.d(TAG, "listSize before: " + list.size() + " " + list.toString());
if(list.remove(activity)){
if(DEBUGMODE) Log.d(TAG, "listSize after: " + list.size() + " " + list.toString());
return true;
}
}
}
return false;
}
public TreeMap<String, ArrayList<String>> getCalendarMap() {
return calenderMap;
}
/***********
* Singelton pattern
***********/
public static void init() {
if (instance == null) {
instance = new DataManager();
}
}
public static DataManager getInstance() {
if (instance == null) {
instance = new DataManager();
}
return instance;
}
}
| gpl-3.0 |
skpdvdd/PAV | pav/src/pav/configurator/Spectrum.java | 2857 |
/*
* Processing Audio Visualization (PAV)
* Copyright (C) 2011 Christopher Pramerdorfer
*
* 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 pav.configurator;
import pav.Util;
import pav.lib.visualizer.Visualizer;
/**
* Configurator for the Spectrum visualizer.
*
* @author christopher
*/
public class Spectrum extends ConfiguratorAbstract
{
@Override
public boolean process(Visualizer subject, String query)
{
if(! (subject instanceof pav.lib.visualizer.Spectrum)) {
return false;
}
String[] q = query.split(" ");
if(q.length < 2) {
return false;
}
if(q[0].equals("mode")) {
return _processMode((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q));
}
if(q[0].equals("freq")) {
return _processFreq((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q));
}
if(q[0].equals("sw")) {
return _processStrokeWeight((pav.lib.visualizer.Spectrum) subject, Util.removeFirst(q));
}
return false;
}
private boolean _processMode(pav.lib.visualizer.Spectrum subject, String[] query)
{
if(query[0].equals("bins")) {
subject.setMode(pav.lib.visualizer.Waveform.MODE_BINS);
return true;
}
else if(query[0].equals("dots")) {
subject.setMode(pav.lib.visualizer.Waveform.MODE_DOTS);
return true;
}
else if(query[0].equals("shape")) {
subject.setMode(pav.lib.visualizer.Waveform.MODE_SHAPE);
return true;
}
return false;
}
private boolean _processFreq(pav.lib.visualizer.Spectrum subject, String[] query)
{
int[] freqs = Util.tryParseInts(query);
if(freqs.length == 1) {
if(freqs[0] == 0) {
subject.noCutoffFrequencies();
return true;
}
else if(freqs[0] > 0) {
subject.setCutoffFrequencies(0, freqs[0]);
return true;
}
}
else if(freqs.length == 2) {
if(freqs[1] > freqs[0] && freqs[0] >= 0) {
subject.setCutoffFrequencies(freqs[0], freqs[1]);
return true;
}
}
return false;
}
private boolean _processStrokeWeight(pav.lib.visualizer.Spectrum subject, String[] query)
{
try {
float sw = Float.parseFloat(query[0]);
if(sw > 0) {
subject.setStrokeWeight(sw);
return true;
}
return false;
}
catch(NumberFormatException e) {
return false;
}
}
}
| gpl-3.0 |
ggasoftware/gga-selenium-framework | gga-selenium-framework-core/src/main/java/com/ggasoftware/uitest/control/interfaces/complex/IForm.java | 529 | package com.ggasoftware.uitest.control.interfaces.complex;
import com.ggasoftware.uitest.control.base.annotations.JDIAction;
import com.ggasoftware.uitest.control.interfaces.base.IComposite;
import com.ggasoftware.uitest.control.interfaces.base.IElement;
import com.ggasoftware.uitest.control.interfaces.base.ISetValue;
/**
* Created by Roman_Iovlev on 7/8/2015.
*/
public interface IForm<T, P> extends IComposite, ISetValue, IElement<P> {
@JDIAction
void fill(T entity);
@JDIAction
void submit(T entity);
}
| gpl-3.0 |
EmilyBjoerk/lsml | src/main/java/org/lisoft/lsml/view_fx/FXMechlabModule.java | 1866 | /*
* @formatter:off
* Li Song Mechlab - A 'mech building tool for PGI's MechWarrior: Online.
* Copyright (C) 2013 Li Song
*
* 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/>.
*/
//@formatter:on
package org.lisoft.lsml.view_fx;
import javax.inject.Named;
import org.lisoft.lsml.messages.MessageXBar;
import org.lisoft.lsml.model.loadout.Loadout;
import org.lisoft.lsml.util.CommandStack;
import dagger.Module;
import dagger.Provides;
/**
* This {@link Module} provides the necessary services for a mechlab window implemented through JavaFX.
*
* @author Li Song
*/
@Module
public class FXMechlabModule {
private final MessageXBar xBar;
private final Loadout loadout;
private final CommandStack stack;
/**
* @param aLoadout
* The data that shall be injected into the services.
*/
public FXMechlabModule(Loadout aLoadout) {
loadout = aLoadout;
xBar = new MessageXBar();
stack = new CommandStack(200);
}
@Provides
Loadout provideLoadout() {
return loadout;
}
@Provides
@Named("local")
MessageXBar provideMessageXBar() {
return xBar;
}
@Provides
@Named("local")
CommandStack provideCommandStack() {
return stack;
}
}
| gpl-3.0 |
Ostrich-Emulators/semtool | common/src/main/java/com/ostrichemulators/semtool/rdf/engine/edgemodelers/LegacyEdgeModeler.java | 11779 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ostrichemulators.semtool.rdf.engine.edgemodelers;
import com.ostrichemulators.semtool.model.vocabulary.SEMONTO;
import com.ostrichemulators.semtool.poi.main.ImportData;
import com.ostrichemulators.semtool.poi.main.ImportMetadata;
import com.ostrichemulators.semtool.poi.main.LoadingSheetData;
import com.ostrichemulators.semtool.poi.main.LoadingSheetData.LoadingNodeAndPropertyValues;
import static com.ostrichemulators.semtool.rdf.engine.edgemodelers.AbstractEdgeModeler.isUri;
import com.ostrichemulators.semtool.rdf.engine.util.QaChecker;
import com.ostrichemulators.semtool.rdf.engine.util.QaChecker.RelationCacheKey;
import static com.ostrichemulators.semtool.rdf.query.util.QueryExecutorAdapter.getCal;
import com.ostrichemulators.semtool.util.Constants;
import static com.ostrichemulators.semtool.util.RDFDatatypeTools.getIriFromRawString;
import static com.ostrichemulators.semtool.util.RDFDatatypeTools.getRDFStringValue;
import com.ostrichemulators.semtool.util.UriBuilder;
import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.model.vocabulary.OWL;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.model.vocabulary.RDFS;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryException;
/**
*
* @author ryan
*/
public class LegacyEdgeModeler extends AbstractEdgeModeler {
private static final Logger log = Logger.getLogger( LegacyEdgeModeler.class );
public LegacyEdgeModeler( QaChecker qa ) {
super( qa );
}
@Override
public IRI addRel( LoadingNodeAndPropertyValues nap, Map<String, String> namespaces,
LoadingSheetData sheet, ImportMetadata metas, RepositoryConnection myrc )
throws RepositoryException {
String stype = nap.getSubjectType();
String srawlabel = nap.getSubject();
String otype = nap.getObjectType();
String orawlabel = nap.getObject();
// get both ends of the relationship...
if ( !hasCachedInstance( stype, srawlabel ) ) {
LoadingNodeAndPropertyValues filler
= sheet.new LoadingNodeAndPropertyValues( srawlabel );
addNode( filler, namespaces, sheet, metas, myrc );
}
IRI subject = getCachedInstance( stype, srawlabel );
if ( !hasCachedInstance( otype, orawlabel ) ) {
LoadingSheetData lsd = LoadingSheetData.nodesheet( sheet.getName(), otype );
LoadingNodeAndPropertyValues filler = lsd.add( orawlabel );
addNode( filler, namespaces, lsd, metas, myrc );
}
IRI object = getCachedInstance( otype, orawlabel );
boolean alreadyMadeRel = isUri( sheet.getRelname(), namespaces );
// ... and get a relationship that ties them together
RelationCacheKey lkey = new RelationCacheKey( nap.getSubjectType(),
nap.getObjectType(), sheet.getRelname(), nap.getSubject(), nap.getObject() );
if ( !hasCachedRelation( lkey ) ) {
IRI connector;
String rellocalname;
if ( alreadyMadeRel ) {
rellocalname = srawlabel + Constants.RELATION_IRI_CONCATENATOR + orawlabel;
connector = metas.getDataBuilder().getRelationIri().build( rellocalname );
}
else {
UriBuilder typebuilder
= metas.getDataBuilder().getRelationIri().add( sheet.getRelname() );
rellocalname = srawlabel + Constants.RELATION_IRI_CONCATENATOR + orawlabel;
connector = typebuilder.add( rellocalname ).build();
}
connector = ensureUnique( connector );
cacheRelationNode( connector, lkey );
}
IRI relClassBaseURI = getCachedRelationClass( sheet.getRelname() );
IRI connector = getCachedRelation( lkey );
if ( metas.isAutocreateMetamodel() ) {
ValueFactory vf = myrc.getValueFactory();
myrc.add( connector, RDFS.SUBPROPERTYOF, relClassBaseURI );
myrc.add( connector, RDFS.LABEL, vf.createLiteral( srawlabel + " "
+ sheet.getRelname() + " " + orawlabel ) );
}
myrc.add( subject, connector, object );
addProperties( connector, nap, namespaces, sheet, metas, myrc );
return connector;
}
@Override
public IRI addNode( LoadingNodeAndPropertyValues nap, Map<String, String> namespaces,
LoadingSheetData sheet, ImportMetadata metas, RepositoryConnection myrc ) throws RepositoryException {
String typename = nap.getSubjectType();
String rawlabel = nap.getSubject();
IRI subject = addSimpleNode( typename, rawlabel, namespaces, metas, myrc );
ValueFactory vf = myrc.getValueFactory();
boolean savelabel = metas.isAutocreateMetamodel();
if ( !metas.isLegacyMode() && rawlabel.contains( ":" ) ) {
// we have something with a colon in it, so we need to figure out if it's
// a namespace-prefixed string, or just a string with a colon in it
Value val = getRDFStringValue( rawlabel, namespaces, vf );
// check if we have a prefixed URI
IRI u = getIriFromRawString( rawlabel, namespaces );
savelabel = ( savelabel && null == u );
rawlabel = val.stringValue();
}
// if we have a label property, skip this label-making
// (it'll get handled in the addProperties function later)
if ( savelabel && !nap.hasProperty( RDFS.LABEL, namespaces ) ) {
myrc.add( subject, RDFS.LABEL, vf.createLiteral( rawlabel ) );
}
addProperties( subject, nap, namespaces, sheet, metas, myrc );
return subject;
}
@Override
public void addProperties( IRI subject, Map<String, Value> properties,
Map<String, String> namespaces, LoadingSheetData sheet,
ImportMetadata metas, RepositoryConnection myrc ) throws RepositoryException {
ValueFactory vf = myrc.getValueFactory();
for ( Map.Entry<String, Value> entry : properties.entrySet() ) {
String propname = entry.getKey();
IRI predicate = getCachedPropertyClass( propname );
Value value = entry.getValue();
if ( sheet.isLink( propname ) ) {
// our "value" is really the label of another node, so find that node
value = addSimpleNode( propname, value.stringValue(), namespaces, metas, myrc );
predicate = getCachedRelationClass( sheet.getSubjectType()
+ sheet.getObjectType() + propname );
}
// not sure if we even use these values anymore
switch ( value.toString() ) {
case Constants.PROCESS_CURRENT_DATE:
myrc.add( subject, predicate,
vf.createLiteral( getCal( new Date() ) ) );
break;
case Constants.PROCESS_CURRENT_USER:
myrc.add( subject, predicate,
vf.createLiteral( System.getProperty( "user.name" ) ) );
break;
default:
myrc.add( subject, predicate, value );
}
}
}
protected IRI addSimpleNode( String typename, String rawlabel, Map<String, String> namespaces,
ImportMetadata metas, RepositoryConnection myrc ) throws RepositoryException {
boolean nodeIsAlreadyUri = isUri( rawlabel, namespaces );
if ( !hasCachedInstance( typename, rawlabel ) ) {
IRI subject;
if ( nodeIsAlreadyUri ) {
subject = getIriFromRawString( rawlabel, namespaces );
}
else {
if ( metas.isAutocreateMetamodel() ) {
UriBuilder nodebuilder = metas.getDataBuilder().getConceptIri();
if ( !typename.contains( ":" ) ) {
nodebuilder.add( typename );
}
subject = nodebuilder.add( rawlabel ).build();
}
else {
subject = metas.getDataBuilder().add( rawlabel ).build();
}
subject = ensureUnique( subject );
}
cacheInstance( subject, typename, rawlabel );
}
IRI subject = getCachedInstance( typename, rawlabel );
myrc.add( subject, RDF.TYPE, getCachedInstanceClass( typename ) );
return subject;
}
@Override
public Model createMetamodel( ImportData alldata, Map<String, String> namespaces,
ValueFactory vf ) throws RepositoryException {
Model model = new TreeModel();
ImportMetadata metas = alldata.getMetadata();
UriBuilder schema = metas.getSchemaBuilder();
boolean save = metas.isAutocreateMetamodel();
if ( null == vf ) {
vf = SimpleValueFactory.getInstance();
}
for ( LoadingSheetData sheet : alldata.getSheets() ) {
String stype = sheet.getSubjectType();
if ( !hasCachedInstanceClass( stype ) ) {
boolean nodeAlreadyMade = isUri( stype, namespaces );
IRI uri = ( nodeAlreadyMade
? getIriFromRawString( stype, namespaces )
: schema.build( stype ) );
cacheInstanceClass( uri, stype );
if ( save && !nodeAlreadyMade ) {
model.add( uri, RDF.TYPE, OWL.CLASS );
model.add( uri, RDFS.LABEL, vf.createLiteral( stype ) );
model.add( uri, RDFS.SUBCLASSOF, schema.getConceptIri().build() );
}
}
if ( sheet.isRel() ) {
String otype = sheet.getObjectType();
if ( !hasCachedInstanceClass( otype ) ) {
boolean nodeAlreadyMade = isUri( otype, namespaces );
IRI uri = ( nodeAlreadyMade
? getIriFromRawString( otype, namespaces )
: schema.build( otype ) );
cacheInstanceClass( uri, otype );
if ( save && !nodeAlreadyMade ) {
model.add( uri, RDF.TYPE, OWL.CLASS );
model.add( uri, RDFS.LABEL, vf.createLiteral( otype ) );
model.add( uri, RDFS.SUBCLASSOF, schema.getConceptIri().build() );
}
}
String rellabel = sheet.getRelname();
if ( !hasCachedRelationClass( rellabel ) ) {
boolean relationAlreadyMade = isUri( rellabel, namespaces );
IRI ret = ( relationAlreadyMade
? getIriFromRawString( rellabel, namespaces )
: schema.getRelationIri( rellabel ) );
IRI relation = schema.getRelationIri().build();
cacheRelationClass( ret, rellabel );
if ( save ) {
if ( !relationAlreadyMade ) {
model.add( ret, RDF.TYPE, OWL.OBJECTPROPERTY );
model.add( ret, RDFS.LABEL, vf.createLiteral( rellabel ) );
model.add( ret, RDFS.SUBPROPERTYOF, relation );
}
// myrc.add( suri, ret, schemaNodes.get( ocachekey ) );
model.add( schema.getConceptIri().build(), RDF.TYPE, RDFS.CLASS );
model.add( schema.getContainsIri(), RDFS.SUBPROPERTYOF, schema.getContainsIri() );
model.add( relation, RDF.TYPE, RDF.PROPERTY );
}
}
}
}
for ( LoadingSheetData sheet : alldata.getSheets() ) {
for ( String propname : sheet.getProperties() ) {
// check to see if we're actually a link to some
// other node (and not really a new property
if ( sheet.isLink( propname ) || hasCachedInstanceClass( propname ) ) {
log.debug( "linking " + propname + " as a " + SEMONTO.has
+ " relationship to " + getCachedInstanceClass( propname ) );
cacheRelationClass( SEMONTO.has, sheet.getSubjectType()
+ sheet.getObjectType() + propname );
continue;
}
boolean alreadyMadeProp = isUri( propname, namespaces );
if ( !hasCachedPropertyClass( propname ) ) {
IRI predicate;
if ( alreadyMadeProp ) {
predicate = getIriFromRawString( propname, namespaces );
}
else {
// UriBuilder bb = schema.getRelationIri().add( Constants.CONTAINS );
predicate = schema.build( propname );
}
cachePropertyClass( predicate, propname );
}
IRI predicate = getCachedPropertyClass( propname );
if ( save && !alreadyMadeProp ) {
model.add( predicate, RDFS.LABEL, vf.createLiteral( propname ) );
// myrc.add( predicate, RDF.TYPE, schema.getContainsIri() );
model.add( predicate, RDFS.SUBPROPERTYOF, schema.getRelationIri().build() );
if ( !metas.isLegacyMode() ) {
model.add( predicate, RDFS.SUBPROPERTYOF, schema.getContainsIri() );
}
}
}
}
return model;
}
}
| gpl-3.0 |
OpenBD/openbd-core | src/org/farng/mp3/InvalidTagException.java | 1714 | package org.farng.mp3;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* An <code>InvalidTagException</code> is thrown if a parse error occurs while a tag is being read from a file. This is
* different from a <code>TagNotFoundException</code>. Each tag (or MP3 Frame Header) has an ID string or some way
* saying that it simply exists. If this string is missing, <code>TagNotFoundException</code> is thrown. If the ID
* string exists, then any other error while reading throws an <code>InvalidTagException</code>.
*
* @author Eric Farng
* @version $Revision: 1637 $
*/
public class InvalidTagException extends TagException {
private static final long serialVersionUID = 1L;
/**
* Creates a new InvalidTagException object.
*/
public InvalidTagException() {
super();
}
/**
* Creates a new InvalidTagException object.
*/
public InvalidTagException(final Throwable exception) {
super(exception);
}
/**
* Creates a new InvalidTagException object.
*
* @param message the detail message.
*/
public InvalidTagException(final String message) {
super(message);
}
/**
* Creates a new InvalidTagException object.
*/
public InvalidTagException(final String message, final Throwable exception) {
super(message, exception);
}
private void writeObject(final ObjectOutputStream out) {
throw new UnsupportedOperationException("Cannot write to Output Stream: " + out.toString());
}
private void readObject(final ObjectInputStream in) {
throw new UnsupportedOperationException("Cannot read from Input Stream: " + in.toString());
}
} | gpl-3.0 |
Ooppa/jTODO | jTODO/src/main/java/jtodo/domain/Database.java | 2106 | /*
* Aineopintojen harjoitustyö: Ohjelmointi 2015 Kevät
* Helsingin yliopisto Tietojenkäsittelytieteen laitos
* Ooppa 2015 - GNU General Public License, version 3.
*/
package jtodo.domain;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Wrapper that can be saved to a file using Serializable class.
*
* @author Ooppa
*/
public class Database implements Serializable {
private ArrayList<Category> categories;
private ArrayList<Task> tasks;
/**
* Creates a new Database object
*/
public Database() {
categories = new ArrayList<>();
tasks = new ArrayList<>();
}
/**
* Returns the Categories packed in ArrayList
*
* @return Categories
*
* @see Category
*/
public ArrayList<Category> getCategories() {
return categories;
}
/**
* Returns the Tasks packed in ArrayList
*
* @return Tasks
*
* @see Task
*/
public ArrayList<Task> getTasks() {
return tasks;
}
public ArrayList<Task> getTasksWithFilter(String filter) {
ArrayList<Task> filtered = new ArrayList<>();
for(Task task : tasks) {
if(doesTaskFitTheFilter(task, filter.toLowerCase())) {
filtered.add(task);
}
}
return filtered;
}
/*
* Check if the filter String matches anything in the task
*/
private boolean doesTaskFitTheFilter(Task task, String string) {
if(task.getName().toLowerCase().contains(string)) {
return true;
}
if(task.getDescription().toLowerCase().contains(string)) {
return true;
}
if(task.getDeadlineAsString().toLowerCase().contains(string)) {
return true;
}
if(task.getPriority().toString().toLowerCase().contains(string)) {
return true;
}
if(task.getCategory()!=null) {
if(task.getCategory().getName().toLowerCase().contains(string)) {
return true;
}
}
return false;
}
}
| gpl-3.0 |
niemandkun/adddxdx | src/main/java/org/adddxdx/graphics/support/components/PerspectiveCamera.java | 2259 | /*
* Copyright (C) 2017 Poroshin Ivan
* This file is part of adddxdx.
*
* adddxdx 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.
*
* adddxdx 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 adddxdx. If not, see <http://www.gnu.org/licenses/>.
*/
package org.adddxdx.graphics.support.components;
import org.adddxdx.graphics.Camera;
import org.adddxdx.math.*;
public class PerspectiveCamera extends Camera {
private static final float DEFAULT_NEAR_PLANE = 0.3f;
private static final float DEFAULT_FAR_PLANE = 1000f;
private static final float DEFAULT_ASPECT_RATIO = 16 / 9f;
private static final float DEFAULT_FIELD_OF_VIEW = FMath.PI / 4;
private float mNearPlane;
private float mFarPlane;
private float mFieldOfView;
private float mAspectRatio;
public PerspectiveCamera() {
mAspectRatio = DEFAULT_ASPECT_RATIO;
mNearPlane = DEFAULT_NEAR_PLANE;
mFarPlane = DEFAULT_FAR_PLANE;
mFieldOfView = DEFAULT_FIELD_OF_VIEW;
}
@Override
public Matrix4 getProjectionMatrix() {
return Projection.perspective(mFieldOfView, mAspectRatio, mNearPlane, mFarPlane);
}
@Override
public void adjustAspectRatio(Size targetSize) {
mAspectRatio = (float) targetSize.getWidth() / targetSize.getHeight();
}
float getAspectRatio() {
return mAspectRatio;
}
float getNearPlane() {
return mNearPlane;
}
void setNearPlane(float nearPlane) {
mNearPlane = nearPlane;
}
float getFarPlane() {
return mFarPlane;
}
void setFarPlane(float farPlane) {
mFarPlane = farPlane;
}
float getFieldOfView() {
return mFieldOfView;
}
void setFieldOfView(float fieldOfView) {
mFieldOfView = fieldOfView;
}
}
| gpl-3.0 |
PistiZ/UsedCarDealership | src/main/java/hu/pistiz/cars/model/Condition.java | 221 | // CHECKSTYLE:OFF
package hu.pistiz.cars.model;
/**
* Autók lehetséges állapot-típusait tartalmazó felsorolás.
*/
public enum Condition
{
hibás, sérült, megkímélt, sérülésmentes, újszerű, kitűnő
}
| gpl-3.0 |
tairo/STEMDu_Ardublock | src/main/java/com/ardublock/translator/block/stemdu/OLEDSetup.java | 1935 | package com.ardublock.translator.block.stemdu;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.TranslatorBlock;
import com.ardublock.translator.block.exception.BlockException;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
public class OLEDSetup extends TranslatorBlock {
public OLEDSetup(Long blockId, Translator translator) {
super(blockId, translator);
// TODO Auto-generated constructor stub
}
public OLEDSetup(Long blockId, Translator translator, String codePrefix, String codeSuffix) {
super(blockId, translator, codePrefix, codeSuffix);
// TODO Auto-generated constructor stub
}
public OLEDSetup(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label) {
super(blockId, translator, codePrefix, codeSuffix, label);
// TODO Auto-generated constructor stub
}
@Override
public String toCode() throws SocketNullException, SubroutineNotDeclaredException, BlockException {
// TODO Auto-generated method stub
translator.addHeaderFile("Wire.h");
translator.addHeaderFile("Adafruit_GFX.h");
translator.addHeaderFile("Adafruit_SSD1306.h");
translator.addDefinitionCommand("#define _STEMDU_OLED_RESET 4");
translator.addDefinitionCommand("#define _STEMDU_OLED_WIDTH " + this.getTranslatorBlockAtSocket(1).toCode());
translator.addDefinitionCommand("#define _STEMDU_OLED_HEIGHT " + this.getTranslatorBlockAtSocket(2).toCode());
translator.addDefinitionCommand("#define _STEMDU_OLED_RESET 4");
translator.addDefinitionCommand("Adafruit_SSD1306 _stemdu_oled_display(_STEMDU_OLED_WIDTH, _STEMDU_OLED_HEIGHT, &Wire, _STEMDU_OLED_RESET);\n");
translator.addSetupCommand("\tif(!_stemdu_oled_display.begin(SSD1306_SWITCHCAPVCC, 0x" + this.getTranslatorBlockAtSocket(0).toCode() + ")) {\t\tfor(;;);\n\t}\n");
return "";
}
}
| gpl-3.0 |
Quanhua-Guan/spmf | ca/pfv/spmf/algorithms/sequentialpatterns/spade_spam_AGP/dataStructures/creators/AbstractionCreator_Qualitative.java | 11929 | package ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.EquivalenceClass;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.Item;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.Itemset;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.Sequence;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.abstractions.Abstraction_Generic;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.abstractions.Abstraction_Qualitative;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.abstractions.ItemAbstractionPair;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.patterns.Pattern;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.patterns.PatternCreator;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.IDList;
import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator;
import java.util.*;
import java.util.Map.Entry;
/**
* This class is the implementation of a creator of a qualitative abstraction.
*
* Copyright Antonio Gomariz Peñalver 2013
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF 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.
*
* SPMF 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
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*
* @author agomariz
*/
public class AbstractionCreator_Qualitative extends AbstractionCreator {
private static AbstractionCreator_Qualitative instance = null;
public static void sclear() {
instance=null;
}
private AbstractionCreator_Qualitative() {
}
public static AbstractionCreator_Qualitative getInstance() {
if (instance == null) {
instance = new AbstractionCreator_Qualitative();
}
return instance;
}
/**
* It creates an default abstraction. The abstraction is established to false
* @return the created abstraction
*/
@Override
public Abstraction_Generic createDefaultAbstraction() {
return Abstraction_Qualitative.create(false);
}
/**
* It creates a relation with the given parameter.
* @param hasEqualRelation The boolean indicatin if the item has an equal
* relation with the previous item in the pattern
* @return the created relation
*/
public Abstraction_Generic createAbstraction(boolean hasEqualRelation) {
return Abstraction_Qualitative.create(hasEqualRelation);
}
/**
* It finds all the frequent 2-patterns in the original database. This method
* is specially useful if we think of parallelizing the execution of the Spade
* algorithm.
* @param sequences the list of sequences
* @param idListCreator the idlist creator for creating the idlists
* @return the list of equivalence classes
*/
@Override
public List<EquivalenceClass> getFrequentSize2Sequences(List<Sequence> sequences, IdListCreator idListCreator) {
Map<Pattern, EquivalenceClass> totalMap = new HashMap<Pattern, EquivalenceClass>();
List<EquivalenceClass> result = new LinkedList<EquivalenceClass>();
//For each Sequence
for (Sequence seq : sequences) {
List<Itemset> itemsets = seq.getItemsets();
//For each itemset in the sequence
for (int i = 0; i < itemsets.size(); i++) {
Itemset currentItemset = itemsets.get(i);
//for each item in the itemset
for (int j = 0; j < currentItemset.size(); j++) {
//we choose it as first item
Item item = currentItemset.get(j);
ItemAbstractionPair par1 = new ItemAbstractionPair(item, createDefaultAbstraction());
//With the rest of items in the same itemset we make a 2-sequence i-extension
for (int k = j + 1; k < currentItemset.size(); k++) {
Item item2 = currentItemset.get(k);
ItemAbstractionPair pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(true));
updateIdList(totalMap, par1, pair2, seq.getId(), (int) currentItemset.getTimestamp(), idListCreator);
}
//With the rest of items in the rest of itemsets we make a 2-sequence s-extension
for (int k = i + 1; k < itemsets.size(); k++) {
Itemset nextItemset = itemsets.get(k);
for (int n = 0; n < nextItemset.size(); n++) {
Item item2 = nextItemset.get(n);
ItemAbstractionPair pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(false));
updateIdList(totalMap, par1, pair2, seq.getId(), (int) nextItemset.getTimestamp(), idListCreator);
}
}
}
}
}
result.addAll(totalMap.values());
Collections.sort(result);
return result;
}
/**
* Helper method for getFrequentSize2Sequence, useful for making the pattern
* and the IdList from two given pairs <item, abstraction>.
* @param totalMap Correspondences between patterns and equivalence classes
* @param pair1 First element of the pattern to create
* @param pair2 Second element of the pattern to create
* @param sid Sequence identifier
* @param tid Transaction timestamp
* @param idListCreator IdlistCreator
*/
public void updateIdList(Map<Pattern, EquivalenceClass> totalMap, ItemAbstractionPair pair1, ItemAbstractionPair pair2, int sid, int tid, IdListCreator idListCreator) {
PatternCreator patternCreator = PatternCreator.getInstance();
List<ItemAbstractionPair> size2PatternElements = new ArrayList<ItemAbstractionPair>(2);
size2PatternElements.add(pair1);
size2PatternElements.add(pair2);
Pattern pattern = patternCreator.createPattern(size2PatternElements);
EquivalenceClass eq = totalMap.get(pattern);
if (eq == null) {
IDList id = idListCreator.create();
eq = new EquivalenceClass(pattern, id);
totalMap.put(pattern, eq);
}
IDList id = eq.getIdList();
idListCreator.addAppearance(id, sid, tid);
}
/**
* It obtains the subpattern that is derived from removing from the given
* pattern, the item specified in the position pointed out by the given index
* @param extension a pattern
* @param index the position
* @return the subpattern
*/
@Override
public Pattern getSubpattern(Pattern extension, int index) {
ItemAbstractionPairCreator pairCreator = ItemAbstractionPairCreator.getInstance();
PatternCreator patternCreator = PatternCreator.getInstance();
List<ItemAbstractionPair> subpatternElements = new ArrayList<ItemAbstractionPair>(extension.size() - 1);
Abstraction_Generic abstraction = null;
int nextIndex = index + 1;
for (int i = 0; i < extension.size(); i++) {
if (i != index) {
if (i == nextIndex) {
if (abstraction == null) {
abstraction = extension.getIthElement(i).getAbstraction();
}
subpatternElements.add(pairCreator.getItemAbstractionPair(extension.getIthElement(i).getItem(), abstraction));
} else {
subpatternElements.add(extension.getIthElement(i));
}
} else {
if (index == 0) {
abstraction = createDefaultAbstraction();
} else {
Abstraction_Qualitative abstractionOfRemovedPair = (Abstraction_Qualitative) extension.getIthElement(i).getAbstraction();
if (!abstractionOfRemovedPair.hasEqualRelation()) {
abstraction = createAbstraction(false);
}
}
}
}
return patternCreator.createPattern(subpatternElements);
}
@Override
public List<EquivalenceClass> getFrequentSize2Sequences(Map<Integer, Map<Item, List<Integer>>> database, Map<Item, EquivalenceClass> frequentItems, IdListCreator idListCreator) {
Map<Pattern, EquivalenceClass> totalMap = new HashMap<Pattern, EquivalenceClass>();
List<EquivalenceClass> result = new LinkedList<EquivalenceClass>();
for (Entry<Integer, Map<Item, List<Integer>>> seq : database.entrySet()) {
Integer sequence = seq.getKey();
List<Entry<Item, List<Integer>>> itemItemsetsAssociation = new ArrayList(seq.getValue().entrySet());
//for each itemset in the sequence
for (int i = 0; i < itemItemsetsAssociation.size(); i++) {
Entry<Item, List<Integer>> currentEntry1 = itemItemsetsAssociation.get(i);
Item item1 = currentEntry1.getKey();
List<Integer> appearances1 = currentEntry1.getValue();
if (!isFrequent(item1, frequentItems)) {
continue;
}
for (int m = 0; m < appearances1.size(); m++) {
int item1Appearance = appearances1.get(m);
ItemAbstractionPair pair1 = new ItemAbstractionPair(item1, createDefaultAbstraction());
for (int j = 0; j < itemItemsetsAssociation.size(); j++) {
Entry<Item, List<Integer>> currentEntry2 = itemItemsetsAssociation.get(j);
Item item2 = currentEntry2.getKey();
List<Integer> appearances2 = currentEntry2.getValue();
if (!isFrequent(item2, frequentItems)) {
continue;
}
for (int k = 0; k < appearances2.size(); k++) {
int item2Apperance = appearances2.get(k);
ItemAbstractionPair pair2 = null;
if (item2Apperance == item1Appearance) {
if (-item2.compareTo(item1) == 1) {
pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(true));
}
} else if (item2Apperance > item1Appearance) {
pair2 = new ItemAbstractionPair(item2, Abstraction_Qualitative.create(false));
}
if (pair2 != null) {
updateIdList(totalMap, pair1, pair2, sequence, item2Apperance, idListCreator);
}
}
}
}
}
}
result.addAll(totalMap.values());
Collections.sort(result);
return result;
}
private boolean isFrequent(Item item1, Map<Item, EquivalenceClass> itemsfrecuentes) {
return (itemsfrecuentes.get(item1)) != null;
}
@Override
public void clear() {
}
}
| gpl-3.0 |
yidumen/dao-bundle | src/main/java/com/yidumen/dao/constant/GoodsStatus.java | 129 | package com.yidumen.dao.constant;
/**
*
* @author 蔡迪旻
*/
public enum GoodsStatus {
SUCCESS,
WAIT,
ERROR,
}
| gpl-3.0 |
DrizzleSuite/DrizzleSMS | src/org/grovecity/drizzlesms/recipients/RecipientProvider.java | 7185 | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.grovecity.drizzlesms.recipients;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import org.grovecity.drizzlesms.contacts.ContactPhotoFactory;
import org.grovecity.drizzlesms.database.DatabaseFactory;
import org.grovecity.drizzlesms.util.GroupUtil;
import org.grovecity.drizzlesms.util.LRUCache;
import org.grovecity.drizzlesms.util.ListenableFutureTask;
import org.grovecity.drizzlesms.database.CanonicalAddressDatabase;
import org.grovecity.drizzlesms.database.GroupDatabase;
import org.grovecity.drizzlesms.util.Util;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
public class RecipientProvider {
private static final Map<Long,Recipient> recipientCache = Collections.synchronizedMap(new LRUCache<Long,Recipient>(1000));
private static final ExecutorService asyncRecipientResolver = Util.newSingleThreadedLifoExecutor();
private static final String[] CALLER_ID_PROJECTION = new String[] {
PhoneLookup.DISPLAY_NAME,
PhoneLookup.LOOKUP_KEY,
PhoneLookup._ID,
PhoneLookup.NUMBER
};
public Recipient getRecipient(Context context, long recipientId, boolean asynchronous) {
Recipient cachedRecipient = recipientCache.get(recipientId);
if (cachedRecipient != null) return cachedRecipient;
else if (asynchronous) return getAsynchronousRecipient(context, recipientId);
else return getSynchronousRecipient(context, recipientId);
}
private Recipient getSynchronousRecipient(final Context context, final long recipientId) {
Log.w("RecipientProvider", "Cache miss [SYNC]!");
final Recipient recipient;
RecipientDetails details;
String number = CanonicalAddressDatabase.getInstance(context).getAddressFromId(recipientId);
final boolean isGroupRecipient = GroupUtil.isEncodedGroup(number);
if (isGroupRecipient) details = getGroupRecipientDetails(context, number);
else details = getRecipientDetails(context, number);
if (details != null) {
recipient = new Recipient(details.name, details.number, recipientId, details.contactUri, details.avatar);
} else {
final Drawable defaultPhoto = isGroupRecipient
? ContactPhotoFactory.getDefaultGroupPhoto(context)
: ContactPhotoFactory.getDefaultContactPhoto(context, null);
recipient = new Recipient(null, number, recipientId, null, defaultPhoto);
}
recipientCache.put(recipientId, recipient);
return recipient;
}
private Recipient getAsynchronousRecipient(final Context context, final long recipientId) {
Log.w("RecipientProvider", "Cache miss [ASYNC]!");
final String number = CanonicalAddressDatabase.getInstance(context).getAddressFromId(recipientId);
final boolean isGroupRecipient = GroupUtil.isEncodedGroup(number);
Callable<RecipientDetails> task = new Callable<RecipientDetails>() {
@Override
public RecipientDetails call() throws Exception {
if (isGroupRecipient) return getGroupRecipientDetails(context, number);
else return getRecipientDetails(context, number);
}
};
ListenableFutureTask<RecipientDetails> future = new ListenableFutureTask<>(task);
asyncRecipientResolver.submit(future);
Drawable contactPhoto;
if (isGroupRecipient) {
contactPhoto = ContactPhotoFactory.getDefaultGroupPhoto(context);
} else {
contactPhoto = ContactPhotoFactory.getLoadingPhoto(context);
}
Recipient recipient = new Recipient(number, contactPhoto, recipientId, future);
recipientCache.put(recipientId, recipient);
return recipient;
}
public void clearCache() {
recipientCache.clear();
}
public void clearCache(Recipient recipient) {
if (recipientCache.containsKey(recipient.getRecipientId()))
recipientCache.remove(recipient.getRecipientId());
}
private RecipientDetails getRecipientDetails(Context context, String number) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = context.getContentResolver().query(uri, CALLER_ID_PROJECTION,
null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
Uri contactUri = Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1));
String name = cursor.getString(3).equals(cursor.getString(0)) ? null : cursor.getString(0);
Drawable contactPhoto = ContactPhotoFactory.getContactPhoto(context,
Uri.withAppendedPath(Contacts.CONTENT_URI, cursor.getLong(2) + ""),
name);
return new RecipientDetails(cursor.getString(0), cursor.getString(3), contactUri, contactPhoto);
}
} finally {
if (cursor != null)
cursor.close();
}
return new RecipientDetails(null, number, null, ContactPhotoFactory.getDefaultContactPhoto(context, null));
}
private RecipientDetails getGroupRecipientDetails(Context context, String groupId) {
try {
GroupDatabase.GroupRecord record = DatabaseFactory.getGroupDatabase(context)
.getGroup(GroupUtil.getDecodedId(groupId));
if (record != null) {
Drawable avatar = ContactPhotoFactory.getGroupContactPhoto(context, record.getAvatar());
return new RecipientDetails(record.getTitle(), groupId, null, avatar);
}
return null;
} catch (IOException e) {
Log.w("RecipientProvider", e);
return null;
}
}
public static class RecipientDetails {
public final String name;
public final String number;
public final Drawable avatar;
public final Uri contactUri;
public RecipientDetails(String name, String number, Uri contactUri, Drawable avatar) {
this.name = name;
this.number = number;
this.avatar = avatar;
this.contactUri = contactUri;
}
}
} | gpl-3.0 |
srnsw/xena | plugins/office/ext/src/jurt/com/sun/star/lib/connections/pipe/pipeConnector.java | 5475 | /*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile$
* $Revision$
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
package com.sun.star.lib.connections.pipe;
import com.sun.star.comp.loader.FactoryHelper;
import com.sun.star.connection.ConnectionSetupException;
import com.sun.star.connection.NoConnectException;
import com.sun.star.connection.XConnection;
import com.sun.star.connection.XConnector;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.registry.XRegistryKey;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* A component that implements the <code>XConnector</code> interface.
*
* <p>The <code>pipeConnector</code> is a specialized component that uses TCP
* pipes for communication. The <code>pipeConnector</code> is generally
* used by the <code>com.sun.star.connection.Connector</code> service.</p>
*
* @see com.sun.star.connections.XAcceptor
* @see com.sun.star.connections.XConnection
* @see com.sun.star.connections.XConnector
* @see com.sun.star.loader.JavaLoader
*
* @since UDK 1.0
*/
public final class pipeConnector implements XConnector {
/**
* The name of the service.
*
* <p>The <code>JavaLoader</code> acceses this through reflection.</p>
*
* @see com.sun.star.comp.loader.JavaLoader
*/
public static final String __serviceName = "com.sun.star.connection.pipeConnector";
/**
* Returns a factory for creating the service.
*
* <p>This method is called by the <code>JavaLoader</code>.</p>
*
* @param implName the name of the implementation for which a service is
* requested.
* @param multiFactory the service manager to be used (if needed).
* @param regKey the registry key.
* @return an <code>XSingleServiceFactory</code> for creating the component.
*
* @see com.sun.star.comp.loader.JavaLoader
*/
public static XSingleServiceFactory __getServiceFactory(
String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey)
{
return implName.equals(pipeConnector.class.getName())
? FactoryHelper.getServiceFactory(pipeConnector.class,
__serviceName, multiFactory,
regKey)
: null;
}
/**
* Writes the service information into the given registry key.
*
* <p>This method is called by the <code>JavaLoader</code>.</p>
*
* @param regKey the registry key.
* @return <code>true</code> if the operation succeeded.
*
* @see com.sun.star.comp.loader.JavaLoader
*/
public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) {
return FactoryHelper.writeRegistryServiceInfo(
pipeConnector.class.getName(), __serviceName, regKey);
}
/**
* Connects via the described pipe to a waiting server.
*
* <p>The connection description has the following format:
* <code><var>type</var></code><!--
* -->*(<code><var>key</var>=<var>value</var></code>),
* where <code><var>type</var></code> should be <code>pipe</code>
* (ignoring case). Supported keys (ignoring case) currently are
* <dl>
* <dt><code>host</code>
* <dd>The name or address of the server. Must be present.
* <dt><code>port</code>
* <dd>The TCP port number of the server (defaults to <code>6001</code>).
* <dt><code>tcpnodelay</code>
* <dd>A flag (<code>0</code>/<code>1</code>) enabling or disabling Nagle's
* algorithm on the resulting connection.
* </dl></p>
*
* @param connectionDescription the description of the connection.
* @return an <code>XConnection</code> to the server.
*
* @see com.sun.star.connections.XAcceptor
* @see com.sun.star.connections.XConnection
*/
public synchronized XConnection connect(String connectionDescription)
throws NoConnectException, ConnectionSetupException
{
if (bConnected) {
throw new ConnectionSetupException("alread connected");
}
try
{
XConnection xConn = new PipeConnection( connectionDescription );
bConnected = true;
return xConn;
}
catch ( java.io.IOException e ) { throw new NoConnectException(); }
}
private boolean bConnected = false;
}
| gpl-3.0 |
transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/tools/math/som/KohonenTrainingsData.java | 1286 | /**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.tools.math.som;
import java.io.Serializable;
import java.util.Random;
/**
* This interface describes the training data for a Kohonen net.
*
* @author Sebastian Land
*/
public interface KohonenTrainingsData extends Serializable {
public double[] getNext();
public int countData();
public void reset();
public void setRandomGenerator(Random generator);
public double[] get(int index);
}
| gpl-3.0 |
SeifScape/lngooglecalsync | src/LotusNotesGoogleCalendarBridge/GoogleService/GoogleImport.java | 29476 | package LotusNotesGoogleCalendarBridge.GoogleService;
import LotusNotesGoogleCalendarBridge.LotusNotesService.NotesCalendarEntry;
import com.google.gdata.client.GoogleService.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.batch.BatchOperationType;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.data.batch.BatchStatus;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.extensions.Reminder.Method;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.util.Calendar;
import java.util.UUID;
public class GoogleImport {
public GoogleImport(String accountname, String password, String calendarName, boolean useSSL) throws Exception {
try {
// Get the absolute path to this app
String appPath = new java.io.File("").getAbsolutePath() + System.getProperty("file.separator");
googleInRangeEntriesFullFilename = appPath = googleInRangeEntriesFilename;
String protocol = "http:";
if (useSSL) {
protocol = "https:";
}
mainCalendarFeedUrl = new URL(protocol + "//www.google.com/calendar/feeds/" + accountname + "/owncalendars/full");
privateCalendarFeedUrl = new URL(protocol + "//www.google.com/calendar/feeds/" + accountname + "/private/full");
service = new CalendarService("LotusNotes-Calendar-Sync");
if (useSSL) {
service.useSsl();
}
service.setUserCredentials(accountname, password);
destinationCalendarName = calendarName;
createCalendar();
} catch (InvalidCredentialsException ex) {
throw new Exception("The username and/or password are invalid for signing into Google.", ex);
} catch (AuthenticationException ex) {
throw new Exception("Unable to login to Google. Perhaps you need to use a proxy server.", ex);
} catch (Exception ex) {
throw ex;
}
}
public GoogleImport() {
}
/**
* Get the calendar feed URL for the calendar we want to update.
* @return The calendar feed URL for the calendar we want to update.
*/
protected URL getDestinationCalendarUrl() throws Exception {
CalendarFeed calendars = null;
int retryCount = 0;
try {
// If true, we already know our calendar URL
if (destinationCalendarFeedUrl != null)
return destinationCalendarFeedUrl;
do {
try {
calendars = service.getFeed(mainCalendarFeedUrl, CalendarFeed.class);
} catch (com.google.gdata.util.ServiceException ex) {
calendars = null;
// If there is a network problem while connecting to Google, retry a few times
if (++retryCount > maxRetryCount)
throw ex;
Thread.sleep(retryDelayMsecs);
}
} while (calendars == null);
for (int i = 0; i < calendars.getEntries().size(); i++) {
CalendarEntry calendar = calendars.getEntries().get(i);
// If true, we've found the name of the destination calendar
if (calendar.getTitle().getPlainText().equals(destinationCalendarName)) {
destinationCalendarFeedUrl = new URL(calendar.getLink("alternate", "application/atom+xml").getHref());
}
}
} catch (Exception ex) {
throw ex;
}
return destinationCalendarFeedUrl;
}
/**
* Creates a Google calendar for the desired name (if it doesn't already exist).
* @throws IOException
* @throws ServiceException
*/
public void createCalendar() throws Exception, IOException, ServiceException {
// If true, the calendar already exists
if (getDestinationCalendarUrl() != null) {
return;
}
CalendarEntry calendar = new CalendarEntry();
calendar.setTitle(new PlainTextConstruct(destinationCalendarName));
// Get this machine's current time zone when creating the new Google calendar
TimeZone localTimeZone = TimeZone.getDefault();
// Set the Google calendar time zone
String timeZoneName = localTimeZone.getID();
TimeZoneProperty tzp = new TimeZoneProperty(timeZoneName);
calendar.setTimeZone(tzp);
calendar.setHidden(HiddenProperty.FALSE);
calendar.setSelected(SelectedProperty.TRUE);
calendar.setColor(new ColorProperty(DEST_CALENDAR_COLOR));
CalendarEntry returnedCalendar = service.insert(mainCalendarFeedUrl, calendar);
returnedCalendar.update();
// Get the feed url reference so that we can add events to the new calendar.
destinationCalendarFeedUrl = new URL(returnedCalendar.getLink("alternate", "application/atom+xml").getHref());
return;
}
/**
* Delete all Google calendar entries for a specific date range.
* @return The number of entries successfully deleted.
*/
public int deleteCalendarEntries() throws Exception {
ArrayList<CalendarEventEntry> googleCalEntries = getCalendarEntries();
return deleteCalendarEntries(googleCalEntries);
}
/**
* Delete the Google calendar entries in the provided list.
* @return The number of entries successfully deleted.
*/
public int deleteCalendarEntries(ArrayList<CalendarEventEntry> googleCalEntries) throws Exception {
try {
if (googleCalEntries.size() == 0)
return 0;
URL feedUrl = getDestinationCalendarUrl();
int retryCount = 0;
// Delete all the entries as a batch delete
CalendarEventFeed batchRequest = new CalendarEventFeed();
for (int i = 0; i < googleCalEntries.size(); i++) {
CalendarEventEntry entry = googleCalEntries.get(i);
BatchUtils.setBatchId(entry, Integer.toString(i));
BatchUtils.setBatchOperationType(entry, BatchOperationType.DELETE);
batchRequest.getEntries().add(entry);
}
CalendarEventFeed feed = null;
do {
try {
feed = service.getFeed(feedUrl, CalendarEventFeed.class);
} catch (com.google.gdata.util.ServiceException ex) {
feed = null;
// If there is a network problem, retry a few times
if (++retryCount > maxRetryCount)
throw ex;
Thread.sleep(retryDelayMsecs);
}
} while (feed == null);
// Get the batch link URL
Link batchLink = feed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
// Send the batch request with retries
CalendarEventFeed batchResponse = null;
do {
try {
batchResponse = service.batch(new URL(batchLink.getHref()), batchRequest);
} catch (com.google.gdata.util.ServiceException ex) {
batchResponse = null;
// If there is a network problem, retry a few times
if (++retryCount > maxRetryCount)
throw ex;
Thread.sleep(retryDelayMsecs);
}
} while (batchResponse == null);
CheckBatchDeleteResults(batchResponse, googleCalEntries);
return batchRequest.getEntries().size();
} catch (Exception ex) {
throw ex;
}
}
/**
* Throw an exception if there were any errors in the batch delete.
* @param batchResponse - The batch response.
* @param googleCalEntries - The original list of items that we tried to delete.
*/
protected void CheckBatchDeleteResults(CalendarEventFeed batchResponse, ArrayList<CalendarEventEntry> googleCalEntries) throws Exception {
// Ensure that all the operations were successful
boolean isSuccess = true;
StringBuffer batchFailureMsg = new StringBuffer("These entries in the batch delete failed:");
for (CalendarEventEntry entry : batchResponse.getEntries()) {
String batchId = BatchUtils.getBatchId(entry);
if (!BatchUtils.isSuccess(entry)) {
isSuccess = false;
BatchStatus status = BatchUtils.getBatchStatus(entry);
CalendarEventEntry entryOrig = googleCalEntries.get(new Integer(batchId));
batchFailureMsg.append("\nID: " + batchId + " Reason: " + status.getReason() +
" Subject: " + entryOrig.getTitle().getPlainText() +
" Start Date: " + entryOrig.getTimes().get(0).getStartTime().toString());
}
}
if (!isSuccess) {
throw new Exception(batchFailureMsg.toString());
}
}
/**
* Get all the Google calendar entries for a specific date range.
* @return The found entries.
*/
public ArrayList<CalendarEventEntry> getCalendarEntries() throws Exception {
try {
ArrayList<CalendarEventEntry> allCalEntries = new ArrayList<CalendarEventEntry>();
URL feedUrl = getDestinationCalendarUrl();
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(new com.google.gdata.data.DateTime(minStartDate.getTime()));
myQuery.setMaximumStartTime(new com.google.gdata.data.DateTime(maxEndDate.getTime()));
// Set the maximum number of results to return for the query.
// Note: A GData server may choose to provide fewer results, but will never provide
// more than the requested maximum.
myQuery.setMaxResults(5000);
int startIndex = 1;
int entriesReturned;
int retryCount = 0;
CalendarEventFeed resultFeed;
// Run our query as many times as necessary to get all the
// Google calendar entries we want
while (true) {
myQuery.setStartIndex(startIndex);
try {
// Execute the query and get the response
resultFeed = service.query(myQuery, CalendarEventFeed.class);
} catch (com.google.gdata.util.ServiceException ex) {
// If there is a network problem while connecting to Google, retry a few times
if (++retryCount > maxRetryCount)
throw ex;
Thread.sleep(retryDelayMsecs);
continue;
}
entriesReturned = resultFeed.getEntries().size();
if (entriesReturned == 0)
// We've hit the end of the list
break;
// Add the returned entries to our local list
allCalEntries.addAll(resultFeed.getEntries());
startIndex = startIndex + entriesReturned;
}
// Remove all entries marked canceled. Canceled entries aren't visible
// in Google calendar, and trying to delete them programatically will
// cause an exception.
for (int i = 0; i < allCalEntries.size(); i++) {
CalendarEventEntry entry = allCalEntries.get(i);
if (entry.getStatus().equals(BaseEventEntry.EventStatus.CANCELED)) {
allCalEntries.remove(entry);
i--;
}
}
if (diagnosticMode)
writeInRangeEntriesToFile(allCalEntries);
return allCalEntries;
} catch (Exception ex) {
throw ex;
}
}
/**
* Write key parts of the Google calendar entries to a text file.
* @param calendarEntries - The calendar entries to process.
*/
public void writeInRangeEntriesToFile(ArrayList<CalendarEventEntry> calendarEntries) throws Exception {
try {
// Open the output file if it is not open
if (googleInRangeEntriesWriter == null) {
googleInRangeEntriesFile = new File(googleInRangeEntriesFullFilename);
googleInRangeEntriesWriter = new BufferedWriter(new FileWriter(googleInRangeEntriesFile));
}
if (calendarEntries == null)
googleInRangeEntriesWriter.write("The calendar entries list is null.\n");
else
for (CalendarEventEntry calEntry : calendarEntries) {
googleInRangeEntriesWriter.write("=== Calendar Entry ===\n");
googleInRangeEntriesWriter.write(" Title: " + calEntry.getTitle().getPlainText() + "\n");
googleInRangeEntriesWriter.write(" IcalUID: " + calEntry.getIcalUID() + "\n");
for (When eventTime : calEntry.getTimes()) {
googleInRangeEntriesWriter.write(" Start Date: " + new Date(eventTime.getStartTime().getValue()) + "\n");
googleInRangeEntriesWriter.write(" End Date: " + new Date(eventTime.getEndTime().getValue()) + "\n");
}
googleInRangeEntriesWriter.write(" Edited Date: " + new Date(calEntry.getEdited().getValue()) + "\n");
googleInRangeEntriesWriter.write(" Updated Date: " + new Date(calEntry.getUpdated().getValue()) + "\n");
googleInRangeEntriesWriter.write("\n\n");
}
} catch (Exception ex) {
throw ex;
}
finally {
if (googleInRangeEntriesWriter != null) {
googleInRangeEntriesWriter.close();
googleInRangeEntriesWriter = null;
}
}
}
// Delete the destination calendar.
//
// TODO What if entries were created in the main calendar (instead of the Lotus Notes
// calendar)? This code only deletes from the Lotus Notes calendar.
// Because this isn't working quite yet, I've disabled the "sync to main calendar"
// checkbox on the Advanced tab.
public void deleteCalendar() throws Exception {
try {
CalendarFeed calendars = service.getFeed(mainCalendarFeedUrl, CalendarFeed.class);
// Loop through each calendar
for (int i = 0; i < calendars.getEntries().size(); i++) {
CalendarEntry calendar = calendars.getEntries().get(i);
// If this is the Lotus Notes calendar, delete it
if (calendar.getTitle().getPlainText().equals(destinationCalendarName)) {
calendar.delete();
}
}
} catch (Exception ex) {
throw ex;
}
}
/**
* Compare the Lotus and Google entries based on the Lotus modified timestamp.
* On exit, lotusCalEntries will only contain the entries we want created and
* googleCalEntries will only contain the entries we want deleted.
*/
public void compareCalendarEntries(ArrayList<NotesCalendarEntry> lotusCalEntries, ArrayList<CalendarEventEntry> googleCalEntries) {
// Loop through all Lotus entries
for (int i = 0; i < lotusCalEntries.size(); i++) {
NotesCalendarEntry lotusEntry = lotusCalEntries.get(i);
// Loop through all Google entries for each Lotus entry. This isn't
// really efficient, but we have small lists (probably less than 300).
for (int j = 0; j < googleCalEntries.size(); j++) {
if ( ! hasEntryChanged(lotusEntry, googleCalEntries.get(j))) {
// The Lotus and Google entries are identical, so remove them from out lists.
// They don't need created or deleted.
lotusCalEntries.remove(i--);
googleCalEntries.remove(j--);
break;
}
}
}
}
/**
* Compare a Lotus and Google entry. Return true if the Lotus entry has changed
* since the last sync.
*/
public boolean hasEntryChanged(NotesCalendarEntry lotusEntry, CalendarEventEntry googleEntry) {
final int googleUIDIdx = 33;
// If the ICAL UID is less than our minimum length, say the entry has changed
if (googleEntry.getIcalUID().length() - 1 < googleUIDIdx)
return true;
String syncUID = lotusEntry.getSyncUID();
// The Google IcalUID has the format: GoogleUID:SyncUID.
// Strip off the "GoogleUID:" part and do a compare.
if (googleEntry.getIcalUID().substring(googleUIDIdx).equals(syncUID)) {
// The two entries match on our first test, but we have to compare
// other values. Why? Say a sync is performed with the "sync alarms"
// option enabled, but then "sync alarms" is turned off. When the
// second sync happens, we want to delete all the Google entries created
// the first time (with alarms) and re-create them without alarms.
if (syncAlarms && lotusEntry.getAlarm()) {
// We are syncing alarms, so make sure the Google entry has an alarm.
// Note: If there is an alarm set, we'll assume the offset is correct.
if (googleEntry.getReminder().size() == 0)
return true;
}
else {
// We aren't syncing alarms, so make sure the Google entry doesn't
// have an alarm specified
if (googleEntry.getReminder().size() > 0)
return true;
}
// Compare the Description field of Google entry to what we would build it as
if (! googleEntry.getPlainTextContent().equals(createDescriptionText(lotusEntry))) {
return true;
}
// The Lotus and Google entries are identical
return false;
}
return true;
}
// This method is for testing purposes.
public void createSampleCalEntry() {
NotesCalendarEntry cal = new NotesCalendarEntry();
cal.setSubject("DeanRepeatTest");
cal.setEntryType(NotesCalendarEntry.EntryType.APPOINTMENT);
cal.setAppointmentType("3");
cal.setLocation("nolocation");
cal.setRoom("noroom");
Date dstartDate, dendDate;
Calendar now = Calendar.getInstance();
now.set(Calendar.YEAR, 2010);
now.set(Calendar.MONTH, 7); // Month is relative zero
now.set(Calendar.DAY_OF_MONTH, 2);
now.set(Calendar.HOUR_OF_DAY, 10);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
dstartDate = now.getTime();
cal.setStartDateTime(dstartDate);
now.set(Calendar.HOUR_OF_DAY, 11);
dendDate = now.getTime();
cal.setEndDateTime(dendDate);
DateTime startTime, endTime;
CalendarEventEntry event = new CalendarEventEntry();
event.setTitle(new PlainTextConstruct(cal.getSubject()));
String whereStr = cal.getGoogleWhereString();
if (whereStr != null) {
Where location = new Where();
location.setValueString(whereStr);
event.addLocation(location);
}
try {
When eventTime = new When();
eventTime.setStartTime(DateTime.parseDateTime(cal.getStartDateTimeGoogle()));
eventTime.setEndTime(DateTime.parseDateTime(cal.getEndDateTimeGoogle()));
event.addTime(eventTime);
Date dstartDate2, dendDate2;
now.set(Calendar.DAY_OF_MONTH, 3);
now.set(Calendar.HOUR_OF_DAY, 10);
dstartDate2 = now.getTime();
cal.setStartDateTime(dstartDate2);
now.set(Calendar.HOUR_OF_DAY, 11);
dendDate2 = now.getTime();
cal.setEndDateTime(dendDate2);
eventTime = new When();
eventTime.setStartTime(DateTime.parseDateTime(cal.getStartDateTimeGoogle()));
eventTime.setEndTime(DateTime.parseDateTime(cal.getEndDateTimeGoogle()));
event.addTime(eventTime);
int j = event.getTimes().size();
j++;
service.insert(getDestinationCalendarUrl(), event);
} catch (Exception e) {
}
}
/**
* Create Lotus Notes calendar entries in the Google calendar.
* @param lotusCalEntries - The list of Lotus Notes calendar entries.
* @return The number of Google calendar entries successfully created.
* @throws ServiceException
* @throws IOException
*/
public int createCalendarEntries(ArrayList<NotesCalendarEntry> lotusCalEntries) throws Exception, ServiceException, IOException {
int retryCount = 0;
int createdCount = 0;
for (int i = 0; i < lotusCalEntries.size(); i++) {
NotesCalendarEntry lotusEntry = lotusCalEntries.get(i);
CalendarEventEntry event = new CalendarEventEntry();
event.setTitle(new PlainTextConstruct(lotusEntry.getSubject()));
// The Google IcalUID must be unique for all eternity or we'll get a
// VersionConflictException during the insert. So start the IcalUID string
// with a newly generate UUID (with the '-' chars removed). Then add the values
// we really want to remember (referred to as the SyncUID).
event.setIcalUID(UUID.randomUUID().toString().replaceAll("-", "") + ":" + lotusEntry.getSyncUID());
StringBuffer sb = new StringBuffer();
event.setContent(new PlainTextConstruct(createDescriptionText(lotusEntry)));
String whereStr = lotusEntry.getGoogleWhereString();
if (whereStr != null) {
Where location = new Where();
location.setValueString(whereStr);
event.addLocation(location);
}
DateTime startTime, endTime;
if (lotusEntry.getEntryType() == NotesCalendarEntry.EntryType.TASK ||
lotusEntry.getAppointmentType() == NotesCalendarEntry.AppointmentType.ALL_DAY_EVENT ||
lotusEntry.getAppointmentType() == NotesCalendarEntry.AppointmentType.ANNIVERSARY)
{
// Create an all-day event by setting start/end dates with no time portion
startTime = DateTime.parseDate(lotusEntry.getStartDateGoogle());
// IMPORTANT: For Google to properly create an all-day event, we must add
// one day to the end date
if (lotusEntry.getEndDateTime() == null)
// Use start date since the end date is null
endTime = DateTime.parseDate(lotusEntry.getStartDateGoogle(1));
else
endTime = DateTime.parseDate(lotusEntry.getEndDateGoogle(1));
}
else if (lotusEntry.getAppointmentType() == NotesCalendarEntry.AppointmentType.APPOINTMENT ||
lotusEntry.getAppointmentType() == NotesCalendarEntry.AppointmentType.MEETING)
{
// Create a standard event
startTime = DateTime.parseDateTime(lotusEntry.getStartDateTimeGoogle());
if (lotusEntry.getEndDateTime() == null)
// Use start date since the end date is null
endTime = DateTime.parseDateTime(lotusEntry.getStartDateTimeGoogle());
else
endTime = DateTime.parseDateTime(lotusEntry.getEndDateTimeGoogle());
}
else if (lotusEntry.getAppointmentType() == NotesCalendarEntry.AppointmentType.REMINDER)
{
// Create a standard event with the start and end times the same
startTime = DateTime.parseDateTime(lotusEntry.getStartDateTimeGoogle());
endTime = DateTime.parseDateTime(lotusEntry.getStartDateTimeGoogle());
}
else
{
throw new Exception("Couldn't determine Lotus Notes event type.\nEvent subject: " + lotusEntry.getSubject() +
"\nEntry Type: " + lotusEntry.getEntryType() +
"\nAppointment Type: " + lotusEntry.getAppointmentType());
}
When eventTime = new When();
eventTime.setStartTime(startTime);
eventTime.setEndTime(endTime);
event.addTime(eventTime);
if (syncAlarms && lotusEntry.getAlarm()) {
Reminder reminder = new Reminder();
reminder.setMinutes(lotusEntry.getAlarmOffsetMinsGoogle());
reminder.setMethod(Method.ALERT);
event.getReminder().add(reminder);
}
retryCount = 0;
do {
try {
service.insert(getDestinationCalendarUrl(), event);
createdCount++;
break;
} catch (Exception ex) {
// If there is a network problem (a ServiceException) while connecting to Google, retry a few times
// before throwing an exception.
if (ex instanceof com.google.gdata.util.ServiceException && ++retryCount <= maxRetryCount)
Thread.sleep(retryDelayMsecs);
else
throw new Exception("Couldn't create Google entry.\nSubject: " + event.getTitle().getPlainText() +
"\nStart Date: " + event.getTimes().get(0).getStartTime().toString(), ex);
}
} while (true);
}
return createdCount;
}
protected String createDescriptionText(NotesCalendarEntry lotusEntry) {
StringBuffer sb = new StringBuffer();
if (syncMeetingAttendees) {
if (lotusEntry.getChairpersonPlain() != null) {
//chair comes out in format: CN=Jonathan Marshall/OU=UK/O=IBM, leaving like that at the moment
sb.append("Chairperson: "); sb.append(lotusEntry.getChairpersonPlain());
}
if (lotusEntry.getRequiredAttendeesPlain() != null) {
if (sb.length() > 0)
sb.append("\n");
sb.append("Required: "); sb.append(lotusEntry.getRequiredAttendeesPlain());
}
if (lotusEntry.getOptionalAttendees() != null){
if (sb.length() > 0)
sb.append("\n");
sb.append("Optional: "); sb.append(lotusEntry.getOptionalAttendees());
}
}
if (syncDescription && lotusEntry.getBody() != null) {
if (sb.length() > 0)
// Put blank lines between attendees and the description
sb.append("\n\n\n");
// Lotus ends each description line with \r\n. Remove all
// carriage returns (\r) because they aren't needed and they prevent the
// Lotus description from matching the description in Google.
String s = lotusEntry.getBody().replaceAll("\r", "");
sb.append(s.trim());
}
// Return a string truncated to a max size
return sb.toString().substring(0, sb.length() < maxDescriptionChars ? sb.length() : maxDescriptionChars);
}
public void setSyncDescription(boolean value) {
syncDescription = value;
}
public void setSyncAlarms(boolean value) {
syncAlarms = value;
}
public void setSyncMeetingAttendees(boolean value){
syncMeetingAttendees = value;
}
public void setMinStartDate(Date minStartDate) {
this.minStartDate = minStartDate;
}
public void setMaxEndDate(Date maxEndDate) {
this.maxEndDate = maxEndDate;
}
public void setDiagnosticMode(boolean value) {
diagnosticMode = value;
}
URL mainCalendarFeedUrl = null;
URL privateCalendarFeedUrl = null;
URL destinationCalendarFeedUrl = null;
CalendarService service;
BufferedWriter googleInRangeEntriesWriter = null;
File googleInRangeEntriesFile = null;
boolean diagnosticMode = false;
boolean syncDescription = false;
boolean syncAlarms = false;
boolean syncMeetingAttendees = false;
// Our min and max dates for entries we will process.
// If the calendar entry is outside this range, it is ignored.
Date minStartDate = null;
Date maxEndDate = null;
final String googleInRangeEntriesFilename = "GoogleInRangeEntries.txt";
// Filename with full path
String googleInRangeEntriesFullFilename;
final int maxRetryCount = 10;
final int retryDelayMsecs = 300;
// The maximum number of chars allowed in a calendar description. Google has some
// limit around 8100 chars. Lotus has a limit greater than that, so choose 8000.
final int maxDescriptionChars = 8000;
String destinationCalendarName;
String DEST_CALENDAR_COLOR = "#F2A640";
}
| gpl-3.0 |
jdno/ASxcel | src/de/jandavid/asxcel/model/Airport.java | 8561 | /**
* This file is part of ASxcel.
*
* ASxcel 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.
*
* ASxcel 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 ASxcel. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jandavid.asxcel.model;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* An airport in AirlineSim has five important parameters:
* - name
* - IATA code
* - size
* - passengers
* - cargo
* These parameters are helpful to the user to choose new
* routes and where to expand to.
*
* @author jdno
*/
public class Airport implements Comparable<Airport> {
/**
* This indicates how much cargo volume this airport has.
* Values range from 0 (lowest) to 10 (highest).
*/
private int cargo = 0;
/**
* This is the country the airport is located in.
*/
private Country country;
/**
* This is the IATA code of the airport.
*/
private String iataCode = "";
/**
* This is the ID the airports has in the database.
*/
private int id;
/**
* This is necessary to access the database.
*/
private Model model;
/**
* This is the name of the airport.
*/
private String name;
/**
* This indicated how much passenger volume this airport has.
* Values range from 0 (lowest) to 10 (highest).
*/
private int passengers = 0;
/**
* This is the size of the airport as it is indicated in
* the game (e.g. "Small airport").
*/
private String size = "";
/**
* At some airports transfer is not possible, which means no passenger
* can change flights at this location.
*/
private boolean transferPossible = true;
/**
* An airport gets initialized with its name, all the other parameters
* can be set later or they can be retrieved from the database if the
* airport has been created already.
* @param name The name of the airport.
* @throws SQLException If an SQL error occurs this gets thrown.
*/
protected Airport(Model model, String name) throws SQLException {
this.model = model;
this.name = name;
syncWithDb();
}
/**
* This constructor initializes an airport with all its attributes. No
* synchronization with the database happens! This is meant as a help
* for the model to load a set of airports with one query from the
* database and initialize them all at once without further queries.
* @param model The model to use
* @param id The ID of the airport (from the database)
* @param name The name of the airport
* @param country The country the airport is in
* @param iata The IATA code of the airport
* @param pax The airports passenger size
* @param cargo The airports cargo size
* @param transferPossible Is a transfer possible
*/
protected Airport(Model model, int id, String name, Country country, String iata, String size, int pax, int cargo, boolean transferPossible) {
this.model = model;
this.id = id;
this.name = name;
this.country = country;
this.iataCode = iata;
this.size = size;
this.passengers = pax;
this.cargo = cargo;
this.transferPossible = transferPossible;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Airport o) {
return name.compareTo(o.getName());
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if(obj instanceof Airport) {
if(((Airport) obj).compareTo(this) == 0) {
return true;
} else {
return false;
}
} else {
return super.equals(obj);
}
}
/**
* This method loads an airport from the database, assuming the airport
* has been created already. If this is the case this instance if Airport
* gets filled with its data, else a new airport gets added to the database
* with the given name.
* @throws SQLException If an SQL error occurs this gets thrown.
*/
private void syncWithDb() throws SQLException {
String query = "SELECT `a`.`id`, `a`.`name`, `a`.`iata`, `a`.`passengers`, " +
"`a`.`cargo`, `a`.`size`, `a`.`transfer`, `c`.`name` FROM `airports` AS `a` " +
"INNER JOIN `countries` AS `c` ON `a`.`country` = `c`.`id` " +
"INNER JOIN `enterprise_has_airport` AS `eha` ON `a`.`id` = `eha`.`airport` " +
"WHERE `a`.`name` = ? AND `eha`.`enterprise` = ? LIMIT 1";
ArrayList<Object> params = new ArrayList<Object>(1);
params.add(name);
params.add(model.getEnterprise().getId());
DatabaseResult dr = model.getDatabase().executeQuery(query, params);
if(dr.next()) {
id = dr.getInt(0);
name = dr.getString(1);
iataCode = dr.getString(2);
passengers = dr.getInt(3);
cargo = dr.getInt(4);
size = dr.getString(5);
transferPossible = dr.getInt(6) == 1 ? true : false;
country = new Country(model, dr.getString(7));
} else {
params.remove(1);
query = "INSERT OR IGNORE INTO `airports` (`name`) VALUES (?)";
model.getDatabase().executeUpdate(query, params);
query = "INSERT OR IGNORE INTO `enterprise_has_airport` (`enterprise` , `airport`) " +
"SELECT '" + model.getEnterprise().getId() + "' AS `enterprise`, " +
"`id` FROM `airports` WHERE `name` = ?";
model.getDatabase().executeUpdate(query, params);
syncWithDb();
}
}
/**
* This is an auxiliary method used by the setter to change values in the
* database without the need to create an own query first.
* @param field The name of the column in the database.
* @param value The value to set.
* @throws SQLException If an SQL error occurs this gets thrown.
*/
private void updateField(String field, Object value) throws SQLException {
String query = "UPDATE `airports` SET `" + field + "` = ? WHERE `id` = ?";
ArrayList<Object> params = new ArrayList<Object>(2);
params.add(value);
params.add(id);
model.getDatabase().executeUpdate(query, params);
}
/**
* @return the cargo
*/
public int getCargo() {
return cargo;
}
/**
* @param cargo the cargo to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setCargo(int cargo) throws SQLException {
updateField("cargo", cargo);
this.cargo = cargo;
}
/**
* @return the country
*/
public Country getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(Country country) {
this.country = country;
}
/**
* @return the iataCode
*/
public String getIataCode() {
return iataCode;
}
/**
* @param iataCode the iataCode to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setIataCode(String iataCode) throws SQLException {
updateField("iata", iataCode);
this.iataCode = iataCode;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setName(String name) throws SQLException {
updateField("name", name);
this.name = name;
}
/**
* @return the passengers
*/
public int getPassengers() {
return passengers;
}
/**
* @param passengers the passengers to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setPassengers(int passengers) throws SQLException {
updateField("passengers", passengers);
this.passengers = passengers;
}
/**
* @return the size
*/
public String getSize() {
return size;
}
/**
* @param size the size to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setSize(String size) throws SQLException {
updateField("size", size);
this.size = size;
}
/**
* @return the transferPossible
*/
public boolean isTransferPossible() {
return transferPossible;
}
/**
* @param transferPossible the transferPossible to set
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public void setTransferPossible(boolean transferPossible) throws SQLException {
updateField("transfer", transferPossible ? 1 : 0);
this.transferPossible = transferPossible;
}
}
| gpl-3.0 |
shadowmage45/AncientWarfare | AncientWarfare/project_resources/meim_resources/JavaExport/balstand.java | 17821 | //auto-generated model template
//template generated by MEIM
//template v 1.0
//author Shadowmage45 (shadowage_catapults@hotmail.com)
package foo.bad.pkg.set.yours.here;
public class balstand extends ModelBase
{
ModelRenderer baseMain;
ModelRenderer basePillar;
ModelRenderer pivot;
ModelRenderer armMain;
ModelRenderer armFront;
ModelRenderer turretHorizontalBrace2;
ModelRenderer turretHorizontalBrace3;
ModelRenderer armMidBrace;
ModelRenderer armSlotLeft;
ModelRenderer armSlotRight;
ModelRenderer armleftVertical3;
ModelRenderer armLeftVertical2;
ModelRenderer armLeftVertical1;
ModelRenderer turretHorizontalBrace4;
ModelRenderer leftTensionerRope;
ModelRenderer leftTensioner;
ModelRenderer leftTensioner2;
ModelRenderer rightTensionerRope;
ModelRenderer rightTensioner;
ModelRenderer rightTensioner2;
ModelRenderer turretHorizontalBrace1;
ModelRenderer armRightVertical3;
ModelRenderer armRightVertical2;
ModelRenderer armRightVertical1;
ModelRenderer trigger1;
ModelRenderer trigger2;
ModelRenderer crankAxle;
ModelRenderer crankHandle1;
ModelRenderer crankHandle2;
ModelRenderer catch2;
ModelRenderer catch1;
ModelRenderer armRightMain;
ModelRenderer armRightMainInner;
ModelRenderer armRightMainInner3;
ModelRenderer armRightMainInner2;
ModelRenderer armRightInner;
ModelRenderer armRightOuter;
ModelRenderer stringRight;
ModelRenderer armLeftMain;
ModelRenderer armLeftMainInner;
ModelRenderer armLeftOuter;
ModelRenderer armLeftMainInner2;
ModelRenderer armLeftMainInner3;
ModelRenderer armLeftInner;
ModelRenderer stringLeft;
ModelRenderer flagPole;
ModelRenderer flagCloth;
public balstand(){
baseMain = new ModelRenderer(this,"baseMain");
baseMain.setTextureOffset(0,21);
baseMain.setTextureSize(256,256);
baseMain.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(baseMain,0.0f, 0.0f, 0.0f);
baseMain.addBox(-7.0f,-2.0f,-7.0f,14,2,14);
basePillar = new ModelRenderer(this,"basePillar");
basePillar.setTextureOffset(0,0);
basePillar.setTextureSize(256,256);
basePillar.setRotationPoint(0.0f, -12.0f, 0.0f);
setPieceRotation(basePillar,0.0f, 0.0f, 0.0f);
basePillar.addBox(-2.0f,0.0f,-2.0f,4,10,4);
pivot = new ModelRenderer(this,"pivot");
pivot.setTextureOffset(17,0);
pivot.setTextureSize(256,256);
pivot.setRotationPoint(0.0f, -2.0f, 0.0f);
setPieceRotation(pivot,0.0f, 0.0f, 0.0f);
pivot.addBox(-1.0f,0.0f,-1.0f,2,2,2);
basePillar.addChild(pivot);
baseMain.addChild(basePillar);
armMain = new ModelRenderer(this,"armMain");
armMain.setTextureOffset(0,128);
armMain.setTextureSize(256,256);
armMain.setRotationPoint(0.0f, -14.0f, 0.0f);
setPieceRotation(armMain,-6.585082E-7f, -2.3593943E-6f, 0.0f);
armMain.addBox(-1.5f,-2.0f,-4.5f,3,2,28);
armFront = new ModelRenderer(this,"armFront");
armFront.setTextureOffset(63,128);
armFront.setTextureSize(256,256);
armFront.setRotationPoint(-1.5f, -2.0f, -11.5f);
setPieceRotation(armFront,0.0f, 0.0f, 0.0f);
armFront.addBox(0.0f,0.0f,0.0f,3,2,4);
armMain.addChild(armFront);
turretHorizontalBrace2 = new ModelRenderer(this,"turretHorizontalBrace2");
turretHorizontalBrace2.setTextureOffset(63,135);
turretHorizontalBrace2.setTextureSize(256,256);
turretHorizontalBrace2.setRotationPoint(11.0f, -1.5f, -4.5f);
setPieceRotation(turretHorizontalBrace2,0.0f, 0.5410521f, 0.0f);
turretHorizontalBrace2.addBox(-13.0f,0.0f,-3.0f,13,1,3);
armMain.addChild(turretHorizontalBrace2);
turretHorizontalBrace3 = new ModelRenderer(this,"turretHorizontalBrace3");
turretHorizontalBrace3.setTextureOffset(63,140);
turretHorizontalBrace3.setTextureSize(256,256);
turretHorizontalBrace3.setRotationPoint(-11.0f, -2.0f, -7.5f);
setPieceRotation(turretHorizontalBrace3,0.0f, 0.0f, 0.0f);
turretHorizontalBrace3.addBox(0.0f,0.0f,0.0f,22,2,3);
armMain.addChild(turretHorizontalBrace3);
armMidBrace = new ModelRenderer(this,"armMidBrace");
armMidBrace.setTextureOffset(0,159);
armMidBrace.setTextureSize(256,256);
armMidBrace.setRotationPoint(-1.5f, -3.0f, -11.5f);
setPieceRotation(armMidBrace,0.0f, 0.0f, 0.0f);
armMidBrace.addBox(0.0f,0.0f,0.0f,3,1,35);
armMain.addChild(armMidBrace);
armSlotLeft = new ModelRenderer(this,"armSlotLeft");
armSlotLeft.setTextureOffset(77,159);
armSlotLeft.setTextureSize(256,256);
armSlotLeft.setRotationPoint(0.5f, -4.0f, -11.5f);
setPieceRotation(armSlotLeft,0.0f, 0.0f, 0.0f);
armSlotLeft.addBox(0.0f,0.0f,0.0f,1,1,35);
armMain.addChild(armSlotLeft);
armSlotRight = new ModelRenderer(this,"armSlotRight");
armSlotRight.setTextureOffset(77,159);
armSlotRight.setTextureSize(256,256);
armSlotRight.setRotationPoint(-1.5f, -4.0f, -11.5f);
setPieceRotation(armSlotRight,0.0f, 0.0f, 0.0f);
armSlotRight.addBox(0.0f,0.0f,0.0f,1,1,35);
armMain.addChild(armSlotRight);
armleftVertical3 = new ModelRenderer(this,"armleftVertical3");
armleftVertical3.setTextureOffset(78,128);
armleftVertical3.setTextureSize(256,256);
armleftVertical3.setRotationPoint(10.0f, -3.0f, -6.0f);
setPieceRotation(armleftVertical3,0.0f, 0.0f, 0.0f);
armleftVertical3.addBox(0.0f,0.0f,0.0f,1,1,1);
armMain.addChild(armleftVertical3);
armLeftVertical2 = new ModelRenderer(this,"armLeftVertical2");
armLeftVertical2.setTextureOffset(78,128);
armLeftVertical2.setTextureSize(256,256);
armLeftVertical2.setRotationPoint(10.0f, -7.0f, -6.0f);
setPieceRotation(armLeftVertical2,0.0f, 0.0f, 0.0f);
armLeftVertical2.addBox(0.0f,0.0f,0.0f,1,1,1);
armMain.addChild(armLeftVertical2);
armLeftVertical1 = new ModelRenderer(this,"armLeftVertical1");
armLeftVertical1.setTextureOffset(83,128);
armLeftVertical1.setTextureSize(256,256);
armLeftVertical1.setRotationPoint(10.0f, -7.0f, -7.0f);
setPieceRotation(armLeftVertical1,0.0f, 0.0f, 0.0f);
armLeftVertical1.addBox(0.0f,0.0f,0.0f,1,5,1);
armMain.addChild(armLeftVertical1);
turretHorizontalBrace4 = new ModelRenderer(this,"turretHorizontalBrace4");
turretHorizontalBrace4.setTextureOffset(63,140);
turretHorizontalBrace4.setTextureSize(256,256);
turretHorizontalBrace4.setRotationPoint(-11.0f, -9.0f, -7.5f);
setPieceRotation(turretHorizontalBrace4,0.0f, 0.0f, 0.0f);
turretHorizontalBrace4.addBox(0.0f,0.0f,0.0f,22,2,3);
armMain.addChild(turretHorizontalBrace4);
leftTensionerRope = new ModelRenderer(this,"leftTensionerRope");
leftTensionerRope.setTextureOffset(114,128);
leftTensionerRope.setTextureSize(256,256);
leftTensionerRope.setRotationPoint(5.5f, -7.0f, -6.0f);
setPieceRotation(leftTensionerRope,0.0f, 0.0f, 0.0f);
leftTensionerRope.addBox(-0.5f,-3.0f,-0.5f,1,11,1);
leftTensioner = new ModelRenderer(this,"leftTensioner");
leftTensioner.setTextureOffset(88,128);
leftTensioner.setTextureSize(256,256);
leftTensioner.setRotationPoint(0.0f, -3.0f, 0.0f);
setPieceRotation(leftTensioner,0.0f, 0.0f, 0.0f);
leftTensioner.addBox(-1.0f,-0.5f,-0.5f,2,1,1);
leftTensionerRope.addChild(leftTensioner);
leftTensioner2 = new ModelRenderer(this,"leftTensioner2");
leftTensioner2.setTextureOffset(88,131);
leftTensioner2.setTextureSize(256,256);
leftTensioner2.setRotationPoint(0.0f, -3.0f, -0.0f);
setPieceRotation(leftTensioner2,0.0f, 0.0f, 0.0f);
leftTensioner2.addBox(-0.5f,-0.5f,-1.0f,1,1,2);
leftTensionerRope.addChild(leftTensioner2);
armMain.addChild(leftTensionerRope);
rightTensionerRope = new ModelRenderer(this,"rightTensionerRope");
rightTensionerRope.setTextureOffset(114,128);
rightTensionerRope.setTextureSize(256,256);
rightTensionerRope.setRotationPoint(-5.5f, -7.0f, -6.0f);
setPieceRotation(rightTensionerRope,0.0f, 0.0f, 0.0f);
rightTensionerRope.addBox(-0.5f,-3.0f,-0.5f,1,11,1);
rightTensioner = new ModelRenderer(this,"rightTensioner");
rightTensioner.setTextureOffset(88,128);
rightTensioner.setTextureSize(256,256);
rightTensioner.setRotationPoint(0.0f, -3.0f, 0.0f);
setPieceRotation(rightTensioner,0.0f, 0.0f, 0.0f);
rightTensioner.addBox(-1.0f,-0.5f,-0.5f,2,1,1);
rightTensionerRope.addChild(rightTensioner);
rightTensioner2 = new ModelRenderer(this,"rightTensioner2");
rightTensioner2.setTextureOffset(88,131);
rightTensioner2.setTextureSize(256,256);
rightTensioner2.setRotationPoint(0.0f, -3.0f, 0.0f);
setPieceRotation(rightTensioner2,0.0f, 0.0f, 0.0f);
rightTensioner2.addBox(-0.5f,-0.5f,-1.0f,1,1,2);
rightTensionerRope.addChild(rightTensioner2);
armMain.addChild(rightTensionerRope);
turretHorizontalBrace1 = new ModelRenderer(this,"turretHorizontalBrace1");
turretHorizontalBrace1.setTextureOffset(63,135);
turretHorizontalBrace1.setTextureSize(256,256);
turretHorizontalBrace1.setRotationPoint(-11.0f, -1.5f, -4.5f);
setPieceRotation(turretHorizontalBrace1,0.0f, -0.5410521f, 0.0f);
turretHorizontalBrace1.addBox(0.0f,0.0f,-3.0f,13,1,3);
armMain.addChild(turretHorizontalBrace1);
armRightVertical3 = new ModelRenderer(this,"armRightVertical3");
armRightVertical3.setTextureOffset(78,128);
armRightVertical3.setTextureSize(256,256);
armRightVertical3.setRotationPoint(-11.0f, -3.0f, -6.0f);
setPieceRotation(armRightVertical3,0.0f, 0.0f, 0.0f);
armRightVertical3.addBox(0.0f,0.0f,0.0f,1,1,1);
armMain.addChild(armRightVertical3);
armRightVertical2 = new ModelRenderer(this,"armRightVertical2");
armRightVertical2.setTextureOffset(78,128);
armRightVertical2.setTextureSize(256,256);
armRightVertical2.setRotationPoint(-11.0f, -7.0f, -6.0f);
setPieceRotation(armRightVertical2,0.0f, 0.0f, 0.0f);
armRightVertical2.addBox(0.0f,0.0f,0.0f,1,1,1);
armMain.addChild(armRightVertical2);
armRightVertical1 = new ModelRenderer(this,"armRightVertical1");
armRightVertical1.setTextureOffset(83,128);
armRightVertical1.setTextureSize(256,256);
armRightVertical1.setRotationPoint(-11.0f, -7.0f, -7.0f);
setPieceRotation(armRightVertical1,0.0f, 0.0f, 0.0f);
armRightVertical1.addBox(0.0f,0.0f,0.0f,1,5,1);
armMain.addChild(armRightVertical1);
trigger1 = new ModelRenderer(this,"trigger1");
trigger1.setTextureOffset(63,146);
trigger1.setTextureSize(256,256);
trigger1.setRotationPoint(-0.0f, -1.0f, 17.5f);
setPieceRotation(trigger1,-1.256629f, 0.0f, 0.0f);
trigger1.addBox(-0.5f,-1.0f,0.0f,1,1,5);
trigger2 = new ModelRenderer(this,"trigger2");
trigger2.setTextureOffset(76,146);
trigger2.setTextureSize(256,256);
trigger2.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(trigger2,1.2217292f, 1.934953E-7f, 3.1625038E-7f);
trigger2.addBox(-0.5f,-4.0f,0.0f,1,4,1);
trigger1.addChild(trigger2);
armMain.addChild(trigger1);
crankAxle = new ModelRenderer(this,"crankAxle");
crankAxle.setTextureOffset(63,153);
crankAxle.setTextureSize(256,256);
crankAxle.setRotationPoint(-2.0f, -2.0f, 21.0f);
setPieceRotation(crankAxle,0.0f, 0.0f, 0.0f);
crankAxle.addBox(0.0f,-0.5f,-0.5f,4,1,1);
crankHandle1 = new ModelRenderer(this,"crankHandle1");
crankHandle1.setTextureOffset(81,146);
crankHandle1.setTextureSize(256,256);
crankHandle1.setRotationPoint(-0.5f, 0.0f, 0.0f);
setPieceRotation(crankHandle1,0.0f, 0.0f, 0.0f);
crankHandle1.addBox(-0.5f,-2.5f,-0.5f,1,5,1);
crankAxle.addChild(crankHandle1);
crankHandle2 = new ModelRenderer(this,"crankHandle2");
crankHandle2.setTextureOffset(86,146);
crankHandle2.setTextureSize(256,256);
crankHandle2.setRotationPoint(-0.5f, 0.0f, 0.0f);
setPieceRotation(crankHandle2,0.0f, 0.0f, 0.0f);
crankHandle2.addBox(-0.5f,-0.5f,-2.5f,1,1,5);
crankAxle.addChild(crankHandle2);
armMain.addChild(crankAxle);
catch2 = new ModelRenderer(this,"catch2");
catch2.setTextureOffset(99,146);
catch2.setTextureSize(256,256);
catch2.setRotationPoint(-1.0f, -6.0f, 20.5f);
setPieceRotation(catch2,-0.8552113f, 0.0f, 0.0f);
catch2.addBox(0.0f,0.0f,0.0f,2,1,4);
armMain.addChild(catch2);
catch1 = new ModelRenderer(this,"catch1");
catch1.setTextureOffset(99,152);
catch1.setTextureSize(256,256);
catch1.setRotationPoint(-1.0f, -6.0f, 17.5f);
setPieceRotation(catch1,0.0f, 0.0f, 0.0f);
catch1.addBox(0.0f,0.0f,0.0f,2,1,3);
armMain.addChild(catch1);
armRightMain = new ModelRenderer(this,"armRightMain");
armRightMain.setTextureOffset(0,215);
armRightMain.setTextureSize(256,256);
armRightMain.setRotationPoint(-5.5f, -5.0f, -6.0f);
setPieceRotation(armRightMain,0.0f, 0.5235982f, 0.0f);
armRightMain.addBox(-6.5f,-1.0f,-1.0f,8,3,1);
armRightMainInner = new ModelRenderer(this,"armRightMainInner");
armRightMainInner.setTextureOffset(0,203);
armRightMainInner.setTextureSize(256,256);
armRightMainInner.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armRightMainInner,0.0f, 0.0f, 0.0f);
armRightMainInner.addBox(-2.5f,-1.0f,0.0f,4,3,1);
armRightMain.addChild(armRightMainInner);
armRightMainInner3 = new ModelRenderer(this,"armRightMainInner3");
armRightMainInner3.setTextureOffset(0,196);
armRightMainInner3.setTextureSize(256,256);
armRightMainInner3.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armRightMainInner3,0.0f, 0.0f, 0.0f);
armRightMainInner3.addBox(-6.5f,0.0f,0.0f,4,1,1);
armRightMain.addChild(armRightMainInner3);
armRightMainInner2 = new ModelRenderer(this,"armRightMainInner2");
armRightMainInner2.setTextureOffset(0,199);
armRightMainInner2.setTextureSize(256,256);
armRightMainInner2.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armRightMainInner2,0.0f, 0.0f, 0.0f);
armRightMainInner2.addBox(-6.5f,-0.5f,-0.5f,4,2,1);
armRightMain.addChild(armRightMainInner2);
armRightInner = new ModelRenderer(this,"armRightInner");
armRightInner.setTextureOffset(0,208);
armRightInner.setTextureSize(256,256);
armRightInner.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armRightInner,0.0f, 0.0f, 0.0f);
armRightInner.addBox(-13.25f,0.0f,-0.5f,7,1,1);
armRightMain.addChild(armRightInner);
armRightOuter = new ModelRenderer(this,"armRightOuter");
armRightOuter.setTextureOffset(0,211);
armRightOuter.setTextureSize(256,256);
armRightOuter.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armRightOuter,0.0f, 0.0f, 0.0f);
armRightOuter.addBox(-13.5f,-0.5f,-1.0f,7,2,1);
armRightMain.addChild(armRightOuter);
stringRight = new ModelRenderer(this,"stringRight");
stringRight.setTextureOffset(0,220);
stringRight.setTextureSize(256,256);
stringRight.setRotationPoint(-13.0f, 0.5f, 0.0f);
setPieceRotation(stringRight,0.0f, -0.5235985f, 0.0f);
stringRight.addBox(0.0f,-0.5f,0.0f,17,1,1);
armRightMain.addChild(stringRight);
armMain.addChild(armRightMain);
armLeftMain = new ModelRenderer(this,"armLeftMain");
armLeftMain.setTextureOffset(0,215);
armLeftMain.setTextureSize(256,256);
armLeftMain.setRotationPoint(5.5f, -6.0f, -6.0f);
setPieceRotation(armLeftMain,0.0f, -0.5235988f, 0.0f);
armLeftMain.addBox(-1.5f,0.0f,-1.0f,8,3,1);
armLeftMainInner = new ModelRenderer(this,"armLeftMainInner");
armLeftMainInner.setTextureOffset(0,203);
armLeftMainInner.setTextureSize(256,256);
armLeftMainInner.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armLeftMainInner,0.0f, 0.0f, 0.0f);
armLeftMainInner.addBox(-1.5f,0.0f,0.0f,4,3,1);
armLeftMain.addChild(armLeftMainInner);
armLeftOuter = new ModelRenderer(this,"armLeftOuter");
armLeftOuter.setTextureOffset(0,211);
armLeftOuter.setTextureSize(256,256);
armLeftOuter.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armLeftOuter,0.0f, 0.0f, 0.0f);
armLeftOuter.addBox(6.5f,0.5f,-1.0f,7,2,1);
armLeftMain.addChild(armLeftOuter);
armLeftMainInner2 = new ModelRenderer(this,"armLeftMainInner2");
armLeftMainInner2.setTextureOffset(0,199);
armLeftMainInner2.setTextureSize(256,256);
armLeftMainInner2.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armLeftMainInner2,0.0f, 0.0f, 0.0f);
armLeftMainInner2.addBox(2.5f,0.5f,-0.5f,4,2,1);
armLeftMain.addChild(armLeftMainInner2);
armLeftMainInner3 = new ModelRenderer(this,"armLeftMainInner3");
armLeftMainInner3.setTextureOffset(0,196);
armLeftMainInner3.setTextureSize(256,256);
armLeftMainInner3.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armLeftMainInner3,0.0f, 0.0f, 0.0f);
armLeftMainInner3.addBox(2.5f,1.0f,-0.0f,4,1,1);
armLeftMain.addChild(armLeftMainInner3);
armLeftInner = new ModelRenderer(this,"armLeftInner");
armLeftInner.setTextureOffset(0,208);
armLeftInner.setTextureSize(256,256);
armLeftInner.setRotationPoint(0.0f, 0.0f, 0.0f);
setPieceRotation(armLeftInner,0.0f, 0.0f, 0.0f);
armLeftInner.addBox(6.25f,1.0f,-0.5f,7,1,1);
armLeftMain.addChild(armLeftInner);
stringLeft = new ModelRenderer(this,"stringLeft");
stringLeft.setTextureOffset(0,220);
stringLeft.setTextureSize(256,256);
stringLeft.setRotationPoint(13.0f, 1.5f, 0.0f);
setPieceRotation(stringLeft,0.0f, 0.5235985f, 0.0f);
stringLeft.addBox(-17.0f,-0.5f,0.0f,17,1,1);
armLeftMain.addChild(stringLeft);
armMain.addChild(armLeftMain);
flagPole = new ModelRenderer(this,"flagPole");
flagPole.setTextureOffset(0,38);
flagPole.setTextureSize(256,256);
flagPole.setRotationPoint(0.0f, -14.0f, 0.0f);
setPieceRotation(flagPole,0.0f, 0.0f, 0.0f);
flagPole.addBox(-10.0f,-25.0f,-6.5f,1,16,1);
flagCloth = new ModelRenderer(this,"flagCloth");
flagCloth.setTextureOffset(5,38);
flagCloth.setTextureSize(256,256);
flagCloth.setRotationPoint(0.0f, -14.0f, 0.0f);
setPieceRotation(flagCloth,0.0f, 0.0f, 0.0f);
flagCloth.addBox(-10.0f,-25.0f,-5.5f,1,8,11);
}
@Override
public void render(Entity entity, float f1, float f2, float f3, float f4, float f5, float f6)
{
super.render(entity, f1, f2, f3, f4, f5, f6);
setRotationAngles(f1, f2, f3, f4, f5, f6, entity);
baseMain.render(f6);
armMain.render(f6);
flagPole.render(f6);
flagCloth.render(f6);
}
public void setPieceRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
}
| gpl-3.0 |
asoem/greyfish | greyfish-utils/src/main/java/org/asoem/greyfish/utils/base/ClassNotInstantiableError.java | 879 | /*
* Copyright (C) 2015 The greyfish authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.asoem.greyfish.utils.base;
public class ClassNotInstantiableError extends Error {
public ClassNotInstantiableError() {
super("Not instantiable");
}
}
| gpl-3.0 |
integram/cleverbus | core/src/test/java/org/cleverbus/core/camel/CamelInOnlyPatternTest.java | 2809 | /*
* Copyright (C) 2015
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cleverbus.core.camel;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class CamelInOnlyPatternTest extends CamelTestSupport{
@Produce
ProducerTemplate producer;
@Test
public void testInOnlyPattern() {
assertEquals("route ONE", producer.requestBody("direct:route1A", "original body", String.class));
assertEquals("route TWO", producer.requestBody("direct:route2A", "original body", String.class));
assertEquals("route THREE", producer.requestBody("direct:route3A", "original body", String.class));
assertEquals("route FOUR", producer.requestBody("direct:route4A", "original body", String.class));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:route1A")
.to("direct:route1B");
from("direct:route1B")
.transform(constant("route ONE"));
from("direct:route2A")
.setExchangePattern(ExchangePattern.InOnly)
.to("direct:route2B?exchangePattern=InOnly");
from("direct:route2B?exchangePattern=InOnly")
.transform(constant("route TWO"));
from("direct:route3A")
.setExchangePattern(ExchangePattern.InOnly)
.to("direct:route3B");
from("direct:route3B")
.setExchangePattern(ExchangePattern.InOnly)
.transform(constant("route THREE"));
from("direct:route4A")
.inOnly("direct:route4B?exchangePattern=InOnly");
from("direct:route4B?exchangePattern=InOnly")
.transform(constant("route FOUR"));
}
};
}
}
| gpl-3.0 |
seasonyuu/SimpleWeChat | app/src/main/java/com/seasonyuu/simplewechat/ui/adapter/ChattingAdapter.java | 3679 | package com.seasonyuu.simplewechat.ui.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.seasonyuu.simplewechat.R;
import com.seasonyuu.simplewechat.bean.Colors;
import com.seasonyuu.simplewechat.bean.FriendInfo;
import com.seasonyuu.simplewechat.bean.MessageInfo;
import com.seasonyuu.simplewechat.bean.UserInfo;
import com.seasonyuu.simplewechat.ui.ChattingActivity;
import com.seasonyuu.simplewechat.ui.widget.HeadTextView;
import java.util.ArrayList;
/**
* Created by seasonyuu on 15/7/13.
*/
public class ChattingAdapter extends RecyclerView.Adapter<ChattingAdapter.ChattingViewHolder> {
private final int VIEW_TYPE_SELF = 0, VIEW_TYPE_FRIEND = 1;
private ArrayList<MessageInfo> list = null;
private Context context;
private FriendInfo friendInfo;
private int colors[];
public ChattingAdapter(Context context) {
list = new ArrayList<>();
this.context = context;
colors = Colors.getColors(context);
}
@Override
public ChattingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ChattingViewHolder holder = null;
switch (viewType) {
case VIEW_TYPE_FRIEND:
holder = new ChattingViewHolder(LayoutInflater.from(context).inflate(R.layout.cell_left, parent, false), viewType);
break;
case VIEW_TYPE_SELF:
holder = new ChattingViewHolder(LayoutInflater.from(context).inflate(R.layout.cell_right, parent, false), viewType);
break;
}
return holder;
}
public ArrayList<MessageInfo> getDataList() {
return list;
}
public void setDateList(ArrayList<MessageInfo> list) {
this.list = list;
}
public void addMessageInfo(MessageInfo info) {
list.add(info);
}
@Override
public int getItemViewType(int position) {
if (list.get(position).fromId.equals(UserInfo.getInstance().getUserId()))
return VIEW_TYPE_SELF;
return VIEW_TYPE_FRIEND;
}
@Override
public void onBindViewHolder(ChattingViewHolder holder, int position) {
holder.setContent(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
class ChattingViewHolder extends RecyclerView.ViewHolder {
private TextView tvContent;
private HeadTextView headTextView;
private int viewType;
public ChattingViewHolder(View itemView, int viewType) {
super(itemView);
tvContent = (TextView) itemView.findViewById(R.id.cell_content);
headTextView = (HeadTextView) itemView.findViewById(R.id.cell_head);
this.viewType = viewType;
}
public void setContent(MessageInfo info) {
tvContent.setText(info.content);
if (viewType == VIEW_TYPE_FRIEND) {
if (friendInfo == null) {
friendInfo = ((ChattingActivity) context).getFriendInfo();
}
headTextView.setText(friendInfo.nickName.substring(0, 1));
headTextView.setBackgroundColor(colors[friendInfo.userid.charAt(0) % 7]);
headTextView.invalidate();
} else {
headTextView.setText(UserInfo.getInstance().getNickName().substring(0, 1));
headTextView.setBackgroundColor(colors[UserInfo.getInstance().getUserId().charAt(0) % 7]);
headTextView.invalidate();
}
}
}
}
| gpl-3.0 |
leodejevga/breathy | Breathy/fade/src/androidTest/java/com/apps/philipps/fade/ExampleInstrumentedTest.java | 737 | package com.apps.philipps;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.fade", appContext.getPackageName());
}
}
| gpl-3.0 |
ccalleu/halo-halo | CSipSimple/src/org/pjsip/pjsua/SWIGTYPE_p_f_p_q_const__pjsip_rx_data_p_int__void.java | 839 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.4
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua;
public class SWIGTYPE_p_f_p_q_const__pjsip_rx_data_p_int__void {
private long swigCPtr;
protected SWIGTYPE_p_f_p_q_const__pjsip_rx_data_p_int__void(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_f_p_q_const__pjsip_rx_data_p_int__void() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_f_p_q_const__pjsip_rx_data_p_int__void obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| gpl-3.0 |
trichner/libschem | src/main/java/ch/n1b/worldedit/jnbt/IntArrayTag.java | 1735 | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.n1b.worldedit.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Int_Array} tag.
*/
public final class IntArrayTag extends Tag {
private final int[] value;
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
public IntArrayTag(int[] value) {
super();
checkNotNull(value);
this.value = value;
}
@Override
public int[] getValue() {
return value;
}
@Override
public String toString() {
StringBuilder hex = new StringBuilder();
for (int b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
return "TAG_Int_Array(" + hex + ")";
}
}
| gpl-3.0 |
afnogueira/Cerberus | source/src/main/java/org/cerberus/service/ILogEventService.java | 1797 | /*
* Cerberus Copyright (C) 2013 vertigo17
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cerberus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.cerberus.entity.LogEvent;
import org.cerberus.exception.CerberusException;
/**
*
* @author vertigo
*/
public interface ILogEventService {
public List<LogEvent> findAllLogEvent() throws CerberusException;
public List<LogEvent> findAllLogEvent(int start, int amount, String colName, String dir, String searchTerm) throws CerberusException;
public Integer getNumberOfLogEvent(String searchTerm) throws CerberusException;
public boolean insertLogEvent(LogEvent logevent) throws CerberusException;
/**
*
* @param message
* @param request
* @return
*/
public void insertLogEvent(String page, String action, String log, HttpServletRequest request);
/**
*
* @param message
* @param request
* @return
*/
public void insertLogEventPublicCalls(String page, String action, String log, HttpServletRequest request);
}
| gpl-3.0 |
DMCsys/smartalkaudio | oss-survey/viper4android_fx-master/android_2.3/src/com/vipercn/viper4android_v2/preference/EqualizerPreference.java | 4887 | package com.vipercn.viper4android_v2.preference;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import java.util.Arrays;
import java.util.Locale;
import com.vipercn.viper4android_v2.R;
public class EqualizerPreference extends DialogPreference
{
protected EqualizerSurface listEqualizer, dialogEqualizer;
private float[] levels = new float[10];
private float[] initialLevels = new float[10];
private static int showedDialogCount;
public EqualizerPreference(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
setLayoutResource(R.layout.equalizer);
setDialogLayoutResource(R.layout.equalizer_popup);
}
@Override
protected void onBindDialogView(View view)
{
super.onBindDialogView(view);
dialogEqualizer = (EqualizerSurface) view.findViewById(R.id.FrequencyResponse);
dialogEqualizer.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
float x = event.getX();
float y = event.getY();
int band = dialogEqualizer.findClosest(x);
int wy = v.getHeight();
float level = (y / wy) * (EqualizerSurface.MIN_DB - EqualizerSurface.MAX_DB) - EqualizerSurface.MIN_DB;
if (level < EqualizerSurface.MIN_DB)
{
level = EqualizerSurface.MIN_DB;
}
if (level > EqualizerSurface.MAX_DB)
{
level = EqualizerSurface.MAX_DB;
}
dialogEqualizer.setBand(band, level);
levels[band] = level;
refreshPreference(levels);
return true;
}
});
for (int i = 0; i < levels.length; i ++)
{
dialogEqualizer.setBand(i, levels[i]);
}
}
@Override
protected void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
{
initialLevels = Arrays.copyOf(levels, levels.length);
if (listEqualizer != null)
{
for (int i = 0; i < levels.length; i ++)
{
listEqualizer.setBand(i, levels[i]);
}
}
refreshPreference(levels);
notifyChanged();
}
else if (showedDialogCount == 1)
{
levels = Arrays.copyOf(initialLevels, levels.length);
refreshPreference(levels);
notifyChanged();
}
showedDialogCount--;
}
protected void refreshPreference(float[] levels)
{
String levelString = "";
for (int i = 0; i < levels.length; i ++)
{
levelString += String.format(Locale.ROOT, "%.1f", Math.round(levels[i] * 10.f) / 10.f) + ";";
}
EqualizerPreference.this.persistString(levelString);
}
@Override
protected void onBindView(View view)
{
super.onBindView(view);
listEqualizer = (EqualizerSurface) view.findViewById(R.id.FrequencyResponse);
for (int i = 0; i < levels.length; i ++)
{
listEqualizer.setBand(i, levels[i]);
}
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue)
{
String levelString = restorePersistedValue ? getPersistedString(null) : (String) defaultValue;
if (levelString != null)
{
String[] levelsStr = levelString.split(";");
if (levelsStr.length != levels.length)
{
return;
}
for (int i = 0; i < levels.length; i ++)
{
initialLevels[i] = levels[i] = Float.valueOf(levelsStr[i]);
}
}
}
@Override
protected void showDialog (Bundle state)
{
super.showDialog(state);
showedDialogCount++;
}
@Override
protected Parcelable onSaveInstanceState ()
{
Parcelable superState = super.onSaveInstanceState();
SavedLevels savedLevels = new SavedLevels(superState);
savedLevels.levels = levels;
savedLevels.initialLevels = initialLevels;
return savedLevels;
}
@Override
protected void onRestoreInstanceState (Parcelable state)
{
SavedLevels levelsState = (SavedLevels)state;
levels = levelsState.levels;
initialLevels = levelsState.initialLevels;
super.onRestoreInstanceState (levelsState.getSuperState());
}
public void refreshFromPreference()
{
onSetInitialValue(true, "0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;");
}
public static class SavedLevels extends BaseSavedState
{
private float[] initialLevels;
private float[] levels;
@Override
public void writeToParcel(Parcel out, int flags)
{
out.writeFloatArray(levels);
out.writeFloatArray(initialLevels);
}
public static final Parcelable.Creator<SavedLevels> CREATOR = new Parcelable.Creator<SavedLevels>()
{
public SavedLevels createFromParcel(Parcel in)
{
return new SavedLevels(in);
}
public SavedLevels[] newArray(int size)
{
return new SavedLevels[size];
}
};
private SavedLevels(Parcel in)
{
super(in);
in.readFloatArray(levels);
in.readFloatArray(initialLevels);
}
private SavedLevels(Parcelable parcelable)
{
super(parcelable);
}
}
}
| gpl-3.0 |
automenta/adams-core | src/main/java/adams/data/random/AbstractDistributionBasedRandomNumberGenerator.java | 3260 | /*
* 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/>.
*/
/**
* AbstractDistributionBasedRandomNumberGenerator.java
* Copyright (C) 2010-2014 University of Waikato, Hamilton, New Zealand
*/
package adams.data.random;
/**
* Ancestor for distribution-based random number generators.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 10203 $
* @param <T> the type of random number to return
*/
public abstract class AbstractDistributionBasedRandomNumberGenerator<T extends Number>
extends AbstractSeededRandomNumberGenerator<T>
implements DistributionBasedRandomNumberGenerator<T> {
/** for serialization. */
private static final long serialVersionUID = -4193009658719437993L;
/** the mean. */
protected double m_Mean;
/** the standard deviation. */
protected double m_Stdev;
/**
* Adds options to the internal list of options.
*/
@Override
public void defineOptions() {
super.defineOptions();
m_OptionManager.add(
"mean", "mean",
getDefaultMean());
m_OptionManager.add(
"stdev", "stdev",
getDefaultStdev(), 0.000001, null);
}
/**
* Returns the default mean to use.
*
* @return the mean
*/
protected double getDefaultMean() {
return 0.0;
}
/**
* Returns the default standard deviation to use.
*
* @return the stdev
*/
protected double getDefaultStdev() {
return 1.0;
}
/**
* Sets the mean to use.
*
* @param value the mean
*/
public void setMean(double value) {
m_Mean = value;
reset();
}
/**
* Returns the mean to use.
*
* @return the mean
*/
public double getMean() {
return m_Mean;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String meanTipText() {
return "The mean to use for the distribution.";
}
/**
* Sets the stdev to use.
*
* @param value the stdev
*/
public void setStdev(double value) {
if (value > 0) {
m_Stdev = value;
reset();
}
else {
getLogger().severe("Standard deviation must be >0, provided: " + value);
}
}
/**
* Returns the stdev to use.
*
* @return the stdev
*/
public double getStdev() {
return m_Stdev;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String stdevTipText() {
return "The standard deviation to use for the distribution.";
}
}
| gpl-3.0 |
devgabrielcoman/logd | app/src/main/java/com/gabrielcoman/logd/library/network/GetSentimentRequest.java | 771 | package com.gabrielcoman.logd.library.network;
import android.support.annotation.NonNull;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class GetSentimentRequest implements NetworkRequest {
private String text;
@NonNull
@Override
public String getUrl() {
return "http://sentiment.vivekn.com";
}
@NonNull
@Override
public String getEndpoint() {
return "/api/text/";
}
@NonNull
@Override
public Map<String, Object> getQuery() {
return ImmutableMap.of();
}
@NonNull
@Override
public Map<String, String> getBody() {
return ImmutableMap.of("txt", text);
}
public GetSentimentRequest(String text) {
this.text = text;
}
}
| gpl-3.0 |
inffeldgroup/sw2016 | app/src/main/java/at/tugraz/inffeldgroup/dailypic/FavouriteHandler.java | 1223 | package at.tugraz.inffeldgroup.dailypic;
import android.content.Context;
import android.net.Uri;
import android.widget.Toast;
import at.tugraz.inffeldgroup.dailypic.db.DbDatasource;
import at.tugraz.inffeldgroup.dailypic.db.UriWrapper;
public class FavouriteHandler {
public static void toggleFavouriteState(Context context, UriWrapper uri) {
if (!DbDatasource.getInstance(context).checkIfExists(uri)) {
DbDatasource.getInstance(context).insert(uri);
}
else{
DbDatasource.getInstance(context).delete(uri);
}
if (uri.isFav()) {
Toast.makeText(context, "Removed from favourites: " + uri.getUri().getLastPathSegment(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Added to favourites: " + uri.getUri().getLastPathSegment(), Toast.LENGTH_LONG).show();
}
uri.setFavourite(!uri.isFav());
DbDatasource.getInstance(context).update(uri);
}
public static boolean getFavouriteState(Context context, UriWrapper uw) {
if (!DbDatasource.getInstance(context).checkIfExists(uw)) {
return true;
} else {
return false;
}
}
}
| gpl-3.0 |
Valkyrinn/Mods | src/main/java/mods/manarz/item/tomes/summons/EntitySummonCreeper.java | 581 | package mods.manarz.item.tomes.summons;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.world.World;
public class EntitySummonCreeper extends EntityCreeper{
private int spellDuration;
public EntitySummonCreeper(World par1World) {
this(par1World, 400);
}
public EntitySummonCreeper(World par1World, int par2Duration) {
super(par1World);
this.spellDuration = par2Duration;
}
public void onLivingUpdate() {
super.onLivingUpdate();
if (!this.worldObj.isRemote) {
spellDuration--;
if (spellDuration <= 0) this.kill();
}
}
}
| gpl-3.0 |
Cride5/jablus | src/uk/co/crider/jablus/gui/JablusWindow.java | 7201 | package uk.co.crider.jablus.gui;
import uk.co.crider.jablus.Constants;
import uk.co.crider.jablus.SimulationInterface;
import uk.co.crider.jablus.data.Data;
import uk.co.crider.jablus.data.DataSet;
import java.awt.BorderLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import jwo.utils.gui.JWStatusBar;
/** Basic top level jablus window, with jablus logo and status bar.
* All windows used by JABLUS components should extend this class */
public class JablusWindow extends JFrame{
/** Unique class ID */
private static final long serialVersionUID = 1207764473502636155L;
/** Image used to represent this program */
// private static Image iconImage = Toolkit.getDefaultToolkit().getImage(JablusWindow.class.getResource(Constants.GUI_ICON_FILE));
// private static ImageIcon iconImage = new ImageIcon(Constants.GUI_ICON_FILE);
/** The status bar */
protected JMenuBar menuBar;
protected JMenu fileMenu;
protected JMenuItem quitItem;
protected JWStatusBar statusBar;
private Image iconImage;
private boolean showMenuBar;
private boolean allowClose;
private boolean showStatusBar;
public JablusWindow(){ this("", true, true, true); }
public JablusWindow(String title, boolean showMenuBar, boolean allowClose){ this(title, showMenuBar, true, allowClose); }
public JablusWindow(String title, boolean showMenuBar, boolean showStatusBar, boolean allowClose){
super();
setTitle(title);
this.showMenuBar = showMenuBar;
this.showStatusBar = showStatusBar;
this.allowClose = allowClose;
initComponents();
}
/** Initialise graphical components */
private void initComponents(){
final JFrame thisFrame = this;
// Set native look and feel
try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
catch (UnsupportedLookAndFeelException ex) { System.out.println("Unable to load native look and feel"); }
catch (ClassNotFoundException e) { System.out.println("Unable to load native look and feel"); }
catch (InstantiationException e) { System.out.println("Unable to load native look and feel"); }
catch (IllegalAccessException e) { System.out.println("Unable to load native look and feel"); }
// Set Icon
// This doesnt work for packaged jars, need to use getResource
/* try {
iconImage = ImageIO.read(new File(Constants.GUI_ICON_FILE));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
String filePath = "/" + Constants.JABLUS_GRAPHICS_DIR + "/" + Constants.GUI_ICON_FILE;
// String filePath = "/" + Constants.GUI_ICON_FILE;
URL url = getClass().getResource(filePath);
System.out.println("path=" + filePath + " url=" + url + " iconfile=" + Constants.GUI_ICON_FILE);
iconImage = Toolkit.getDefaultToolkit().getImage(url);
setIconImage(iconImage);
// Set top-level layout
// setLayout(new BorderLayout(0, 0));
// Set up basic menu
if(showMenuBar){
menuBar = new JMenuBar();
setJMenuBar(menuBar);
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
quitItem = new JMenuItem("Quit", KeyEvent.VK_Q);
quitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
getWindowListeners()[0].windowClosing(new WindowEvent(thisFrame, WindowEvent.WINDOW_CLOSING));
}
});
fileMenu.add(quitItem);
}
// Set up toolbar
// toolBar = new JToolBar();
// add(toolBar, BorderLayout.NORTH);
// Set Status bar
if(showStatusBar){
statusBar = new JWStatusBar();
add(statusBar, BorderLayout.SOUTH);
}
// Terminate program on close
if(allowClose)
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
else
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
/** Set the window title */
public void setTitle(String title){
super.setTitle(title.equals("") ? Constants.JABLUS_WINDOW_TITLE : Constants.JABLUS_WINDOW_TITLE + " - " + title);
}
/** Set the value of the status bar */
public void setStatus(String status){
if(statusBar != null)
statusBar.setMessage(status);
}
/** Set the progress of the progress bar */
public void setProgress(int progress){
if(statusBar != null)
statusBar.setProgress(progress);
}
/** Moves the window to the center of the screen */
protected void center(){
Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setLocation(p.x - getWidth() / 2, p.y - getHeight() / 2);
}
/** Get historic data used to populate temporal data views (eg trend graphs) */
public static Hashtable<String, List<Data>> getPastData(SimulationInterface sim, Data item, List<Data> time, DisplayParams displayParams){
//System.out.println("SimulationGUI: Generating past data for " + item);
Hashtable<String, List<Data>> pastData = new Hashtable<String, List<Data>>();
if(sim.canToStart()){
sim.toStart();
// Incrament through history data until we reach current state
// filling pastData object as we go
while(!sim.atCurrentState()){
// Retrive history snapshot
DataSet snapshot = sim.getSnapshot();
// Add time to time list
time.add(snapshot.getItem(Constants.TEMPORAL_TIME));
//System.out.println("JablusWindow: Adding past data " + snapshot);
// Get stored data item
Data pastItem = snapshot.getItem(item.getId());
//System.out.println("JablusWindow: Getting past item " + item.getName() + ", resulting in pastItem=" + pastItem);
if(pastItem != null){
getPastData((Data)pastItem, pastData, displayParams);
}
// Incrament history pointer
sim.stepForward();
}
}
//System.out.println("JablusWindow: PastData=");
//for(List list : pastData.values()){
// System.out.println(list);
//}
//System.out.println(time);
return pastData;
}
private static void getPastData(Data item, Hashtable<String, List<Data>> pastData, DisplayParams displayParams){
if(item instanceof DataSet){
for(Data subItem : ((DataSet)item).getItems())
getPastData(subItem, pastData, displayParams);
}
else{
// Only add pastData item if it needs to be displayed
if(displayParams.display(item.getId(), DisplayParams.ADD_GRAPH | DisplayParams.SHOW_TEXT)){
// Retrive existing list if it exists
List<Data> l = pastData.get(item.getName());
// If it doesn't exist then create it and add it to the pastData object
if(l == null){
l = new LinkedList<Data>();
pastData.put(item.getName(), l);
}
// Add item to past data
l.add(item);
}
}
}
/** For testing purposes */
public static void main(String[] args){
JablusWindow window = new JablusWindow();
window.setVisible(true);
}
}
| gpl-3.0 |
Arcadianer/Reverse-Pacman | Reverse Pacman/src/block/t3.java | 582 | package block;
/**
* Game Block
*
* @author Manuel Plonski
* @see block
*/
import ch.aplu.jgamegrid.GGBackground;
import ch.aplu.jgamegrid.Location;
public class t3 extends block {
public t3() {
super("T-3","s", "res/t3.gif");
// TODO Auto-generated constructor stub
blockmovment=true;
}
@Override
public void draw(Location lc, GGBackground bd) {
// TODO Auto-generated method stub
bd.drawImage(path, lc.x*30, lc.y*30);
}
@Override
public block clone() {
// TODO Auto-generated method stub
return new t3();
}
}
| gpl-3.0 |
MIND-Tools/mind-compiler | common-frontend/src/main/java/org/ow2/mind/value/BasicValueKindDecorator.java | 2338 |
package org.ow2.mind.value;
import java.util.Map;
import org.objectweb.fractal.adl.ADLException;
import org.ow2.mind.value.ast.Array;
import org.ow2.mind.value.ast.BooleanLiteral;
import org.ow2.mind.value.ast.CompoundValue;
import org.ow2.mind.value.ast.CompoundValueField;
import org.ow2.mind.value.ast.MultipleValueContainer;
import org.ow2.mind.value.ast.NullLiteral;
import org.ow2.mind.value.ast.NumberLiteral;
import org.ow2.mind.value.ast.PathLiteral;
import org.ow2.mind.value.ast.Reference;
import org.ow2.mind.value.ast.SingleValueContainer;
import org.ow2.mind.value.ast.StringLiteral;
import org.ow2.mind.value.ast.Value;
import com.google.inject.Inject;
public class BasicValueKindDecorator implements ValueKindDecorator {
@Inject
protected ValueKindDecorator recursiveValueKindDecorator;
public void setValueKind(final Value value, final Map<Object, Object> context)
throws ADLException {
if (value instanceof Array) {
value.astSetDecoration(KIND_DECORATION, "array");
} else if (value instanceof BooleanLiteral) {
value.astSetDecoration(KIND_DECORATION, "boolean");
} else if (value instanceof CompoundValue) {
value.astSetDecoration(KIND_DECORATION, "compound");
for (final CompoundValueField field : ((CompoundValue) value)
.getCompoundValueFields()) {
recursiveValueKindDecorator.setValueKind(field.getValue(), context);
}
} else if (value instanceof NullLiteral) {
value.astSetDecoration(KIND_DECORATION, "null");
} else if (value instanceof NumberLiteral) {
value.astSetDecoration(KIND_DECORATION, "number");
} else if (value instanceof PathLiteral) {
value.astSetDecoration(KIND_DECORATION, "path");
} else if (value instanceof Reference) {
value.astSetDecoration(KIND_DECORATION, "reference");
} else if (value instanceof StringLiteral) {
value.astSetDecoration(KIND_DECORATION, "string");
}
if (value instanceof SingleValueContainer) {
recursiveValueKindDecorator.setValueKind(
((SingleValueContainer) value).getValue(), context);
}
if (value instanceof MultipleValueContainer) {
for (final Value subValue : ((MultipleValueContainer) value).getValues()) {
recursiveValueKindDecorator.setValueKind(subValue, context);
}
}
}
}
| gpl-3.0 |
johny-c/ring_escape | RingEscapeServer/src/edu/johny/ringescape/server/ServerDatabase.java | 7269 | package edu.johny.ringescape.server;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
/**
* Handles all interactions with the MySQL Database
* @author Ioannis Chiotellis
**/
public class ServerDatabase implements AppConstants {
private final static String url = "jdbc:mysql://localhost:3306/";
private final static String DB_NAME = "ringescape_server_db";
private final static String driver = "com.mysql.jdbc.Driver";
private final static String userName = "johny";
private final static String password = "123";
private Connection connection = null;
private ResultSet resultSet = null;
private PreparedStatement preparedStatement = null;
Utils u = new Utils();
/** 1 Open the DataBase **/
void connect() {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName(driver).newInstance();
// Connect
connection = DriverManager.getConnection(url + DB_NAME, userName,
password);
u.log("-Connected to the database\n");
} catch (Exception e) {
e.printStackTrace();
}
}
/** 2 Close the DataBase **/
void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
// Disconnect
if (connection != null) {
connection.close();
u.log("-Disconnected from database\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 3 Insert a new game and return its id **/
int insertGame(int players) throws SQLException {
String str = "INSERT INTO GAMES (g_players) VALUES (" + players + ")";
PreparedStatement st = connection.prepareStatement(str,
Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
int g_id = -1;
while (rs.next()) {
g_id = rs.getInt(1);
}
st.close();
return g_id;
}
/** 4 Insert a new player with his game(id) and return his id **/
int insert(Player p) throws SQLException {
String str = "INSERT INTO PLAYERS (p_name, p_radius, p_lat, p_lon, p_offset, p_status, p_game_id) VALUES(?,?,?,?,?,?,?)";
PreparedStatement st = connection.prepareStatement(str,
Statement.RETURN_GENERATED_KEYS);
st.setString(1, p.getName());
st.setInt(2, p.getRadius());
st.setDouble(3, p.getLatitude());
st.setDouble(4, p.getLongitude());
st.setLong(5, p.getOffset());
st.setInt(6, Player.WAITING);
st.setInt(7, p.getGameId());
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
int p_id = -1;
while (rs.next()) {
p_id = rs.getInt(1);
}
st.close();
return p_id;
}
/** 5 Get how many players are in a game **/
int getPlayersInGame(int gameId) throws SQLException {
String str = "SELECT g_players FROM GAMES WHERE game_id=" + gameId + "";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(str);
int players = 0;
while (rs.next()) {
players = rs.getInt(1);
}
st.close();
return players;
}
/** 6 Initialize the status of all players to FREE **/
void initStatuses(int game_id) throws SQLException {
String str = "UPDATE PLAYERS SET p_status=? WHERE p_game_id=? AND p_status!=?";
PreparedStatement st = connection.prepareStatement(str);
st.setInt(1, Player.FREE);
st.setInt(2, game_id);
st.setInt(3, Player.QUITTED);
st.executeUpdate();
st.close();
}
/** 7 Update a player's location according to client's message **/
void updateLocation(int id, String update) throws SQLException {
String str = "UPDATE PLAYERS SET p_lat=?, p_lon=? WHERE player_id=?";
String[] loc = update.split(FIELD_DELIM);
PreparedStatement st = connection.prepareStatement(str);
st.setDouble(1, Double.valueOf(loc[0]));
st.setDouble(2, Double.valueOf(loc[1]));
st.setInt(3, id);
st.executeUpdate();
st.close();
}
/** 8 Get a player's status to resolve hit conflicts **/
int selectStatus(int id) throws SQLException {
String str = "SELECT p_status FROM PLAYERS WHERE player_id=" + id + "";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(str);
int status = 0;
while (rs.next()) {
status = rs.getInt(1);
}
st.close();
return status;
}
/**
* 9 Update a player's status to THREATENED and store his hitter for
* possible award
**/
void storeThreat(int hitter_id, int player_id) throws SQLException {
u.log("*************STORING THREAT + hitterID = " + hitter_id
+ " victimID = " + player_id);
String str = "UPDATE PLAYERS SET p_status=?, p_hitter=? WHERE player_id=?";
PreparedStatement st = connection.prepareStatement(str);
st.setInt(1, Player.THREATENED);
st.setInt(2, hitter_id);
st.setInt(3, player_id);
st.executeUpdate();
st.close();
}
/** 10 Update a player's status **/
void updateStatus(int player_id, int new_status) throws SQLException {
String str = "UPDATE PLAYERS SET p_status=? WHERE player_id=?";
PreparedStatement st = connection.prepareStatement(str);
st.setInt(1, new_status);
st.setInt(2, player_id);
st.executeUpdate();
st.close();
}
/** 11 Update a player's score **/
void updateScore(int player_id, int points) throws SQLException {
String str = "UPDATE PLAYERS SET p_score=p_score+? WHERE player_id=?";
PreparedStatement st = connection.prepareStatement(str);
st.setInt(1, points);
st.setInt(2, player_id);
st.executeUpdate();
st.close();
}
/** 12 Get a game update to send back to the clients **/
String getGameUpdate(int game_id) throws SQLException {
String str = "SELECT player_id, p_lat, p_lon, p_status, p_score, p_hitter "
+ "FROM PLAYERS WHERE p_game_id="
+ game_id
+ " AND p_status!="
+ Player.EXITED + "";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(str);
String result = "";
while (rs.next()) {
int id = rs.getInt(1);
result += id + FIELD_DELIM;
result += rs.getDouble(2) + FIELD_DELIM;
result += rs.getDouble(3) + FIELD_DELIM;
int status = rs.getInt(4);
result += status + FIELD_DELIM;
if (status == Player.QUITTED)
updateStatus(id, Player.EXITED);
result += rs.getInt(5) + FIELD_DELIM;
result += rs.getInt(6) + REC_DELIM;
}
st.close();
if (result.endsWith(REC_DELIM))
result = result.substring(0, result.length() - 1);
return result;
}
/** 13 Get a player's location to check if he has escaped **/
double[] getLocation(int player_id) throws SQLException {
String str = "SELECT p_lat, p_lon FROM PLAYERS WHERE player_id="
+ player_id + "";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(str);
double[] result = new double[2];
while (rs.next()) {
result[0] = rs.getDouble(1);
result[1] = rs.getDouble(2);
}
st.close();
return result;
}
/** 14 Delete the location data at the end **/
void deleteLocations(int game_id) throws SQLException {
String str = "UPDATE PLAYERS SET p_status=?, p_lat=?, p_lon=? WHERE p_game_id=?";
PreparedStatement st = connection.prepareStatement(str);
st.setInt(1, Player.EXITED);
st.setNull(2, Types.DOUBLE);
st.setNull(3, Types.DOUBLE);
st.setInt(4, game_id);
st.executeUpdate();
st.close();
}
}
| gpl-3.0 |
cortiz/profile | security-provider/src/test/java/org/craftercms/security/authentication/impl/RememberMeManagerImplTest.java | 8190 | package org.craftercms.security.authentication.impl;
import java.util.UUID;
import javax.servlet.http.Cookie;
import org.bson.types.ObjectId;
import org.craftercms.commons.crypto.impl.NoOpTextEncryptor;
import org.craftercms.commons.http.CookieManager;
import org.craftercms.commons.http.RequestContext;
import org.craftercms.profile.api.PersistentLogin;
import org.craftercms.profile.api.Profile;
import org.craftercms.profile.api.services.AuthenticationService;
import org.craftercms.profile.api.services.ProfileService;
import org.craftercms.security.authentication.Authentication;
import org.craftercms.security.authentication.AuthenticationManager;
import org.craftercms.security.exception.rememberme.CookieTheftException;
import org.craftercms.security.exception.rememberme.InvalidCookieException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.craftercms.security.authentication.impl.RememberMeManagerImpl.*;
/**
* Unit tests for {@link org.craftercms.security.authentication.impl.RememberMeManagerImpl}.
*
* @author avasquez
*/
public class RememberMeManagerImplTest {
private static final String LOGIN_ID = UUID.randomUUID().toString();
private static final String LOGIN_TOKEN = UUID.randomUUID().toString();
private static final String LOGIN_TOKEN2 = UUID.randomUUID().toString();
private static final ObjectId PROFILE_ID = ObjectId.get();
private RememberMeManagerImpl rememberMeManager;
@Mock
private AuthenticationService authenticationService;
@Mock
private AuthenticationManager authenticationManager;
@Mock
private ProfileService profileService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(authenticationService.createPersistentLogin(PROFILE_ID.toString())).thenReturn(getLogin());
when(authenticationService.getPersistentLogin(LOGIN_ID)).thenReturn(getLogin());
when(authenticationService.refreshPersistentLoginToken(LOGIN_ID)).thenReturn(getLogin2());
when(authenticationManager.authenticateUser(getProfile(), true)).thenReturn(getAuthentication());
when(profileService.getProfile(PROFILE_ID.toString(), new String[0])).thenReturn(getProfile());
rememberMeManager = new RememberMeManagerImpl();
rememberMeManager.setAuthenticationService(authenticationService);
rememberMeManager.setAuthenticationManager(authenticationManager);
rememberMeManager.setProfileService(profileService);
rememberMeManager.setEncryptor(new NoOpTextEncryptor());
rememberMeManager.setRememberMeCookieManager(new CookieManager());
}
@Test
public void testEnableRememberMe() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
rememberMeManager.enableRememberMe(getAuthentication(), context);
String cookieValue = response.getCookie(REMEMBER_ME_COOKIE_NAME).getValue();
assertEquals(getSerializedLogin(), cookieValue);
}
@Test
public void testDisableRememberMe() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
request.setCookies(new Cookie(REMEMBER_ME_COOKIE_NAME, getSerializedLogin()));
rememberMeManager.disableRememberMe(context);
assertNull(response.getCookie(REMEMBER_ME_COOKIE_NAME).getValue());
verify(authenticationService).deletePersistentLogin(LOGIN_ID);
}
@Test
public void testAutoLogin() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
request.setCookies(new Cookie(REMEMBER_ME_COOKIE_NAME, getSerializedLogin()));
Authentication auth = rememberMeManager.autoLogin(context);
assertNotNull(auth);
assertEquals(getProfile(), auth.getProfile());
String cookieValue = response.getCookie(REMEMBER_ME_COOKIE_NAME).getValue();
assertEquals(getSerializedLoginWithRefreshedToken(), cookieValue);
}
@Test
public void testAutoLoginWithInvalidId() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
request.setCookies(new Cookie(REMEMBER_ME_COOKIE_NAME, getSerializedLoginWithInvalidId()));
Authentication auth = rememberMeManager.autoLogin(context);
assertNull(auth);
assertNull(response.getCookie(REMEMBER_ME_COOKIE_NAME).getValue());
}
@Test(expected = InvalidCookieException.class)
public void testAutoLoginWithInvalidProfile() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
request.setCookies(new Cookie(REMEMBER_ME_COOKIE_NAME, getSerializedLoginWithInvalidProfile()));
rememberMeManager.autoLogin(context);
}
@Test(expected = CookieTheftException.class)
public void testAutoLoginWithInvalidToken() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContext context = new RequestContext(request, response, null);
request.setCookies(new Cookie(REMEMBER_ME_COOKIE_NAME, getSerializedLoginWithInvalidToken()));
rememberMeManager.autoLogin(context);
}
protected String getSerializedLogin() {
return serializeLogin(LOGIN_ID, PROFILE_ID.toString(), LOGIN_TOKEN);
}
protected String getSerializedLoginWithRefreshedToken() {
return serializeLogin(LOGIN_ID, PROFILE_ID.toString(), LOGIN_TOKEN2);
}
protected String getSerializedLoginWithInvalidId() {
return serializeLogin(UUID.randomUUID().toString(), PROFILE_ID.toString(), LOGIN_TOKEN);
}
protected String getSerializedLoginWithInvalidProfile() {
return serializeLogin(LOGIN_ID, ObjectId.get().toString(), LOGIN_TOKEN);
}
protected String getSerializedLoginWithInvalidToken() {
return serializeLogin(LOGIN_ID, PROFILE_ID.toString(), UUID.randomUUID().toString());
}
protected String serializeLogin(String id, String profileId, String token) {
StringBuilder serializedLogin = new StringBuilder();
serializedLogin.append(id).append(SERIALIZED_LOGIN_SEPARATOR);
serializedLogin.append(profileId).append(SERIALIZED_LOGIN_SEPARATOR);
serializedLogin.append(token);
return serializedLogin.toString();
}
protected PersistentLogin getLogin() {
PersistentLogin login = new PersistentLogin();
login.setId(LOGIN_ID);
login.setToken(LOGIN_TOKEN);
login.setProfileId(PROFILE_ID.toString());
return login;
}
protected PersistentLogin getLogin2() {
PersistentLogin login = new PersistentLogin();
login.setId(LOGIN_ID);
login.setToken(LOGIN_TOKEN2);
login.setProfileId(PROFILE_ID.toString());
return login;
}
protected Profile getProfile() {
Profile profile = new Profile();
profile.setId(PROFILE_ID);
return profile;
}
protected Authentication getAuthentication() {
return new DefaultAuthentication(null, getProfile(), true);
}
}
| gpl-3.0 |
Greymerk/minecraft-roguelike | src/main/java/greymerk/roguelike/monster/profiles/ProfileZombie.java | 2227 | package greymerk.roguelike.monster.profiles;
import java.util.Random;
import greymerk.roguelike.monster.IEntity;
import greymerk.roguelike.monster.IMonsterProfile;
import greymerk.roguelike.monster.MonsterProfile;
import greymerk.roguelike.treasure.loot.Enchant;
import greymerk.roguelike.treasure.loot.Shield;
import greymerk.roguelike.treasure.loot.provider.ItemTool;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ProfileZombie implements IMonsterProfile {
@Override
public void addEquipment(World world, Random rand, int level, IEntity mob) {
if(level == 4 && rand.nextInt(20) == 0){
MonsterProfile.get(MonsterProfile.PIGMAN).addEquipment(world, rand, level, mob);
return;
}
if(level == 3 && rand.nextInt(100) == 0){
MonsterProfile.get(MonsterProfile.WITCH).addEquipment(world, rand, level, mob);
return;
}
if(level == 2 && rand.nextInt(300) == 0){
MonsterProfile.get(MonsterProfile.EVOKER).addEquipment(world, rand, level, mob);
return;
}
if(level == 1 && rand.nextInt(200) == 0){
MonsterProfile.get(MonsterProfile.JOHNNY).addEquipment(world, rand, level, mob);
return;
}
if(rand.nextInt(100) == 0){
MonsterProfile.get(MonsterProfile.RLEAHY).addEquipment(world, rand, level, mob);
return;
}
if(rand.nextInt(100) == 0){
MonsterProfile.get(MonsterProfile.ASHLEA).addEquipment(world, rand, level, mob);
return;
}
if(rand.nextInt(40) == 0){
MonsterProfile.get(MonsterProfile.BABY).addEquipment(world, rand, level, mob);
return;
}
if(level > 1 && rand.nextInt(20) == 0){
MonsterProfile.get(MonsterProfile.HUSK).addEquipment(world, rand, level, mob);
return;
}
if(level < 3 && rand.nextInt(20) == 0){
MonsterProfile.get(MonsterProfile.VILLAGER).addEquipment(world, rand, level, mob);
return;
}
ItemStack weapon = ItemTool.getRandom(rand, level, Enchant.canEnchant(world.getDifficulty(), rand, level));
mob.setSlot(EntityEquipmentSlot.MAINHAND, weapon);
mob.setSlot(EntityEquipmentSlot.OFFHAND, Shield.get(rand));
MonsterProfile.get(MonsterProfile.TALLMOB).addEquipment(world, rand, level, mob);
}
}
| gpl-3.0 |
mruffalo/seal | src/io/FastqReader.java | 659 | package io;
import java.io.BufferedReader;
import java.io.Reader;
/**
* TODO: Determine how these classes should work at a high level. Perhaps
* similar to a BufferedReader: instantiate with another Reader and provide a
* getFragment method? It probably makes sense for this class to use a
* BufferedReader; its {@link java.io.BufferedReader#readLine()} method isn't
* worth reinventing.
*
* @author mruffalo
*/
public class FastqReader
{
private static enum State
{
READ_HEADER,
READ_DATA,
QUALITY_HEADER,
QUALITY_DATA;
}
private final BufferedReader source;
public FastqReader(Reader in)
{
source = new BufferedReader(in);
}
}
| gpl-3.0 |
otavanopisto/pyramus | pyramus/src/main/java/fi/otavanopisto/pyramus/views/settings/ReportCategoriesViewController.java | 2755 | package fi.otavanopisto.pyramus.views.settings;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import fi.internetix.smvc.controllers.PageRequestContext;
import fi.otavanopisto.pyramus.I18N.Messages;
import fi.otavanopisto.pyramus.breadcrumbs.Breadcrumbable;
import fi.otavanopisto.pyramus.dao.DAOFactory;
import fi.otavanopisto.pyramus.dao.reports.ReportCategoryDAO;
import fi.otavanopisto.pyramus.domainmodel.reports.ReportCategory;
import fi.otavanopisto.pyramus.framework.PyramusViewController;
import fi.otavanopisto.pyramus.framework.UserRole;
import fi.otavanopisto.pyramus.util.JSONArrayExtractor;
/**
* The controller responsible of the Report Categories view of the application.
*
* @see fi.otavanopisto.pyramus.json.settings.SaveReportCategoriesJSONRequestController
*/
public class ReportCategoriesViewController extends PyramusViewController implements Breadcrumbable {
/**
* Processes the page request by including the corresponding JSP page to the response.
*
* @param pageRequestContext Page request context
*/
public void process(PageRequestContext pageRequestContext) {
ReportCategoryDAO categoryDAO = DAOFactory.getInstance().getReportCategoryDAO();
List<ReportCategory> categories = categoryDAO.listAll();
Collections.sort(categories, new Comparator<ReportCategory>() {
public int compare(ReportCategory o1, ReportCategory o2) {
if (o1.getIndexColumn() == o2.getIndexColumn() || o1.getIndexColumn().equals(o2.getIndexColumn())) {
return o1.getName() == null ? -1 : o2.getName() == null ? 1 : o1.getName().compareTo(o2.getName());
}
else {
return o1.getIndexColumn() == null ? -1 : o2.getIndexColumn() == null ? 1 : o1.getIndexColumn().compareTo(o2.getIndexColumn());
}
}
});
String jsonCategories = new JSONArrayExtractor("name", "id").extractString(categories);
this.setJsDataVariable(pageRequestContext, "reportCategories", jsonCategories);
pageRequestContext.setIncludeJSP("/templates/settings/reportcategories.jsp");
}
/**
* Returns the roles allowed to access this page.
*
* @return The roles allowed to access this page
*/
public UserRole[] getAllowedRoles() {
return new UserRole[] { UserRole.MANAGER, UserRole.STUDY_PROGRAMME_LEADER, UserRole.ADMINISTRATOR };
}
/**
* Returns the localized name of this page. Used e.g. for breadcrumb navigation.
*
* @param locale The locale to be used for the name
*
* @return The localized name of this page
*/
public String getName(Locale locale) {
return Messages.getInstance().getText(locale, "settings.reportCategories.pageTitle");
}
}
| gpl-3.0 |
iamareebjamal/open-event-orga-app | app/src/main/java/com/eventyay/organizer/common/di/module/AndroidModule.java | 866 | package com.eventyay.organizer.common.di.module;
import android.content.Context;
import android.content.SharedPreferences;
import com.f2prateek.rx.preferences2.RxSharedPreferences;
import com.eventyay.organizer.OrgaProvider;
import com.eventyay.organizer.common.Constants;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class AndroidModule {
@Provides
@Singleton
Context providesContext() {
return OrgaProvider.context;
}
@Provides
@Singleton
SharedPreferences sharedPreferences(Context context) {
return context.getSharedPreferences(Constants.FOSS_PREFS, Context.MODE_PRIVATE);
}
@Provides
@Singleton
RxSharedPreferences rxSharedPreferences(SharedPreferences sharedPreferences) {
return RxSharedPreferences.create(sharedPreferences);
}
}
| gpl-3.0 |
a-v-k/astrid | src/main/java/com/todoroo/astrid/provider/Astrid3ContentProvider.java | 13696 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.provider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.DatabaseDao;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.dao.RemoteModelDao;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.StoreObject;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.data.UserActivity;
import org.tasks.BuildConfig;
import org.tasks.injection.ContentProviderComponent;
import org.tasks.injection.InjectingContentProvider;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import javax.inject.Inject;
import dagger.Lazy;
/**
* Astrid 3 Content Provider. There are two ways to use this content provider:
* <ul>
* <li>access it directly just like any other content provider
* <li>use the DAO classes from the Astrid API library
* </ul>
* <p>
* The following base URI's are supported:
* <ul>
* <li>content://com.todoroo.astrid/tasks - task data ({@link Task})
* <li>content://com.todoroo.astrid/metadata - task metadata ({@link Metadata})
* <li>content://com.todoroo.astrid/store - non-task store data ({@link StoreObject})
* </ul>
* <p>
* Each URI supports the following components:
* <ul>
* <li>/ - operate on all items (insert, delete, update, query)
* <li>/123 - operate on item id #123 (delete, update, query)
* <li>/groupby/title - query with SQL "group by" (query)
* </ul>
* <p>
* If you are writing a third-party application to access this data, you may
* also consider using one of the Api DAO objects like TaskApiDao.
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class Astrid3ContentProvider extends InjectingContentProvider {
/** URI for making a request over all items */
private static final int URI_DIR = 1;
/** URI for making a request over a single item by id */
private static final int URI_ITEM = 2;
/** URI for making a request over all items grouped by some field */
private static final int URI_GROUP = 3;
private static final UriMatcher uriMatcher;
private static Database databaseOverride;
// --- instance variables
private boolean open;
@Inject Lazy<Database> database;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
for(Uri uri : new Uri[] { Task.CONTENT_URI, Metadata.CONTENT_URI, StoreObject.CONTENT_URI, UserActivity.CONTENT_URI }) {
String authority = BuildConfig.APPLICATION_ID;
String table = uri.toString();
table = table.substring(table.indexOf('/', 11) + 1);
uriMatcher.addURI(authority, table, URI_DIR);
uriMatcher.addURI(authority, table + "/#", URI_ITEM);
uriMatcher.addURI(authority, table +
AstridApiConstants.GROUP_BY_URI + "*", URI_GROUP);
}
}
public Astrid3ContentProvider() {
setReadPermission(AstridApiConstants.PERMISSION_READ);
setWritePermission(AstridApiConstants.PERMISSION_WRITE);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case URI_DIR:
case URI_GROUP:
return "vnd.android.cursor.dir/vnd.astrid";
case URI_ITEM:
return "vnd.android.cursor/vnd.astrid.item";
default:
throw new IllegalArgumentException("Unsupported URI " + uri + " (" + uriMatcher.match(uri) + ")");
}
}
@Override
protected void inject(ContentProviderComponent component) {
component.inject(this);
}
/* ======================================================================
* ========================================================== helpers ===
* ====================================================================== */
private class UriHelper<TYPE extends AbstractModel> {
/** empty model. used for insert */
public TYPE model;
/** dao */
public DatabaseDao<TYPE> dao;
/** creates from given model */
public boolean create() {
return dao.createNew(model);
}
/** updates from given model */
public void update() {
dao.saveExisting(model);
}
}
private UriHelper<?> generateHelper(Uri uri, boolean populateModel) {
final Database db = getDatabase();
if(uri.toString().startsWith(Task.CONTENT_URI.toString())) {
UriHelper<Task> helper = new UriHelper<>();
helper.model = populateModel ? new Task() : null;
helper.dao = new RemoteModelDao<>(db, Task.class);
return helper;
} else if(uri.toString().startsWith(Metadata.CONTENT_URI.toString())) {
UriHelper<Metadata> helper = new UriHelper<>();
helper.model = populateModel ? new Metadata() : null;
helper.dao = new DatabaseDao<>(db, Metadata.class);
return helper;
} else if(uri.toString().startsWith(StoreObject.CONTENT_URI.toString())) {
UriHelper<StoreObject> helper = new UriHelper<>();
helper.model = populateModel ? new StoreObject() : null;
helper.dao = new DatabaseDao<>(db, StoreObject.class);
return helper;
} else if(uri.toString().startsWith(UserActivity.CONTENT_URI.toString())) {
UriHelper<UserActivity> helper = new UriHelper<>();
helper.model = populateModel ? new UserActivity() : null;
helper.dao = new RemoteModelDao<>(db, UserActivity.class);
return helper;
}
throw new UnsupportedOperationException("Unknown URI " + uri);
}
public static void setDatabaseOverride(Database override) {
databaseOverride = override;
}
private Database getDatabase() {
if (!open) {
database.get().openForWriting();
open = true;
}
if(databaseOverride != null) {
return databaseOverride;
}
return database.get();
}
/* ======================================================================
* =========================================================== delete ===
* ====================================================================== */
/**
* Delete from given table
* @return number of rows deleted
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
UriHelper<?> helper = generateHelper(uri, false);
switch (uriMatcher.match(uri)) {
// illegal operations
case URI_GROUP:
throw new IllegalArgumentException("Only the / or /# URI is valid"
+ " for deletion.");
// valid operations
case URI_ITEM: {
String itemSelector = String.format("%s = '%s'",
AbstractModel.ID_PROPERTY, uri.getPathSegments().get(1));
if(TextUtils.isEmpty(selection)) {
selection = itemSelector;
} else {
selection = itemSelector + " AND " + selection;
}
}
case URI_DIR:
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri + " (" + uriMatcher.match(uri) + ")");
}
return getDatabase().delete(helper.dao.getTable().name, selection, selectionArgs);
}
/* ======================================================================
* =========================================================== insert ===
* ====================================================================== */
/**
* Insert key/value pairs into given table
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
UriHelper<?> helper = generateHelper(uri, true);
switch (uriMatcher.match(uri)) {
// illegal operations
case URI_ITEM:
case URI_GROUP:
throw new IllegalArgumentException("Only the / URI is valid"
+ " for insertion.");
// valid operations
case URI_DIR: {
helper.model.mergeWith(values);
readTransitoriesFromModelContentValues(helper.model);
if(!helper.create()) {
throw new SQLException("Could not insert row into database (constraint failed?)");
}
Uri newUri = ContentUris.withAppendedId(uri, helper.model.getId());
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
/* ======================================================================
* =========================================================== update ===
* ====================================================================== */
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
UriHelper<?> helper = generateHelper(uri, true);
switch (uriMatcher.match(uri)) {
// illegal operations
case URI_GROUP:
throw new IllegalArgumentException("Only the / or /# URI is valid"
+ " for update.");
// valid operations
case URI_ITEM: {
String itemSelector = String.format("%s = '%s'",
AbstractModel.ID_PROPERTY, uri.getPathSegments().get(1));
if(TextUtils.isEmpty(selection)) {
selection = itemSelector;
} else {
selection = itemSelector + " AND " + selection;
}
}
case URI_DIR:
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri + " (" + uriMatcher.match(uri) + ")");
}
Cursor cursor = query(uri, new String[] { AbstractModel.ID_PROPERTY.name },
selection, selectionArgs, null);
try {
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long id = cursor.getLong(0);
helper.model.mergeWith(values);
readTransitoriesFromModelContentValues(helper.model);
helper.model.setId(id);
helper.update();
helper.model.clear();
}
getContext().getContentResolver().notifyChange(uri, null);
return cursor.getCount();
} finally {
cursor.close();
}
}
private void readTransitoriesFromModelContentValues(AbstractModel model) {
ContentValues setValues = model.getSetValues();
if (setValues != null) {
Set<Entry<String, Object>> entries = setValues.valueSet();
Set<String> keysToRemove = new HashSet<>();
for (Entry<String, Object> entry: entries) {
String key = entry.getKey();
if (key.startsWith(AbstractModel.RETAIN_TRANSITORY_PREFIX)) {
String newKey = key.substring(AbstractModel.RETAIN_TRANSITORY_PREFIX.length());
Object value = setValues.get(key);
model.putTransitory(newKey, value);
keysToRemove.add(key);
}
}
for (String key : keysToRemove) {
setValues.remove(key);
}
}
}
/* ======================================================================
* ============================================================ query ===
* ====================================================================== */
/**
* Query by task.
* <p>
* Note that the "sortOrder" field actually can be used to append any
* sort of clause to your SQL query as long as it is not also the
* name of a column
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String groupBy = null;
UriHelper<?> helper = generateHelper(uri, false);
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(helper.dao.getTable().name);
switch (uriMatcher.match(uri)) {
case URI_GROUP:
groupBy = uri.getPathSegments().get(2);
case URI_DIR:
break;
case URI_ITEM:
String itemSelector = String.format("%s = '%s'",
AbstractModel.ID_PROPERTY, uri.getPathSegments().get(1));
builder.appendWhere(itemSelector);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri + " (" + uriMatcher.match(uri) + ")");
}
Cursor cursor = builder.query(getDatabase().getDatabase(), projection, selection, selectionArgs, groupBy, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
// --- change listeners
public static void notifyDatabaseModification(Context context) {
ContentResolver cr = context.getContentResolver();
cr.notifyChange(Task.CONTENT_URI, null);
}
}
| gpl-3.0 |
Cuzzie/expensesapp | src/main/java/org/cuzzie/expensesapp/repository/TransactionRepository.java | 656 | package org.cuzzie.expensesapp.repository;
import org.cuzzie.expensesapp.model.Transaction;
import org.springframework.data.jpa.repository.Temporal;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.List;
/**
* Created by Cuzzie on 6/18/2017.
*/
@Repository
public interface TransactionRepository extends CrudRepository<Transaction, Integer> {
List<Transaction> findByUserIdAndDateBetweenOrderByDateDesc(int userId, @Temporal(TemporalType.DATE) Date startDate, @Temporal(TemporalType.DATE) Date endDate);
}
| gpl-3.0 |
bigttrott/thebubbleindex | application/thebubbleindex-standalone/src/main/java/org/thebubbleindex/plot/DerivativePlot.java | 17350 | package org.thebubbleindex.plot;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.SegmentedTimeline;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.thebubbleindex.exception.FailedToRunIndex;
import org.thebubbleindex.inputs.Indices;
import org.thebubbleindex.logging.Logs;
import org.thebubbleindex.runnable.RunContext;
import org.thebubbleindex.swing.BubbleIndexWorker;
import org.thebubbleindex.util.Utilities;
/**
* Plots the derivatives of The Bubble Index with JFreeChart
*
* @author thebubbleindex
*/
public class DerivativePlot {
private final int maxWindows = 4;
private final List<Integer> backtestDayLengths = new ArrayList<Integer>(maxWindows);
private final List<String> dailyPriceData;
private final Date begDate;
private final Date endDate;
private final Indices indices;
private final RunContext runContext;
private final ThreadLocal<SimpleDateFormat> dateformat = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
/** MouseEvent X & Y. */
private int m_iX, m_iY;
private double m_dX, m_dXX;
/**
* @param index0Value
* stores the mouse position relative to price data
* @param indexValue
* stores the mouse position relative to deriv data
*/
private double index0Value = 0.0;
private final double indexValue[] = { 0.0, 0.0, 0.0, 0.0 };
public final ChartPanel chartPanel;
private final String selectionName;
private final List<String> dailyPriceDate;
private final String categoryName;
private final boolean isCustomRange;
private int dailyPriceDataSize;
private final BubbleIndexWorker bubbleIndexWorker;
static {
// set a theme using the new shadow generator feature available in
// 1.0.14 - for backwards compatibility it is not enabled by default
ChartFactory.setChartTheme(new StandardChartTheme("JFree/Shadow", true));
}
public DerivativePlot(final BubbleIndexWorker bubbleIndexWorker, final String categoryName,
final String selectionName, final String windowsString, final Date begDate, Date endDate,
final boolean isCustomRange, final List<String> dailyPriceData, final List<String> dailyPriceDate,
final Indices indices, final RunContext runContext) {
Logs.myLogger.info("Initializing Bubble Index Derivative Plot.");
this.bubbleIndexWorker = bubbleIndexWorker;
this.selectionName = selectionName;
this.dailyPriceDate = dailyPriceDate;
this.categoryName = categoryName;
this.isCustomRange = isCustomRange;
this.dailyPriceData = dailyPriceData;
this.begDate = begDate;
this.endDate = endDate;
this.indices = indices;
this.runContext = runContext;
dailyPriceDataSize = dailyPriceData.size();
final String windowsStringArray[] = windowsString.split(",");
final Set<Integer> windowSet = new HashSet<Integer>(maxWindows);
for (int i = 0; i < windowsStringArray.length; i++) {
if (backtestDayLengths.size() >= maxWindows)
break;
final Integer window = Integer.parseInt(windowsStringArray[i]);
if (!windowSet.contains(window)) {
backtestDayLengths.add(window);
windowSet.add(window);
}
}
final String title = "The Bubble Index\u2122: " + this.selectionName + " (Derivatives)";
chartPanel = createChart();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
drawDerivativePlot(title);
}
});
}
/**
* DerivativePlot manages the display settings of the JFreeChart
*
* @param title
*/
public void drawDerivativePlot(final String title) {
// get the screen size as a java dimension
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height * 9 / 10;
int width = screenSize.width * 9 / 10;
// adjust several settings of the frame and display
final JFrame f = new JFrame(title);
f.setPreferredSize(new Dimension(width, height));
f.setTitle(title);
f.setLayout(new BorderLayout(0, 5));
f.add(chartPanel, BorderLayout.CENTER);
chartPanel.setMouseWheelEnabled(true);
chartPanel.setHorizontalAxisTrace(true);
chartPanel.setVerticalAxisTrace(true);
// add a mouse listener
chartPanel.addChartMouseListener(new ChartMouseListener() {
@Override
public void chartMouseClicked(final ChartMouseEvent event) {
// Do nothing
}
@Override
public void chartMouseMoved(final ChartMouseEvent e) {
int iX = e.getTrigger().getX();
m_iX = iX;
m_dX = (double) iX;
drawRTInfo();
}
});
final JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
f.add(panel, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
final int result = JOptionPane.showConfirmDialog(f, "Are you sure?");
if (result == JOptionPane.OK_OPTION) {
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(false);
f.dispose();
}
}
});
f.setVisible(true);
}
/**
* Creates a chart.
*
* @return A chart.
*/
private ChartPanel createChart() {
// Create datasets
final XYDataset dataset = createDerivDataset();
final XYDataset dataset2 = createDataset();
final JFreeChart chart = ChartFactory.createTimeSeriesChart(
"The Bubble Index\u2122: " + selectionName + " (Derivatives)", // title
"Date", // x-axis label
"Derivative Value (Relative)", // y-axis label
dataset, // data
true, // create legend?
false, // generate tooltips?
false // generate URLs?
);
chart.setBackgroundPaint(Color.white);
// Create deriv dataset and add to the plot
final XYPlot plot = (XYPlot) chart.getPlot();
final NumberAxis axis2 = new NumberAxis("Price");
axis2.setAutoRangeIncludesZero(false);
plot.setRangeAxis(1, axis2);
plot.setDataset(1, dataset2);
plot.mapDatasetToRangeAxis(1, 1);
plot.setBackgroundPaint(Color.BLACK);
plot.setDomainGridlinesVisible(false);
plot.setRangeGridlinesVisible(false);
// plot.setDomainGridlinePaint(Color.white);
// plot.setRangeGridlinePaint(Color.white);
plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
// draw lines
final XYItemRenderer r = plot.getRenderer();
if (r instanceof XYLineAndShapeRenderer) {
final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setBaseShapesVisible(false);
renderer.setBaseShapesFilled(false);
renderer.setDrawSeriesLineAsPath(true);
renderer.setSeriesPaint(0, Color.WHITE);
renderer.setSeriesPaint(1, Color.GREEN);
renderer.setSeriesPaint(2, Color.BLUE);
renderer.setSeriesPaint(3, Color.RED);
}
final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
renderer2.setBaseShapesVisible(false);
renderer2.setBaseShapesFilled(false);
renderer2.setDrawSeriesLineAsPath(true);
renderer2.setSeriesPaint(0, Color.YELLOW);
plot.setRenderer(1, renderer2);
// init date axis
final DateAxis axis = (DateAxis) plot.getDomainAxis();
if (isCustomRange) {
// Set the horizontal range
axis.setRange(begDate, endDate);
}
axis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());
return new ChartPanel(chart);
}
/*
* createDataset the Price Data time series
*
* @return dataset containing the Price time series
*/
private XYDataset createDataset() {
Logs.myLogger.info("Creating data set for the price data.");
final TimeSeriesCollection dataset = new TimeSeriesCollection();
final TimeSeries s1 = new TimeSeries(selectionName + " Price Data");
final List<Double> DoubleValues = new ArrayList<Double>(dailyPriceDataSize);
listToDouble(dailyPriceData, DoubleValues);
for (int i = 0; i < dailyPriceDataSize; i++) {
if (isCustomRange) {
Date tempDate = null;
try {
tempDate = dateformat.get().parse(dailyPriceDate.get(i));
} catch (final ParseException e) {
}
final int compareBegValue = tempDate.compareTo(begDate);
final int compareEndValue = tempDate.compareTo(endDate);
if (compareBegValue < 0 || compareEndValue > 0) {
continue;
}
}
final int[] DateValuesArray = new int[3];
getDateValues(DateValuesArray, dailyPriceDate.get(i));
s1.add(new Day(DateValuesArray[2], DateValuesArray[1], DateValuesArray[0]), DoubleValues.get(i));
}
dataset.addSeries(s1);
return dataset;
}
/**
* createDerivDataset create the dataset containing derivative values
*
* @return
*/
private XYDataset createDerivDataset() {
Logs.myLogger.info("Creating derivative data set for each window.");
if (runContext.isGUI()) {
bubbleIndexWorker.publishText("Creating derivative data set for each window.");
} else {
System.out.println("Creating derivative data set for each window.");
}
final TimeSeriesCollection dataset = new TimeSeriesCollection();
final TimeSeries[] TimeSeriesArray = new TimeSeries[4];
for (int i = 0; i < backtestDayLengths.size(); i++) {
TimeSeriesArray[i] = new TimeSeries(
selectionName + " " + Integer.toString(backtestDayLengths.get(i)) + " Deriv.");
final List<String> DateList = new ArrayList<String>(dailyPriceDataSize);
final List<String> DataListString = new ArrayList<String>(dailyPriceDataSize);
final List<Double> DataListDouble = new ArrayList<Double>(dailyPriceDataSize);
final List<Double> DataListDeriv = new ArrayList<Double>(dailyPriceDataSize);
final String previousFilePath = indices.getUserDir() + "ProgramData" + indices.getFilePathSymbol()
+ categoryName + indices.getFilePathSymbol() + selectionName + indices.getFilePathSymbol()
+ selectionName + Integer.toString(backtestDayLengths.get(i)) + "days.csv";
if (new File(previousFilePath).exists()) {
Logs.myLogger.info("Found previous file = {}", previousFilePath);
try {
Utilities.ReadValues(previousFilePath, DataListString, DateList, true, true);
} catch (final FailedToRunIndex ex) {
if (runContext.isGUI()) {
bubbleIndexWorker.publishText("Failed to read previous file: " + previousFilePath);
} else {
System.out.println("Failed to read previous file: " + previousFilePath);
}
}
DataListDeriv.add(0.0);
listToDouble(DataListString, DataListDouble);
for (int j = 1; j < DataListDouble.size(); j++) {
DataListDeriv.add(DataListDouble.get(j) / DataListDouble.get(j - 1) - 1.0);
}
// Limit the deriv values to [-0.5, 0.5] for display
for (int j = 1; j < DataListDeriv.size(); j++) {
if (DataListDeriv.get(j) > 0.5) {
DataListDeriv.set(j, 0.5);
}
if (DataListDeriv.get(j) < -0.5) {
DataListDeriv.set(j, -0.5);
}
}
for (int j = 0; j < DataListDeriv.size(); j++) {
if (isCustomRange) {
Date tempDate = null;
try {
tempDate = dateformat.get().parse(DateList.get(j));
} catch (final ParseException e) {
}
final int compareBegValue = tempDate.compareTo(begDate);
final int compareEndValue = tempDate.compareTo(endDate);
if (compareBegValue < 0 || compareEndValue > 0) {
continue;
}
}
final int[] DateValuesArray = new int[3];
getDateValues(DateValuesArray, DateList.get(j));
TimeSeriesArray[i].add(new Day(DateValuesArray[2], DateValuesArray[1], DateValuesArray[0]),
DataListDeriv.get(j));
}
}
dataset.addSeries(TimeSeriesArray[i]);
}
return dataset;
}
/**
* getDateValues
*
* @param DateValues
* @param DateString
*/
public void getDateValues(final int[] DateValues, final String DateString) {
// format of string is YYYY-MM-DD
final String[] temp = DateString.split("-");
if (temp.length == DateValues.length) {
for (int i = 0; i < temp.length; i++) {
DateValues[i] = Integer.parseInt(temp[i]);
}
}
else {
Logs.myLogger.error("Invalid input. temp.lenght = {}, DateValues.lenght = {}.", temp.length,
DateValues.length);
}
}
/**
* listToDouble
*
* @param DataListString
* @param DataListDouble
*/
private void listToDouble(final List<String> DataListString, final List<Double> DataListDouble) {
for (String DataListString1 : DataListString) {
DataListDouble.add(Double.parseDouble(DataListString1));
}
}
/**
* WZW override Draw a realtime tooltip at top banner(store X,Y,... value)
*/
private void drawRTInfo() {
final Rectangle2D screenDataArea = chartPanel.getScreenDataArea(this.m_iX, this.m_iY);
if (screenDataArea == null)
return;
final Graphics2D g2 = (Graphics2D) chartPanel.getGraphics();
final int iDAMinX = (int) screenDataArea.getMinX();
final int iDAMinY = (int) screenDataArea.getMinY();
final XYPlot plot = (XYPlot) chartPanel.getChart().getPlot();
final DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
final double dXX = dateAxis.java2DToValue(this.m_dX, screenDataArea, domainAxisEdge);
this.m_dXX = dXX;
// ^Get title and data
final ArrayList<String> alInfo = getInfo();
final int iLenInfo = alInfo.size();
// ^Customize dynamic tooltip display
String[] asV;
String sT, sV;
final FontMetrics fontMetrics = g2.getFontMetrics();
final int iFontHgt = fontMetrics.getHeight();
g2.setColor(Color.BLACK);
g2.fillRect(iDAMinX + 1, iDAMinY, 100, 18 * iFontHgt); // +1/-1 = offset
g2.setColor(Color.WHITE);
final TimeSeriesCollection collect2 = (TimeSeriesCollection) plot.getDataset(1);
if (this.m_dXX < collect2.getXValue(0, 0)) {
this.index0Value = 0.0;
}
else {
final int[] closeValues = collect2.getSurroundingItems(0, (long) this.m_dXX);
this.index0Value = collect2.getYValue(0, closeValues[0]);
}
final TimeSeriesCollection collect = (TimeSeriesCollection) plot.getDataset(0);
for (int i = 0; i < collect.getSeriesCount(); i++) {
if (this.m_dXX < collect.getXValue(i, 0)) {
this.indexValue[i] = 0.0;
}
else {
final int[] closeValues = collect.getSurroundingItems(i, (long) this.m_dXX);
this.indexValue[i] = collect.getYValue(i, closeValues[0]);
}
}
for (int i = iLenInfo - 1; i >= 0; i--) {
asV = alInfo.get(i).split("\\|");
sT = asV[0];
sV = asV[1];
g2.drawString(sT, iDAMinX + 20, iDAMinY + (i * 3 + 1) * iFontHgt);
g2.drawString(sV, iDAMinX + 20, iDAMinY + (i * 3 + 2) * iFontHgt);
}
g2.dispose();
}
/*
* WZW override get Info
*/
private ArrayList<String> getInfo() {
final DecimalFormat dfV = new DecimalFormat("#,###,###,##0.0000");
final String[] asT = new String[6];
final int size = backtestDayLengths.size();
final List<Integer> tempList = new ArrayList<Integer>(4);
for (int i = 0; i < 4; i++) {
if (i < size) {
tempList.add(backtestDayLengths.get(i));
} else {
tempList.add(backtestDayLengths.get(size - 1));
}
}
for (int i = 0; i < 4; i++) {
// only display the first four
final String windowIntString = Integer.toString(tempList.get(3 - i));
asT[i] = selectionName + windowIntString + ":";
}
asT[4] = "Price:";
asT[5] = "Date:";
final int iLenT = asT.length;
final ArrayList<String> alV = new ArrayList<String>(iLenT);
String sV = "";
// ^Binding
for (int i = iLenT - 1; i >= 0; i--) {
switch (i) {
case 0:
sV = String.valueOf(dfV.format(this.indexValue[3]));
break;
case 1:
sV = String.valueOf(dfV.format(this.indexValue[2]));
break;
case 2:
sV = String.valueOf(dfV.format(this.indexValue[1]));
break;
case 3:
sV = String.valueOf(dfV.format(this.indexValue[0]));
break;
case 4:
sV = String.valueOf(dfV.format(this.index0Value));
break;
case 5:
sV = getHMS();
break; // ^Customize display for timeseries(intraday) only
}
alV.add(asT[i] + "|" + sV);
}
return alV;
}
/*
* WZW override get Hour Minute Seconds
*/
private String getHMS() {
final long lDte = (long) this.m_dXX;
final Date dtXX = new Date(lDte);
final String date = dateformat.get().format(dtXX);
return date;
}
} | gpl-3.0 |
cercatore/Flipper | src/com/dozingcatsoftware/bouncy/AboutActivity.java | 1595 | package com.dozingcatsoftware.bouncy;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import com.dozingcatsoftware.bouncy.R;
public class AboutActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.about);
// get text to display by replacing "[TABLE_RULES]" with contents of string resource table[level]_rules
String baseText = getString(R.string.about_text);
String tableRulesText = null;
try {
String fieldName = "table" + getIntent().getIntExtra("level", 1) + "_rules";
int tableRulesID = (Integer)R.string.class.getField(fieldName).get(null);
tableRulesText = getString(tableRulesID);
}
catch(Exception ex) {
tableRulesText = null;
}
if (tableRulesText==null) tableRulesText = "";
String displayText = baseText.replace("[TABLE_RULES]", tableRulesText);
TextView tv = (TextView)findViewById(R.id.aboutTextView);
tv.setText(displayText);
}
public static Intent startForLevel(Context context, int level) {
Intent aboutIntent = new Intent(context, AboutActivity.class);
aboutIntent.putExtra("level", level);
context.startActivity(aboutIntent);
return aboutIntent;
}
}
| gpl-3.0 |
gMat000/JVC-Forums-Reader | src/com/forum/jvcreader/jvc/JvcArchivedTopic.java | 5136 | package com.forum.jvcreader.jvc;
import com.forum.jvcreader.utils.InternalStorageHelper;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
public class JvcArchivedTopic extends JvcTopic implements Serializable
{
public static final int MAX_POSTS_PER_FILE = 200;
private static final long serialVersionUID = 1L;
transient private ArrayList<ArrayList<JvcPost>> postsPageList;
transient private int currentFile = -1;
transient private int currentPageStart;
transient private int currentPageEnd;
transient private boolean authorPostsOnly;
private int archivedPageCountPerFile;
private int archivedPostsPerPage;
private int archivedPageCount;
private int archivedFileCount;
public JvcArchivedTopic(JvcTopic topic, int postsPerPage, int pageStart, int pageEnd, boolean authorPostsOnly)
{
super(topic.getForum(), topic.getTopicId());
currentPageStart = Math.max(pageStart, 1);
currentPageEnd = Math.min(pageEnd, 5000);
this.authorPostsOnly = authorPostsOnly;
archivedPostsPerPage = Math.min(Math.max(postsPerPage, 1), MAX_POSTS_PER_FILE);
archivedPageCountPerFile = (int) Math.floor((double) MAX_POSTS_PER_FILE / postsPerPage);
archivedPageCount = 0;
archivedFileCount = 0;
}
public void deleteTopicContent() throws IOException
{
for(int i = 0; i < archivedFileCount; i++)
{
InternalStorageHelper.deleteFile(getForum().getContext(), getFileName(i));
}
}
public boolean archivePages(OnPageArchivedListener listener) throws IOException, JvcErrorException
{
if(JvcUserData.isTopicInArchivedTopics(this))
throw new IllegalArgumentException("Topic already in archived topics");
ArrayList<ArrayList<JvcPost>> tempPageList = new ArrayList<ArrayList<JvcPost>>();
ArrayList<JvcPost> tempPostList = new ArrayList<JvcPost>();
String authorName = null;
int fileCounter = 0;
if(authorPostsOnly && currentPageStart > 1)
{
listener.onUpdateState(OnPageArchivedListener.FETCHING_AUTHOR_NAME, 0);
if(requestPosts(JvcTopic.SHOW_POSTS_FROM_PAGE, 1))
{
throw new JvcErrorException(getRequestError());
}
else
{
authorName = getRequestResult().get(0).getPostPseudo().toLowerCase();
}
}
for(int i = currentPageStart; i <= currentPageEnd; i++)
{
listener.onUpdateState(OnPageArchivedListener.FETCHING_PAGE, i);
if(requestPosts(JvcTopic.SHOW_POSTS_FROM_PAGE, i))
{
throw new JvcErrorException(getRequestError());
}
else
{
ArrayList<JvcPost> postList = getRequestResult();
if(i == 1 && authorName == null)
authorName = postList.get(0).getPostPseudo().toLowerCase();
for(JvcPost post : postList)
{
if(authorPostsOnly && !post.getPostPseudo().toLowerCase().equals(authorName))
continue;
tempPostList.add(post);
if(tempPostList.size() == archivedPostsPerPage)
{
tempPageList.add(tempPostList);
archivedPageCount++;
tempPostList = new ArrayList<JvcPost>();
if(tempPageList.size() == archivedPageCountPerFile)
{
InternalStorageHelper.writeSerializableObject(getForum().getContext(), getFileName(fileCounter), tempPageList);
fileCounter++;
archivedFileCount = fileCounter; /* Always update this in case of abort */
tempPageList.clear();
}
}
}
}
}
if(tempPostList.size() > 0)
{
tempPageList.add(tempPostList); /* Append last page */
archivedPageCount++;
}
if(tempPageList.size() > 0) /* Append last file */
{
InternalStorageHelper.writeSerializableObject(getForum().getContext(), getFileName(fileCounter), tempPageList);
fileCounter++;
archivedFileCount = fileCounter; /* Always update this in case of abort */
}
if(fileCounter > 0)
{
listener.onUpdateState(OnPageArchivedListener.SAVING_TOPIC, 0);
JvcUserData.addToArchivedTopics(this);
return true;
}
else
{
return false;
}
}
public int getPostCountPerPage()
{
return archivedPostsPerPage;
}
public int getArchivedPageCount()
{
return archivedPageCount;
}
public int getInitialPageEnd()
{
return currentPageEnd;
}
private String getFileName(int fileId)
{
return "ArchivedTopic_" + getTopicId() + "_" + fileId + ".jvc";
}
public ArrayList<JvcPost> getPostsFromPage(int page) throws ClassNotFoundException, IOException
{
if(page >= 1 && page <= getArchivedPageCount())
{
final int requestedPageFile = (int) Math.floor((page - 1) / archivedPageCountPerFile);
if(postsPageList == null || currentFile != requestedPageFile)
{
postsPageList = (ArrayList<ArrayList<JvcPost>>) InternalStorageHelper.readSerializableObject(getForum().getContext(), getFileName(requestedPageFile));
currentFile = requestedPageFile;
}
return postsPageList.get((page - 1) - currentFile * archivedPageCountPerFile);
}
else
{
throw new IllegalArgumentException("Page number requested invalid");
}
}
public interface OnPageArchivedListener
{
public static final int FETCHING_AUTHOR_NAME = 1;
public static final int FETCHING_PAGE = 2;
public static final int SAVING_TOPIC = 3;
public void onUpdateState(int state, int arg1);
}
}
| gpl-3.0 |
marmundo/LojaCelular | src/com/phonesaragao/principal/Principal.java | 986 | package com.phonesaragao.principal;
import java.sql.SQLException;
import com.phonesaragao.dao.CelularDAO;
import com.phonesaragao.modelo.Celular;
public class Principal {
private Celular criaCelular(){
Celular c=new Celular();
c.setMarca("Samsung");
c.setMemoriaArmazenamento(16);
c.setMemoriaRam(2);
c.setModelo("A10");
c.setPreco(800.00);
c.setProcessador("Qualcom");
c.setResolucaoCameraFrontal(5);
c.setResolucaoCameraTraseira(10);
c.setTamanhoTela(5);
c.setVelocidadeProcessador(2);
return c;
}
public static void main(String[] args) {
Principal p=new Principal();
Celular c=p.criaCelular();
CelularDAO cDao=new CelularDAO();
try {
System.out.println(cDao.listarTodosCelulares().toString());
/* if(cDao.inserir(c)){
System.out.println("Celular inserido!");
}*/
cDao.fechar();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| gpl-3.0 |
Curtis3321/Essentials | Essentials/src/net/ess3/settings/Commands.java | 2559 | package net.ess3.settings;
import java.util.List;
import lombok.*;
import net.ess3.settings.commands.*;
import net.ess3.storage.Comment;
import net.ess3.storage.ListType;
import net.ess3.storage.StorageObject;
@Data
@EqualsAndHashCode(callSuper = false)
public class Commands implements StorageObject
{
private Afk afk = new Afk();
private Back back = new Back();
private God god = new God();
private Help help = new Help();
private Home home = new Home();
private Lightning lightning = new Lightning();
private net.ess3.settings.commands.List list = new net.ess3.settings.commands.List();
private Near near = new Near();
private SocialSpy socialspy = new SocialSpy();
private Spawnmob spawnmob = new Spawnmob();
private Teleport teleport = new Teleport();
private Tempban tempban = new Tempban();
private Speed speed = new Speed();
@ListType
@Comment(
"When a command conflicts with another plugin, by default, Essentials will try to force the OTHER plugin to take\n"
+ "priority. If a command is in this list, Essentials will try to give ITSELF priority. This does not always work:\n"
+ "usually whichever plugin was updated most recently wins out. However, the full name of the command will always work.\n"
+ "For example, if WorldGuard and Essentials are both enabled, and WorldGuard takes control over /god, /essentials:god\n"
+ "will still map to Essentials, whereas it might normally get forced upon WorldGuard. Commands prefixed with an \"e\",\n"
+ "such as /egod, will always grant Essentials priority.\n"
+ "We should try to take priority over /god. If this doesn't work, use /essentials:god or /egod.\n"
+ "If god is set using WorldGuard, use /ungod to remove then use whichever you see fit.")
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private List<String> overridden = null;
@ListType
@Comment("Disabled commands will be completely unavailable on the server.")
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private List<String> disabled = null;
public boolean isDisabled(final String commandName)
{
if (disabled == null)
{
return false;
}
for (String disabledCommand : disabled)
{
if (commandName.equalsIgnoreCase(disabledCommand))
{
return true;
}
}
return false;
}
public boolean isOverridden(final String commandName)
{
if (overridden == null)
{
return false;
}
for (String overriddenCommand : overridden)
{
if (commandName.equalsIgnoreCase(overriddenCommand))
{
return true;
}
}
return false;
}
}
| gpl-3.0 |
Greymerk/minecraft-roguelike | src/main/java/greymerk/roguelike/theme/ThemeIce.java | 555 | package greymerk.roguelike.theme;
import greymerk.roguelike.worldgen.MetaBlock;
import greymerk.roguelike.worldgen.MetaStair;
import greymerk.roguelike.worldgen.blocks.BlockType;
import greymerk.roguelike.worldgen.blocks.StairType;
public class ThemeIce extends ThemeBase{
public ThemeIce(){
MetaBlock walls = BlockType.get(BlockType.SNOW);
MetaStair stair = new MetaStair(StairType.QUARTZ);
MetaBlock pillar = BlockType.get(BlockType.ICE_PACKED);
this.primary = new BlockSet(walls, stair, pillar);
this.secondary = this.primary;
}
}
| gpl-3.0 |
salcedonia/acide-0-8-release-2010-2011 | acide/src/acide/configuration/toolBar/menuBarToolBar/AcideMenuBarToolBarConfiguration.java | 1535 | /*
* ACIDE - A Configurable IDE
* Official web site: http://acide.sourceforge.net
*
* Copyright (C) 2007-2011
* Authors:
* - Fernando Sáenz Pérez (Team Director).
* - Version from 0.1 to 0.6:
* - Diego Cardiel Freire.
* - Juan José Ortiz Sánchez.
* - Delfín Rupérez Cañas.
* - Version 0.7:
* - Miguel Martín Lázaro.
* - Version 0.8:
* - Javier Salcedo Gómez.
*
* 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 acide.configuration.toolBar.menuBarToolBar;
/**
* ACIDE - A Configurable IDE menu bar tool bar configuration.
*
* @version 0.8
*/
public class AcideMenuBarToolBarConfiguration {
/**
* Loads the ACIDE - A Configurable IDE menu bar tool bar configuration from
* a file given as a parameter.
*
* @param filePath configuration file path.
*/
public void load(String filePath) {
}
}
| gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/gde/buss/dao/AgeRetDAO.java | 4300 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.gde.buss.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import ar.gov.rosario.siat.base.buss.dao.GenericDAO;
import ar.gov.rosario.siat.base.buss.dao.SiatHibernateUtil;
import ar.gov.rosario.siat.def.buss.bean.Recurso;
import ar.gov.rosario.siat.gde.buss.bean.AgeRet;
import ar.gov.rosario.siat.gde.iface.model.AgeRetSearchPage;
import ar.gov.rosario.siat.gde.iface.model.AgeRetVO;
import coop.tecso.demoda.iface.helper.DemodaUtil;
import coop.tecso.demoda.iface.helper.ListUtil;
import coop.tecso.demoda.iface.helper.ModelUtil;
import coop.tecso.demoda.iface.helper.StringUtil;
import coop.tecso.demoda.iface.model.Estado;
public class AgeRetDAO extends GenericDAO {
private Log log = LogFactory.getLog(AgeRetDAO.class);
public AgeRetDAO() {
super(AgeRet.class);
}
public List<AgeRet> getBySearchPage(AgeRetSearchPage ageRetSearchPage) throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
String queryString = "from AgeRet t ";
boolean flagAnd = false;
if (log.isDebugEnabled()) {
log.debug("log de filtros del AgeRetSearchPage: " + ageRetSearchPage.infoString());
}
// Armamos filtros del HQL
if (ageRetSearchPage.getModoSeleccionar()) {
queryString += flagAnd ? " and " : " where ";
queryString += " t.estado = "+ Estado.ACTIVO.getId();
flagAnd = true;
}
// filtro mandatario excluidos
List<AgeRetVO> listAgeRetExcluidos = (List<AgeRetVO>) ageRetSearchPage.getListVOExcluidos();
if (!ListUtil.isNullOrEmpty(listAgeRetExcluidos)) {
queryString += flagAnd ? " and " : " where ";
String listIdExcluidos = ListUtil.getStringIdsFromListModel(listAgeRetExcluidos);
queryString += " t.id NOT IN ("+ listIdExcluidos + ") ";
flagAnd = true;
}
// filtro por descripcion
if (!StringUtil.isNullOrEmpty(ageRetSearchPage.getAgeRet().getDesAgeRet())) {
queryString += flagAnd ? " and " : " where ";
queryString += " UPPER(TRIM(t.desAgeRet)) like '%" +
StringUtil.escaparUpper(ageRetSearchPage.getAgeRet().getDesAgeRet()) + "%'";
flagAnd = true;
}
// filtro por Recurso
if (!ModelUtil.isNullOrEmpty(ageRetSearchPage.getAgeRet().getRecurso())){
queryString += flagAnd ? " and " : " where ";
queryString += " t.recurso.id = " + ageRetSearchPage.getAgeRet().getRecurso().getId();
flagAnd = true;
}
queryString += " order by t.id ";
if (log.isDebugEnabled()) log.debug(funcName + ": Query: " + queryString);
List<AgeRet> listAgeRet = (ArrayList<AgeRet>) executeCountedSearch(queryString, ageRetSearchPage);
log.debug("EN GETY BY SEARCH PAGE DESPUES DE LA LISTA");
if (log.isDebugEnabled()) log.debug(funcName + ": exit");
return listAgeRet;
}
/**
* Retorna la lista de AgeRet para un recurso dado
*
* @param area
* @return
*/
public List<AgeRet> getListActivosByRecurso(Recurso recurso){
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM AgeRet p WHERE p.estado = "+Estado.ACTIVO.getId();
if (recurso!=null)
queryString += " AND p.recurso.id = "+recurso.getId();
Query query = session.createQuery(queryString);
return (List<AgeRet>)query.list();
}
/**
* Obtiene el Agente de Retencion para un CUIT y Recurso dado
*
* @param cuit
* @param recurso
* @return
*/
public AgeRet getByCuitYRecurso(String cuit, Long idRecurso) {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM AgeRet p WHERE " + "p.recurso.id = "+idRecurso;
queryString += " AND p.cuit = '"+cuit+"'";
queryString += " AND p.estado = "+Estado.ACTIVO.getId();
Query query = session.createQuery(queryString);
query.setMaxResults(1);
return (AgeRet) query.uniqueResult();
}
}
| gpl-3.0 |
DanCorder/Archiverify | src/main/java/com/dancorder/Archiverify/FileHashGenerator.java | 1403 | // Archiverify is an archive synching and verification tool
// Copyright (C) 2014 Daniel Corder (contact: archiverify@dancorder.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package com.dancorder.Archiverify;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.codec.digest.DigestUtils;
class FileHashGenerator {
String calculateMd5(Path file) throws IOException {
if (!Files.exists(file)) {
return null;
}
FileInputStream stream = null;
try {
stream = new FileInputStream(file.toString());
return DigestUtils.md5Hex(stream);
}
finally {
if (stream != null) {
stream.close();
}
}
}
}
| gpl-3.0 |
cereda/wsn2spa | src/main/java/br/usp/poli/lta/cereda/nfa2dfa/utils/Triple.java | 1792 | /**
* ------------------------------------------------------
* Laboratório de Linguagens e Técnicas Adaptativas
* Escola Politécnica, Universidade São Paulo
* ------------------------------------------------------
*
* 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.
*
**/
package br.usp.poli.lta.cereda.nfa2dfa.utils;
/**
* @author Paulo Roberto Massa Cereda
* @version 1.0
* @since 1.0
*/
public class Triple<A, B, C> {
private A first;
private B second;
private C third;
public Triple(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
public C getThird() {
return third;
}
public void setThird(C third) {
this.third = third;
}
public Triple() {
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(").append(first).append(", ");
sb.append(second).append(", ");
sb.append(third).append(")");
return sb.toString();
}
}
| gpl-3.0 |
marcelohama/mp-ofertas | MPOfertas/app/src/main/java/com/mercadopago/mpofertas/LoginActivity.java | 4717 | package com.mercadopago.mpofertas;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.AccountPicker;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.mercadopago.mpofertas.device.SharedPref;
import com.mercadopago.mpofertas.ui.DashboardActivity;
import com.mercadopago.mpofertas.utils.Utilities;
/**
* Created by mthama on 06/09/16.
*/
public class LoginActivity extends MPActionBarActivity {
private static final int REQUEST_CODE_EMAIL = 1;
private Context context;
private Button enterbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.context = this;
// full screen mode
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// load xml view
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
enterbtn = (Button) findViewById(R.id.activity_login_enterbtn);
enterbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logIn();
}
});
if (Utilities.checkNetwork(LoginActivity.this) == 0) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(getResources().getString(R.string.label_networkproblem))
.setCancelable(false)
.setPositiveButton(
context.getResources().getString(R.string.action_ok),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
finish();
}
}
);
final AlertDialog alert = builder.create();
alert.show();
} else{
logIn();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
// save email
SharedPref.saveEmail(context, accountName);
// got email, generate firebase id
configuraNotificacoes();
// go ahead
goToDashboard();
return;
}
}
Toast.makeText(
context,
getResources().getString(R.string.action_cantlogin),
Toast.LENGTH_LONG
).show();
}
private void logIn() {
boolean hasEmail = SharedPref.loadEmail(LoginActivity.this) != null;
if (hasEmail) {
goToDashboard();
} else {
// we do not have email, so we should get it
Intent intent = AccountPicker.newChooseAccountIntent(
null, null,
new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }, false,
getResources().getString(R.string.label_whyselectaccount),
null, null, null
);
startActivityForResult(intent, REQUEST_CODE_EMAIL);
}
}
private void goToDashboard() {
// we have both, so we just go through!
Intent newApp = new Intent(
LoginActivity.this,
DashboardActivity.class
);
newApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newApp.putExtra(
"fragmentIndex",
getIntent().getIntExtra("fragmentIndex", 0)
);
newApp.putExtra(
"openDrawer",
getIntent().getBooleanExtra("openDrawer", false)
);
startActivity(newApp);
finish();
}
private void configuraNotificacoes() {
FirebaseMessaging.getInstance().subscribeToTopic(AppConstants.NOTIFICATION_TOPIC);
Log.d(AppConstants.TAG, "Token: " + FirebaseInstanceId.getInstance().getToken());
}
} | gpl-3.0 |
Karlosjp/Clase-DAM | Luis Braille/2 DAM/Servicios y procesos/1 Trimestre/Ejercicios profesor/JAVA_053_C_PIZZERIA/src/ingredientes/SalsaBarbacoa.java | 256 | // Crear la subclase de Ingrediente, SalsaBarbacoa.
package ingredientes;
import interfaces.InterfazPrecios;
public class SalsaBarbacoa extends Ingrediente {
public SalsaBarbacoa() {
super(InterfazPrecios.PRECIO_SALSA_BARBACOA);
}
} | gpl-3.0 |
Dennisbonke/NealegamingTUT | src/main/java/com/dennisbonke/letsmodng/blocks/AlabasterOven.java | 8416 | package com.dennisbonke.letsmodng.blocks;
import com.dennisbonke.letsmodng.LetsModNG;
import com.dennisbonke.letsmodng.tileentity.TileEntityAlabasterOven;
import cpw.mods.fml.common.network.internal.FMLNetworkHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.Random;
public class AlabasterOven extends BlockContainer{
private final boolean isActive;
@SideOnly(Side.CLIENT)
private IIcon iconFront;
@SideOnly(Side.CLIENT)
private IIcon iconTop;
private static boolean keepInventory;
private Random rand = new Random();
public AlabasterOven(boolean isActive){
super(Material.iron);
this.isActive = isActive;
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister){
this.blockIcon = iconRegister.registerIcon(LetsModNG.modid + ":" + "AlabasterOvenSide");
this.iconFront = iconRegister.registerIcon(LetsModNG.modid + ":" +(this.isActive ? "AlabasterOvenFrontOn" : "AlabasterOvenFrontOff"));
this.iconTop = iconRegister.registerIcon(LetsModNG.modid + ":" + "AlabasterOvenTop");
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int metadata){
return side == 3 ? this.iconFront : (side == 1 ? this.iconTop : (side == 0 ? this.iconTop : (side != metadata ? this.blockIcon : this.iconFront)));
}
public Item getItemDropped(int i, Random random, int j){
return Item.getItemFromBlock(LetsModNG.blockAlabasterOvenIdle);
}
public void onBlockAdded(World world, int x, int y, int z){
super.onBlockAdded(world, x, y, z);
this.setDefaultDirection(world, x, y, z);
}
private void setDefaultDirection(World world, int x, int y, int z) {
if(!world.isRemote){
Block b1 = world.getBlock(x, y, z - 1);
Block b2 = world.getBlock(x, y, z + 1);
Block b3 = world.getBlock(x - 1, y, z);
Block b4 = world.getBlock(x + 1, y, z);
byte b0 = 3;
if(b1.func_149730_j() && !b2.func_149730_j()){
b0 = 3;
}
if(b2.func_149730_j() && !b1.func_149730_j()){
b0 = 2;
}
if(b3.func_149730_j() && !b4.func_149730_j()){
b0 = 5;
}
if(b4.func_149730_j() && !b3.func_149730_j()){
b0 = 4;
}
world.setBlockMetadataWithNotify(x, y, z, b0, 2);
}
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ){
if(!world.isRemote){
FMLNetworkHandler.openGui(player, LetsModNG.instance, LetsModNG.guiIDAlabasterOven, world, x, y, z);
}
return true;
}
@Override
public TileEntity createNewTileEntity(World world, int i) {
return new TileEntityAlabasterOven();
}
@SideOnly(Side.CLIENT)
public void randomDisplayTick(World world, int x, int y, int z, Random random){
if (this.isActive){
int direction = world.getBlockMetadata(x, y, z);
float x1 = (float)x + 0.5F;
float y1 = (float)y + random.nextFloat();
float z1 = (float)z + 0.5F;
float f = 0.52F;
float f1 = random.nextFloat() * 0.6F - 0.3F;
if (direction == 4){
world.spawnParticle("smoke", (double)x1 - f, (double)(y1), (double)(z1 + f1), 0D, 0D, 0D);
world.spawnParticle("flame", (double)x1 - f, (double)(y1), (double)(z1 + f1), 0D, 0D, 0D);
}
if (direction == 5){
world.spawnParticle("smoke", (double)x1 + f, (double)(y1), (double)(z1 + f1), 0D, 0D, 0D);
world.spawnParticle("flame", (double)x1 + f, (double)(y1), (double)(z1 + f1), 0D, 0D, 0D);
}
if (direction == 2){
world.spawnParticle("smoke", (double)x1 + f1, (double)(y1), (double)(z1 - f), 0D, 0D, 0D);
world.spawnParticle("flame", (double)x1 + f1, (double)(y1), (double)(z1 - f), 0D, 0D, 0D);
}
if (direction == 3){
world.spawnParticle("smoke", (double)x1 + f1, (double)(y1), (double)(z1 + f), 0D, 0D, 0D);
world.spawnParticle("flame", (double)x1 + f1, (double)(y1), (double)(z1 + f), 0D, 0D, 0D);
}
}
}
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityplayer, ItemStack itemstack){
int l = MathHelper.floor_double((double)(entityplayer.rotationYaw * 4.0F / 360.F) + 0.5D) & 3;
if(l == 0){
world.setBlockMetadataWithNotify(x, y, z, 2, 2);
}
if(l == 1){
world.setBlockMetadataWithNotify(x, y, z, 5, 2);
}
if(l == 2){
world.setBlockMetadataWithNotify(x, y, z, 3, 2);
}
if(l == 3){
world.setBlockMetadataWithNotify(x, y, z, 4, 2);
}
if(itemstack.hasDisplayName()){
((TileEntityAlabasterOven)world.getTileEntity(x, y, z)).setGuiDisplayName(itemstack.getDisplayName());
}
}
public static void updateAlabasterOvenBlockState(boolean active, World worldObj, int xCoord, int yCoord, int zCoord) {
int i = worldObj.getBlockMetadata(xCoord, yCoord, zCoord);
TileEntity tileentity = worldObj.getTileEntity(xCoord, yCoord, zCoord);
keepInventory = true;
if (active){
worldObj.setBlock(xCoord, yCoord, zCoord, LetsModNG.blockAlabasterOvenActive);
}else{
worldObj.setBlock(xCoord, yCoord, zCoord, LetsModNG.blockAlabasterOvenIdle);
}
keepInventory = false;
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, i, 2);
if (tileentity != null){
tileentity.validate();
worldObj.setTileEntity(xCoord, yCoord, zCoord, tileentity);
}
}
public void breakBlock(World world, int x, int y, int z, Block oldblock, int oldMetadata){
if (!keepInventory){
TileEntityAlabasterOven tileentity = (TileEntityAlabasterOven) world.getTileEntity(x, y, z);
if (tileentity != null){
for (int i = 0; i < tileentity.getSizeInventory(); i++){
ItemStack itemstack = tileentity.getStackInSlot(i);
if (itemstack != null){
float f = this.rand.nextFloat() * 0.8F + 0.1F;
float f1 = this.rand.nextFloat() * 0.8F + 0.1F;
float f2 = this.rand.nextFloat() * 0.8F + 0.1F;
while(itemstack.stackSize > 0){
int j = this.rand.nextInt(21) + 10;
if (j > itemstack.stackSize){
j = itemstack.stackSize;
}
itemstack.stackSize -= j;
EntityItem item = new EntityItem(world, (double)((float)x + f), (double)((float)y + f1), (double)((float)z + f2), new ItemStack(itemstack.getItem(), j, itemstack.getItemDamage()));
if (itemstack.hasTagCompound()){
item.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
}
world.spawnEntityInWorld(item);
}
}
}
world.func_147453_f(x, y, z, oldblock);
}
}
super.breakBlock(world, x, y, z, oldblock, oldMetadata);
}
public Item getItem(World world, int x, int y, int z){
return Item.getItemFromBlock(LetsModNG.blockAlabasterOvenIdle);
}
}
| gpl-3.0 |
FthrNature/unleashed-pixel-dungeon | src/main/java/com/shatteredpixel/pixeldungeonunleashed/sprites/SeniorSprite.java | 1847 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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.shatteredpixel.pixeldungeonunleashed.sprites;
import com.watabou.noosa.TextureFilm;
import com.shatteredpixel.pixeldungeonunleashed.Assets;
import com.watabou.utils.Random;
public class SeniorSprite extends MobSprite {
private Animation kick;
public SeniorSprite() {
super();
texture( Assets.MONK );
TextureFilm frames = new TextureFilm( texture, 15, 14 );
idle = new Animation( 6, true );
idle.frames( frames, 18, 17, 18, 19 );
run = new Animation( 15, true );
run.frames( frames, 28, 29, 30, 31, 32, 33 );
attack = new Animation( 12, false );
attack.frames( frames, 20, 21, 20, 21 );
kick = new Animation( 10, false );
kick.frames( frames, 22, 23, 22 );
die = new Animation( 15, false );
die.frames( frames, 18, 24, 25, 25, 26, 27 );
play( idle );
}
@Override
public void attack( int cell ) {
super.attack( cell );
if (Random.Float() < 0.3f) {
play( kick );
}
}
@Override
public void onComplete( Animation anim ) {
super.onComplete( anim == kick ? attack : anim );
}
}
| gpl-3.0 |
selfbus/tools-libraries | sbtools-knxcom/src/main/java/org/selfbus/sbtools/knxcom/link/netip/frames/DescriptionRequest.java | 958 | package org.selfbus.sbtools.knxcom.link.netip.frames;
import java.net.InetAddress;
import org.selfbus.sbtools.knxcom.link.netip.types.ServiceType;
import org.selfbus.sbtools.knxcom.link.netip.types.TransportType;
/**
* Request a description of the KNXnet/IP server.
*/
public class DescriptionRequest extends AbstractEndPointFrame
{
/**
* Create a description request object.
*
* @param type - the transport type of the sender.
* @param addr - the address of the sender.
* @param port - the port of the sender.
*/
public DescriptionRequest(TransportType type, InetAddress addr, int port)
{
super(type, addr, port);
}
/**
* Create a description request object.
*/
public DescriptionRequest()
{
super();
}
/**
* @return {@link ServiceType#DESCRIPTION_REQUEST}.
*/
@Override
public ServiceType getServiceType()
{
return ServiceType.DESCRIPTION_REQUEST;
}
}
| gpl-3.0 |
debmalya/JavaVAD | src/main/java/com/deb/ehcache/EhCacheEventListener.java | 721 | /**
* Copyright 2015-2016 Knowesis Pte Ltd.
*
*/
package com.deb.ehcache;
import com.deb.vad.SilenceDetector;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author debmalyajash
*
*/
public class EhCacheEventListener<K,V> implements CacheEventListener<K, V> {
private static final Logger logger = LoggerFactory.getLogger(EhCacheEventListener.class);
/* (non-Javadoc)
* @see org.ehcache.event.CacheEventListener#onEvent(org.ehcache.event.CacheEvent)
*/
@Override
public void onEvent(CacheEvent<K, V> event) {
if (logger.isDebugEnabled()) {
logger.debug(event.getType().toString());
}
}
}
| gpl-3.0 |
itachi1706/Applied-Energistics-2 | src/main/java/appeng/util/ClassInstantiation.java | 3167 | /*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 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.
*
* Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import com.google.common.base.Optional;
import appeng.core.AELog;
public class ClassInstantiation<T>
{
private final Class<? extends T> template;
private final Object[] args;
public ClassInstantiation( final Class<? extends T> template, final Object... args )
{
this.template = template;
this.args = args;
}
public Optional<T> get()
{
@SuppressWarnings( "unchecked" )
final Constructor<T>[] constructors = (Constructor<T>[]) this.template.getConstructors();
for( final Constructor<T> constructor : constructors )
{
final Class<?>[] paramTypes = constructor.getParameterTypes();
if( paramTypes.length == this.args.length )
{
boolean valid = true;
for( int idx = 0; idx < paramTypes.length; idx++ )
{
final Class<?> cz = this.args[idx].getClass();
if( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) )
{
valid = false;
}
}
if( valid )
{
try
{
return Optional.of( constructor.newInstance( this.args ) );
}
catch( final InstantiationException e )
{
e.printStackTrace();
}
catch( final IllegalAccessException e )
{
e.printStackTrace();
}
catch( final InvocationTargetException e )
{
e.printStackTrace();
}
break;
}
}
}
return Optional.absent();
}
private boolean isClassMatch( Class<?> expected, Class<?> got, final Object value )
{
if( value == null && !expected.isPrimitive() )
{
return true;
}
expected = this.condense( expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class );
got = this.condense( got, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class );
return expected == got || expected.isAssignableFrom( got );
}
private Class<?> condense( final Class<?> expected, final Class<?>... wrappers )
{
if( expected.isPrimitive() )
{
for( final Class clz : wrappers )
{
try
{
if( expected == clz.getField( "TYPE" ).get( null ) )
{
return clz;
}
}
catch( final Throwable t )
{
AELog.error( t );
}
}
}
return expected;
}
}
| gpl-3.0 |
Timeslice42/TFCraft | TFC_Shared/src/TFC/Entities/AI/EntityAIRutt.java | 4514 | package TFC.Entities.AI;
import java.util.*;
import TFC.*;
import TFC.Core.TFC_Time;
import TFC.Entities.EntityAnimalTFC;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.entity.*;
import net.minecraft.client.gui.inventory.*;
import net.minecraft.block.*;
import net.minecraft.block.material.*;
import net.minecraft.crash.*;
import net.minecraft.creativetab.*;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.effect.*;
import net.minecraft.entity.item.*;
import net.minecraft.entity.monster.*;
import net.minecraft.entity.player.*;
import net.minecraft.entity.projectile.*;
import net.minecraft.inventory.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;
import net.minecraft.network.*;
import net.minecraft.network.packet.*;
import net.minecraft.pathfinding.*;
import net.minecraft.potion.*;
import net.minecraft.server.*;
import net.minecraft.stats.*;
import net.minecraft.tileentity.*;
import net.minecraft.util.*;
import net.minecraft.village.*;
import net.minecraft.world.*;
import net.minecraft.world.biome.*;
import net.minecraft.world.chunk.*;
import net.minecraft.world.gen.feature.*;
public class EntityAIRutt extends EntityAIBase
{
private EntityAnimalTFC theAnimal;
World theWorld;
private EntityAnimalTFC targetMate;
int field_48261_b;
float field_48262_c;
public EntityAIRutt (EntityAnimalTFC par1EntityAnimal, float par2)
{
field_48261_b = 0;
theAnimal = par1EntityAnimal;
theWorld = par1EntityAnimal.worldObj;
field_48262_c = par2;
setMutexBits (3);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute ()
{
if (theAnimal.getAttackTarget()!= null){
return false;
}
if (theAnimal.getHealth()*3 <= theAnimal.getMaxHealth()){
theAnimal.ruttVictor = false;
if(theAnimal.getAttackTarget()!=null&&theAnimal.getAttackTarget().getClass() == theAnimal.getClass()){
((EntityAnimalTFC)theAnimal.getAttackTarget()).ruttVictor = true;
}
return false;
}
if (theAnimal.hunger < 84000 || theAnimal.sex == 1 || !(TFC_Time.getMonth() >= theAnimal.matingStart && TFC_Time.getMonth() <= theAnimal.matingEnd)||theAnimal.breeding != 0||theAnimal.getAttackTarget()!=null)
{
return false;
}
else
{
theAnimal.rutting = true;
return true;
}
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean continueExecuting ()
{
return !((theAnimal.getHealth() <= theAnimal.getMaxHealth() / 4)||(theAnimal.ruttVictor))||theAnimal.getAttackTarget()!=null;
}
/**
* Resets the task
*/
public void resetTask ()
{
theAnimal.rutting = false;
if (theAnimal.ruttVictor){
theAnimal.setInLove(true);
}
}
/**
* Updates the task
*/
public void updateTask ()
{
float f = 8F;
List list = theWorld.getEntitiesWithinAABB (theAnimal.getClass (), theAnimal.boundingBox.expand (f, f, f));
for (Iterator iterator = list.iterator () ; iterator.hasNext () ;)
{
Entity entity = (Entity) iterator.next ();
EntityAnimalTFC entityanimal = (EntityAnimalTFC) entity;
if (entityanimal.rutting)
{
theAnimal.setAttackTarget(entityanimal);
}
}
}
/**
* Removed for having no use. Please delete to clear up the code when confirmed by dunk
*
private EntityAnimalTFC func_48258_h ()
{
float f = 8F;
List list = theWorld.getEntitiesWithinAABB (theAnimal.getClass (), theAnimal.boundingBox.expand (f, f, f));
for (Iterator iterator = list.iterator () ; iterator.hasNext () ;)
{
Entity entity = (Entity) iterator.next ();
EntityAnimalTFC entityanimal = (EntityAnimalTFC) entity;
if (theAnimal.canMateWith (entityanimal))
{
return entityanimal;
}
}
return null;
}
private void func_48257_i ()
{
theAnimal.mate(targetMate);
}
*/
}
| gpl-3.0 |
sufficientlysecure/ad-away | app/src/main/java/org/adaway/ui/prefs/PrefsVpnFragment.java | 2492 | package org.adaway.ui.prefs;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import org.adaway.R;
import org.adaway.ui.prefs.exclusion.PrefsVpnExcludedAppsActivity;
import org.adaway.vpn.VpnService;
import static org.adaway.util.Constants.PREFS_NAME;
/**
* This fragment is the preferences fragment for VPN ad blocker.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
public class PrefsVpnFragment extends PreferenceFragmentCompat {
private static final int RESTART_VPN_REQUEST_CODE = 2000;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
// Configure preferences
getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
addPreferencesFromResource(R.xml.preferences_vpn);
// Bind pref actions
bindExcludedSystemApps();
bindExcludedUserApps();
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
PrefsActivity.setAppBarTitle(this, R.string.pref_vpn_title);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == RESTART_VPN_REQUEST_CODE) {
restartVpn();
}
}
private void bindExcludedSystemApps() {
ListPreference excludeUserAppsPreferences = findPreference(getString(R.string.pref_vpn_excluded_system_apps_key));
excludeUserAppsPreferences.setOnPreferenceChangeListener((preference, newValue) -> {
restartVpn();
return true;
});
}
private void bindExcludedUserApps() {
Context context = requireContext();
Preference excludeUserAppsPreferences = findPreference(getString(R.string.pref_vpn_excluded_user_apps_key));
excludeUserAppsPreferences.setOnPreferenceClickListener(preference -> {
startActivityForResult(new Intent(context, PrefsVpnExcludedAppsActivity.class), RESTART_VPN_REQUEST_CODE);
return true;
});
}
private void restartVpn() {
Context context = requireContext();
if (VpnService.isStarted(context)) {
VpnService.stop(context);
VpnService.start(context);
}
}
}
| gpl-3.0 |
teiniker/teiniker-lectures-securedesign | web-applications/secure-communication/http/HttpURLConnection-Client/src/test/java/org/se/lab/AbstractHttpClientTest.java | 4254 | package org.se.lab;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.junit.Before;
public abstract class AbstractHttpClientTest
{
protected Logger logger = Logger.getLogger(this.getClass());
protected Proxy PROXY;
protected String HOST;
protected String PORT;
@Before
public void setup() throws IOException
{
// read connection settings
Properties properties = new Properties();
properties.load(new FileInputStream("src/test/resources/http.properties"));
HOST = properties.getProperty("http.host");
PORT = properties.getProperty("http.port");
logger.debug("Connect to " + HOST + ":" + PORT);
// configure proxy
String proxyAddress = properties.getProperty("http.proxy.address");
String proxyPort = properties.getProperty("http.proxy.port");
if(proxyAddress != null && proxyPort != null)
{
logger.debug("Use proxy " + proxyAddress + ":" + proxyPort);
int port = Integer.parseInt(proxyPort);
PROXY = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port));
}
else
{
PROXY = Proxy.NO_PROXY;
}
}
public String httpGetRequest(URL url)
{
HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) url.openConnection(PROXY);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "text/html");
logger.debug("URL: " + url);
logger.debug("Request-Method: " + connection.getRequestMethod());
// read response
int httpResponseCode = connection.getResponseCode();
logger.debug("Response-Code: " + httpResponseCode);
logger.debug("Response-Content-Length:" + connection.getContentLength());
String content;
if(httpResponseCode >= 400)
{
content = readResponseContent(connection.getErrorStream());
throw new HttpClientException("Invalid HTTP response!", url,
connection.getResponseCode(), content);
}
content = readResponseContent(connection.getInputStream());
return content.toString();
}
catch (IOException e)
{
throw new HttpClientException("IO problems", e);
}
finally
{
if(connection != null)
connection.disconnect();
}
}
public String httpPostRequest(URL url, String requestContent)
{
HttpURLConnection connection = null;
try
{
// send request
connection = (HttpURLConnection) url.openConnection(PROXY);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "text/html");
logger.debug("URL: " + url);
logger.debug("Request-Method: " + connection.getRequestMethod());
logger.debug("Request-Content:\n" + requestContent);
OutputStreamWriter w = new OutputStreamWriter(connection.getOutputStream());
w.write(requestContent);
w.flush();
w.close();
// receive response
int httpResponseCode = connection.getResponseCode();
logger.debug("Response-Code: " + httpResponseCode);
logger.debug("Response-Content-Length:" + connection.getContentLength());
String content;
if(httpResponseCode >= 400)
{
content = readResponseContent(connection.getErrorStream());
throw new HttpClientException("Invalid HTTP response!", url,
connection.getResponseCode(), content);
}
content = readResponseContent(connection.getInputStream());
return content.toString();
}
catch (IOException e)
{
logger.debug("IO problems", e);
throw new HttpClientException("IO problems", e);
}
finally
{
if(connection != null)
connection.disconnect();
}
}
protected String readResponseContent(InputStream in)
throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer content = new StringBuffer();
while((line=reader.readLine()) != null)
{
content.append(line).append("\n");
}
logger.debug("Response-Content:\n" + content.toString());
return content.toString();
}
}
| gpl-3.0 |
protyposis/Studentenportal | Studentenportal/src/main/java/at/ac/uniklu/mobile/sportal/ui/GenericListAdapter.java | 2452 | /*
* Copyright (c) 2014 Mario Guggenberger <mario.guggenberger@aau.at>
*
* This file is part of AAU Studentenportal.
*
* AAU Studentenportal 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.
*
* AAU Studentenportal 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 AAU Studentenportal. If not, see <http://www.gnu.org/licenses/>.
*/
package at.ac.uniklu.mobile.sportal.ui;
import java.util.List;
import android.app.ListActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Generic base adapter that takes care of recycling views. Extension classes only need to update the
* views ({@link #updateView(int, View)}) and do not need to take care of the view recycling process.
*/
public abstract class GenericListAdapter<T> extends BaseAdapter {
private int mViewResourceId;
protected ListActivity mContext;
protected List<T> mList;
public GenericListAdapter(ListActivity context, List<T> list, int viewResourceId) {
this.mContext = context;
this.mList = list;
this.mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView;
if (convertView == null) {
itemView = (View)mContext.getLayoutInflater().inflate(mViewResourceId, parent, false);
} else {
// recycle existing view
itemView = (View)convertView;
}
updateView(position, itemView);
return itemView;
}
protected abstract void updateView(int position, View itemView);
public List<T> getItemList() {
return mList;
}
}
| gpl-3.0 |
bsantanna/tbainterview | remotecontrol/api/src/main/java/software/btech/tbainterview/remotecontrol/api/resource/RemoteControlResource.java | 2940 | package software.btech.tbainterview.remotecontrol.api.resource;
import org.apache.commons.lang.RandomStringUtils;
import software.btech.tbainterview.core.api.AbstractResource;
import software.btech.tbainterview.core.cache.CacheService;
import software.btech.tbainterview.remotecontrol.api.cache.CarPositionCacheRepository;
import software.btech.tbainterview.remotecontrol.api.domain.transfer.CarList;
import software.btech.tbainterview.remotecontrol.api.domain.transfer.CarPosition;
import software.btech.tbainterview.remotecontrol.api.domain.transfer.RepositionCommand;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
@Path("/api/remotecontrol")
public class RemoteControlResource extends AbstractResource {
@Inject
private CarPositionCacheRepository cacheRepository;
@Inject
private CacheService cacheService;
@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
public Response createCarIntance() {
String carId = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
CarPosition carPosition = this.cacheRepository.find(carId);
while (carPosition != null) {
carId = RandomStringUtils.randomAlphanumeric(10).toLowerCase();
carPosition = this.cacheRepository.find(carId);
}
carPosition = new CarPosition();
this.cacheRepository.save(carPosition, carId);
URI uri = UriBuilder.fromUri("/api/remotecontrol/position/" + carId).build();
return created(uri);
}
@DELETE
@Path("{carId}")
public Response deleteCarInstance(@PathParam("carId") String carId) {
CarPosition carPosition = this.cacheRepository.find(carId);
if (carPosition == null) {
return notFound("Car not found: " + carId);
}
this.cacheRepository.delete(carId);
return noContent();
}
@GET
@Path("/position/{carId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCarPosition(@PathParam("carId") String carId) {
CarPosition carPosition = this.cacheRepository.find(carId);
if (carPosition == null) {
return notFound("Car not found: " + carId);
}
return ok(carPosition, MediaType.APPLICATION_JSON);
}
@POST
@Path("/position/{carId}")
@Consumes(MediaType.APPLICATION_JSON)
public Response postCarPosition(@PathParam("carId") String carId, @Valid CarPosition carPosition) {
RepositionCommand repositionCommand = new RepositionCommand(carId, carPosition);
this.cacheService.publish("reposition_command", repositionCommand);
return ok(repositionCommand, MediaType.APPLICATION_JSON);
}
@GET
@Path("/list")
@Consumes(MediaType.APPLICATION_JSON)
public Response getCarList() {
CarList carList = new CarList();
carList.getIds().addAll(this.cacheRepository.findAll().keySet());
return ok(carList, MediaType.APPLICATION_JSON);
}
}
| gpl-3.0 |
denlap007/maestro | core/src/main/java/net/freelabs/maestro/core/handler/package-info.java | 821 | /*
* Copyright (C) 2015-2016 Dionysis Lappas (dio@freelabs.net)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Provides classes to handle the container types.
*/
package net.freelabs.maestro.core.handler;
| gpl-3.0 |
jeronangell/DarkOrbitBot | Testhing Ground/src/workingFinder/bonesBox.java | 3942 | package workingFinder;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import imglogic.Colorlogic;
import imglogic.GetImage;
import imglogic.ImgRobot;
import imglogic.searchMath;
import triangle.Rtriangle;
import userControls.Mouse;
public class bonesBox {
private ImgRobot imgrob=new ImgRobot();
public Mouse mouse = new Mouse();
Rtriangle tryangle=new Rtriangle();
private GetImage getimage=imgrob.image;
private searchMath imgmath=imgrob.smath;
private Colorlogic clgc=imgrob.clogic;
private Point[] bbPNts;
private int pntcnt;
private BufferedImage img;
private Point clickpoint;
public void rightclick(Point p){
mouse.rightclick(p);
}
private boolean cargoC(Color c){
return(clgc.colMoreLess(c, new Color(200,82,92)));
}
private boolean cargoC(BufferedImage img, int x, int y){
if(imgmath.searchBoundries(img,new Point(x,y))){
return cargoC(clgc.pointColor(img, x, y));
}else{
return false;
}
}
private boolean filter1(int x,int y){
return !(cargoC(img, x, y)&&cargoC(img, x+1, y)
||cargoC(img, x-1, y))&&
!clgc.pointColor(img, x, y,31,36,43)&&
!clgc.pointColor(img, x, y,28,33,40)&&
!clgc.pointColor(img, x, y,27,33,38)&&
!clgc.pointColor(img, x, y,7,7,7)&&
!clgc.pointColor(img, x, y,0,0,0)&&
!clgc.pointColor(img, x, y,22,38,47);
}
public boolean findBonesBox3(){
Point p = new Point(30,70);
img = getimage.screanImage(p,getimage.scwidth-60,getimage.scheight-140);
pntcnt=0;
bbPNts=new Point[20];
//thisPaliePic(400,400);
for(int y= 4;y<img.getHeight()-4;y+=60){
for(int x=4;x<img.getWidth()-4;x+=60){
if(filter1(x,y)){
//this is a brod filter most brighter colors will set it of
loop:for(int i =(-30);i<30;i+=16){
for(int j =(-30);j<30;j+=16){
if(filter2(x+j,y+i)){
break loop;
}
}
}
}else{
filter2(x,y);
}
}
}
//System.out.println(bnum);
//System.out.println(itorations);
if(pntcnt!=0){
rightclick(findClosePnt());
System.out.println("hipotinose = "+hipotinose);
return true;
}
return false;
}
private boolean filter2(int x,int y){
if(cargoC(img, x+1, y)
||cargoC(img, x-1, y)){
filter3(x,y);
return true;
}
return false;
}
public int hipotinose=0;
private void filter3(int x,int y){
loop:for(int x1=(-17);x1<8;x1++){
for(int y1=(-17);y1<8;y1++){
int tempx=x+x1;
int tempy=y+y1;
if(cargoC(img, tempx, tempy)){
if(filter4(tempx,tempy)){
if(filter5(tempx-13,tempy-15)){
bbPNts[pntcnt]=new Point(tempx+7,tempy+5);
pntcnt++;
break loop;
}
}
}
}
}
}
private boolean filter4(int x, int y) {
for(int i=0;i<3;i++){
for(int x1=0;x1<13;x1+=1){
if(!cargoC(img, x+x1-i, y)
&&!cargoC(img, x+x1-i, y+7)){
return false;
}
}
for(int y1=0;y1<9;y1+=1){
if(!cargoC(img, x, y+y1-i)
&&!cargoC(img, x+12, y+y1-i)){
return false;
}
}
}
return true;
}
private boolean filter5(int x1,int y1) {
int fp=46;
for (int y = 2; y < fp; y+=3) {
if(!cargoC(img, y+x1,y1)
&&!cargoC(img, y+x1,y1+fp)
&&!cargoC(img,x1+fp,y+y1)
&&!cargoC(img, x1,y+y1)){
}else{
return false;
}
}
return true;
}
private Point findClosePnt(){
clickpoint=new Point(0,0);
Point p1 = new Point(30,70);
int[] e =new int[20];
int i=0;
int numpnt = 0;
for(Point p:bbPNts){
if(p!=null){
e[i]=(int) tryangle.findhipotinose(getimage.centerpt,new Point(p.x,p.y-115));
numpnt++;
i++;
}else{
break;
}
}
int small = 18000;
for(int l=0;l<numpnt;l++){
if(bbPNts[l]==null){
break;
}
if(small>e[l]){
small=e[l];
hipotinose =e[l];
clickpoint=new Point(p1.x+bbPNts[l].x,p1.y+bbPNts[l].y-10);
}
}
return clickpoint;
}
}
| gpl-3.0 |
TonyClark/ESL | src/ast/query/rules/Query.java | 3866 | package ast.query.rules;
import java.util.Arrays;
import ast.general.AST;
import ast.query.QueryError;
import ast.query.body.BodyElement;
import ast.query.body.Call;
import ast.query.body.DBName;
import ast.query.machine.Machine;
import ast.query.value.Int;
import ast.query.value.Term;
import ast.query.value.Value;
import ast.query.value.Var;
import ast.types.TypeError;
import exp.BoaConstructor;
import history.History;
import runtime.data.Key;
import values.JavaObject;
import values.Located;
import values.LocationContainer;
import xpl.Interpreter;
@BoaConstructor(fields = { "rules", "elements", "value" })
public class Query implements Located, LocationContainer {
static Machine typeCheckingMachine = null;
static Machine getTypeCheckingMachine() {
if (typeCheckingMachine == null) {
JavaObject o = (JavaObject) Interpreter.readFile("xpl/query.xpl", "query", "esl/query/typeCheck.q", "file", new exp.Str("esl/query/typeCheck.q"));
RuleBase typeCheckRules = ((Query) o.getTarget()).getRules();
typeCheckingMachine = new Machine(typeCheckRules.compile(), null);
}
return typeCheckingMachine;
}
public RuleBase rules;
public BodyElement[] elements;
public Value value;
private int lineStart = -1;
private int lineEnd = -1;
public Query() {
super();
}
public RuleBase getRules() {
return rules;
}
public BodyElement[] getElements() {
return elements;
}
public Value getValue() {
return value;
}
public static void print(Object[] elements) {
System.out.println("ARRAY " + Arrays.toString(elements));
}
public int getLineEnd() {
return lineEnd;
}
public int getLineStart() {
return lineStart;
}
public Object satisfy(History history) {
Call.setDBNames(new DBName[] { new DBName(Key.getKey("actor"), 3), new DBName(Key.getKey("send"), 4), new DBName(Key.getKey("state"), 4) });
ClauseTable table = rules.compile();
Machine machine = new Machine(rules.compile(), history);
Var var = new Var();
machine.init(Key.getKey("main"), var);
return machine.recons(machine.deref(var));
}
public void setLineEnd(int lineEnd) {
this.lineEnd = lineEnd;
}
public void setLineStart(int lineStart) {
this.lineStart = lineStart;
}
public Located getLocated(int charIndex) {
return AST.getLocated(this, charIndex);
}
public void check() {
rules.check();
}
public void spy(String name) {
rules.spy(Key.getKey(name));
}
public void spyAll() {
rules.spyAll();
}
public void unspyAll() {
rules.unspyAll();
}
public void unspy(String name) {
rules.unspy(Key.getKey(name));
}
public boolean spied(String name) {
return RuleBase.spied(name);
}
public void typeCheck() {
typeCheck(getRules());
}
public static synchronized void typeCheck(RuleBase rules) {
try {
rules = rules.resolveTypes();
Machine machine = getTypeCheckingMachine();
Key typeCheck = Key.getKey("typeCheck");
Var var = new Var();
machine.init(typeCheck, RuleBase.asTerm(rules), var);
runtime.data.Term term = (runtime.data.Term) machine.recons(var);
if (term != null) {
Object[] values = term.getValues();
int start = (Integer) values[0];
int end = (Integer) values[1];
String message = values[2].toString();
throw new TypeError(start, end, message);
}
} catch (QueryError e) {
Term term = (Term) e.getValue();
Value[] values = term.getValues();
int start = ((Int) values[0]).getValue();
int end = ((Int) values[1]).getValue();
String message = values[2].toString();
throw new TypeError(start, end, message);
} catch (TypeError te) {
throw te;
}
}
public void setDefs() {
rules.setDefs();
}
}
| gpl-3.0 |
Borlea/EchoPet | modules/v1_13_R2/src/com/dsh105/echopet/compat/nms/v1_13_R2/entity/type/EntityIllagerAbstractPet.java | 2198 | /*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.echopet.compat.nms.v1_13_R2.entity.type;
import com.dsh105.echopet.compat.api.entity.IPet;
import com.dsh105.echopet.compat.api.entity.SizeCategory;
import com.dsh105.echopet.compat.api.entity.type.nms.IEntityIllagerAbstractPet;
import com.dsh105.echopet.compat.nms.v1_13_R2.entity.EntityPet;
import net.minecraft.server.v1_13_R2.DataWatcher;
import net.minecraft.server.v1_13_R2.DataWatcherObject;
import net.minecraft.server.v1_13_R2.DataWatcherRegistry;
import net.minecraft.server.v1_13_R2.Entity;
import net.minecraft.server.v1_13_R2.EntityTypes;
import net.minecraft.server.v1_13_R2.World;
/**
* @since May 23, 2017
*/
public class EntityIllagerAbstractPet extends EntityPet implements IEntityIllagerAbstractPet{
protected static final DataWatcherObject<Byte> a = DataWatcher.a(EntityIllagerAbstractPet.class, DataWatcherRegistry.a);
public EntityIllagerAbstractPet(EntityTypes<? extends Entity> type, World world){
super(type, world);
}
public EntityIllagerAbstractPet(EntityTypes<? extends Entity> type, World world, IPet pet){
super(type, world, pet);
}
protected void initDatawatcher(){
super.initDatawatcher();
this.datawatcher.register(a, (byte) 0);
}
protected void a(int paramInt, boolean paramBoolean){
int i = this.datawatcher.get(a);
if(paramBoolean){
i |= paramInt;
}else{
i &= (paramInt ^ 0xFFFFFFFF);
}
this.datawatcher.set(a, (byte) (i & 0xFF));
}
@Override
public SizeCategory getSizeCategory(){
return SizeCategory.REGULAR;
}
}
| gpl-3.0 |
rmachedo/MEater | src/edu/umd/rhsmith/diads/meater/modules/tweater/oauth/XmlOAuthSource.java | 495 | package edu.umd.rhsmith.diads.meater.modules.tweater.oauth;
import org.apache.commons.configuration.XMLConfiguration;
public class XmlOAuthSource implements OAuthSource {
@Override
public OAuthInfo getOAuthInfo(String name) throws OAuthLoadException {
try {
XMLConfiguration xml = new XMLConfiguration(name + ".xml");
OAuthConfig oAuth = new OAuthConfig();
oAuth.loadConfigurationFrom(xml);
return oAuth;
} catch (Exception e) {
throw new OAuthLoadException(e);
}
}
}
| gpl-3.0 |